C Explore
C Explore
‘C’ FUNDAMENTALS:-
RC : RunC :- INTERPRETER
MC : MicrosoftC:-compiler
TC : Turbo C :- compiler
HISTORY OF ‘C’:-
1. Declaration ( if any)
2. Accepting datas.
3. Manipulating datas/ making decessions.
4. Printing the output.
GENERAL STRUCTURE OF A C PROGRAM:-
Main ( )
Program statements;
Function calls;
Declaration arguments;
Note:- The main ( ) is considered as a building block of the program. It is a system defined
function . The only component that is required in every C program is the main() function. In its
simplest form, the main() function consists of the name main followed by a pair of empty
parentheses (()) and a pair of braces ({}). Within the braces are statements that make up the
main body of the program. Under normal circumstances, program execution starts at the first
statement in main() and terminates at the last statement in main().
! * + \ “ <
# ( = | { >
% ) [ ; } /
^ - ] ‘ ?
& _ : , (blank)
X 4th
Y12 “x”
Sum_ order-no
TABLE
There are certain reserve words , called keywords that have standard
predefined meaning mc. These keywords can be used only for their
intended
const if typedef
do register void
else short
while enum
signed
DATA TYPES:-
Required
floating-point 3.4E381
floating-point 1.8E3082
Constants
Constants are data items whose values are not changed during proram
execution time.
Constants:-
Constant
Numeric constants:-
Numeric constants consists of numeric digits, they may or may not have
decimal point(.). These are the rules for defining numeric constants:-
Integer constants:-
123 3#5
3705 98 5
Real constants:-
Floating point constants are numeric constants that contain decimal point.
Some valid floating point constants are:-
0.5,5.3,4000.0,0.0073,39.0807,5597.
Character constants:-
‘9’ ‘four’
‘D’ “d”
‘ ‘ ‘’
‘#’ y
; ASCII value(59)
String constants:-
A string constant has zero , one or more than one character. A string
constant is enclosed within double quotes(“ “) . At the end of string , \0 is
automatically places b the compiler.
8
Symbolic constant:-
These constants are generally defined at the begini9ng of the program as:-
Note:- Here ‘name’:- is the symbolic name for the constant , and is
generally written in uppercase letters
# define PI 3.14159625
# define Ch ‘Y’
Variables:-
Declaration of variable:-
Note:-The type and range of values that a variable can store depends upon
its datatype.
Datatype variablename;
Initialization of variable:-
For example:-
int a=5;
float x=8.9,y=10.5;
char ch=’y’;
double num=0.15197e-7;
Expressions:-
10
Statements:-
Expression statement:-
For example:-
X=5;
X=y-z;
Func(a,b);
11
Compound statement:-
Int l=4,b=2,h=3;
Note:-The variables that are declared inside a block can be used only inside
that block.
Comments:-
Simple program */
Input –Output in C
12
There are three main functions of any program – it takes data as input
,process this data and gives the output . The input operation involves
movement of data from an input device(generally keyboard) to computer
memory, while in output operation the data moves from computer memory
to the output device(generally screen).
Input –output is performed through a library function that are supplied with
every C-compiler. These functions considered standard for all input-output
operations in C.The set of library functions that performs input-output
operation is known as standard I/O library. The most commonly used input-
output function in C is printf( ) and scanf( ).
For example:- If a program uses any function from the standard I/O library,
then it should include the header files stdio.h which contains the definition of
the printf( ) and scanf( ) function that should be declared as:-
#include<stdio.h>
Similarly there are several other header files like math.h ,string.h
alloc.h etc.
Conversion specification:-
%c A single character
%d A decimal integer
%f A floating point number
%ld Long range of decimal
13
Note:- A string variable is not preceded by & sign to get the address.
For example:-
#include<stdio.h>
14
main()
{
int basic;
float hra;
char grade;
-------------
scanf(“ %d %f
%c”,&basic,&hra,&grade); --------
------- }
Here the control string has three conversion specifications characters %d,%f
and %c , means that one integer value , one floating point value and one
single character can be entered as input . These values are stored in the
variables basic, hra and grade. The input data can be entered as:-
1500 200.50 A
main( )
{
printf(“ C is excellent \n “);
Output:-
C is excellent
Example 2:-#include<stdio.h>
main( )
{
int roll_no;
char grade;
float perc;
scanf(“%d%c%f”,&roll_no,&grade,&perc);
Formatted input and output means that data is entered and displayed
in a particular format. Through format specifications, better presentation of
result can be obtained.
NOTE:-If the length of input is more than this maximum field width then
the values are not stored correctly.
For example:-
Scanf(“%2d%3d”,&a,&b);
(i) When input data length is less than the given field width
, then the input values are unaltered and stored in given
variable.
Input:- 6 39
Input:- 26 394
(iii) When input data length is more than the given field
width , then the input values are altered and stored in
the variable.
For example:-
Printf(“a=%3d,b=%4d”,a,b);
(i) When the length of the variable is less than the width specifies.
17
Value of variable:- 78 9
Output:-
a = 7 8 , b = 9
The width specifies of first data is 3 while there are only 2 digit in it , so
there is one leading blank. The width specifies
(ii) When the length of the variable is equal to the width specifies.
Result a = 2 6 3 , b = 1 9 4 1
:-
(iii) When length of variable is more than the width specifies , then
also the output is printed correctly.
Result :- a = 2 6 9 1 , B = 1 9 4 1 2
%wf:- Here ‘w’ is the integer number specifying the total width
of the input data(including the digits before and after decimal and the
decimal itself).
For example:-
(i) When input data length is less than the given width ,
values are unaltered and stored in the variable.
Input:- 5 5.9
18
(iii) When input data length is greater than the given width ,
values are altered and stored in the given variable.
For example:-
Note:- If the total length of the variable is less than the specified width ‘w’ ,
then the value is right justified with leading blanks . If the number of digits
after decimal is more than ‘n’ then the digits are rounded off.
Output:-
x = 8 . 0 , y = 5 . 9 0
Output:-
x = 2 5 . 3 , y = 1 6 3 5 . 9 2
Output:-
x = 1 5 . 2 , y = 6 5 . 8 8
char str[8];
scanf(“%3s”,str);
Only first three characters of this input will be stored in the string . so the
characters in the string will be :- ‘s’ , ‘r’ ,’i’, ‘\0’
%w.ns :-Here w is the specified field width. Decimal point and ‘n’
are optional. If present then ‘n’ specified that only first n characters
of the string will be displayed and (w-n) leading blanks are displayed
before string.
(i) printf(“%3s”,”sureskumar”);
result:-
S u r e s k u m a R
(ii) printf(“%10s”,”reeta”);
result:-
r e e t a
20
(iii) printf(“%.3s”,”sureshkumar”);
result:-
S u r
(iv) printf(“%8.3s”,”sureshkumar”);
result:-
s u R
Character I/O:-
#include<stdio.h>
Main( )
char ch;
ch=getchar( );
putchar(ch);
}
21
For example:- +x -y
For example:-
Conditional Operator:-
Synatax:-
a>b ? a : b ;
Here first the expression a>b is evaluated , if the value is true then
the value of variable a becomes the value of conditional expressional
otherwise the value of b becomes the value of overall conditional expression.
Max=a>b ? a : b;
since the expression a<b is true , so the first printf function is executed .
which are:-
1. Arithmatic operator
2. Assignment operator
4. Relational operator
5. Logical operator
6. Comma operator
23
7. Sizeof operator
8. Bitwise operator
Arithmatic operator:-
Operator purpose
+ Addition
- Substaction
* Multiplication
/ Division
% Gives the reminder in integer division
For example:-
Expression Result
a+b 21
a-b 13
a*b 68
a/b 4
a%b 1
Assignment operators:-
X=8 // 8 is assigned to X
When the variable on the left hand side of assignment operator also occurs
on right hand side then we can avoid writing the variable twice by using
compound statement operator.
Note:- These operators should be used only with variables, they can’t be
used with constants or expressions .
x=x+1
y=x
x=x+1
y=x
y=x
26
x=x+1
y=x
Relatioanl operator:-
Operator Meaning
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
Let us take two variables a=9 and b=5 , and form simple relational
expressions with them
Logical operator:-
Operator Meaning
&& AND
|| OR
! NOT
Note:- Here logical NOT is a unary operator while the other two are binary
operators.
AND(&& ) Operator:-
This operator gives the net result true if both the conditions are true ,
otherwise the result is false.
Boolean Table
Here both the conditions a==10 and b<a are true , and hence this whole
expression is true .Since the logical operators return 1 for true hence the the
value of this expression is 1.
OR( || ) operator:-
This operator gives the net result false, if both the conditions have the
value false , otherwise the result is true .
Boolean Table
(a>=b) || (b>15)
Not ( ! ) operator:-
Condition Result
False True
True False
! (a = = 10)
The value of the condition (a==10) is true . NOT operator negates the value
of the condition . hence the result is false.
Bitwise Operator:-
Bitwise AND(&):-
Boolean Table
Let us take a=0x293B and b=0x1A2F are two integer variables. The binary
representation of these variables and the result after performing bitwise
AND operation :-
Bitwiswe OR:-
31
Boolean Table
Bitwise XOR(^):-
Boolean Table
Boolean Table
This operator is used for shifting the bits left. It requires two
operands. The left operand whose bits are shifted and the right operand
indicates the number of bits to be shifted and the right operand indicates
the number of bits to be shifted . On shifting the bits left, an equal number of
bit positions on the right are vacated . These positions are filled in with 0 bits
. Let us take an integer variable a =0x1346 .
On shifting all bits to the left by 4 , the leftmost 4 bits are lost
while the rightmost 4 bit positions become empty which are filled with 0
bits.
This operator is used for shifting the bits right. It requires two
operands. The right operand whose bits are shifted and the left operand
indicates the number of bits to be shifted and the left operand indicates the
number of bits to be shifted. On shifting the bits right, an equal number of
bit positions on the left are vacated . These positions are filled in with 0 bits .
Let us take an integer variable a =0x1346 .
CONTROL STATEMENTS
if statement
if –else statement
else if statement
switch statement
34
2. Looping statement----------------
for statement
while statement
do----while statement
3. jumping statement----------------
break statement
continue statement
goto statement
The if Statement:-
If ( condition ) conditi
{ on
……………………….. true
Statement-block
35
Statement-block
………………………..
}
false
#include<stdio.h>
Main( )
int num;
scanf(“%d”,&num);
if( num<0 )
If (condition)
conditi
{ on
................
Statement-block- Statement-block-
Statement-block-12 1
36
. ...............
else
. .................
Statement-block-2
. ................. }
#include<stdio.h>
main( )
Int a,b;
Scanf(“%d %d”,&a,&b);
if( a>b )
else
if (condition 1)
statement A; True
37
False
Conditio
n1
else if (condition 2)
statement B;
Stat A
True False
else if(condition 3) Conditio
n2
statement C;
Fals
else Stat B True e
Conditio
statement D; n3
Stat C Stat D
Next statement
/* program to find out the grade of a student when the marks of 4 subjects
are given .The method of assigning garde is as:-
per>=85 grade=A
per<40 grade=E
#include<stdio.h>
main ( )
{
38
float m1,m2,m3,m4,total,per;
char grade;
scanf(“%d%d%d%d”,&m1,&m2,&m3,&m4);
total=m1+m2+m3+m4;
per=total/4;
if( per>=85 )
grade=’A’;
grade=’B’;
grade=’C’;
grade=’D’;
else
grade=’E’;
Nested if statement:-
if( condition1 )
{ true false
Conditio
n1
if( condition2 )
statement 1; Statement 3
true false
Conditio
n2
Statement 1 Statement 2
39
else
statement 2;
else
statement 3;
#include<stdio.h>
main ( )
int a,b,c;
scanf(“%d%d%d”,&a,&b,&c);
if ( a > b )
if ( a > c )
else
printf(“3rd no is greater”);
else if ( b > c )
else
printf(“3rd no is greater”);
40
Switch statement:-
switch ( expression )
break;
break;
break;
break;
default : statement-block-default
does not match any of the case values , control goes to the default keyword,
which is usually at end of the statement.
Note :- The floating point or string constant can’t used as a case value.
Now we’ll see some valid and invalid ways of writing switch
expressions and case constants.
Valid invalid
switch(a) switch(f)
switch(a>b) switch(a+4.5)
switch(func(a,b)) case a:
Now let us see how the switch statement works. Firstly the switch
expression is evaluated , then the value of this expression is compared one
by one with every case constant , then all statements under that particular
case are executed . If none of the case constant matches with the value of
the expression then the block of statements under default is executed .
‘default’ is optional . If it is not present and no case matches then no action
takes place. These cases and default can in any order.
Looping statement :-
loop we can execute a part of the program repeatedly till some condition is
true. Ther are three loop statement in C:-
(i) while
(ii) do while
(iii) for
While loop:-
While(condition)
False
{ While(conditi
on)
Statement ;
True
Statement ;
--------------
Body of loop
}
Next statement
out of loop
First the condition is evaluated, if it is true then the statements in the body
of lop are executed . After the execution , again the condition is checked
and if it is found to be true then again the statements in the body of loop
are executed . This means that these statements are executed continuously
till the condition is true and when it becomes false, the loop terminates and
the control comes out of the loop. Each execution of the loop body is
known as iterartion
43
#include<stdio.h>
main( )
int n,r,sum=0;
scanf(“%d”,&n);
while(n>0)
r=n%10;
sum+=r;
n=n/10;
Printf(“sum of digits=%d”,sum);
Do while loop:-
The do-while statement, like while statement , is also suited for problems
where it is not known in advance that how many times a statement will be
executed .
do
Statement ;
Statement ;
---------------
} while(condition);
44
Here firstly the statements inside loop body are executed and then the
condition is evaluated . If the condition is true , then again the loop body is
executed and this process continues until the condition become false .
#include<stdio.h>
main( )
int n,count=0,rem;
scanf(“%d”,&n);
do
n/=10;
count++;
}while(n>0);
For loop:-
statement ;
statement ;
---------
main( )
int a,b,i;
int result=0;
scanf(“ %d%d”,&a,&b);
for ( i=1;i<=b;i++)
result=result+a;
printf(“%d %d = %d\n”,a,b,result);
Nesting of loop:-
other type of loop. For example a for loop may be nested inside another for
loop or a while loop. Similarly while and do---while loops can be nested.
main( )
int I,j;
printf(“j=%d\t”,j);
printf(“\n”);
Output:
i=1
i=2
i=3
Infinite loop:- The loops that go on executing infinitely and never terminate
are called infinite loops. Sometimes we write these loops by mistake while
sometimes we deliberately make use of these loops in out programs .
(A) for(i=0;i<=5;i--)
printf(“%d”,i);
47
do
Printf(“%d”,k);
Sum=sum+k;
}while(k<5);
break statement:-
break;
For example:-
main( )
int n;
for( n=1;n<=5;n++)
if(n==3)
Break;
}
48
Printf(“number = %d \n”,n);
Output:
Number=1
Number=2
Continue statement:-
continue;
#include<stdio.h>
main( )
int n;
for(n=1;n<=5;n++)
if(n==3)
continue;
Output:-
Number=1
Number=2
Number=4
Number =5
Array:
50
Characteristics of array:
6. The array index starts from 0 to n-1 for the array of size n.
LINEAR ARRAYS
A linear array a is a list of a finite number n of homogeneous data elements such
that
int a[4];
3 3 4 43
2
Examples:
int a[5];
for(i=0;i<5;i++)
printf(“enter a number:”);
scanf(“%d”,&a[i]);
for(i=0;i<5;i++)
printf(“%d”,a[i]);
void main()
int a[100];
int n,s=0;
float avg;
scanf(“%d”,&n);
for(i=0;i<n;i++)
printf(“enter a number:”);
scanf(“%d”,&a[i]);
52
s=s+a[i];
avg=(float)s/n;
printf(“sum= %d avg=%f”,s,avg);
Void main()
int n,k;
Int a[100];
scanf(“%d”,&n);
for(i=0;i<n;I++)
printf(“enter a number:”);
scanf(“%d”,&a[i]);
sacnf(“%d”,&k);
for(i=0;i<n;i++)
If(a[i]==k)
exit(0);
53
The elements of the array are referenced by two index sets consisting of m
and n consecutive integer numbers
The size of the two dimensional array is denoted by m*n and pronounced as m by n.
Systax:
Example:
Int a[3][3];
Float p[3][3];
Row 0 00 01 02
Row 1 10 11 12
Row 2 20 21 22
The elements are stored column by column i.e, m elements of the first column and
stored in first m locations, elements of the 2 nd column are stored in next m columns
and so on.
for (i=0;i<m;i++)
for (j=0;j<n;j++)
printf(“%d”,a[j][i]);
Rowmajor order:
The elements are stored column by row i.e, n elements of the first row and stored
in first n locations, elements of the 2nd row are stored in next n rows and so on.
for (i=0;i<m;i++)
for (j=0;j<n;j++)
printf(“%d”,a[i][j]);
int a[3][3]={{1,4,5},{6,4,33},{45,66,54}};
55
float g[3][2]={{2.3,3.4},{4.5,3.4},{2.3,5,3}};
for (i=0;i<3;i++)
for (j=0;j<3;j++)
Printf(“enter a no:”);
Scanf(“%d”,&a[i][j]);
Example:
void main()
int a[3][3];
int s=0;
float avg;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
printf(“enter a number:”);
scanf(“%d”,&a[i][j]);
s=s+a[i][j];
56
for (i=0;i<m;i++)
for (j=0;j<n;j++)
printf(“%5d”,a[i][j]);
printf(“\n”);
avg= (float)s/n;
printf(“sum= %d avg=%f”,s,avg);
Matrix addition
void main()
int a[3][3],b[3][3];
for (i=0;i<3;i++)
for (j=0;j<3;j++)
printf(“enter a number:”);
scanf(“%d”,&a[i][j]);
for (i=0;i<3;i++)
for (j=0;j<3;j++)
printf(“enter a number:”);
scanf(“%d”,&b[i][j]);
for (i=0;i<3;i++)
for (j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
for (i=0;i<m;i++)
for (j=0;j<n;j++)
printf(“%5d”,c[i][j]);
}printf(“\n”);
FUNCTIONS
The best way to handle complex problems to split the problems, called sub
problems that can be handled easily. This we are used to do in our day-to-day
working. Once all these sub problems are solved separately, solutions of these sub
problems can be synthesized to generate the solution of the given complex
problem.
58
Defining a Function
Local declarations
………………………….
………………………….
Executable body
………………………….
The first statement of the function must be the function defining statement
specifying the return type, name and formal arguments.
If the type of the function is omitted, then it is assumed of type integer (int).
But it is recommended that the return type must be explicitly specified.
Function Prototype
A function prototype is a function declaration that specifies the return type and the
data types of the arguments. The main purpose of the function prototyping is to
prevent errors caused by data type mismatches between the values passed to a
function and the type of values function is expecting.
It is important to note that name of the formal argument is optional. Further, names
of formal argument in a function prototype and in the function defining statement
can be different.
int factorial(int);
Accessing a function
Like library functions, the user-defined functions are accessed from a function
simply by its name, including the actual arguments, if any, enclosed within
parenthesis. However, parenthesis must follow the name even if there is no actual
argument to be passed to the function. The actual arguments, if any, must
correspond in number, type, and order with formal arguments can be constants,
variables or expressions.
When the name of the function is encountered, the control is transferred to the
called function. The formal argument s are replaced by the actual arguments and
the execution of the function is carried out. When the return statement is executed
or last statement has finshed its execution, the control is transferred back to the
calling function.
Note: Note that semicolon must follow the function call if it is a solitary statement
but not the function definition. However, if the function call occurs as part of
another statement then semicolon after the function call may or may not be used.
This will be determined the actual; place of call.
return [exp];
where exp can be a constant, variable or expression. Use of parenthesis around exp
is optional. The return statement serves two purposes:
Note: There is key limitation of return statement is that it can return only one
value. If you want your function to return two or more values to the calling function,
you need another mechanism.
61
The mechanism to pass data to a function is via argument list, where individual
arguments are called actual arguments. These arguments are enclosed in
parenthesis after the function name. The actual arguments must correspond in
number, type, order with formal arguments specified in the function definition. The
actual arguments can be constants, variables, array names or expressions.
Call by value
Call by Value
In this approach, the names of the arguments are used in the function call. In this
way the values of the arguments are passed to the function. When control is
transferred to the calling function, the values of the actual arguments are
substituted to the corresponding formal arguments and the body of the function is
executed. If the called function is supposed to return value, it is returned via return
statement.
Call by Address
In this approach, the addresses of the actual arguments are used in the function
call. In this way the addresses of the actual arguments are passed to the function.
When control is transferred to the called function, the addresses of the actual
arguments are substituted to corresponding formal arguments and the body of the
function is executed. The formal arguments are declared as pointers to types that
match the data types of the actual arguments. This approach is of practical
importance while passing arrays and structures among function, and also passing
back more than one value to the calling functions.
Note: It is important that arguments in a function in C are passed from right to left.
While defining a function, the information to the compiler regarding the return type
of the function and the data types of the arguments must be provided. As described
in the beginning of this chapter that there are two ways to specify the data types of
the formal arguments:
62
1. In the argument list, only the names of the formal arguments are used. The
data types of these arguments are specified before the body of the function
begins. To illustrate this approach, consider an example of defining a
samplefunction() function that takes four arguments. Of these arguments,
first is of type integer, second is of type real, third is of type character, and
fourth one of type integer.
63
float arg2;
char arg3;
2. In the argument list itself, that data type of each argument is specified
individually. Using this approach the definition of the above samplefunction()
function may look like
I hope with this short recap of C language, you will in a position to take off and
enjoy implementing different data structures.
64
CONCEPT OF RECURSION
Recursion Defined
In order that the program should not continue indefinitely, a recursive function
must have that following properties:
1. There must be certain criteria, called base criteria, for which the function
does not call itself.
2. Each time the function does call itself(directly or indirectly), it must be closer
to the base criteria, i.e it uses an argument(s) closer than the one it was
given.
Depth of Recursion
The depth of recursive function P with given set of arguments refer to the maximum
level number of P during its execution.
Example:
65
Factorial Function
The factorial of a positive number n, written as n!, is the product of the positive
integers from 1 to n:
n!= 1.2.3….(n-2).(n-3)
where as
0!=1
0!=1
1!=1
2!=1.2=2
3!=1.2.3=6
4!=1.2.3.4=24
5!=1.2.3.4.5=120
and so on.
Observe that
4!=4.3!=24
5!=5.4!=120
n!=n.(n-1)!
Thus, this definition of n! is recursive, since it refers to itself when it uses (n-1)!.
However.
1. The value of n! is explicitly given when n=0. Thus 0 is that base value for n
and
void main()
scanf(“%d%d”,&a,&b);
printf(“gcd=%d”,gcd(a,b));
Int r;
If(b==0)
Return a;
Else
r=a-(a/b)*b;
return(gcd(b,n));
}
67
POINTER
Pointer is a variable that represents the location of the data item where the data
item may be integer , float, char etc.
6. They increase the execution speed and thus the program execution time
Example:
suppose v is a variable that represents some particular data item. The compiler will
automatically assign memory cells for this data item. The data item can be
accessed if we know the location of the memory cells. The address of v’s memory
location can be determined by the expression &v, where & is a unary operator
called the address operator, that evaluates the address of its operand.
pv=&v;
This new variable is called a pointer to v, since it points to the location where v is
stored in memory. How ever pv represents v’s address not its value. Thus pv is
referred to as a pointer variable.
Address Address
of v of v
pv v
68
the data item represented by v can be accessed by the expression *pv, where * is a
unary operator, that operates only on a pointer variable. Therefore *pv and v both
represents the same data item.
Example:
#include<stdio.h>
main()
int u=3;
int v;
int *pu;
int *pv;
pu=&u;
v=*pu;
pv=&v;
Example:
main()
int u1,u2;
int v=3;
int *pv;
u1=2*(v+5)
69
pv=&v;
u2=2*(*pv+5);
printf(“u1=%d u2=%d”,u1,u2);
Pointers are often passed to a function as arguments. This allows data items with in
the calling portion of the program to be accessed by the function, altered with in
the function and then returned to the calling portion of the program to be accessed
by the function, altered with in the function and then returned to the calling portion
of the program in altered form.
When an argument is passed by value, the data item is copied to the function. Thus
any alteration made to the data item with in the function is not carried over into the
calling routine. When an argument is passed by reference, how ever the address of
a data item is passed to the function. The contents of that address can be accessed
freely, either with in the function or with in the calling routine. More ever, any
change that is made to the data item will be recognized in both the function and
calling routine. Thus the use of a pointer as a function argument permits the
corresponding data item to be altered globally from with in the function.
Void main()
int u=1,v=3;
f1(u,v);
f2(&u,&v);
{
70
Printf(“%d %d”,x,y);
x++;
y++;
printf(“%d %d”,*pa,*pb);
pa++;
pb++;
printf(“%d %d”,*pa,*pb);
Example:
void main()
int a,b;
scanf(“%d%d”,&a,&b);
swap(&a,&b);
{
71
int k;
k=*pa;
*pa=*pb;
*pb=k;
e.g: p=&a;
e.g: p=NULL;
e.g: p++,p--,p+2,p-2
4.two pointer variables can be compared provided both pointer variables have
same data type.
e.g:
if(pa==pb)
e.g: pa-pb
chain of pointers:
P2 p1 variable
Address 2 Address1 value
Here the pointer variable p2 contains the address of the pointer variable p1 , which
points to the location that contains the desired value. This is known as multi
indirections.
72
Eg:
Int **p2;
This indirection tells the compiler that p2 is a pointer to a pointer int type.
We can accesss the target value indirectly pointed to by pointer by applying the
indirection operator twice.
Eg:
main()
Int x,*p1,**p2;
x=100;
p1=&x;
p2=&p1;
printf(“%d”,**p2);
Int x[5]={1,2,3,4,5};
Suppose the base address of x is 1000 and assuming that each integer requires two
bytes, the five elements will be stored as follows:
Value
Base address
If we declare p as an integer pointer, then we can make the pointer p to point to the
array x by the following statement:
P=x;
This is equivalent to
P=&x[0];
Now we can access every value of x using p++ to move from one element to
another. The relationship between p and x is shown as:
p=&x[0](=1000)
p+1=&x[1](=1002)
p+2=&x[2](=1004)
p+3=&x[3](=1005)
p+4=&x[4](=1008)
=1000+(3*2)=1006
void main()
int *p,sum,I;
int x[5]={5,9,6,3,7};
i=0;
p=x;
for(i=0;i<5;i++)
s=s+*p;
74
p++;
printf(“sum=%d”,s);
Columns
0 1 2
Rows 0 p
3 1 p+1
5 2 p+2
*(*(P+2)+2)
Char str[5]=”good”;
The complier automatically inserts the null character ‘\0’ at the end of string. C
supports an alternative method to create strings using pointer variables of type
char.
75
Eg:
Char *str=”GOOD”
This creates a string for the literal and then stores its address in the pointer str.
The pointer str now points to the first charcter of the string “good” as:
G O O D \0
st
We can also use the run time assignment for giving values to a string pointer.
Char *string1;
string1=”good”
string1=”good”
is not a string copy because the variable string1 is a pointer, not a string.
void main()
int l,i;
char nam[50];
char *p;
printf(“enter a string:”);
gets(st);
p=st;
for(i=0;*p!=’\0’;i++)
printf(“%c”,*p);
}
76
printf(“length=%d”,l);
Array of pointers
Char name[3][25];
This says that the name is a table containing three names, each with a maximum
length of 25 characters(including null character). The total storage requirements for
the name table are 75 bytes.
We know that rarely the individual strings will be of equal lengths. There fore,
instead of making each row a fixed number of characters, we can make it a pointer
to a string of varying length.
For example:
Name[1] Australia
Name[2] India
This declaration allocates only 28 bytes, sufficient to hold all the characters as
shown:
N e w Z E a l a n d \0
A u s t r A l i a \0
I n d i a \0
There are four library routines known as “memory management functions” that can
be used for allocating and freeing memory during program execution.
malloc(): allocates request size of bytes and returns a pointer to the first byte of
the allocated
space
malloc(): allocates request size of bytes and returns a pointer to the first byte of
the allocated space
A block of memory may be allocated using the function malloc. The malloc function
reserves a block of memory or specified size and returns a pointer of type void. This
means that we can assign it to any type of pointer. It takes the following :
Ptr is a pointer of type cast type. The malloc returns a pointer to an area of memory
with size byte size.
main()
int *a;
int n,i,j,k;
scanf(“%d”,&n);
for(i=0;i<n;i++)
pritnf(“enter a no:”);
scanf(“%d”,(a+i));
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
If(a[i]>a[j])
k=a[i];
a[i]=a[j];
a[j]=k;
free(a);
for(i=0;i<n;i++)
pritnf(“%d”,*(a+i));
free(a);
Calloc()
79
Calloc is another memory allocation function that is normally used for requesting
memory space at run time for storing derived data types such as arrays and
structures. While malloc allocates a single block of storage space , calloc allocates
multiple blocks of storage, each of the same size, and then sets all bytes to zero.
Sysntax:
Ex:
struct student
int rollno;
char nm[20];
}*s;
free()
This function release memory which are allocated dynamically by malloc and
calloc function.
Syntax:
free(ptr);
Ex:
free(x);
realloc()
This function realloc modifies the size of a dynamic array which are already
allocated by malloc or calloc.
Syn:
ptr=realloc(ptr,new size);
}
80
Storage class:-
(b) What will be the initial value of the variable, if the initial value
is not specifically assigned .(i.e. the default initial value).
(c) What is the scope of the variable ; i.e. in which functions the
value of the variable would be available.
(d) What is the life of the variable ; i.e. how long would the
variable exist.
Storage Memory
main( )
auto int i =2
Printf(“%d”,i);
printf(“%d”,i);
Output :- 3 2 1
defined
register float q;
register double a;
register long c;
main( )
register int I;
printf(“\n %d “,i); }
Storage Memory
function calls
main ( ) main( )
{ {
increment( ); increment( );
increment( ); increment( );
increment( ); increment( );
} }
increment( ) increment( )
{ {
printf(“%d\n”,i); printf(“%d\n”,i);
i=i+1; i=i+1;
} }
1 1
1 2
1 3
Like auto variables , static variables are also local to the block in which they
are declared . The difference between them is that static variables don’t
disappear when the function is nom longer persist. If the control comes back
to the same function again the static variables have the same values they
had last time around.
Storage Memory
scope Global
Come to an end
int i;
main ( )
Printf(“\ni=%d”,i);
increment( );
increment( );
decrement( );
decrement( );
increment( )
i=i+1;
}
85
decrement( )
i=i-1;
i=0
on incrementing i=1
on incrementing i=2
on decrementing i=1
on decrementing i=0
Defining a structure:-
86
struct tagname
Datatype member1;
Datatype member2;
----------------------
-----------------------
Datatype member N;
};
Here struct is a keyword , which tells the compiler that a structure is being
defined ,memebr1,member2………….memberN are known as members of
the structure and are declared inside curly braces, like int , char ,float
,array ,pointers or another structure type.Tagname is the name of the
structure and it is used further in the program to declare variables of this
structure type.
char name[20]
int rollno;
float marks;
} stu1,stu2,stu3;
87
Here stu1,stu2 and stu3 are variables of type struct student . when we
declare a variable while defining the structure template, the tagname is
optional .
struct
char name[20];
int rollno;
float marks;
}stu1,stu2,stu3;
If we declare variables in this way , then we’ll not be able to declare other
variables of this structure type anywhere else in the program nor can we
send these structure variables to functions.
struct student
char name[20]
int rollno;
float marks;
};
struct student
{
88
char name[20]
int rollno;
float marks;
} stu1=(“mary”,25,98);
struct student stu2=(“john”,24,67.5);
Here value of members of stu1 will be “mary” for name, 25 for rollno,98 for
marks . Here value of members of stu2 will be “john” for name, 24 for
rollno,67.5 for marks .
Note:-
struct student
char name[20]
int rollno;
float marks=99; /* invalid */
} stu1;
Structvariable . member
For example:-
struct student
{
89
char name[20]
int rollno;
float marks;
};
#include<stdio.h>
#include<string .h>
struct student
char name[20]
int rollno;
float marks;
};
main( )
strcpy(stu2.name,”john”);
90
stu2.rollno=26;
stu2.marks=98;
Output :-
For example:-
struct student
char name[20]
int rollno;
float marks;
91
};
main( )
Stu2=stu1;
Output:-
#include<stdio.h>
main( )
{
92
struct student
char name[20]
int rollno;
float marks;
};
Output:-
Array of structure:-
#include<stdio.h>
Struct student
char name[20];
int rollno;
float marks;
};
main( )
int i;
for(i=0;i<10;i++)
Scanf(“%s%d
%f”,stuarr[i].name,&stuarr[i].rollno,&stuarr[i].marks);
for(i=0;i<10;i++)
printf(“%s %d %f \n”,
stuarr[i].anme,stuarr[i[.rollno,stuarr[i].marks);
}
94
Note:- In some compiler tha above program may not work correctly and will
give the message “ floating point formats not linked “ at run time . this
problem occurs because the floating point formats (for scanf( ) and other
related functions ) are not always linked , to reduce the size of executable
file. The solution to this problem will be given in the manual of your
compiler.For example,Borland C suggests the inclusion of these two lines to
solve this problem.
#program extrf_floatconvert
void link ( )
{ float x,*ptr=&x; }
#include<stdio.h>
Struct student
Char name[20];
int rollno;
int submarks[4];
};
main( )
int i,j;
for(i=0;i<3;i++)
scanf(“%d” , &stuarr[i].rollno);
for( j=0;j<4;j++)
scanf(“%d”,&stuarr[i].submarks[j]);
for(i=0;i<3;i++)
for(j=0;j<4;j++)
printf(“%d “, stuarr[i].submarks[j]);
printf(“\n”);
Syntax:-
Struct tag1
{
Member1;
Member2;
Struct tag2
Member1;
Member2;
…………..
Member m;
} var1;
………………….
Member n;
}var2;
97
For example:-
struct student
char name[20];
int rollno;
struct date
int day;
int month;
int year;
} birthdate;
float marks;
}stu1,sty2;
Here we have defined a structure date inside the structure student . This
structure date has three members day, month ,year and birthdate is a
variable of type struct date . we can access the members of inner struc
ture as:-
Pointers to structures:-
#include<stdio.h>
Struct student
char name[20]
int rollno;
int marks
};
main( )
Printf(“Name : %s \t”,ptr->name);
Printf(“Rollno : %d \t “,ptr->rollno);
Printf(“marks : %d \t “,ptr->marks);
Here ptr is a pointer variable that can point to a variable of type struct
student. We will use the & operator to access the starting address of a
structure variable, so ptr can point to stu by writing:- ptr=&stu
There are two ways of accessing the members of structure through the
structure pointer:-
2. Ptr->name
For example:-
99
int *p=&stu.rollno;
float *ptr=&stu.marks;
Struct student
char name[20];
int *ptrmem;
};
Stu.ptrmem or stuptr->ptrmem
Since the priority of dot and arrow operators is more than that of
dereference operator , hence the expression *stu.ptrmem is equivalent to
*(stu.ptrmem) and the expression *stuptr->ptrmem is equivalent to *(stuptr-
>ptrmem)
#include<stdio.h>
#include<string.h>
Struct student
100
char name[20]
int rollno;
int marks
};
display(struct student);
main( )
Strcpy(stu2.name, “mary”);
Stu2,rollno=18;
Stu2.marks=90;
display(stu1.name,stu1.rollno,stu1.marks);
display(stu2.name, stu2.rollno,stu2.marks);
Printf(“Name : %s \t”,name);
Printf(“marks : %d \n”,marks);
UNION
Union is a data structure where all the union members will refer to the single
location which are allocated by union whose member size is larger.
101
Union tag
Member1;
Member2;
…..
Member n;
}v;
Eg:
{ {
int a; int a;
float a; float b;
char c; char c;
}k; }k; b
b
c
a b c a b c
2 4 1
Eg:
struct student
102
int rollno;
char nm[20];
float m1,m2,m3;
union result
char gd;
char div[3];
}res;
}s;
DATA FILES
Many applications require that information be written to or read from an auxiliary
storage devices. Such information is stored on the device in the form of a data file.
Thus data file allow us to store information permanently and to access and alter
that information when ever necessary.
There are two different types of data files. Stream oriented data files and system
oriented data files.
Stream oriented data files are generally easier to work with than system oriented
data files and are there fore more commonly used.
Stream oriented data files can be divided into two categories . In the first category
are data files comprising consecutive characters. These characters can be
interpreted as individual data items or as components of strings or numbers. The
manner in which these characters are interpreted is determined either by the
particular library function used to transfer the information or by format specification
with in the library function.
The second category of stream oriented data files , often referred to as unformatted
data files, organizes data into blocks containing contiguous bytes of information.
These blocks represent more complex data structures such as arrays, structure. A
103
separate set of library functions is available for processing stream oriented data
files of this type. These library function provide single instructions that can transfer
entire arrays or structure to or from data files.
FILE *ptr;
Where FILE is a special structure type that establishes the buffer area, and ptr is a
pointer variable that indicates the beginning of the buffer area. The structure FILE
is defined with in stdio.h header file.
The library function fopen is used to open a file. This function is typically written as
Ptr=fopen(filename,file type);
Where file name and file type are strings that represents the name of the data file
and the manner in which the data file will be utilized respectively.
Eg:
FILE *fp;
fp=fopen(“x.txt”,”w”);
104
CLOSING A FILE
Syntax: fclose(fp);
Syntax: fputc(ch,fp);
Where ch is a character and fp is the file pointer. This function stores a single char
ch into file.
Ex:
#include<process.h>
FILE *fp;
fp=fopen(“text.txt”,”w”);
while(ch=getchar()!=’\n’)
Ch=toupper(ch);
fpuc(ch,fp);
fclose(fp);
fp=fopen(“text1.text”,”r”);
if(!fp)
exit(0);
105
While((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
Void main()
char ch;
FILE *fp,*fp1;
fp=fopen(“x.txt”,”w”);
fp1=fopen(“y.txt”,”w”);
if(!fp)
exit(0);
While((ch=fgetc(fp))!=EOF)
fputc(ch,fp);
fclose(fp);
fclose(fp1);
106
fputs():
syntax:
fputs(s,fp);
fgets():
syntax:
fgets(s,I,fp);
Example:
main()
char st[80];
FILE *fp;
fp=fopen(“x.txt”,”w”);
while(strlen(gets(st))>0)
fputs(st,fp);
fputc(‘\n’);
fclose(fp);
fp=fopen(“x.txt”,”r”);
while(fgets(st,79,fp)!=NULL)
107
puts(fp);
fclose(fp);
The getw and putw are integer oriented functions. They are similar to the getc and
putc function and are used to read and write integer values from a file.
putw():
Syntax:
putw(v,fp);
getw():
Syntax:
int g=getw(v,fp);
Example:
Ans:
main()
Int n;
FILE *fp;
int a,i;
fp=fopen(“even.dat”,”w”);
108
scanf(“%d”,&n);
for(i=0;i<n;i++)
printf(“enter a no:”);
scanf(“%d”,&a);
if(a%2==0)
fpuw(a,fp);
fclose(fp);
fp=fopen(“even.dat”,”r”);
while(a=fgetw(fp))
printf(“%d”,a);
fclose(fp);
For formatted reading and writing of character, string, integers, float data uses two
library functions:
fscanf():
109
fprintf():
Example:
main()
char ch=’y’;
struct emp
{
int empno;
char nm[20];
float sal;
}e;
FILE *fp;
fp=fopen(“emp.dat”,”w”);
while(ch==’y’)
printf(“enter empno,nm,sal:”);
scanf(“%d%s%f”,&e.empno,e.nm,&e.sal);
fprintf(fp,”%d%d%f”\n”,e.empno,e.nm,&e.sal);
fflush(stdin);
scanf(“%c”,&ch);
}
110
fclose(fp);
fp=fopen(“emp.dat”,”r”);
while((fscanf(fp,”%d%s%f”,&e.empno,e.nm,&e.sal)!=NULL)
printf((“\n %d%s%f”,e.empno,e.nm,e.sal);
fclose(fp);
fwrite():
syntax:
fwrite(s,I1,i2,f);
eg:
fwrite(&e,sizeof(e),1,fp);
fread():
syntax:
Eg:
fread(&e,sizeof(e),1,fp);
main()
char ch=’y’;
struct emp
{
111
int empno;
char nm[20];
float sal;
}e;
FILE *fp;
fp=fopen(“emp.dat”,”w”);
while(ch==’y’)
printf(“enter empno,nm,sal:”);
scanf(“%d%s%f”,&e.empno,e.nm,&e.sal);
fwrite(&e,sizeof(e),1,fp);
fflush(stdin);
scanf(“%c”,&ch);
fclose(fp);
fp=fopen(“emp.dat”,”r”);
while((fwrite(&e,sizeof(e),1,fp))
printf((“\n %d%s%f”,e.empno,e.nm,e.sal);
fclose(fp);
number of arguments and argv is and array of strings which stores the argument
list.
Syntax:
example:
#include<stdio.h>
FILE *fp1,*fp2;
Char ch;
If(argc!=3)
pritnf(“syntax error…:”);
exit(0);
If(strcmp(argv[1],argv[2])==0)
exit(0);
fp1=fopen(argv[1],”r”);
if(!fp1)
exit(0);
}
113
fp2=fopen(argv[2],”w”);
while((ch=fgetc(fp1))!=EOF)
fputc(ch,fp2);
fclose(fp1);fclose(fp2);
C PREPORCESSOR:
The c preprocessor is a program that processes our source program that processes
our source program before it is passed to the compiler.
1. Macro expansion
2. File inclusion
3. Contional compilation
4. Miscellaneous directives.
Macro expansion:
# define upper 25
The macro template and its macro expansion are separated by blanks or
tabs. A space between # and define is optional. It is never terminated by
semi colon.
Eg:
#define PI 3.1415
114
main()
{
float r=6.25;
float area;
area=PI * r*r;
Eg2:
Main()
Int a=30;
If (ARANGE)
printf(“with in range”);
else
printf(“out of range”);
main()
Float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf(“area of circle=%f”,a);
115
a=AREA(r2);
printf(“area of circle=%f”,a);
File inclusion:
The preprocessor command for file inclusion looks like this:
#include “filename”
And its simply causes the entire contents of file name ro be inserted into the
source code at that point in the program.
These are:
#include <filename>
#include “goto.c”
This command would look for the goto.c in the current directory as well as
the prescribed list of directories as mentioned in the include in the include
search path that might have been setup.
#include<goto.c>
This command would look for the file goto.c in the specified list of directories
only.
Conditional compilation:
116
We can, if we want have the compiler skip over part of a source code by
inserting the processing commands #ifdef and #endif, which have the
general form:
#ifdef macroname
Statement 1;
Statement 2;
Statement 3
#endif
Eg:
#define background 5
#ifdef background
#define background 4
#else
#define background 3
#endif
Miscellaneous directives:
#undef directive
In order to undefine a macro which has been already define we can use
#undef
Eg:
#undef max
117