Programming in c
Programming in c
Programming in c
PERAMBALUR-621 212
PROGRAMMING IN C
CLASS: I BCA
SUBMITTED BY
Mrs.P.ANITHA
ASSISTANT PROFESSOR
PROGRAMMING IN C
UNIT – I
Overview of C
1
A brief history
C is a programming language developed at “AT & T’s Bell Laboratories” of USA in 1972. It was written
by Dennis Ritchie (Fig 2).
The programming language C was first given by Kernighan and Ritchie, in a classic book called “The C
Programming Language, 1st edition”. For several years the book “The C Programming Language, 1st edition”
was the standard on the C programming. In 1983 a committee was formed by the American National Standards
Institute (ANSI) to develop a modern definition for the programming language C . In 1988 they delivered the
final standard definition ANSI C.
Features of C
Portability
Modularity
Extensible
Speed
Mid-level programming language
Flexibility
Rich Library
Advantages of C
1. C programming is the building block for many other high level programming languages existing today
2. A C program written in one computer can easily run on another computer without making any change
2
4. A C program is a collection of functions supported by the C library. So we can easily add our own
functions to C library. Hence we can extend any existing C program according to the need of our
applications
5. Since C is a structured language, we can split any big problem into several sub modules. Collection of
these modules makes up a complete program. This modular concept makes the testing and debugging
easier
Structure of a C program
Documentation Section:
It consist of a set of comment lines
The comment lines begins with /* and ends with */ or a single set of // in the beginning of the line
These lines are not executable
Comments are very helpful in identifying the program features
3
Preprocessor Section:
It is used to link system library files, for defining the macros and for defining the conditional inclusion
Eg: #include<stdio.h>, #include<conio.h>, #define MAX 100, etc.,
main():
Every ‘C’ program must have one main() function, which specifies the starting of a ‘C’ program. It
contains the following two parts
Declaration Part:
This part is used to declare the entire variables that are used in the executable part of the program and
these are called local variables
Execution Part:
It contains at least one valid C Statement.
The Execution of a program begins with opening brace ’{‘ and ends with closing brace ’}’
The closing brace of the main function is the logical end of the program
Example Program
/* addition.c – To find the average of two numbers and print them out together with their average */
#include <stdio.h>
void main( )
{
int first, second;
float avg;
printf("Enter two numbers: ");
scanf("%d %d", &first, &second);
printf("The two numbers are: %d, %d", first, second);
avg = (first + second)/2;
printf("Their average is %f", avg);
}
4
Compilation and Execution of C program
1. Creating the program
2. Compiling the Program
3. Linking the Program with system library
4. Executing the program
5
6
The above illustration provides a lucid description of how to compile and execute a C program.
C Tokens
C tokens, Identifiers and Keywords are the basic elements of a C program. C tokens are the basic
buildings blocks in C. Smallest individual units in a C program are the C tokens. C tokens are of six types. They
are,
1. Keywords
Keywords are those words whose meaning is already defined by Compiler. They cannot be used as
Variable Names. There are 32 Keywords in C. C Keywords are also called as Reserved words. There are 32
keywords in C. They are given below:
7
2. Identifiers
Identifiers are the names given to various program elements such as variables , arrays & functions.
Basically identifiers are the sequences of alphabets or digits.
The constants refer to fixed values that the program may not change or modify during its execution.
Constants can be of any of the basic data types like an integer constant, a floating constant and a character
constant. There is also a special type of constant called enumeration constant.
(OR)
Constant is a any value that cannot be changed during program execution. In C, any number, single
character, or character string is known as a constant.
Primary Constants
Secondary Constants
8
Numeric constant
Character constant
String constant
Numeric constant:
Numeric constant consists of digits. It required minimum size
of 2 bytes and max 4 bytes.
It may be positive or negative but by default sign is always positive. No comma or space is allowed
within the numeric constant and it must have at least 1 digit. The allowable range for integer constants is -32768
to 32767. Truly speaking the range of an Integer constant depends upon the compiler.
For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767.
For a 32-bit compiler the range would be even greater. Mean by a 16-bit or a 32- bit compiler, what
range of an Integer constant has to do with the type of compiler.
Real constant is also called floating point constant. To construct real constant we
must follow the rule of ,
real constant must have at least one digit.
9
It must have a decimal point.
It could be either positive or negative.
Default sign is positive.
No commas or blanks are allowed within a real constant.
Ex.: +325.34
426.0
-32.76
Character constant
String constant
Set of characters are called string and when sequence of characters are
enclosed within a double quote (it may be combination of all kind of symbols) is a
string constant.
String constant has zero, one or more than one character and at the
end of the string null character(\0) is automatically placed by compiler.
Some examples are “,sarathina” , “908”, “3”,” ”, “A” etc.
In C although same characters are enclosed within single and double quotes it represents different
meaning such as “A” and ‘A’ are different because first one is string attached with null character at the end but
second one is character constant with its corresponding ASCII value is 65.
Symbolic constant
#define MAX 10
#define CH ‘b’
10
#define NAME “sony”
Eg:
Integer Constants- 45, 215u
Floating Constants- 3.14, 4513E-5L
Character Constants- \t, \n
4. Strings
A string in C is actually a one-dimensional array of characters which is terminated by a null character '\0'.
Eg:
char str = {‘S’, ’A’, ’T’, ’H’, ’Y’, ’A’, ’B’, ’A’, ’M’, ’A’}
5. Special Symbols
The symbols other than alphabets, digits and white spaces for example - [] () {} , ; : * … = # are the special
symbols.
6. Operators
An Operator is a symbol that specifies an operation to be performed on the operands. The data items that
operators act upon are called operands. Operators which require two operands are called Binary operators.
Operators which require one operand are called Unary Operators.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Sizeof() Operators
Variable:
A variable is an identifier that is used to represent some specified type of information within a designated
portion of the program.
11
A variable may take different values at different times during the execution
(Or)
Variable is a data name which is used to store some data value or symbolic names for storing program
computations and results. The value of the variable can be change during the execution.
Syntax:
Data-type variable-name;
Example:
int number;
float average;
Variable initialization
When we assign any initial value to variable during the declaration, is called initialization of variables.
When variable is declared but contain undefined value then it is called garbage value. The variable is initialized
with the assignment operator such as
Syntax:
Data type variable name=constant;
Example:
int a=20;
Or int a;
a=20;
statements
Assignment statement
A value can be stored in a variable with the use of assignment operator. The assignment operator(=) is used in
assignment statement and assignment expression. Operand on the left hand side should be variable and the
operand on the right hand side should be variable or constant or any expression. When variable on the left hand
side is occur on the right hand side then we can avoid by writing the
compound statement.
For example,
int x= y;
int Sum=x+y+z;
Data Types in C
12
C has a concept of 'data types' which are used to define a variable before its use. The definition of a
variable will assign storage for the variable and define the type of data that will be held in the location. The value
of a variable can be changed any time.
int
float
double
char
Scope of a variable
A scope in any programming is a region of the program where a defined variable can have its existence and
beyond that variable cannot be accessed. There are three places where variables can be declared in C
programming language:
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only by
statements that are inside that function. Local variables are not known to functions outside their own. Following
is the example using local variables. Here all the variables a, b and c are local to main() function.
13
#include <stdio.h>
main ()
{
/* local variable declaration */
int a, b, c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
}
Global Variables
Global variables are defined outside of a function, usually on top of the program. The global variables will hold
their value throughout the lifetime of your program and they can be accessed inside any of the functions defined
for the program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your
entire program after its declaration. Following is the example using global and local variables:
#include <stdio.h>
/* global variable declaration */
int g;
main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
}
Qualifier
14
When the qualifier unsigned is used the number is always positive, and when
signed is used number may be positive or negative.
If the sign qualifier is not mentioned, then by default sign qualifier is assumed. The range of values for
signed data types is less than that of unsigned data type.
Because in signed type, the left most bit is used to represent sign, while in unsigned type this bit is also
used to represent the value. The size and range of the different data types on a 16 bit machine is given below:
Type conversion is the method of converting one type of data into another data type.
This type of conversion is done automatically. The resultant value of an expression depends upon
the operand which occupies more space, which means the result value converted into highest
data type.
The compiler converts all operands into the data type of the largest operand.
This type of type conversion is done implicitly,this method is called as implicit type conversion.
Eg.1
float a,b,c;
a=10,b=3;
c=a/b
output= > c= 3.3 {4 bytes(float) (All the variables are same datatype}
Eg.2
15
int a,b,c;
a=10,b=3;
c=a/b;
output= >c=3{2 bytes(int)}
Eg.3
int a;
float b,c;
a=10,b=3;
c=a/b;
output=> c=3.3 {4 bytes(float) highest datatype is float}
Type casting
This method is used,when user wants to change the type of the data.
(datatype)operand
Eg.1
Eg:2
int x=10,y=3;
z=x/(float)y;(ie z=10/3.0;)
output=>3.3(float)
The type of the x is not changed, only the type of the value can be changed
Since the type of conversion is done explicitly, this type conversion is called as explicit type conversion
The following rules have to be followed while converting the expression from one type to another to avoid the
loss of information:
In ‘c’ language several functions are available for input/output operations. These
functions are collectively known as the standard I/O library.
16
1.Unformatted input /output statements
These statements are used to input /output a single /group of characters from/to the input/output devices .Here the
user cannot specify the type of data that is going to be input/output.
The following are the Unformatted input /output statements available in ‘C’.
Example:
char x;
x=getchar( );
A putchar( ) function is used to display one character at a time on the standard output device.
Syntax: putchar(charvariable);
Example:
char x;
putchar(x);
The function which is used to give the value of variable through keyboard is called input function. The
function which is used to display or print the value on the screen is called output function.
Note : - In C language we use two built in functions, one is used for reading and another is used for displaying
the result on the screen. They are scanf() and printf() functions. They are stored in the header file named stdio.h.
17
General format for scanf( ) function
The control sting specifies the field format in which the data is to be entered.
%d –integer
%f – float
%c- char
%s – string
% ld – long integer
%u – Unsigned Integer
Example:
scanf(“%d%f”,&x,&a) - reading a integer and a float value In the above scanf ( ) function , we don’t use any
format. This type of Input is called as the Unformatted Input function.
Output Function : To print the value on the screen or to store the value on the file, the output functions are used.
printf() is the function which is use to display the output on the screen.
printf(“control string”,variable1,variable2,…..);
Example
Formatted Output of Integer :Similar to formatted input , there is a formatted output also to have the output in
a format manner.
\n – new line
\b – back space
\f – form feed
\r – carriage return
\t - horizontal tab
\v – vertical tab
18
The format speciation is as follows
%wd
Where w – is the field width of the number to be write . d will indicates as data type in integer number.
Examples:
output:
printf(“%-6d”,9876);
output:
printf(“%06”,9876);
output:
%w.pf
Where w – is the field width of the number to be read . p indicates the number of digits to be read after
the decimal point f – indicates that data type in float(real) number.
%w.pf
Where w – is the field width of the number to be read . p indicates the number of digits to be displayed
after the decimal point f – indicates that data type in float(real) number.
Example:
19
Float y = 98.7682
Printf(“ %f ”, y); // output: 98.7682
printf(“%7.2f ”,y);
output:
printf(“%-7.2f ”,y);
output:
%ws or %wc
where,
%c is used to read a single character.
Example:
Char name;
Scanf(“%c”, &name); \\ I / P : a
Char name[20];
Scanf(%s”,&name); \\ I / P : sathyabama
The character will be displayed right-justified in the field of w, left-justified by placing a minus sign
before the integer w.
20
Example:
Char x = ‘a’;
Char name[20] = “anil kumar gupta”;
Printf(“%c”, x); // output: a
Printf(“%s”,name); // output: anil kumar gupta
Printf(“%20s”, name);
Output:
Printf(“%-20.10s”, name);
Output:
Printf(“%.5s”, name);
Output:
UNIT – II
If an arithmetic expression is given, there are some rules to be followed to evaluate the value of it. These rules are
called as the priority rules. They are also called as the hierarchy rules. According to these rules, the expression is
evaluated as follows;
21
Rule 1 :- If an expression contains parentheses , the expression within the parentheses will be performed first.
Within the parentheses , the priority is to be followed.
Rule 2 :- If it has more than parentheses , the inner parenthesis is performed first.
Rule 3:- If more than one symbols of same priority , it will be executed from left to right.
C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of
equal precedence in an expression are applied
22
Example for evaluating an expression
Operators
An Operator is a symbol that specifies an operation to be performed on the operands. The data items that
operators act upon are called operands. Operators which require two operands are called Binary operators.
Operators which require one operand are called Unary Operators.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Sizeof() Operators
Arithmetic Operators
Arithmetic Operators are used to perform mathematical calculations like addition, subtraction, multiplication,
division and modulus.
23
Rules For Arithmetic Operators
1. C allows only one variable on left hand side of = eg. c=a*b is legal, but a*b=c is not legal.
2. Arithmetic operations are performed on the ASCII values of the characters and not on characters themselves
3. Operators must be explicitly written.
4. Operation between same type of data yields same type of data, but operation between integer and float yields a
float result.
Example Program
#include <stdio.h>
int main()
{
int m=40,n=20, add,sub,mul,div,mod;
add = m+n;
sub = m-n;
mul = m*n;
div = m/n;
mod = m%n;
printf(“Addition of m, n is : %d\n”, add);
printf(“Subtraction of m, n is : %d\n”, sub);
printf(“Multiplication of m, n is : %d\n”, mul);
printf(“Division of m, n is : %d\n”, div);
printf(“Modulus of m, n is : %d\n”, mod);
}
Output
Addition of m, n is : 60
Subtraction of m, n is : 20
Multiplication of m, n is : 800
Division of m, n is : 2
Modulus of m, n is : 0
Relational Operators
24
Relational Operators are used to compare two or more operands. Operands may be variables, constants or
expression
Example Program
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf(“m and n are equal”);
}
else
{
printf(“m and n are not equal”);
}
}
Output
Logical Operators
Logical Operators are used to combine the results of two or more conditions. It is also used to test more
than one condition and make decision.
25
Example Program
#include <stdio.h>
int main()
{
int a=40,b=20,c=30;
if ((a>b )&& (a >c))
{
printf(“ a is greater than b and c”);
}
else
if(b>c)
printf(“b is greater than a and c”);
else
prinf(“c is greater than a and b”);
}
Output
Conditional Operator
It itself checks the condition and executed the statement depending on the condition.
Syntax:
Condition? Exp1:Exp2
26
Example:
X=(a>b)?a:b
The ‘?:’ operator acts as ternary operator. It first evaluate the condition, if it is true then exp1 is
evaluated, if condition is false then exp2 is evaluated. The drawback of Assignment operator is that after the ?
or : only one statement can occur.
Example Program
#include <stdio.h>
int main()
{
int x,a=5,b=3;
x = (a>b) ? a : b ;
printf(“x value is %d\n”, x);
}
Output
x value is 5
Bitwise Operators
Bitwise Operators are used for manipulation of data at bit level. It operates on integer only.
Example Program
#include <stdio.h>
main()
{
int c1=1,c2;
c2=c1<<2;
printf(“Left shift by 2 bits c1<<2=%d”,c2);
}
27
Output
Special operators:
sizeof () operator:
#include<stdio.h>
int main()
{
int ivar = 100;
char cvar = 'a';
float fvar = 10.10;
printf("%d", sizeof(ivar));
printf("%d", sizeof(cvar));
printf("%d", sizeof(fvar));
return 0;
}
Output :
214
In the above example we have passed a variable to size of operator. It will print the value of variable
using sizeof() operator.
#include<stdio.h>
int main()
{
printf("%d", sizeof(int));
printf("%d", sizeof(char));
printf("%d", sizeof(float));
return 0;
}
Output :
214
28
In this case we have directly passed an data type to an sizeof.
#include<stdio.h>
int main()
{
printf("%d", sizeof(10));
printf("%d", sizeof('A'));
printf("%d", sizeof(10.10));
return 0;
}
Output :
214
In this example we have passed the constant value to a sizeof operator. In this case sizeof will print the size
required by variable used to store the passed value.
#include<stdio.h>
int main()
{
int num = 10;
printf("%d", sizeof(sizeof(num)));
return 0;
}
Output:
We can use nested sizeof in c programming. Inner sizeof will be executed in normal fashion and the result of
inner sizeof will be passed as input to outer sizeof operator.
Innermost Sizeof operator will evaluate size of Variable “num” i.e 2 bytes Outer Sizeof will evaluate Size of
constant “2” .i.e 2 bytes
Comma(,) Operator:
1. Comma Operator has Lowest Precedence i.e it is having lowest priority so it is evaluated at last.
2. Comma operator returns the value of the rightmost operand when multiple comma operators are used inside an
expression.
3. Comma Operator Can acts as –
Operator : In the Expression
Separator: Function calls, Function definitions, Variable declarations and Enum declarations
29
Example:
#include<stdio.h>
void main()
{
Output
In this case value of rightmost operator will be assigned to the variable. In this case value of num2 will
be assigned to variable res.
#include<stdio.h>
int main()
{
int i;
i = 1,2,3;
printf("i:%d\n",i);
return 0;
}
Output:
i:1
Explanation:
i = 1,2,3;
1. Above Expression contain 3 comma operator and 1 assignment operator.
2. If we check precedence table then we can say that “Comma” operator has lowest precedence than assignment
operator
3. So Assignment statement will be executed first .
30
4. 1 is assigned to variable “i”.
#include<stdio.h>
int main()
{
int i;
i = (1,2,3);
printf("i:%d\n",i);
return 0;
}
Output:
i:3
Explanation:
i = (1,2,3);
1. Bracket has highest priority than any operator.
2. Inside bracket we have 2 comma operators.
3. Comma operator has associativity from Left to Right.
4. Comma Operator will return rightmost operand
i = (1,2,3) Assign 3 to variable i.
#include<stdio.h>
#include< conio.h>
void main()
{
clrscr();
printf("Computer","Programming");
getch();
}
Output:
Computer
You might feel that answer of this statement should be “Programming” because comma operator always
returns rightmost operator, in case of printf statement once comma is read then it will consider preceding things
as variable or values for format specifier.
#include<stdio.h>
#include< conio.h>
31
void main()
{
int choice = 2 ;
switch(choice)
{
case 1,2,1:
printf("\nAllas");
break;
case 1,3,2:
printf("\nBabo");
break;
case 4,5,3:
printf("\nHurray");
break;
}
}
Output :
Babo
#include<stdio.h>
int main()
{
int i,j;
for(i=0,j=0;i<5;i++)
{
printf("\nValue of J : %d",j);
j++;
}
return(0);
}
Output:
Value of J : 0
Value of J : 1
Value of J : 2
Value of J : 3
Value of J : 4
#include<stdio.h>
int main()
{
32
int num1,num2;
int a=10,b=20;
return(0);
}
Note : Use of comma operator for multiple declaration in same statement.
Expressions
An expression is a combination of variables, constants, operators and function call. It can be arithmetic,
logical and relational for example:-
int z= x+y // arithmatic expression
a>b //relational
a==b // logical
func(a, b) // function call
Expressions consisting entirely of constant values are called constant expressions.
So, the expression
121 + 17 - 110
is a constant expression because each of the terms of the expression is a constant
value. But if i were declared to be an integer variable, the expression
180 + 2 – j
would not represent a constant expression
In ‘c’ language several functions are available for input/output operations. These
functions are collectively known as the standard I/O library.
These statements are used to input /output a single /group of characters from/to the input/output devices .Here the
user cannot specify the type of data that is going to be input/output.
The following are the Unformatted input /output statements available in ‘C’.
33
A getchar( ) function reads only one character through the keyboard.
Example:
char x;
x=getchar( );
A putchar( ) function is used to display one character at a time on the standard output device.
Syntax: putchar(charvariable);
Example:
char x;
putchar(x);
This is used to accept a single character from the standard input to a character variable.
Example:
char c;
c=getc( );
Example:
char c;
putc(c );
the gets( ) and puts( ) function
The gets( ) function is used to read the string from the standard input device.
Example:
gets( s);
The puts( ) function is used to display the string to the standard output device
.
Syntax: puts(string variable);
34
Example:
puts( s);
#include<stdio.h>
main()
{
char scientist[40];
puts("Enter Name");
gets(scientist);
puts("Print the Name");
puts(scientist);
}
output:
The function which is used to give the value of variable through keyboard is called input function. The
function which is used to display or print the value on the screen is called output function.
Note : - In C language we use two built in functions, one is used for reading and another is used for displaying
the result on the screen. They are scanf() and printf() functions. They are stored in the header file named stdio.h.
The control sting specifies the field format in which the data is to be entered.
%d –integer
%f – float
%c- char
%s – string
% ld – long integer
%u – Unsigned Integer
Example:
scanf(“%d%f”,&x,&a) - reading a integer and a float value In the above scanf ( ) function , we don’t use any
format. This type of Input is called as the Unformatted Input function.
35
Formatted Input of Integer
Example:
Example the statement scanf(“%d %*d %d),&a,&b); will assign the data 123 456 789
as follows: 123 is assigned to a , 456 skipped because of * and 789 to b
Output Function : To print the value on the screen or to store the value on the file, the output functions are used.
printf() is the function which is use to display the output on the screen.
The General format of the printf() function is
printf(“control string”,variable1,variable2,…..);
Example
\n – new line
\b – back space
\f – form feed
\r – carriage return
\t - horizontal tab
\v – vertical tab
%wd
36
Where w – is the field width of the number to be write . d will indicates as data type in integer number.
Examples:
output:
printf(“%-6d”,9876);
output:
printf(“%06”,9876);
output:
%w.pf
Where w – is the field width of the number to be read . p indicates the number of digits to be read after
the decimal point f – indicates that data type in float(real) number.
Example
scanf(“%2.1f %5.2f”,&num1,&num2);
data line is 50.1 31425.20
the value 50.1 is assigned to num1 and 31425.20 is assigned to num2.
An input field may be skipped by specifying * in the place of field width.
Example: the statement scanf(“%f %*f %f), &a,&b); will assign the data 12.3 4.56 78.9
as follows: 12.3 is assigned to a , 4.56 skipped because of * and 78.9 to b.
37
%w.pf
Where w – is the field width of the number to be read . p indicates the number of digits to be displayed
after the decimal point f – indicates that data type in float(real) number.
Example:
Float y = 98.7682
Printf(“ %f ”, y); // output: 98.7682
printf(“%7.2f ”,y);
output:
printf(“%-7.2f ”,y);
output:
%ws or %wc
where,
%c is used to read a single character.
Example:
Char name;
Scanf(“%c”, &name); \\ I / P : a
Char name[20];
Scanf(%s”,&name); \\ I / P : sathyabama
38
The character will be displayed right-justified in the field of w, left-justified by placing a minus sign
before the integer w.
Example:
Char x = ‘a’;
Char name[20] = “anil kumar gupta”;
Printf(“%c”, x); // output: a
Printf(“%s”,name); // output: anil kumar gupta
Printf(“%20s”, name);
Output:
Printf(“%-20.10s”, name);
Output:
Printf(“%.5s”, name);
Output:
LIBRARY FUNCTIONS
Definition
C Library functions are inbuilt functions in C language which are clustered in a group and stored in a
common place called Library. Each and every library functions in C executes explicit functions. In order to get
the pre- defined output instead of writing our own code, these library functions will be used. Header file consists
of these library functions like Function prototype and data definitions.
Every input and output operations (e.g., writing to the terminal) and all mathematical operations (e.g.,
evaluation of sines and cosines) are put into operation by library functions.
The C library functions are declared in header files (.h) and it is represented as [file_name].h
The Syntax of using C library functions in the header file is declared as “#include<file_name.h>”. Using
this syntax we can make use of those library functions.
39
#include<filename.h>” command defines that in C program all the codes are included in the header files
followed by execution using compiler.
It is required to call the suitable header file at the beginning of the program in terminal in order to use a
library function. A header file is called by means of the pre-processor statement given below,
#include<filename.h>
Whereas the filename represents the header file name and #include is a pre- processor directive.
To access a library function the function name must be denoted, followed by a list of arguments, which
denotes the information being passed to the function.
Example
In case if you want to make use of printf() function, the header file <stdio.h> should be included at the
beginning of the C program.
#include <stdio.h>
int main()
{
/* NOTE: Error occurs if printf() statement is written without using the header file */
printf(" Hello World");
}
The „main() function‟ is also a library function which is called at the initial of the program.
Example
To find the square root of a number we use our own part of code to find them but this may not be most
efficient process which is time consuming too. Hence in C programming by declaring the square root function
sqrt() under the library function “math.h” will be used to find them rapidly and less time consuming too. Square
root program using the library functions is given below:
#include <stdio.h>
#include <math.h>
int main()
{
float num,root;
printf("Enter a number to find square root."); scanf("%f",&num);
root=sqrt(num); /* Computes the square root of num and stores in root. */
printf("Square root of %.2f=%.2f",num,root);
return 0;
}
40
Adding User Defined functions in C library:
In C Programming we can declare our own functions in C library which is called as user-defined
functions.
It is possible to include, remove, change and access our own user defined function to or from C library
functions.
Once the defined function is added to the library it is merely available for all C programs which are more
beneficial of including user defined function in C library function
Once it is declared it can be used anywhere in the C program just like using other C library functions.
By using these library functions in GCC compilers (latest version), compilation time can be consumed
since these functions are accessible in C library in the compiled form.
Commonly the header files in C program are saved as ”file_name.h” in which all librar
functions are obtainable. These header files include source code and this source code is
further added in main C program file where we include this header file via “#include
<file_name.h>” command.
Step 1:
For instance, hereby given below is a test function that is going to be included in the C library function.
Write and save the below function in a file as “addition.c”
addition(int a, int b)
{
int sum;
total =a + b; return sum;
}
Step 2:
step 3:
41
Step 4:
To add this function to library, use the command given below (in turbo C). c:\> tlib math.lib + c:\
addition.obj
+ represents including c:\addition.obj file in the math library. We can delete this file using –
(minus).
Step 5:
Create a file “addition.h” and declare sample of addition() function like below. int addition (int a,
int b);
Now “addition.h” file has the prototype of function “addition”.
Note : Since directory name changes for each and every IDE, Kindly create, compile and add
files in the particular directory.
Step 6:
Here is an example to see how to use our newly added library function in a C program.
# include <stdio.h>
// User defined function is included here.
# include “c:\\addition.h”
int main ( )
{
42
int total;
// calling function from library total = addition (10, 20);
printf ("Total = %d \n", total);
}
Output:
Total = 30
Source code checking for all header files can be checked inside “include” directory following C compiler
that is installed in system.
For instance, if you install DevC++ compiler in C directory in our system, “C:\Dev-Cpp\include” is the
path where all header files will be readily available.
C library functions and header files in which they are declared in conio.h is listed below:
The entire C programming inbuilt functions that are declared in conio.h header file are given below. The source
code for conio.h header file is also given below for your reference.
List of inbuilt conio.h file C functions:
43
C – stdio.h library functions
44
UNIT – III
DECISION STATEMENT AND ARRAYS
CONTROL STRUCTURES
CONDITIONAL STATEMENT
Decision Making Statement
If Statement:
The if statement is a decision making statement.
It is used to control the flow of execution of the statement and also used to the logically whether the
condition is true or false
It is always used in conjunction with condition.
45
Syntax:
If(condition)
{
True statements;
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf(“Enter one value”);
scanf(“%d”,&i);
if(i<=25)
printf(“The entered no %d is < 25”,i);
getch();
}
Output:
Enter one value 5
The entered no 5 is < 25
It is basically two way decision making statement and always used in conjunction with condition.
46
It is used to control the flow of expression and also used to carry the logical test and then pickup one of
the two possible actions depending on the logical test.
If the condition is true, then the true statements are executed otherwise false statements are executed.
The true and false statements may be single or group of statements.
Syntax:
If (condition)
True statements;
else
False statements;
#include<stdio.h>
#include<conio.h> void main()
{
int a,b;
printf(“Enter two value”); scanf(“%d%d”,&a,&b);
if(a>b)
printf(“The given no %d is greatest”,a);
else
printf(“The given no %d is greatest”,b);
}
Output:
47
Nested if..else Statement:
When a series of if_else statements are needed in a program, we can write an entire if_else statement
inside another if and it can be further nested. This is called nesting if.
Syntax:
if(condition 1)
{
if(condition 2)
{
True statement 2;
else
False statement 2;
}
else
False statement 1;
}
Example 1: //program to find the greatest of three numbers.
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a == 100 )
{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
Output:
Syntax:
if(condition 1)
{
True ststement 1;
}
else if(condition 2)
{
True statement 2;
}
else if(condition 3)
{
True statement 3;
else
Default statement;
}
Switch Statement
The switch statement is used to execute a particular group of statements from several available groups of
statements.
It allows us to make a decision from the number of choices.
It is a multi-way decision statement.
Syntax:
switch(expression)
49
{
case 1: state ment; break;
case 2: state ment; break;
default: statement;
break;
}
// program to print the give number is odd / even using switch case statement.
#include<stdio.h>
#include<conio.h> void main()
{
int a,b,c;
printf(“Enter one value”); scanf(“%d”,&a);
switch(a%2)
{
case 0:
printf(“The given no %d is even”, a);
break;
default :
printf(“The given no %d is odd”, a);
break;
}
}
50
Output:
Unconditional statement
Break statement
Syntax:
break;
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break;
printf(“%d”,i); }
}
Output:
1 2 3 4 5
51
Continue Statement
In some situation, we want to take the control to the beginning of the loop, bypassing the statement
inside the loop which have not been executed, for this purpose the continue is used.
When the statement continue is encountered inside any loop, control automatically passes to the
beginning of the loop.
Syntax:
continue;
While(condition)
{
……..
if(condition)
continue;
……….
}
52
Goto Statement:
C provides the goto statement to transfer control unconditionally from one place to another place in the
program.
A goto statement can change the program control to almost anywhere in the program unconditionally.
The goto statement require a label to identify the place to move the execution.
The label is a valid variable name and must be ended with colon(:).
Syntax:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf(“Enter the numbers”);
scanf(“%d%d”,&a,&b);
if(a==b)
goto equal;
} else
{
printf(“%d and %d are not equal”,a,b);
exit(0);
Output:
}
equal: printf(“%d and %d are equal”,a,b);
53
LOOPING STATEMENTS
A loop statement allows us to execute certain block of code repeatedly until test condition is false.
1. for loop
2. while loop
3. do...while loop
for loop:
This program takes a positive integer from user and stores it in variable n. Then, for loop is executed
which checks whether the number entered by user is perfectly divisible by i or not starting with initial value of i
equals to 2 and increasing the value of i in each iteration. If the number entered by user is perfectly divisible by i
then, flag is set to 1 and that number will not be a prime number but, if the number is not perfectly divisible by i
until test condition i<=n/2 is true means, it is only divisible by 1 and that number itself and that number is a
prime number.
55
While Loop
while loop repeatedly executes a target statement as long as a given condition is true.
Initialization;
while(condition)
{
----------
---------
----------
------
Increment/decrement;
}
For Single Line of Code – Opening and Closing braces are not needed. while(1) is used for Infinite Loop
Initialization, Increment/Decrement and Condition steps are on different Line.
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then only code is
executed ]
C Program to Find Number of Digits in a Number
#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
n/=10; /* n=n/10 */
++count;
}
printf("Number of digits: %d",count);
}
Output:
Enter an integer: 34523 Number of digits: 5
56
Types of infinite while loop
Semicolon at the end of while loop
#include<stdio.h> void main()
{
int num=300;
while(num>255); //Note it Carefully printf("Hello");
}
Output :
Will not print anything
3. In the program variable num doesn‟t get incremented , condition remains true forever.
4. As Above program does not have Loop body , It won‟t print anything
DO..WHILE
57
Using Do-While Loop
#include<stdio.h>
void main() { int i = 1;
do {
printf("%d", i); i++;
} while (i <= 5);
}
Output
1
2
3
4
5
ARRAYS
Introduction:
So far we have used only single variable name for storing one data item. If we need to store multiple
copies of the same data then it is very difficult for the user. To overcome the difficulty a new data
structure is used called arrays.
An array permits homogeneous data. It means that similar types of elements are stored contiguously
in the memory under one variable name.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100 variables named
as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C programming arrays is
introduced in C which gives the capability to store the 100 roll numbers in the contiguous memory which
has 100 blocks and which can be accessed by single variable name.
58
The above array is declared as int a [5];
In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.
1. Individual data items can be accessed by the name of the array and an integer enclosed in square
bracket called subscript variable / index
2. Subscript Variables helps us to identify the item number to be accessed in the contiguous memory.
What is Contiguous Memory?
1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.
3. Suppose inside memory we have reserved 1000-1200 memory addresses for special purposes then
we can say that these 200 blocks are going to reserve contiguous memory.
Contiguous Memory Allocation
1. Two registers are used while implementing the contiguous memory scheme. These registers are
base register and limit register.
2. When OS is executing a process inside the main memory then content of each register are as
Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non - contiguous
allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address from base
register and then it will refer relative address of memory location with respect to base address.
59
How to allocate contiguous memory?
Size: Number of elements or capacity to store elements in an array. It is always mentioned in square
brackets [ ].
Type: Refers to data type. It decides which type of element is stored in the array. It is also instructing the
compiler to reserve memory according to the data type.
Base: The address of the first element is a base address. The array name itself stores address of the first
element.
Index: The array name is used to refer to the array element. For example num[x], num is array and x is
index. The value of x begins from 0.The index value is always an integer value.
Range: Value of index of an array varies from lower bound to upper bound. For example in num[100] the
range of index is 0 to 99.
Word: It indicates the space required for an element. In each memory location, computer can
store a data piece. The space occupation varies from machine to machine. If the size of element is more
than word (one byte) then it occupies two successive memory locations. The variables of data type int,
float, long need more than one byte in memory.
Characteristics of an array:
1. The declaration int a [5] is nothing but creation of five variables of integer types in memory
instead of declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from one another
with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the other
elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or array
variable of its type.
6. Array elements are stored in contiguous memory locations.
Array Declaration:
60
Array has to be declared before using it in C Program. Array is nothing but the collection of elements of
similar data types.
Syntax:
Requirement Explanation
Data Type specifies the type of the array. We can compute the size
Data Type required for storing the single cell of array.
Valid identifier is any valid variable or name given to the array. Using this
Valid Identifier identifier name array can be accessed.
Types of Array
1. Single or One Dimensional array is used to represent and store data in a linear form.
2. Array having only one subscript variable is called One-Dimensional array
61
3. It is also called as Single Dimensional Array or Linear Array
Single Dimensional Array Declaration and initialization:
Syntax for declaration: <data type> <array name> [size];
Syntax for initialization: <data type> <array name> [size] = {val1, val2, …, valn};
Examples for initialization:
Whenever we declare an array, we initialize that array directly at compile time.Initializing 1-D Array is
called as compiler time initialization if and only if we assign certain set of values to array element before
executing program. i.e. at compilation time.
Here we are learning the different ways of compile time initialization of an array.
62
In the above example we have specified the size of array as 5 directly in the initialization statement.
Compiler will assign the set of values to particular element of the array.
As at the time of compilation all the elements are at specified position So This initialization scheme is
Called as “Compile Time Initialization“.
Graphical Representation:
In this scheme of compile time Initialization, We do not provide size to an array but instead we provide set
of values to the array.
Explanation:
1. Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines the Size
of An Array.
2. After counting the number of elements inside the braces, The size of array is considered as 5
during complete execution.
3. This type of Initialization Scheme is also Called as “Compile Time Initialization“
Example Program
#include <stdio.h> int
main()
63
int i;
for (i=0;i<5;i++) {
printf(“\n Array Element num [%d] = %d”,i, num[i]); } return
0; }
Output:
Accessing Array
1. We all know that array elements are randomly accessed using the subscript variable.
2. Array can be accessed using array-name and subscript variable written inside pair of square
brackets [ ].
Consider the below example of an array
arr[0] = 51; arr[1] = 32; arr[2] = 43; arr[3] = 24; arr[4] = 5; arr[5] =26;
void main()
{
64
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\nElement at arr[%d] is %d",i,arr[i]);
}
getch();
}
Output:
Element at arr[0] is 51
Element at arr[1] is 32
Element at arr[2] is 43
Element at arr[3] is 24
Element at arr[4] is 5
Element at arr[5] is 26
How a[i] Works?
We have following array which is declared like int arr[] = { 51,32,43,24,5,26};
As we have elements in an array, so we have track of base address of an array. Below things are
important to access an array.
So whenever we tried accessing array using arr[i] then it returns an element at the location*(arr
+ i)
65
Accessing array a[i] means retrieving element from address (a + i).
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]);
}
getch();
}
Output:
51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
55 5 5
26 26 26 26
Operations with One Dimensional Array
67
&element);
printf("\nEnter the location");
scanf("%d", &location);
//Create space at the specified location for
(i = num; i >= location; i--) { arr[i] =
arr[i - 1]; }
num++;
arr[location - 1] = element;
//Print out the result of insertion for
(i = 0; i < num; i++)
printf("n %d", arr[i]);
return (0);
}
Output:
Enter no of elements: 5 1 2 3
45
Enter the element to be inserted: 6 Enter
the location: 2
16234 5
1. Array having more than one subscript variable is called Multi-Dimensional array.
2. Multi Dimensional Array is also called as Matrix.
Syntax: <data type> <array name> [row subscript][column subscript];
69
Example: Two Dimensional Arrays
Declaration: Char name[50][20];
Initialization:
int a[3][3] = { 1, 2, 3
5, 6, 7
8, 9, 0};
In the above example we are declaring 2D array which has 2 dimensions. First dimension will refer the
row and 2nd dimension will refer the column.
The following information are given by the compiler after the declaration
1 integer roll 1 10
70
Declaration and use of 2D Arrays:
int a[3][4];
for(i=0;i<row,i++)
for(j=0;j<col,j++) {
printf("%d",a[i][j]); } Meaning
of Two Dimensional Arrays:
Declaration a[3][4]
No of Rows 3
No of Columns 4
No of Cells 12
Memory Representation:
71
6. This is integer array so each element requires 2 bytes of memory.
Basic Memory Address Calculation:
a[0][0] 4000
a[0][1] 4002
a[0][2] 4004
a[1][0] 4006
a[1][1] 4008
a[1][2] 4010
a[2][0] 4012
a[2][1] 4014
a[2][2] 4016
72
73
Initializing 2D Array
For initializing 2D Array we need to assign values to each element of an array using the below syntax.
Example Program
#include<stdio.h> int
main()
{
int i, j;
int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 } };
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]); }
printf("\n"); }
return 0;
}
Output:
1 4
5 2
6 5
We have declared an array of size 3 X 2, it contains overall 6
elements.
74
Row 1: {1, 4},
Row 2: {5, 2},
Row 3: {6, 5}
We have initialized each row independently a[0]
[0] = 1
a[0][1] = 4
Method 2: Combine and Initializing 2D Array
Initialize all Array elements but initialization is much straight forward. All values are assigned sequentially
and row-wise
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
Example Program:
#include <stdio.h> int
main() {
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
} printf("\n"); }
return 0;
}
Output:
1 4
5 2
6 5
Method 3: Some Elements could be initialized
int a[3][2] = { { 1 }, { 5 , 2 }, { 6 } };
Now we have again going with the way 1 but we are removing some of the elements from the array.
Uninitialized elements will get default 0 value. In this case we have declared and initialized 2-D array like
this
75
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1 }, { 5, 2 }, { 6 }};
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]); }
printf("\n"); }
return 0;
}
Output:
1 0
5 2
6 0
Accessing 2D Array Elements:
76
printf("%d\t", a[i][j]); }
printf("\n"); }
return (0);
}
How it Works?
1. For Every value of row Subscript , the column Subscript incremented from 0 to n-1 columns
2. i.e. For Zeroth row it will accept zeroth, first, second column (a[0][0], a[0][1], a[0][2]) elements
3. In Next Iteration Row number will be incremented by 1 and the column number again initialized to 0.
4. Accessing 2-D Array: a[i][j] Element From ith Row and jth Column
77
UNIT IV
1. Individual element is passed to function using Pass By Value parameter passing scheme
2. An original Array element remains same as Actual Element is never passed to Function. Thus function body
cannot modify Original Value.
3. Suppose we have declared an array „arr[5]‟ then its individual elements are arr[0],arr[1]…arr[4].
Thus we need 5 function calls to pass complete array to a function.
Consider an array int arr[5] = {11, 22, 33, 44, 55};
{
printf("\nElement : %d",num);
}
void main() { int
arr[5],i;
clrscr();
printf("\nEnter the array elements : "); for(i=0;i<
5;i++)
scanf("%d",&arr[i]);
printf("\nPassing array element by element....."); for(i=0;i< 5;i++)
fun(arr[i]); getch();
}
Output:
78
Enter the array elements : 1 2 3 4 5 Passing array
element by element..... Element : 1
Element : 2
Element : 3
Element : 4
Element : 5
Disadvantage of this Scheme:
1. This type of scheme in which we are calling the function again and again but with different array element is
too much time consuming. In this scheme we need to call function by pushing the current status into the
system stack.
2. It is better to pass complete array to the function so that we can save some system time required for pushing
and popping.
3. We can also pass the address of the individual array element to function so that function can modify the
original copy of the parameter directly.
Example Program #2: Passing 1-D Array Element by Element to function
#include<stdio.h> void
show(int b); void main() {
int arr[3] = {1,2,3}; int i;
for(i=0;i<3;i++) show(arr[i]);
}
void show(int x)
{
printf("%d ",x);
}
Output:
12 3
STRINGS
A string is a sequence of character enclosed with in double quotes (“ ”) but ends with
\0. The compiler puts \0 at the end of string to specify the end of the string.
To get a value of string variable we can use the two different types of formats.
79
Using gets() function as : gets(string variable);
C library supports a large number of string handling functions. Those functions are stored under the header file string.h
in the program.
Syntax
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str[20]; int
strlength; clrscr();
printf(‚Enter String:‛); gets(str);
strlength=strlen(str);
printf(‚Given String Length Is: %d‛, strlength); getch();
}
Output:
Syntax
80
strcat (StringVariable1, StringVariable 2);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20],str2[20]; clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
printf(‚ Concatenation String is:%s‛, strcat(str1,str2)); getch();
}
Output:
Syntax
strcmp(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20]; int res;
81
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmp(str1,str2);
printf(‚ Compare String Result is:%d‛,res); getch();
}
Output:
strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.
Syntax
strcmpi(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20]; int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmpi(str1,str2);
printf(‚ Compare String Result is:%d‛,res); getch();
}
82
Output:
strcpy() function is used to copy one string to another. strcpy() function copy the contents of second string to first
string.
Syntax
strcpy(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str1[20], str2[20]; int res;
clrscr();
printf(‚Enter First String:‛);
scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2); strcpy(str1,str2)
printf(‚ First String is:%s‛,str1); printf(‚
Second String is:%s‛,str2); getch();
}
Output:
83
Syntax
strlwr(StringVariable);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str[20]; clrscr();
printf(‚Enter String:‛); gets(str);
printf(‚Lowercase String : %s‛, strlwr(str)); getch();
}
Output:
Syntax
strrev(StringVariable);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20]; clrscr();
printf(‚Enter String:‛); gets(str);
printf(‚Reverse String : %s‛, strrev(str)); getch();
}
Output:
Syntax
strupr(Stringvariable);
Example:
#include<stdio.h>
#include<conio.h> void
main()
{
char str[20]; clrscr();
printf(‚Enter String:‛); gets(str);
printf(‚Uppercase String : %s‛, strupr(str)); getch();
}
Output:
variables that are defined with in a body of function or block. The local variables can be used only
in that function or block in which they are declared.
Same variables may be used in different functions such as function()
function2 ()
int a=0;
85
b=20;
Global variable:-
the variables that are defined outside of the function is called global variable. All functions in the program can
access and modify global variables. Global variables are automatically initialized at the time of initialization.
Example:
#include<stdio.h> void
function(void); void
function1(void); void
void main()
function1();
function2();
function()
function 1()
{
prinf(“inside function a=%d,b=%d\n”,a,b);
function 2()
{
86
prinf(“inside function a=%d,b=%d\n”,a,);
Static variables: static variables are declared by writing the key word static.
-syntax:-
-the static variables initialized only once and it retain between the function call. If its variable is not
initialized, then it is automatically initialized to zero.
Example:
fun1();
fun2();
void fun1()
{
int a=10, static int b=2; printf(“a=%d,
b=%d”,a,b); a++;
b++;
Output:a= 10 b= 2
a=10 b= 3
87
POINTERS
Definition:-
A pointer is a variable whose value is the address of another variable. Like any variables, we must declare
a pointer variable at the beginning of the program. We can create pointer to any variable type as given in
te below examples.
datatype *pointervariable;
POINTER OPERATORS:
(1) #include<stdio.h>
void main()
{
89
int n = 10;
printf("\nValue of n is : %d",n); printf("\nAddress of
n is : %u",&n);
}
Output :
Value of n is : 10
Address of n is : 1002
Explanation:
Consider the above example, where we have used to print the address of the variable using ampersand
operator.
In order to print the variable we simply use name of variable while to print the address of the variable we
use ampersand along with %u
printf("\nValue of &n is : %u",&n);
(2) #include<stdio.h>
Void main()
{
Int n=20;
Printf(“The value of n is: %d”,n);
Printf(“The address of n is: %u”,&n);
Printf(“The value of n is: %d”,*(&n));
}
OUTPUT:
The value of n is:20
The address of n is:1002 The
value of n is:20
Explanation:
In the above program, first printf displays the value of n. The second printf displays the address of the
variable n i.e) 1002, which is obtained by using &n(address of variable n). The last printf can be
explained as follows,
*(&n) = *(Address of variable n)
=*(1002)
=Value at address 1002
Therefore *(&n)=20
90
UNDERSTANDING ADDRESS OPERATOR
Below example will clearly explain the initialization of Pointer Variable. #include<stdio.h>
int main()
{
return(0);
}
Note :
Pointers are always initialized before using it in the program
#include<stdio.h>
void main()
{
int i = 5;
int *ptr;
ptr = &i;
printf("\nAddress of i : %u",&i);
printf("\nValue of ptr is : %u",ptr);
}
91
OUTPUT:
Address of i : 65524
Value of ptr is : 65524
After assigning the address of variable to pointer, i.e after the execution of this statement – ptr =
&i;
/* Program to display the contents of the variable and their address using pointer variable*/
(1) #include<stdio.h>
main()
{
int i = 3, *j; j
= &i;
92
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3 Value
of i = 3 Value of i = 3
Value of i 3
Value of j 65524
Address of i 65524
Address of j 65522
POINTER EXPRESSIONS
Like any other variables pointer variables can be used in an expression. In general, expressions
involving pointer conform to the same rules as other expressions. The pointer expression is a linear
combination of pointer variables, variables and operators. Pointer expression gives either numerical
output or address output.
Example:
y = *p1 * *p2; sum
= sum + *p1; z = 5
- *p2/*p1;
*p2 = *p2 + 10;
OUTPUT:
Address of a 65522
Address of b 65524
a=30 b=6
93
x=30 y=31
EXPLANATION OF PROGRAM:
In the above example program, ptr1, ptr2 are the pointer variables which are used to store the
address of the two variables a and b respectively using the statements ptr1=&a, ptr2=&b. In the pointer
expressions which are given below, the value of x and y are calculated as follows,
x=*ptr1+ *ptr2 - b;
=30 + 6 – 6
x=30
y=b - *ptr1/ *ptr2 +a;
=6 - 30/6 + 30
=6 – 5 + 30
y=31
POINTER ASSIGNMENT
We can use a pointer on the right-hand side of an assignment statement to assign its value to
another pointer. For example,
#include< stdio.h >
void main()
{
int *p1,*p2;
int x=99;
p1=&x;
p2=p1; /*pointer assignment*/
printf(“\nValues at p1 and p2: %d %d”,*p1,*p2); /*print the value of x twice*/ printf(“\nAddresses
pointed to by p1 and p2: %u %u”,p1,p2); /*print the address of x twice*/
}
OUTPUT:
Values at p1 and p2: 99 99
Addresses pointed to by p1 and p2: 5000 5000
EXPLANATION OF PROGRAM:
After the assignment sequence,
p1=&x;
p2=p1;
Both p1and p2 point to x. Thus both p1 and p2 refer to the same value.
When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address gives location of the first element which is also allocated by the
compiler.
94
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five element will be
stored as follows
Here variable arr will give the base address, which is a constant pointer pointing to the element, arr[0].
Therefore arr is containing the address of arr[0] i.e 1000.
We can declare a pointer of type int to point to the array arr. int
*p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
POINTER TO ARRAY
As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access the
array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
95
#include <stdio.h>
void subtractAndPrint(int x, int y); void
subtractAndPrint(int x, int y) { int z = x -
y;
printf("Simon says, the answer is: %d\n", z);
}
int main()
{
void (*sapPtr)(int, int) = subtractAndPrint; (*sapPtr)(10, 2);
sapPtr(10, 2);
}
The pointer can be used as an argument in functions. The arguments or parameters to the function
are passed in two ways.
Call by value
Call by reference
In ‘C Language there are two ways that the parameter can be passed to a function they are
o Call by value
o Call by reference
Call by Value:
This method copies the value of actual parameter into the formal parameter of the
function.
The changes of the formal parameters cannot affect the actual parameters, because formal
arguments are photocopy of the actual argument.
The changes made in formal argument are local to the block of the called functions. Once control
return back to the calling function the changes made disappear.
Example:
#include<stdio.h>
#include<conio.h>
void cube(int);
int cube1(int);
void main() Output:
{
int a; Enter one values 3
clrscr();
printf(“Enter one values”); scanf(“%d”,&a); Value of cube function is 3
printf(“Value of cube function is=%d”, cube(a)); Value of cube1 function is 729
printf(“Value of cube1 function is =%d”, cube1(a ));
getch();
}
void cube(int x)
{
x=x*x*x*;
return x;
}
int cube1(int x)
{
x=x*x*x*;
96
return x;
}
Call by reference
Call by reference is another way of passing parameter to the function.
Here the address of argument are copied into the parameter inside the function, the
address is used to access arguments used in the call.
Hence changes made in the arguments are permanent.
Here pointer are passed to function, just like any other arguments.
Example:-
#include<stdio.h>
#include<conio.h>
void swap(int,int);
void main()
{ Output:
int a=5,b=10; clrscr();
printf(“Before swapping a=%d b=%d”,a,b); Before swapping a=5 b=10
swap(&a,&b);
After swapping a=10 b=5
printf(“After swapping a=%d b=%d”,a,b); getch();
}
void swap(int *x,int *y)
{
int *t;
t=*x;
*x=*y;
*y=t;
}
A function can return a single value by its name or return multiple values through pointer parameters.
Since pointers are a data type in c, we can also force a function to return a pointer to the calling function.
Program:
int *larger(int*,int*);
void main() Output:
{
int a=10; 20
int b=20;
int *p;
p =larger(&a,&b);
printf(“%d”,*p);
}
int *larger(int *x, int *y)
{
if(*x>*y)
return(x);
else }
97
return (y);
98
};
#include <stdio.h>
struct name{int a;
float b;
};
int main()
scanf("%d",&(*ptr).a);
scanf("%f",&(*ptr).b);
printf("Displaying: ");
99
printf("%d%f",(*ptr).a,
(*ptr).b); return 0;
In this example, the pointer variable of type struct name is referenced to the address of p.
Then, only the structure member through pointer can can accessed.
Structure pointer member can also be accessed using -> operator.
To access members of structure with structure variable, we used the dot . operator. But when we
have a pointer of structure type, we use arrow -> to access structure members.
struct Book
char name[10];
int price;
int main()
struct Book b;
ptr->price = 500;
In this program, “record1″ is normal structure variable and “ptr” is pointer structure variable. As
you know, Dot(.) operator is used to access the data using normal structure variable and arrow(-
#include <stdio.h>
#include <string.h>
struct student
int id;
int main()
int i;
ptr = &record1;
}
101
Output:
Records of STUDENT1:
Id is: 1
Name is: Raju Percentage is: 90.500000
he above program, the pointer *p will print all the values stored in the array one by one. We can also use
the Base address (a in above case) to act as pointer and print all the values.
Notice, that there is equal difference (difference of 1 byte) between any two consecutive elements
of array.
int *ptr;
ptr = &my_array[0]; /* pointer points to the first integer in our array */
And then we could print out our array either using the array notation or by dereferencing our pointer. The
following code illustrates this:
and try once more.Each time try and predict the outcome and carefully look at the actual outcome.
103
In C, the standard states that wherever we might use &var_name[0] we can replace that with var_name,
thus in our code where we wrote:
ptr = &my_array[0];
we can write:
ptr = my_array;
#include<stdio.h>
#include<conio.h>
void main()
{
int numArray[10]; int
i, sum = 0;
int *ptr;
104
for (i = 0; i < 10; i++)
scanf("%d", &numArray[i]);
ptr = numArray;
EXPLANATION OF PROGRAM:
105
print ( &num, 5, num);
}
print ( int *j, int n, int b[5])
{
int i;
for(i=0;i<=4;i++)
106
{
printf ( " %u %d %d %u \n ", &j[i] , *j , *(b+i) , &b); j++;
}
}
In this example we have a single dimensional array num and a function print . We are passing, the address
to the first element of the array, the number of elements and the array itself, to this function. When the
function receives this arguments, it maps the first one to another pointer j and the array num is
copied into another array b . (The type declarations are made here itself. Note that these declarations can
also be given just below this line). j is now a pointer to the array b.
Inside the function we are printing out the address of the array element and the value of the array element in two
ways. One using the pointer j and the other using the array b. If we compile and run this code we get the following
out put,
3221223408 10 10
3221223376
3221223416 20 20
3221223376
3221223424 30 30
3221223376
Note that as we increment j it points to the successive elements of the array. We can get both the address
of the array elements and the value stored there using this. However the array name, which acts also as
the pointer to its base address, is not able to give us the address of its elements. Or in other words, the
array name is a constant pointer. Also note that while j ispoints to the elements of the array num, b is
pointing to its copy.
Next we have an example that uses a two dimensional array. Here care should be taken to declare
the number of columns correctly.
Pointer example-2
#include <stdio.h>
#include <math.h>
main()
107
int I , j ;
Here we have a pointer p and a pointer array q. The first assignment statement is
to make the pointer p points to the array arr. While assigning, we also declare the type
of the variable arr. Note that variables on both side of this statement should have the
same type. Next line is a similar statement, now with q and arr. Since q is a pointer
array, the array can be directly assigned to it and there is no need for specifying the type
of the variable. In the next line we make the pointer r to point to the pointer array q .
Then we will print out the different values. Here is what we get from this,
ARRAY OF POINTERS
Just like array of integers or characters, there can be array of pointers too. An array of pointers can be
declared as :
For example :
char *ptr[3];
The above line declares an array of three character pointers. Let’s take a working example :
108
#include<stdio.h
> int main(void)
{
char *p1 =
"Himanshu"; char *p2
= "Arora"; char *p3 =
"India";
char *arr[3];
arr[0] =
p1; arr[1]
= p2;
arr[2] =
p3;
p1 =
[Himanshu] p2
= [Arora]
p3 = [India]
arr[0] =
[Himanshu] arr[1]
= [Arora] arr[2] =
So we see that array now holds the address of strings.
Let us consider the following example, which makes use of an array of 3 integers:
int main ()
{
109
int var[] = {10, 100, 200};
int i;
OUTPUT:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
There may be a situation when we want to maintain an array, which can store pointers to an int or char or
any other data type available. Following is the declaration of an array of pointers to an integer:
int *ptr[3];
This declares ptr as an array of 3 integer pointers. Thus, each element in ptr, now holds a pointer to an int
value.
Following example makes use of three integers, which will be stored in an array of pointers as follows:
OUTPUT:
Value of var[0] = 10
Value of var[1] = 100
110
Value of var[2] = 200
111
UNIT V
STRUCTURES
Arrays are used for storing a group of SIMILAR data items. In order to store a group of data
items, we need structures. Structure is a constructed data type for packing different types of data that are
logically related. The structure is analogous to the “record” of a database. Structures are used for
organizing complex data in a simple and meaningful way.
Structure Definition
Structures are defined first and then it is used for declaring structure variables. Let us see how to
define a structure using simple example given below:
struct book
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};
The keyword “struct” is used for declaring a structure. In this example, book is the name of the structure
or the structure tag that is defined by the struct keyword. The book structure has six fields and they are
known as structure elements or structure members. Remember each structure member may be of a
112
different data type. The structure tag name or the structure name can be used to declare variables of the
structure data type.
struct tagname
Data_type member1;
Data_type member2;
…………….
……………
};
Note:
1. To mark the completion of the template, semicolon is used at the end of the template.
2. Each structure member is declared in a separate line.
First, the structure format is defined. Then the variables can be declared of that structure type. A structure
can be declared in the same way as the variables are declared. There are two ways for declaring a
structure variable.
1) Declaration of structure variable at the time of defining the structure (i.e structure
definition and structure variable declaration are combined)
struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
} b1,b2,b3;
The b1, b2, and b3 are structure variables of type struct book.
NOTE:
Structure tag name is optional.
E.g.
struct
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
}b1, b2, b3;
114
Declaration of structure variable at a later time is not possible with this type of declaration. It is a
drawback in this method. So the second method can be preferred.
Structure members are not variables. They don‟t occupy memory until they are
associated with a structure variable.
Syntax
STRUCTURE_Variable.STRUCTURE_Members
The different ways for storing values into structure variable is given below:
b1.pages = 786;
b1.price = 786.50;
strcpy(b1.author, ‚John‛);
Example
115
#include<stdio.h>
#include<conio.h>
struct book
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};
116
Enter the Book Id: 786
Enter the Book Name: Programming Enter
the Author Name: John Enter the
Price: 123.50
Enter the Year: 2015
Enter the Total No. of Pages: 649 Enter the
Publisher Name: Tata McGraw
786 Programming 2118 123.500000 2015 649 Tata
Structure Initialization
Example
main()
{
struct
{
int rollno;
int attendance;
}
s1={786, 98};
}
The above example assigns 786 to the rollno and 98 to the attendance. Structure
Example
main()
{
struct student
{
int rollno;
int attendance;
};
struct student s1={786, 98};
struct student s2={123, 97};
}
Note:
117
Individual structure members cannot be initialized within the template. Initialization is possible only with
the declaration of structure members.
Structures can also be nested. i.e A structure can be defined inside another structure.
Example
struct employee
{
int empid;
char empname[20];
int basicpay;
int da;
int hra;
int cca;
} e1;
In the above structure, salary details can be grouped together and defined as a separate structure.
Example
struct employee
{
int empid;
char empname[20];
struct
{
int basicpay;
int da;
int hra;
int cca;
} salary;
} e1;
The structure employee contains a member named salary which itself is another structure that contains
four structure members. The members inside salary structure can be referred as below:
e1.salary.basicpay
e1.salary.da;
e1.salary.hra;
e1.salary.cca;
118
However, the inner structure member cannot be accessed without the inner structure variable.
Example
e1.basicpay
e1.da e1.hra
e1.cca
are invalid statements
Moreover, when the inner structure variable is used, it must refer to its inner structure member. If it
doesn‟t refer to the inner structure member then it will be considered as an error.
Example
e1.salary (salary is not referring to any inner structure member. Hence it is wrong)
Array of Structures
A Structure variable can hold information of one particular record. For example, single record of
student or employee. Suppose, if multiple records are to be maintained, it is impractical to create multiple
structure variables. It is like the relationship between a variable and an array. Why do we go for an array?
Because we don‟t want to declare multiple variables and it is practically impossible. Assume that you
want to store 1000 values. Do you declare 1000 variables like a1, a2, a3…. Upto a1000? Is it easy to
maintain such code ? Is it a good coding? No. It is not. Therefore, we go for Arrays. With a single
name, with a single variable, we can store 1000 values. Similarly, to store 1000 records, we cannot declare
1000 structure variables. But we need “Array of Structures”.
An array of structure is a group of structure elements under the same structure variables.
The above code creates 1000 elements of structure type student. Each element will be structure
data type called student. The values can be stored into the array of structures as follows:
s1[0].student_age = 19;
Example
119
#include<stdio.h>
#include<conio.h>
struct book
{
int bookid;
char bookname[20];
char author[20];
};
Struct b1[5];
main()
{
int i;
clrscr();
for (i=0;i<5;i++)
{
printf("Enter the Book Id: ");
scanf("%d", &b1[i].bookid);
printf("Enter the Book Name: ");
scanf("%s", b1[i].bookname);
printf("Enter the Author Name: ");
scanf("%s", b1[i].author);
}
for (i=0;i<5;i++)
{
printf("%d \t %s \t %s \n", b1[i].bookid, b1[i].bookname, b1[i].author);
}
getch();
}
Output:
Example
struct sample
{
int no;
float avg;
} a;
121
void main( )
{
a.no=75;
a.avg=90.25;
fun(a);
}
Output
Method 1 :- Individual member of the structure is passed as an actual argument of the function call. The
actual arguments are treated independently. This method is not suitable if a structure is very large
structure.
Method 2:- Entire structure is passed to the called function. Since the structure declared as the
argument of the function, it is local to the function only. The members are valid for the
function only. Hence if any modification done on any member of the structure , it is not reflected in the
original structure.
Method 3 :- Pointers can be used for passing the structure to a user defined function. When the pointers
are used , the address of the structure is copied to the function. Hence if any modification done on any
member of the structure , it is reflected in the original structure.
{
Local Variable declaration;
Statement 1;
122
Statement 2;
--------------
-------------
Statement n;
}
Example :
#include <stdio.h>
struct st
{
char name[20];
int no;
int marks;
};
int main( )
{
struct st x ,y;
int res;
printf(‚\n Enter the First Record‛);
scanf(‚%s%d%d‛,x.name,&x.no,&x.marks);
printf(‚\n Enter the Second Record‛);
scanf(‚%s%d%d‛,y.name,&y.no,&y.marks); res
= compare ( x , y );
if (res == 1)
printf(‚\n First student has got the Highest Marks‛);
else
printf(‚\n Secondstudent has got the Highest Marks‛);compare ( struct st st1 , struct
st st2)
{
if (st1.marks > st2. marks )
return ( 1 );
else
return ( 0 );
}
In the above example , x and y are the structures sent from the main ( ) function as the actual
parameter to the formal parameters st1 and st2 of the function compare ( ).
#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
123
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example *sptr)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr->num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr->num2);
}
//-------------------------------------
void print(struct Example *sptr)
{
printf("\nNum1 : %d",sptr->num1);
printf("\nNum2 : %d",sptr->num2);
}
//-------------------------------------
void main()
{
int i;
clrscr();
for(i=0;i<3;i++)
accept(&s[i]);
for(i=0;i<3;i++)
print(&s[i]);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
124
In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can be
accessed from called function. This concept is very useful while writing very big programs in C.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void main()
{
struct student record;
record.id=1; strcpy(record.name,
"Raju"); record.percentage =
86.5;
func(record);
getch();
}
A structure variable can be passed to the function as an argument as normal variable. If structure is
passed by value, change made in structure variable in function definition does not reflect in original
structure variable in calling function.
125
Write a C program to create a structure student, containing name and roll. Ask user the name and
roll of a student in main function. Pass this structure to a function and display the information in
that function.
#include <stdio.h>
struct student
{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration otherwise
compiler shows error */
int main()
{
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name); printf("Enter
roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument return
0;
}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Output
In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to another
function with all members and their values. So, this structure can be accessed from called function by its
address.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
126
void func(struct student *record);
void main()
{
struct student record;
record.id=1; strcpy(record.name,
"Raju"); record.percentage =
86.5;
func(&record);
getch();
}
Id is: 1
Name is:
Raju
Percentage is: 86.500000
The address location of structure variable is passed to function while passing it by reference. If
structure is passed by reference, change made in structure variable in function definition reflects in
original structure variable in the calling function.
127
Write a C program to add two distances(feet-inch system) entered by user. To solve this program,
make a structure. Pass two structure variable (containing distance in feet and inch) to add function
by reference and display the result in main function without returning it.
#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3); int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet); printf("Enter
inch: "); scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet); printf("Enter
inch: "); scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3);
/*passing structure variables dist1 and dist2 by value whereas passing structure
variable dist3 by reference */
printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch); return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3)
{
/* Adding distances d1 and d2 and storing it in d3 */ d3-
>feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) { /* if inch is greater or equal to 12,
converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}
Output
First distance
Enter feet: 12
Enter inch: 6.8
128
Second distance
Enter feet: 5
Enter inch: 7.5
Sum of distances = 18'-2.3"
Explanation
In this program, structure variables dist1 and dist2 are passed by value (because value of dist1 and dist2
does not need to be displayed in main function) and dist3 is passed by reference ,i.e, address of dist3
(&dist3) is passed as an argument. Thus, the structure pointer variable d3 points to the address of dist3. If
any change is made in d3 variable, effect of it is seed in dist3 variable in main function.
Structure variables also can be declared as global variables as we declare other variables in C.
So, When a structure variable is declared as global, then it is visible to all the functions in a program. In
this scenario, we don‟t need to pass the structure to any function separately.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure void
structure_demo();
int main()
{
record.id=1; strcpy(record.name,
"Raju"); record.percentage =
86.5;
structure_demo();
return 0;
}
void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
129
Output:
Id is: 1
Name is:
Raju
Percentage is: 86.500000
Array of Structure can be passed to function as a Parameter.function can also return Structure as return
type.Structure can be passed as follow
Example :
#include<stdio.h>
#include<conio.h>
//-------------------------------------
struct Example
{
int num1;
int num2;
}s[3];
//-------------------------------------
void accept(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nEnter num1 : ");
scanf("%d",&sptr[i].num1);
printf("\nEnter num2 : ");
scanf("%d",&sptr[i].num2);
}
}
//-------------------------------------
void print(struct Example sptr[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\nNum1 : %d",sptr[i].num1);
printf("\nNum2 : %d",sptr[i].num2);
}
}
//-------------------------------------
void main()
{
130
int i;
clrscr();
accept(s,3);
print(s,3);
getch();
}
Output :
Enter num1 : 10
Enter num2 : 20
Enter num1 : 30
Enter num2 : 40
Enter num1 : 50
Enter num2 : 60
Num1 : 10
Num2 : 20
Num1 : 30
Num2 : 40
Num1 : 50
Num2 : 60
Explanation :
Inside main structure and size of structure array is passed. When reference (i.e ampersand) is not specified
in main , so this passing is simple pass by value. Elements can be accessed by using dot [.] operator
Union
The concept of Union is borrowed from structures and the formats are also same. The distinction
between them is in terms of storage. In structures , each member is stored in its own location but in Union
, all the members are sharing the same location. Though Union consists of more than one members , only
one member can be used at a particular time. The size of the cell allocated for an Union variable depends
upon the size of any member within Union occupying more no:- of bytes. The syntax is the same as
structures but we use the keyword union instead of struct.
union emp
{
char name[20];
int eno; float
salary;
} employee;
where employee is the union variable which consists of the member name,no and
salary. The compiler allocates only one cell for the union variable as
131
20 Bytes Length
20 bytes cell can be shared by all the members because the member name is occupying the highest no:- of
bytes. At a particular time we can handle only one member.To access the members of an union , we have
to use the same format of structures.
union student
{
char name[20]; char
subject[20]; float
percentage;
};
int main()
{
union student record1;
union student record2;
132
printf(" Name : %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
133
record2.percentage = 99.50;
Output:
Union r
Name :
Subject
Percent
Union r
example
Subject
Percent
134
Explanation for above C union program:
There are 2 union variables declared in this program to understand the difference in accessing values
of union members.
Then, “Maths” is assigned to union member “record1.subject”. Now, memory location name is
changed to “record1.subject” with the value “Maths” (Union can hold only one member at a
time).
Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location name
is changed to “record1.percentage” with value “86.50”.
Like this, name and value of union member is replaced every time on the common storage space.
So, we can always access only one union member for which value is assigned at last.
If we want to access all member values using union, we have to access the member before
assigning values to other members as shown in record2 union variable in this program.
Each union members are accessed in record2 example immediately after assigning values to
them.
If we don‟t access them before assigning values to other member, member name and value
will be over written by other member as all members are using same memory.
We can‟t access all members in union at same time but structure can do that.
In this program, union variable “record” is declared while declaring union itself as shown in the
below program.
#include <stdio.h>
135
#include <string.h>
union student
{
char name[20]; char
subject[20]; float
percentage;
}record;
int main()
{
strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;
Name
Subjec
:
Percen
136
Note:
We can access only one member of union at a time. We can‟t access all member values at the same
time in union. But, structure can access all member values at the same time. This is because, Union
allocates one common storage space for all its members. Where as Structure allocates storage space for all
its members separately.
Union allocates one common storage space for all its members.
Structure allocates storage Union finds that which of its member needs high storage space
1 space for all its members over other members and allocates that much space
separately.
{ {
int mark; char int mark; char
name[6]; name[6];
double average; double average;
}; };
137
1. Write a C program to initialize an array using functions.
#include<stdio.h> int
main()
int k, c(), d[ ]={c(),c(),c(),c(),c()};
printf(‚\nArray d[] elements are:‛);
for(k=0;k<5;k++)
printf(‚%2d‛,d[k]);
return(0);
}
c()
{
int m,n; m++;
printf(‚\nEnter number d[%d] : ‛,m);
scanf(‚%d‛,&n);
return(n);
}
Output:
13
8
printf(‚Enter 10 Numbers :‛);
for(x=0;x<10;x++)
{
if(x<5)
a[x]=read(); else
b[x-5]=read();
}
printf(‚\nArray A & B‛);
for(x=0;x<5;x++)
{
printf(‚\n%7d%8d‛,a[x],b[x]);
change(&a[x],&b[x]);
}
printf(‚\nNow A & B‛);
for(x=0;x<5;x++)
{
printf(‚\n%7d%8d‛,a[x],b[x]);
}
}
int read()
{
int x;
scanf(‚%d‛,&x);
return(x);
}
void change(int *a,int *b)
{
int *k;
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
Output:
Enter 10 Numbers:
13
9
0123456789
Array A & B 0
5
1 6
2 7
3 8
4 9
Now A & B 5 0
6 1
7 2
8 3
9 4
14
0
FUNCTION
A function is a self contained block of codes or sub programs with a set of statements that perform
some specific task or coherent task when it is called.
It is something like to hiring a person to do some specific task like, every six months servicing a
bike and hand over to it.
Any ‘C’ program contain at least one function i.e main(). There are basically
1. Library function
System defined function can’t be modified, it can only read and can be used. These function are
supplied with every C compiler
Source of these library function are pre complied and only object code get used by the user by linking to
the code by linker
Syntax:-
Return type name of function (type 1 arg 1, type2 arg2, type3 arg3) Return type
So when user gets his own function three thing he has to know, these are.
Function declaration
Function definition
Function call
14
1
These three things are represented like
function(arg1,arg2,arg3);
Statement;
Return value;
}
Function declaration:-
Function declaration is also known as function prototype. It inform the compiler about three thing, those
are name of the function, number and type of argument received by the function and the type of value
returned by the function.
While declaring the name of the argument is optional and the function prototype always terminated by
the semicolon.
Function definition:-
Function definition consists of the whole description and code of the function. It tells about what
function is doing what are its inputs and what are its out put It consists of two parts function header
Syntax:-
return type function(type 1 arg1, type2 arg2, type3 arg3) /*function header*/
Statement 1;
14
2
Statement 2;
Return value
The return type denotes the type of the value that function will return and it is optional and if it is
omitted, it is assumed to be int by default. The body of the function is the compound statements or
block which consists of local variable declaration statement and optional return statement.
The local variable declared inside a function is local to that function only. It can’t be used anywhere in
the program and its existence is only within this function.
Function Call
When the function get called by the calling function then that is called, function call. The compiler
execute these functions when the semicolon is followed by the function name.
Example:-
function(arg1,arg2,arg3);
The argument that are used inside the function call are called actual argument
Ex:-
Actual argument
The arguments which are mentioned or used inside the function call is knows as actual argument and
these are the original values and copy of these are actually sent to the called function
It can be written as constant, expression or any function call like Function (x);
(a*b, c*d);
Function(2,3,sum(a, b));
Formal Arguments
The arguments which are mentioned in function definition are called formal arguments or dummy
arguments.
These arguments are used to just hold the copied of the values that are sent by the calling function
14
3
through the function call.
These arguments are like other local variables which are created when the function call starts and
destroyed when the function ends.
The basic difference between the formal argument and the actual argument are
1) The
formal argument are declared inside the parenthesis where as the local variable
declared at the beginning of the function block.
2). The formal argument are automatically initialized when the copy of actual arguments are
passed while other local variable are assigned values through the statements.
Order number and type of actual arguments in the function call should be match with the order number
and type of the formal arguments.
Return type
It is used to return value to the calling function. It can be used in two way as return
Or return(expression); Ex:-
return (a);
return (a*b);
return (a*b+c);
st
Here the 1 return statement used to terminate the function without returning any value
main()
{
int a,b;
scanf(“%d%d”,&a,&b); int
S=sum(a,b);
printf(“summation is = %d”,s);
{
14
4
int z=x1+y1;
Return z;
Advantage of function
By using function large and difficult program can be divided in to sub programs and solved. When we
want to perform some task repeatedly or some code is to be used more than once at different place in the
program, then function avoids this repeatition or rewritten over and over.
Notes:-
main()
{
function1()
function1()
Statement;
function2;
function 2()
So every function in a program must be called directly or indirectly by the main() function. A function
can be called any number of times.
A function can call itself again and again and this process is called recursion.
14
5
A function can be called from other function but a function can’t be defined in another function
14
6
Function that have no argument and no return value is written as:- void function(void);
main()
void function()
Statement;
Example:- void
me();
main()
me();
printf(“in main”);
void me()
printf(“come on”);
Output: come on
inn main
70
ii) Function with no argument but return value
Syntax:-
int fun(void);
main()
int r;
r=fun();
int fun()
reurn(exp);
Example:- int
sum();
main()
%d\n, b”);
int sum()
int a,b,s;
71
s=a+b;
return s;
Here called function is independent and are initialized. The values aren’t passed by the calling
function .Here the calling function and called function are communicated partly with each other.
Here the function have argument so the calling function send data to the called function but called
function dose n’t return value.
Syntax:-
main()
int (a,b);
Statement;
72
Here the result obtained by the called function.
Here the calling function has the argument to pass to the called function and the called function
returned value to the calling function.
Syntax:-
fun(int,int);
main()
int r=fun(a,b);
int fun(intx,inty)
{
return(exp);
}
Example:
main()
{
a,num;
73
int num=fun(a);
int fun(int x)
++x;
return x;
}
There are two way through which we can pass the arguments to the function such as call by value and
call by reference.
1. Call by value
In the call by value copy of the actual argument is passed to the formal argument and the operation is
done on formal argument.
When the function is called by ‘call by value’ method, it doesn’t affect content of the actual argument.
Changes made to formal argument are local to block of called function so when the control back to calling
function the changes made is vanish.
Example:-
main()
int x,y;
change(int,int);
74
printf(“enter two values:\n”);
scanf(“%d%d”,&x,&y);
change(x ,y);
int k;
k=a;
a=b;
b=k;
2. Call by reference
Instead of passing the value of variable, address or reference is passed and the function operate on
address of the variable rather than value.
Here formal argument is alter to the actual argument, it means formal arguments calls the actual
arguments.
Example:-
void main()
75
{
int a,b;
values:\n”); scanf(“%d%d”,&a,&b);
change(&a,&b);
int k;
k=*a;
*a=*b;
*b= k;
So here instead of passing value of the variable, directly passing address of the variables. Formal argument
directly access the value and swapping is possible even after calling a function.
76
Recursion
When function calls itself (inside function body) again and again then it is called as recursive
function. In recursion calling function and called function are same. It is powerful technique of writing
complicated algorithm in easiest way. According to recursion problem is defined in term of itself. Here
statement with in body of the function calls the same function and same times it is called as circular
definition. In other words recursion is the process of defining something in form of itself.
Syntax:
main ()
rec();
fact(int);
void main()
80 *Under revision
{
int num;
printf(“enter a number”);
scanf(“%d”,&num);
f=fact(num);
printf(“factorial is =%d\
n”f);
If (num==0||num==1)
retu
rn
1;
else
return(num*fact(num-1));
MCQ
1.All keywords in C are in ____________
a) LowerCase letters
b) UpperCase letters
c) CamelCase letters
d) None of the mentioned
Answer: a
2. Which of the following is not a valid C variable name?
a) int number;
b) float rate; 81 *Under revision
c) int variable_count;
d) int $main;
Answer: d
3. Who invented C Language.?
A) Charles Babbage
B) Grahambel
C) Dennis Ritchie
D) Steve Jobs
ANS: A
4. C Language is a successor to which language.?
A) FORTRAN
B) D Language
C) BASIC
D) B Language
ANS :D
5. C language was invented in the year.?
A) 1999
B) 1978
C) 1972
D) 1990
ANS :C
6. A C program is a combination of.?
A) Statements
B) Functions
C) Variables
D) All of the above
ANS :D
7. Which of the following special symbol allowed in a variable name?
A.* (asterisk)
B.| (pipeline)
C.- (hyphen)
D._ (underscore)
Answer: Option D
82 *Under revision
8. How would you round off a value from 1.66 to 2.0?
A.ceil(1.66)
B.floor(1.66)
C.roundup(1.66)
D.roundto(1.66)
Answer: Option A
9. The keyword used to transfer control from a function back to the calling function is
A.switch
B.goto
C.go back
D.return
Answer: Option D
10.
In C, if you pass an array as an argument to a function, what actually gets passed?
83 *Under revision