C Programming: Selected Topics in CSA
C Programming: Selected Topics in CSA
1
C Language
• The C language was written in 1970 for the first
UNIX system.
• In 1988, the American National Standards
Institute (ANSI) adopted a ''new and improved''
version of C, known today as ''ANSI C''.
2
A First Program
#include <stdio.h>
void main()
{
printf("\nHello World\n");
}
4
Compilation
• Create a text file with editor and convention end with ''.c ''
• There are many C compilers around. The cc being the defau
lt Sun compiler. The GNU C compiler gcc is popular and ava
ilable for many platforms.
• To Compile your program simply invoke the command cc. T
he command must be followed by the name of the (C) progr
am :
cc program.c
• If compilation success, the output file called a.out
• It is more convenient to use a -o and filename in the compila
tion as in
cc -o program.exe program.c
• The output file called as the name following the "-o" argume
nt instead of a.out . 5
• The C Compilation Model
– We will briefly highlight key features of the C
Compilation model here
6
• The Preprocessor
– The Preprocessor accepts source code as input and i
s responsible for
• removing comments
• interpreting special preprocessor directives denoted by #.
– For example
#include -- includes contents of a named file. Files usually calle
d header files. e.g
#include <math.h> -- standard library maths file
#include <stdio.h> -- standard library I/O file
#define -- defines a symbolic name or constant. Macro
substitution.
Eg. #define MAX_ARRAY_SIZE 100
int array[MAX_ARRAY_SIZE]
7
• C Compiler
– The C compiler translates source to assembly code. The source code is
received from the preprocessor
• Assembler
– The assembler creates object code. On a UNIX system you may see
files with a .o suffix (.OBJ on MSDOS) to indicate object code files
• Link Editor
– If a source file references library functions or functions defined in other
source files the link editor combines these functions (with main()) to
create an executable file. External Variable references resolved here
also
8
– -c
• Suppress the linking process and produce a .o file for each s
ource file listed. Several can be subsequently linked by the c
c command, for example:
cc file1.o file2.o ...... -o executable
– -llibrary
• Link with object libraries. This option must follow the source fi
le arguments. The object libraries are archived and can be st
andard, third party or user created libraries. Probably the mo
st commonly used library is the math library ( math.h). You m
ust link in this library explicitly if you wish to use the maths fu
nctions (note do note forget to #include <math.h> header fil
e), for example:
cc calc.c -o calc -lm
9
– -Ldirectory
• Add directory to the list of directories containing object-library routin
es. The linker always looks for standard and other system libraries i
n /lib and /usr/lib. If you want to link in libraries that you have create
d or installed yourself (unless you have certain privileges and get th
e libraries installed in /usr/lib) you will have to specify where you file
s are stored, for example:
cc prog.c -L/home/myname/mylibs mylib.a
– -Ipathname
• Add pathname to the list of directories in which to search for #includ
e files with relative filenames (not beginning with slash /).
• BY default, The preprocessor first searches for #include files in the
directory containing source file, then in directories named with -I opti
ons (if any), and finally, in /usr/include. So to include header files sto
red in /home/myname/myheaders you would do:
cc prog.c -I/home/myname/myheaders
• Note: System library header files are stored in a special place (/usr/i
nclude) and are not affected by the -I option.
10
Variable
• int -> integer variable
• short -> short integer
• long -> long integer
• float -> single precision real (floating point) varia
ble
• double -> double precision real (floating point) v
ariable
• char -> character variable (single byte)
11
Printf Function
• The general syntax of printf function:
#define ANGLE_MIN 0
#define ANGLE_MAX 360
18
Conditionals
• Conditionals are used within the if and while
constructs:
if (conditional_1)
{
...block of statements executed if conditional_1 is true...
}
else if (conditional_2)
{
...block of statements executed if conditional_2 is true...
}
else
{
...block of statements executed otherwise...
}
19
• Conditionals are logical operations involving comparison
of quantities (of the same type) using the
– conditional operators:
< smaller than
<= smaller than or equal to
== equal to
!= not equal to
>= greater than or equal to
> greater than
– boolean operators
&& and
|| or
! not
20
#include "stdio.h"
void main()
{
int xx;
for(xx = 5; xx < 15; xx = xx + 1) {
if (xx == 8)
break;
printf("In the break loop, xx is now %d\n",xx);
}
• Find maximum:
x=(a>b?a:b)
• Find minimum:
x=(a<b?a:b)
22
Switch Function
• Another conditional use is in the switch construct:
switch (expression)
{
case const_expression_1:
{
...block of statements...
break;
}
case const_expression_2:
{
...block of statements...
break;
}
default:
{
...block of statements..
}
} 23
#include "stdio.h"
void main()
{
int truck;
for (truck = 3; truck < 13; truck = truck + 1) {
switch (truck) {
case 3 : printf("The value is three\n");
break;
case 4 : printf("The value is four\n");
break;
case 5 :
case 6 :
case 7 :
case 8 : printf("The value is between 5 & 8\n");
break;
case 11 : printf("The value is eleven\n");
break;
default : printf("The value is undefined\n");
break;
} /* end of switch */
} /* end of for loop */
}
28
void main()
{
float x, y; /* x and y are of float type */
float *fp, *fp2; /* fp and fp2 are pointers to float */
x = 6.5; /* x now contains the value 6.5 */
*fp = 9.2;
printf("New value of x is %f = %f \n", *fp, x);
30
#define SIZE 3
void main()
{
float x[SIZE];
float *fp;
int i;
/* initialize the array x */
for (i = 0; i < SIZE; i++)
x[i] = 0.5*(float)i; /* use a "cast" to force i */
/* print x */
for (i = 0; i < SIZE; i++)
printf(" %d %f \n", i, x[i]);
32
void main()
{
char text_1[100], text_2[100], text_3[100];
char *ta, *tb;
int i;
/* set message to be an arrray of characters; initialize it to the constant string "..." */
/* let the compiler decide on its size by using [] */
char message[] = "Hello, I am a string; what are you?";
printf("Original message: %s\n", message);
33
''string.h'' Library Functions
char *strcpy(s,ct) -> copy ct into s, including ''\0''; return s
char *strncpy(s,ct,n) -> copy ncharcater of ct into s, return s
char *strncat(s,ct) -> concatenate ct to end of s; return s
char *strncat(s,ct,n) -> concatenate n character of ct to end
of s, terminate with ''\0''; return s
int strcmp(cs,ct) -> compare cs and ct; return 0 if cs=ct,
<0 if cs0 if cs>ct
char *strchr(cs,c) -> return pointer to first occurence of c
in cs or NULL if not encountered
size_t strlen(cs) -> return length of cs
34
#include < string.h>
void main()
{
char line[100], *sub_text;
37
I/O to and from files
• Similar statements also exist for handling I
/O to and from files. The statements are fs
canf() and fprintf()
• define a local ''pointer'' of type FILE
#include < stdio.h>
(note that the uppercase is necessary
FILE *fp;
here)
fp = fopen(name, mode);
fscanf(fp, "format string", variable list); • ''open'' the file and associate it with
the local pointer via fopen
fprintf(fp, "format string", variable list);
fclose(fp ); • perform the I/O operations using fs
canf and fprintf
• disconnect the file from the task wit
h fclose
38
• The ''mode'' argument in the fopen specifies the
purpose/positioning in opening the file: ''r'' for rea
ding, ''w'' for writing, and ''a'' for appending to the
file.
#include < stdio.h>
void main()
{
FILE *fp;
int i;
fp = fopen("foo.dat", "w"); /* open foo.dat for writing */
fprintf(fp, "\nSample Code\n\n"); /* write some info */
for (i = 1; i <= 10 ; i++)
fprintf(fp, "i = %d\n", i);
fclose(fp); /* close the file */
}
39
Functions
• A function has the following layout:
return-type function-name ( argument-list-if-necessary )
{
...local-declarations...
...statements...
return return-value;
}
40
• Some library functions are defined in header files.
41
• Arguments are always passed by value in C
function calls. This means that local ''copies'' of
the values of the arguments are passed to the
routines. Any change made to the arguments
internally in the function are made only to the
local copies of the arguments.
• To change (or define) an argument in the
argument list, this argument must be passed as
an address.
42
#include < stdio.h>
void exchange(int a, int b);
void main()
{ /* The argument value won’t be exchanged */
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a, b);
exchange(a, b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
void exchange(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", a, b);
}
43
#include < stdio.h>
void exchange ( int *a, int *b );
void main()
{/* The argument value will be exchanged */
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a, b);
exchange(&a, &b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
void exchange ( int *a, int *b )
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", *a, *b);
}
44
Command-line arguments
• The full statement of the first line of the program
is:
main(int argc, char** argv)
• The commmand-line arguments are stored in an
array of character strings called argv.
• An integer, called argc, which specifies the num
ber of string in the argv array.
45
• For example,
a.out -i 2 -g -x 3 4
the program would receive
argc = 7
argv[0] = "a.out"
argv[1] = "-i"
argv[2] = "2"
argv[3] = "-g"
argv[4] = "-x"
argv[5] = "3"
argv[6] = "4"
46
Time Functions
• We can access the clock time with UNIX
system calls and concentrate on
applications of timing functions in C
• Uses of time functions include:
• telling the time.
• timing programs and functions.
• setting number seeds.
47
Basic time functions
• Prototypes:
– Time Data Type: time_t
– time_t time(time_t *tloc) -- returns the time since 00:00:00
GMT, Jan. 1, 1970, measured in seconds.
– If tloc is not NULL, the return value is also stored in the loc
ation to which tloc points
48
Example 1: Time (in seconds) to
perform some computation
/* timer.c */
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
main() {
int i;
time_t start_t, end_t;
(void) time(&start_t);
for (i=1;i<=300;++i)
printf(''%d %d %d\n'',i, i*i, i*i*i); (void)
time(&end_t);
printf(''\n Time to do 300 squares and cubes= %d seconds\n'',
(int) end_t – start_t);
} 49
Example 2: Set a random number
seed
/* random.c */
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
main() {
int i;
time_t t1;
(void) time(&t1);
for (i=0;i<5;++i)
printf(''%d \n'', lrand48());
}
50
• lrand48() returns non-negative long integers
uniformly distributed over the interval (0, 2**31)
51
Suggestion Solution
52
Solution: Write a program that counts from 1 to 12 and prints the
count and its inversion to 5 decimal places for each count. This
will require a floating point number.
1 1.00000
2 0.50000
3 0.33333
……
#include <stdio.h>
main() {
int i;
float f;
53
Solution: Write a C program to print out the square root from 1 to
100 using math.h function.
#include <math.h>
main() {
int i;
printf("\t Number \t\t Square Root of Number\n\n");
54
Solution: Try to modify the program to count the number of line
in a text file.
55
Solution: Try to write a program simply to print out all the
arguments and the name of the program.
56