[go: up one dir, main page]

0% found this document useful (0 votes)
94 views56 pages

C Programming: Selected Topics in CSA

The document provides an overview of the C programming language including: - A first C program that prints "Hello World" - The C compilation process involving preprocessing, compilation, assembly, and linking - Common data types like int, char, and float - Common functions like printf() - Control structures like while, for, and do-while loops - How to define symbolic constants using #define

Uploaded by

midhungbabu88
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views56 pages

C Programming: Selected Topics in CSA

The document provides an overview of the C programming language including: - A first C program that prints "Hello World" - The C compilation process involving preprocessing, compilation, assembly, and linking - Common data types like int, char, and float - Common functions like printf() - Control structures like while, for, and do-while loops - How to define symbolic constants using #define

Uploaded by

midhungbabu88
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 56

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''.

The C Programming Language -- ANSI C


Brian W. C. Kernighan & Dennis M. Ritchie
Prentice Hall, 1988

2
A First Program
#include <stdio.h>
void main()
{
printf("\nHello World\n");
}

• Save the file in *.c extension.


• Use gcc command for compilation. Eg.
$ gcc hello.c
• A file called a.out will be created.
• Execute the programme simply by typing ./a.out
• As the result ''Hello World'' are printed out.
3
• The program will start from ''main'' function. The ''mai
n'' function establishes the overall logic of the code.
• All C codes must have a ''main'' function.
• printf(), an output function from the I/O (input/output) li
brary (defined in the file stdio.h)
– ''\n'' prints a ''new line'' character, which brings the cursor onto
the next line.
• The first statement ''#include < stdio.h>'‘. The ''.h'' files
are by convention ''header files'' which contain definitio
ns of variables and functions necessary for the functio
ning of a program.

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

• Some Useful Compiler Options


– Now that we have a basic understanding of the compilation model we
can now introduce some useful and sometimes essential common
compiler options

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:

printf( "format", variables );


• where "format" specifies the converstion specification and
variables is a list of quantities to print.

– %.nd integer (optional n = number of columns; if 0, pad with


zeroes)
– %ld long
– %m.nf float or double (optional m = number of columns, n = nu
mber of decimal places)
– %ns string (optional n = number of columns)
– %c character
– \n \t to introduce new line or tab
– \g ring the bell (''beep'') on the terminal 12
#include <stdio.h>
char a; /* first variable */
int b; /* second variable */
float c; /* third variable */
main()
{
a = 'A'; b = 9; f = 2.3;
printf( "%c%d%f reversed is %f%d%c\n",
a , b , c , c , b , a);
return (0);
}

What is the output ?


13
While Loop
• while loop:
while (expression)
{
...block of statements to execute...
}
Eg.
#include "stdio.h"
void main()
{
int count;
count = 0;
while (count < 6) {
printf("The value of count is %d\n",count);
count = count + 1;
}
} 14
• Do …. while loop:
do
{
...block of statements to execute...
} while (expression)
Eg.
#include <stdio.h>
~Using do loop~
int main() {
The following program is
int number = 44;
a game that allows a use
int guess;
r to guess a number betw
printf("Guess a number between 1 and 100\n");
een 1 and 100.
do {
printf("Enter your guess: ");
A "do" loop is appropriate
scanf("%d",&guess);
since we know that winni
if (guess > number)
ng the game always requi
printf("Too high\n");
res at least one guess.
if (guess < number)
printf("Too low\n");
} while (guess != number);
printf("You win. The answer is %d",number);
} 15
For Loop
• for loop:

for (expression_1; expression_2; expression_3)


{
...block of statements to execute...
}

• This structure may be rewritten in the easier syntax of the f


or loop as:

for (i = initial_i; i <= i_max; i = i + i_increment)


{
...block of statements...
}
16
#include "stdio.h"
void main()
{
int index;
for(index = 0; index < 6; index = index + 1)
{
printf("The value of the index is %d\n",index);
} /* end of for loop */
}
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
…… 17
Symbolic Constants
• You can define constants of any type by using
the #define compiler directive.

#define ANGLE_MIN 0
#define ANGLE_MAX 360

• The values of #define cannot be changed in the


programming running.

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);
}

for(xx = 5; xx < 15; xx = xx + 1) {


if (xx == 8)
continue;
printf("In the continue loop, xx is now %d\n",xx);
}
}

What is the output ?


21
( condition ? true : false )
• ( condition ? Executed if true
: Executed if false )

• 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 */
}

What is the output ?


24
<math.h> Function
• double exp(double x); exponential of x
• double log(double x); natural logarithm of x
• double log10(double x); base-10 logarithm of x
• double pow(double x, double y); x raised to power y
• double sqrt(double x); square root of x
• double ceil(double x); smallest integer not less than x
• double floor(double x); largest integer not greater than x
• double fabs(double x); absolute value of x
• double sin(double x); sine of x
• double cos(double x); cosine of x
• double tan(double x); tangent of x
• double asin(double x); arc-sine of x
• double acos(double x); arc-cosine of x
• double atan(double x); arc-tangent of x

Write a C program to print out the square root fr


om 1 to 100 using math.h function. 25
Pointers
• All variables in a program reside in memory
float x;
x = 6.5;
the compiler reserve 4 bytes of memory (on a 32-bit
computer) for the floating-point variable x, then put the ''
''value'' 6.5 in it.

• Sometimes we want to know where a variable resides in


memory. The address (location in memory) of any
variable is obtained by placing the operator ''&'' before its
name. Therefore &x is the address of x. C allows us to
go one stage further and define a variable, called a
pointer which is the address of variables.
26
float x;
float* px;
x = 6.5;
px = &x;

• defines px to be a pointer to objects of type float, and


sets it equal to the address of x
• The content of the memory location referenced by a
pointer is obtained using the ''*'' operator (this is
called dereferencing the pointer). Thus, *px refers to the
value of x.
27
• C allows us to perform arithmetic operations usin
g pointers
• For example, if px is a pointer to a variable x of t
ype float, then the expression px + 1 refers not t
o the next bit or byte in memory but to the locatio
n of the next float after x (4 bytes away on most
workstations)

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 */

printf("Value of x is %f, address of x %ld\n", x, &x);

fp = &x; /* fp now points to location of x */


printf("Value in memory location fp is %f\n", *fp);

*fp = 9.2;
printf("New value of x is %f = %f \n", *fp, x);

*fp = *fp + 1.5; /* perform arithmetic */


printf("Final value of x is %f = %f \n", *fp, x);

y = *fp; /* transfer values */


fp2 = fp;
printf("Transfered value into y = %f and fp2 = %f \n", y, *fp2);
}

What is the output ?


29
Array
• Arrays of any type can be formed in C.
type name[dim];
• In C, arrays starts at position 0.
• if v is an array, *v is the same thing as v[0], *(v+
1) is the same thing as v[1], and so on.

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]);

fp = x; /* make fp point to array x */

/* print via pointer arithmetic, members of x are adjacent to


each other in memory *(fp+i) refers to content of */
memory location (fp+i) or x[i] */
for (i = 0; i < SIZE; i++)
printf(" %d %f \n", i, *(fp+i));
}
31
Character Array
• A string constant , such as "I am a string" is an a
rray of characters, but it terminated by the speci
al null character "\0'' so programs can find the e
nd of the string.
• Since strings are conventionally terminated by th
e null character ''\0'', we require one extra storag
e location in the array!
• C does not provide any operator which manipula
te entire strings at once. Special functions availa
ble from the standard string library string.h only.

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);

/* copy the message to text_1 the hard way */


i=0;
while ( (text_1[i] = message[i]) != '\0' )
i++;
printf("Text_1: %s\n", text_1);

/* use explicit pointer arithmetic */


ta=message;
tb=text_2;
while ( ( *tb++ = *ta++ ) != '\0' )
;
printf("Text_2: %s\n", text_2);
}

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;

strcpy(line,"hello, I am a string;"); /* initialize string */


printf("Line: %s\n", line); /* add to end of string */
strcat(line," what are you?");
printf("Line: %s\n", line);

/* find length of string; strlen brings back length as type size_t */


printf("Length of line: %d\n", (int)strlen(line));

/* find occurence of substrings */


if ( (sub_text = strchr ( line, 'W' ) )!= NULL )
printf("String starting with \"W\" ->%s\n", sub_text);
if ( ( sub_text = strchr ( line, 'w' ) )!= NULL )
printf("String starting with \"w\" ->%s\n", sub_text);
if ( ( sub_text = strchr ( sub_text, 'u' ) )!= NULL )
printf("String starting with \"w\" ->%s\n", sub_text);
}
35
I/O Capabilities
• C provides (through its libraries) a variety of I/O r
outines. At the character level, getchar() reads o
ne character at a time from stdin, while putchar
() writes one character at a time to stdout.

#include < stdio.h>


void main()
{
int i, nc;
nc = 0; Try to modify the program
i = getchar(); to count the number of line
while (i != EOF) { in a text file.
nc = nc + 1;
i = getchar();
}
printf("Number of characters in file = %d\n", nc);
36
}
Higher-Level I/O capabilities
• We have already seen that printf handles formatt
ed output to stdout. The counterpart statement f
or reading from stdin is scanf()
scanf("format string", variables);

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;
}

• If return-type is omitted, C defaults to int.


The return-value must be of the declared type.

40
• Some library functions are defined in header files.

< stdio.h> -> defining I/O routines


< ctype.h> -> defining character manipulation routines
< string.h> -> defining string manipulation routines
< math.h> -> defining mathematical routines
< stdlib.h> -> defining number conversion, storage allocation
and similar tasks
< stdarg.h> -> defining libraries to handle routines with variable
numbers of arguments
< time.h> -> defining time-manipulation routines

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"

Try to write a program simply to print out all the arguments


and the name of the program.

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

– time() returns the value of time on success

– On failure, it returns (time_t) -1. time_t is typedefed to a lon


g (int) in <sys/types.h> and <sys/time.h> header files

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);

srand48((long) t1); /* use time in seconds to set seed */


printf(''5 random numbers    (Seed = %d):\n'' , (int) 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)

• A similar function drand48() returns double


precision numbers in the range [0.0,1.0)

• srand48() sets the seed for these random


number generators. It is important to have
different seeds when we call the functions
otherwise the same set of pseudo-random
numbers will generated. time() always provides
a unique seed

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;

for (i=1; i<=12; i++) {


f=1/(float)i;
printf("Inverse of %d is %.5f\n", i, 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");

for (i=0; i<=100; ++i)


printf("\t %d \t\t\t %f \n",i, sqrt((double) i));
}

54
Solution: Try to modify the program to count the number of line
in a text file.

#include < stdio.h>


void main()
{
int c, nc = 0, nl = 0;
while ( (c = getchar()) != EOF )
{
nc++;
if (c == '\n') nl++;
}
printf("Number of characters = %d, number of lines = %d\n“, nc, nl);
}

55
Solution: Try to write a program simply to print out all the
arguments and the name of the program.

#include < stdio.h>


main(int argc, char** argv)
{
int i;
printf("argc = %d\n", argc);
for (i = 0; i < argc; i++)
printf("argv[%d] = \"%s\"\n", i, argv[i]);
}

56

You might also like