Professional Documents
Culture Documents
for
NTP
1007v1.1 - CW1 1
Overview of C - Session 1
OBJECTIVE:
Participants will be able to recapitulate
their knowledge of C Programming.
SCOPE:
Salient features of C programming are
covered.
1007v1.1 - CW1 2
Overview of C - Session 1
Books Recommended
Programming in ANSI C by E.
Balagurusamy (TMH).
The Programming Language C by
Kernighan and Ritchie, PHI.
1007v1.1 - CW1 3
Overview of C - Session 1
Overview of C
Overview of a C Program
C Elements & Operators
Control Flow Statements
Pointers to
Simple Variables
Arrays
Structures
Character arrays
Creation of Dynamic variables
1007v1.1 - CW1 4
Overview of C - Session 1
Overview of C Contd.
C Functions
Call by Value
Call by Reference
Program variables
• Scope and Longevity
Function arguments
• Pointers to Pointers
• Functions
File Management in C
Command Line Arguments
C Preprocessor
1007v1.1 - CW1 5
Overview of C - Session 1
Overview of a C Program
Every C program contains one or
more C functions in one/more C
source files.
One function named main is where
program execution always begins. It
can be located anywhere, need not
be the first one.
Each source file is compiled
separately.
1007v1.1 - CW1 6
Overview of C - Session 1
Overview of a C Program Contd.
1007v1.1 - CW1 9
Overview of C - Session 1
C Elements
1007v1.1 - CW1 10
Overview of C - Session 1
C Elements - Constants
(a) Integers:
DECIMAL: 12345 123L 123U
OCTAL: 012345 0456LU
HEX: 0x12345
Prefix 0 for octal constant and 0x for
hexadecimal constants.
Suffix L/l for Long integers, default:
short.
Suffix U/u for unsigned, default: signed.
1007v1.1 - CW1 11
Overview of C - Session 1
C Elements - Constants Contd.
(b)Character Constants:
1007v1.1 - CW1 12
Overview of C - Session 1
C Elements - Constants Contd.
1007v1.1 - CW1 13
Overview of C - Session 1
C Elements - Constants Contd.
g) Declared Constants:
Declared by the const qualifier for
variable of any type.
The value of the variable cannot be
modified.
const float pi = 3.1416;
1007v1.1 - CW1 17
Overview of C - Session 1
Types and Declarations
(a) Basic Types:
void: Special Type
char Single byte ,signed/unsigned.
intImplementation dependent size
signed/unsigned, short or long.
float single-precision real
Double double-precision real
Type qualifier long can be applied to
double to specify extended precision.
1007v1.1 - CW1 18
Overview of C - Session 1
Types and Declarations Contd.
(b) Arrays:
C allows multidimensional arrays.
Arrays in C are indexed from 0.
Example:
int A[10][10];
First element: A[0][0]
Last element: A[9][9]
size = 100 elements
1007v1.1 - CW1 19
Overview of C - Session 1
Types and Declarations Contd.
( c) Enumeration:
Provide a method of associating a
constant set of values starting from zero
to a set of identifiers automatically.
Advantage over #define:
Automatic generation of constant values.
Example
enum days {Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday };
enum days workingday, holiday;
1007v1.1 - CW1 20
Overview of C - Session 1
Types and Declarations Contd.
(d) Structures:
#define MAXSZ 100
struct list_tag {int count,entry [MAXSZ];};
struct list_tag list, *listptr;
Access of individual parts of a structure:
(i) list.count, list.entry[5]
(ii)Use -> instead of dot when de-
referencing a pointer to a structure.
1007v1.1 - CW1 21
Overview of C - Session 1
Types and Declarations Contd.
Bit Fields:
struct person{char name[10],
address[20]; unsigned sex:1,
age:7;} emp[100];
Here the last byte of structure person
will contain:
* 1 bit for sex (0 or 1), and a
* 7-bit unsigned field to store age
<= 27-1
1007v1.1 - CW1 22
Overview of C - Session 1
Types and Declarations Contd.
(e) Unions:
These are variant structures of C.
Similar to structures except that only
one member of union is active at a time.
Different members of a union are
distinguished by a tag field.
It is programmer’s responsibility to
keep track of which member is currently
being used.
1007v1.1 - CW1 23
Overview of C - Session 1
Union: Example
To compute the area, volume and
circumference of geometrical figures
enum shape_tag{CIRCLE,
RECTANGLE, TRIANGLE};
enum triangle_tag {EQUILATERAL,
ISOSCELES, SCALENE};
1007v1.1 - CW1 24
Overview of C - Session 1
Union: Example Contd.
1007v1.1 - CW1 26
Overview of C - Session 1
Advantages of Union
1007v1.1 - CW1 27
Overview of C - Session 1
Naming a Type: typedef
(f) Typedef:
A structure can be given a name.:
typedef struct list_tag List_type;
Now a variable of this structure type can be
declared as:
List_type list; instead of struct list_tag list;
(though both are equivalent)
We could have defined the structure and the
type at the same time as:
typedef struct list_tag
{int count, entry[MAXSZ];}List_type;
The list_tag is optional in above declaration.
1007v1.1 - CW1 28
Overview of C - Session 1
C Operators
Order Associativity
1. Function Call: ( ) L to R
1007v1.1 - CW1 29
Overview of C - Session 1
C Operators Contd.
Order Associativity
2. Logical NOT: ! R to L
Ones Complement: ~
Arithmetic Unary: ++ -- + -
Pointer Reference (Indirection): *
Address of: &
Type cast conversion: (type)
Size of an object: sizeof
3. Arithmetic Binary: * / % L to R
4. Arithmetic Binary: + - L to R
1007v1.1 - CW1 30
Overview of C - Session 1
C Operators Contd.
Order Associativity
5. Bitwise left/right shifts: << >> L to R
6. Relational: < <= > >= L to R
7. Relational: == != L to R
8. Bitwise AND: & L to R
9. Bitwise XOR: ^ L to R
10.Bitwise OR: | L to R
11.Logical AND: && L to R
12.Logical OR: || L to R
1007v1.1 - CW1 31
Overview of C - Session 1
C Operators Contd.
Order Associativity
13. Conditional expression: ?: R to L
Example: x = (a > b) ? a : b;
Same as: if (a > b) x=a; else x=b;
14. Assignment: R to L
= += -= *= /= %= &= ^= |= >>= <<=
15. Comma: , L to R
Example: z = (x=10, y=5, x+y);
Value of z = 15, also used in if, for, while.
1007v1.1 - CW1 32
Overview of C - Session 1
Control Flow Statements
1007v1.1 - CW1 33
Overview of C - Session 1
Control Flow Statements
(b) Switch: Multiway branch on single expression.
Switch (expression) {
case constant_expr : statements
case constant_expr : statements
/* as many cases as needed…*/
default: statements }
It is important to note that the cases fall
through, i.e., execution will continue to the
following case unless explicit action is taken to
leave the switch.
Use break as the last action of a case to leave
the switch.
1007v1.1 - CW1 34
Overview of C - Session 1
Control Flow Statements Contd.
( c) Loops:
(i) while (expression) statements
where statements will be executed as long as
expression evaluates to nonzero.
(ii) for (expr1; expr2; expr3) statements
All three expressions are optional but
semicolons are not. The for is equivalent to:
expr1;
while (expr2) {statements; expr3;}
(iii) do-while loop
Tests for loop termination at the end.
do statements while (expression);
The loop will be executed at least once.
1007v1.1 - CW1 35
Overview of C - Session 1
Control Flow Statements Contd.
(iv) break for early exit from a loop
The break will cause execution to continue
after the enclosing for, while, do or switch.
(v) continue to skip a part of loop body
The continue will result in skipping the
following statements and continuing the next
iteration of the enclosing for, while, or do loop
to execute.
(vi) goto: It is not looked upon with favor. Can be
used for early exit from a loop and also to exit
a switch instead of a break.
1007v1.1 - CW1 36
Overview of C - Session 1
Pointers to Simple Variables
Example : char *p; char c = ‘a’;
p is a pointer to a character variable.
p = NULL; /* p is a null pointer*/
Address of a simple variable can be
obtained by the unary operator &:
p = &c; /* p contains address of c */
Following declaration does the same:
Char c = ‘a’, *p = &c;
1007v1.1 - CW1 37
Overview of C - Session 1
Pointers to Simple Variables Contd.
1007v1.1 - CW1 38
Overview of C - Session 1
Pointers to Arrays
Declare a 1-dimensional array of
integers and its pointer:
int a[10], *q = a;
1007v1.1 - CW1 39
Overview of C - Session 1
Pointers to Arrays Contd.
Declare a 2-d array of integers and its pointer:
int b[ ][4] ={{75, 27, 11, 35}, {22,19, 30, 8}, {40,
5, 90, 13}}, *p = b;
75 27 11 35
The matrix b: 22 19 30 08
40 05 90 13
p: Pointer to 1st row, p+i : Pointer to ith row,
*(p+i) : Pointer to 1st element in ith row,
*(p+i)+j : Pointer to jth element in ith row,
*(*(p+i)+j) : element a[i][j] same as *(*(b+i)+j)
1007v1.1 - CW1 40
Overview of C - Session 1
Pointers to Arrays Contd.
#include “stdio.h”
int a[][3]={30,40,50,33,44,55,21,31,41};
void main (void)
{int j,k, (*ptr)[3]=a;
1007v1.1 - CW1 41
Overview of C - Session 1
Pointers to Arrays Contd.
Program Output
ptr=106
address value
106 33
108 44
110 55
ptr=112
address value
112 21
114 31
116 41
1007v1.1 - CW1 43
Overview of C - Session 1
Pointers to Arrays Contd.
Operations on Pointers
Note that if we increment i by 1, p is
incremented by 4, the size of each row.
Integer expression can be added to or
subtracted from a pointer.
Two pointers can be compared if they point
to the same array. Otherwise the comparison
is not meaningful.
When handling arrays, use pointer access
method instead of indexing which is much
slower.
1007v1.1 - CW1 44
Overview of C - Session 1
Pointers to structures
1007v1.1 - CW1 45
Overview of C - Session 1
Pointers to Character Arrays Contd.
One Dimensional Character Arrays
char line[100], *p;
Let p point to start of array: p=&line[0];
Array name is synonym for its starting address:
p = line; /* same as above */
Perform the assignments: *p = ‘a’; and
*(p+1) = ‘b’; /*p points to start of line */
Do the same by pointer incrementing:
*p++ = ‘a’; *p++ = ‘b’;
Now p points to line[2]. This is equivalent to:
line[0] = ‘a’; line[1] = ‘b’;
Difference between *p[3] and (*p)[3]:
Array of 3 pointers - Pointer to an array with each
row containing 3 elements.
1007v1.1 - CW1 46
Overview of C - Session 1
Pointers to Character Arrays
Contd.
Two Dimensional Character Arrays
Declare a 2-d array to store 3 names:
char name1[3][12];
Three rows, each stores a name 12 char long (including
null char). Total storage requirements = 36 bytes.
Ragged Arrays:
Rarely individual strings will be of equal length.
Instead of making each row of fixed number of chars,
make it a pointer to a string of varying length (total
bytes used now = 28).
char *name2[3] = {“New Zealand”,“Australia”,“India”};
Here name2 is an array of 3 pointers, each pointing to
a particular string.
Accessing jth character in ith string: *(name 2[i] + j)
1007v1.1 - CW1 47
Overview of C - Session 1
Creation of Dynamic Variables
Declare the pointer variable p as:
node_type p;
malloc( ) allocates a block of memory of size
of node_type node:
p = (node_type * ) malloc ( sizeof
(node_type));
p = pointer returned for the storage area of
type node_type.
sizeof(node_type) returns the number of bytes
occupied by a variable of type node_type.
free(p) ; returns the space used by the
dynamic variable.
1007v1.1 - CW1 48
Overview of C - Session 1
Functions
A task is broken into separate functions
in modular programming because it is
easier to deal .
The main program called main is a
function which may invoke other
functions.
The information passed to a function is
called an argument.
The information received by the
function is called a parameter.
1007v1.1 - CW1 49
Overview of C - Session 1
Functions Contd.
1007v1.1 - CW1 50
Overview of C - Session 1
Arguments to Functions
Call by Value:
void f(int k)
{ k - -;
printf(“k is %d\n”, k);
}
Call by reference
void g(int *k)
{ *k = 4;
}
1007v1.1 - CW1 51
Overview of C - Session 1
Arguments to Functions
Contd.
The Caller Functions
void caller1(void)
{ int i = 10;
printf(“i = %d\n”, i);
f(i);
printf(“i = %d\n”, i);
}
void caller2(void)
{ int i = 10;
printf(“i = %d\n”, i);
g(&i);
printf(“i = %d\n”, i);
}
1007v1.1 - CW1 52
Overview of C - Session 1
Arguments to Functions
Contd.
NOTE:
Arrays are always passed by reference.
1007v1.1 - CW1 53
Overview of C - Session 1
Function Prototypes and Include Files
function prototype is a declaration of a function type
(what it returns) and the number and type of
arguments: void f(int);
is the function prototype for function f. It expects one
argument of type int and it does not return any value.
Standard Library Functions:
They have their prototypes in *.h files where * denotes
a name available with a compiler. Function strcpy and
so many string processing functions have their
prototypes in the file string.h. So we include this file in
the program as:
#include <string.h> /*Angular brackets*/
Other *.h files that we create are in current directory
and their names are enclosed in double quotes.
1007v1.1 - CW1 54
Overview of C - Session 1
Program Variables
Variables in C differ in behavior from those in most
other languages. It all depends on the storage class a
variable may assume.
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
We will discuss scope and longevity of these 4 storage
classes of variables.
Scope determines over what part(s) of the program a
variable is actually available for use (active).
Longevity refers to the period during which a
variable retains a value.
1007v1.1 - CW1 55
Overview of C - Session 1
Program Variables Contd.
Depending on their place of declaration,
variables may also be classified as:
Internal or Local :
Declared within a particular function.
External or Global:
Declared outside of any function.
1007v1.1 - CW1 56
Overview of C - Session 1
Automatic Variables
It is the class of a variable by default.
They are declared within a function, and
known as internal or local variables.
They are created when the function is called
and destroyed automatically when the
function is exited. Therefore their scope and
lifetime is the body of the function.
They can also be defined within a set of braces
known as “blocks” and are meaningful only
there.
Locals can have same names, but they are
distinct variables in their region.
1007v1.1 - CW1 57
Overview of C - Session 1
Automatic Variables Contd.
main()
{ int n=80;
If (n <= 100)
{int n=5, sum;
printf(“ n=%d, “, n)
}; /* sum is valid only within braces*/
function2();
printf(“ %d\n“, n);
}
function1()
{int n=10;
printf(“ %d, “, n);
}
function2()
{int n= 100;
function1();
printf(“ %d, “, n);
} /* Output: n=5 10 100 80 */
1007v1.1 - CW1 58
Overview of C - Session 1
External Variables
They are global variables that are both alive
and active through out the
entire program.
They are declared in the beginning of a
source program outside any function and
initialized to zero by default.
Multiple source files of a program can share
a variable if it is declared as extern in all
those files and defined in exactly one
(usually the main) file.
1007v1.1 - CW1 59
Overview of C - Session 1
External Variables Contd.
Example
register int count;
1007v1.1 - CW1 64
Overview of C - Session 1
Auto/Static/External Variables
Example of a multi-file C program
file1.c file2.c
void func1() extern int m;
void func2() static int count = m;
void func3() func2()
int m; /* global */ { int k;
main() k = m; count ++;
{int k = m; printf{“k=%d“, k);}
m = m + 1; func3()
func1();func2(); { count ++;
func3(); func1(); printf(“count=
printf(“m=%d %d”, count);}
k=%d\n”, m, k);}
1007v1.1 - CW1 65
Overview of C - Session 1
Auto/Static/External Variables
Example of a multi-file C program
file1.c
func1()
{static int j = 1;
m = m + 1;
printf(“j=%d “, ++j);
}
RESULTS:
j=2 k=2 count=2 j=3 m=3 k=0
1007v1.1 - CW1 66
Overview of C - Session 1
Pointer to Function as Argument
A function has an address location in memory just like
a variable. A pointer to a function is declared as:
type (*funptr)();
type is the type of value returned by the function,
funptr is the pointer to the function.
Example:
#include <math.h>
#define pi = 3.14159
main() /* main */
{double y(double);
double table(double(*)(), double, double, double)
printf(“Table of Y(x) = 2x2-x+1\n”);
table(y, 0.0, 1.0, 0.5);
printf(“Table of cos(x)\n”);
table(cos, 0.0, 1.0, 0.5); } /* end of main*/
1007v1.1 - CW1 67
Overview of C - Session 1
Pointer to Function as Argument Contd.
double y(double x)
{return(2*x*x-x+1);}
double table(double (*f)(), initval, lastval, step)
{double a, value;
for(a=initval; a<=lastval; a+=step)
value = (*f)(a); /* y/cos replaces *f */
printf(“%5.1f%10.4F\n”, a, value);
}
1007v1.1 - CW1 68
Overview of C - Session 1
Pointer to Function as ArgumentContd.
RESULTS
Table of cos(x)
0.01.0000
0.50.8776
1.00.5403
1007v1.1 - CW1 69
Overview of C - Session 1
Pointer to Pointer as Argument
Contd.
We invoke a function f that modifies
whatever the pointer p points at:
void f(char *);
void main(void)
{char c=‘b’; f(&c);}
void f(char *p) {*p = ‘a’;}
What if we want to modify the pointer
itself, instead of what it points to?
1007v1.1 - CW1 70
Overview of C - Session 1
Pointer to Pointer as Argument
Contd.
Then pass pointer by reference.
void g(char **);
void main(void) /*main */
{char line[10]={‘a’,’b’,’c’,’d’,’e’,’f’,
‘g’,’h’,’I’,’j’}, *p = line;
for(int j=0; j<10; g(&p))
printf(“%s”, *p);} /end of main*/
void g(char **ptr) {(*ptr)++;}
Result: abcdefghij
1007v1.1 - CW1 71
Overview of C - Session 1
Functions that return a Pointer
If each node of a linked list is defined as:
typedef struct node_tag
{float info;struct node_tag *next;} node_type;
We can write a function makenode which creates such
a node and returns a pointer to the new node:
node_type *makenode(float item)
{node_type *p;
if ((p = (node_type *) malloc
(sizeof(node_type))) != NULL)
p -> info = item;
return p;}
1007v1.1 - CW1 72
Overview of C - Session 1
File Management in C
Why File Management is important?
Until now we have used I/o functions like
scanf and printf to read/write data
from/to keyboard/screen.
This works fine for small data.
It is cumbersome and time consuming to
handle large volumes of data the same
way.
Further one cannot afford to lose
volumes of data on program termination
or when computer is turned off.
1007v1.1 - CW1 73
Overview of C - Session 1
File Management in C Contd.
Therefore more flexible approach is
needed by storing data on hard disk to
overcome the said problems.
There are two distinct ways to do I/O in
C:
* Low-level I/O using UNIX system
calls
* High-level I/O using functions of
standard I/O library of C
We shall discuss the later scheme and
use the following functions:
1007v1.1 - CW1 74
Overview of C - Session 1
File Management Functions
1007v1.1 - CW1 80
Overview of C - Session 1
Example: File Management Contd.
1007v1.1 - CW1 84
Overview of C - Session 1
Command Line Arguments(CLA)
Contd.
while !feof(stdin)
{fscanf(stdin, “%s %d %f”, item.name,
&item.number, &item.price);
fprintf(stdout, “%s %d %.2f”, item.name,
item.number, item.value);
fprintf(fp, “%s %d %.2f”, item.name,
item.number, item.value);}
fclose(fp);
} /* end main */
1007v1.1 - CW1 85
Overview of C - Session 1
The C Preprocessor
It is a program that processes the source code
before it passes through the compiler
It provides tools normally unavailable in other
high-level languages.
The tools can be used by programmers to
make the program easy to read and modify,
portable and more efficient.
The preprocessor operates under the control
of certain directives which are placed before
the function main. All directives begin with the
symbol # in column 1 and do not require
semicolon at the end.
1007v1.1 - CW1 86
Overview of C - Session 1
The C Preprocessor
Contd.
1007v1.1 - CW1 87
Overview of C - Session 1
Macro Substitution
1007v1.1 - CW1 88
Overview of C - Session 1
Simple Macro Substitution
1007v1.1 - CW1 89
Overview of C - Session 1
Macro Substitution with Arguments
1007v1.1 - CW1 90
Overview of C - Session 1
Macro Substitution with Arguments
Contd.
1007v1.1 - CW1 91
Overview of C - Session 1
Nested Macro Substitution
One predefined macro can be used in the
definition of another macro:
#define QUAD(X) SQUARE(X)*SQUARE(X))
Now expand QUAD(1+2):
(SQUARE(1+2)*SQUARE(1+2))
= (((1+2)*(1+2))*((1+2)*(1+2))).
Undefining a Macro
#undef SQUARE
This is useful if we want to restrict the
definition to a particular part of the program.
1007v1.1 - CW1 92
Overview of C - Session 1
File Inclusion
1007v1.1 - CW1 93
Overview of C - Session 1
Compiler Control Directives
Following 3 situations may be faced while
developing a large program:
(Discussion is limited to only a few more
common macros)
1007v1.1 - CW1 94
Overview of C - Session 1
Compiler Control Directives
Contd.
Example
#ifndef TEST or #ifdef TEST
#define TEST 1 #undef TEST
#endif #endif
* define is erroneous if TEST is already
defined.
* Undef is erroneous if TEST is not defined.
1007v1.1 - CW1 95
Overview of C - Session 1
Compiler Control Directives
Contd.
1007v1.1 - CW1 96
Overview of C - Session 1
Compiler Control Directives
Contd.
Example:
main ()
{…
#ifdef IBM_PC
{ … } /* code for IBM_PC */
#else
{ … } /* code for HP machine */
#endif
…}
1007v1.1 - CW1 97
Overview of C - Session 1
Compiler Control Directives Contd.
1007v1.1 - CW1 98
Overview of C - Session 1
Compiler Control Directives Contd.
Example
...
#ifdef DEBUG
printf … /* The main concern
#endif here is conditional
… compilation. */
…
#ifdef DEBUG
printf …
#endif
1007v1.1 - CW1 99
Overview of C - Session 1
Summary
In this session you have revised:
Overview of a C Program
C Elements & Operators
Control Flow Statements
Pointers to Simple Variables, Arrays, Structures,
Char arrays;Creation of Dynamic variables.
C Functions
Call by Value and Reference,
Program variables: Scope and Longevity,
Pointers to Pointers and functions as arguments.
File Management in C
Command line arguments.
C Preprocessor
1007v1.1 - CW1 100
Overview of C - Session 1