C Notes Annai
C Notes Annai
1 INTRODUCTION TO C 1-27
3 ARRAYS 53-70
1
PROGRAMMING IN C
Objective:
To impart basic knowledge of Programming Skills in C language.
Unit I
Introduction to C – Constants, Variables, Data types – Operator and Expressions.
Unit II
Managing Input and Output operations – Decision Making and Branching – Decision making and Looping.
Unit III
Arrays – Character Arrays and Strings – User defined Functions.
Unit IV
Structures and unions – Pointers – File management in C.
Unit V
Dynamic memory allocation – Linked lists- Preprocessors – Programming Guide lines.
Text Book:
1. Balagurusamy E .,Programming in ANSI C , Sixth Edition, McGraw-Hill, 2012
Reference Book:
1. R.S.Bichkar, Programming with C, University Press, 2012
2
UNIT-I
INTRODUCTION TO C
History of C
C language is developed by Mr. Dennis Ritchie in the year 1972 at bell laboratory at USA,
C is a simple and structure Oriented Programming Language.
In the year 1988 C programming language standardized by ANSI
(American national standard institute), that version is called ANSI-C.
In the year of 2000 C programming language standardized by ISO that version is called C-99.
All other programming languages were derived directly or indirectly from C programming concepts
.
Overview of C
C is a computer programming language developed in 1972 by Dennis M. Ritchie at the Bell
Laboratories
C is a simple and structure oriented programming language.
C is also called mother Language of all programming Language.
It is the most widely used computer programming language, this language is used for develop
system software and Operating System.
All other programming languages were derived directly or indirectly from C programming
concepts.
It is a robust language with rich set of built-in functions and operators that can be used to write
any complexprogram.
The C compiler combines the capabilities of an assembly language with features of a high-level
language.
Programs Written in C are efficient and fast. This is due to its variety of data type and
powerful operators.
It is many time faster thanBASIC.
C is highly portable this means that programs once written can be run on another machines with little
or nomodification.
Another important feature of C program, is its ability to extenditself.
A C program is basically a collection of functions that are supported by C library. We can also create
our own function and add it to Clibrary.
C language is the most widely used language in operating systems and embedded system
development today.
3
SIMPLE C PROGRAM:(Compile and Run)
Using an IDE - Turbo C
We will recommend you to useTurbo C IDE, oldest IDE for c programming.
It is freely available over internet and is good for abeginner.
Step 1 :Open turbo C IDE(Integrated Development Environment), click on File and then click on New
4
Step 3 :Click on compile or press Alt+f9 to compile the code
Step 5 :Output
5
Difference between Compile and Run
You must be thinking why it is a 2 step process, first we compile the code and then we run the code.
So, compilation is the process where the compiler checks whether the program is correct syntax
wise, and there are no errors in thesyntax.
When we run a compiled program, then it actually executes the statements inside
themain()function.
Documentation Section
This section consists of comment lines which include the name of programmer, the author and
other details like time and date of writing theprogram.
Documentation section helps anyone to get an overview of theprogram.
There are two ways in which we can writecomments.
Using // - This is use to write a single linecomment.
Using /* */ - The statements enclosed within /* and */ , are used to write multi-
line comments.
Example of comments :
6
Link Section
The link section consists of the header files of the functions that are used in the program. It provides
instructions to the compiler to link functions from the system library.
Example:
#include<stdio.h>
#include<conio.h>
#include<math.h>
Definition Section
All the symbolic constants are written in definitionsection.
Macros are known as symbolicconstants.
Example:
#define PI3.14
#define TRUE1
There are some variables that are used in more than onefunction.
Such variables are called global variables and are declared in the global declaration section that is
outside of all thefunctions.
This section also declares all theuser-defined functions.
Example:
int total ;
1. Declaration part: The declaration part declares all thevariablesused in the executablepart.
2. Executable part: There is at least one statement in the executablepart.
These two parts must appear between the opening and closingbraces.
Theprogram executionbegins at the opening brace and ends at the closingbrace.
The closing brace of the main function is the logical end of theprogram.
All statements in the declaration and executable part end with asemicolon.
Subprogram section:
If the program is amulti-function programthen the subprogram section contains all theuser-
defined functionsthat are called in the main ()function.
User-defined functions are generally placed immediately after the main () function, although
they may appear in anyorder.
7
Example of Basic Structure of C Program:
Output:
CHARACTER SET:
Characters are used in forming either words or numbers or even expressions in Cprogramming.
Characters in C are classified into 4groups:
i. Letters:
In C programming, we can use both uppercase and lowercase letters of English language
Uppercase Letters: A to Z
Lowercase Letters: a to z
8
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
ii. Digits:
iv. WhiteSpaces:
In C Programming, white spaces contains:
BlankSpaces
Tab
CarriageReturn
NewLine
9
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
CTOKENS:
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
Each and every smallest individual units in a C program are known as Ctokens.
Do if static while
IDENTIFIERS:
10
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
CONSTANTS:
Constants refer to fixed values. They are also called as
literals. Constants are categorized into two basic types
Real Constant:
A real constant is combination of a whole number followed by a decimal point
and the fractional part. Example: 0.0083 -0.75 .95215.
Integer numbers are inadequate to represent quantities that vary continuously,
suchas distances, heights, temperatures, prices and soon.
11
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
The exponent is an integer with an optional plus or minus sign followed by a series ofdigits.
The letter e separating the mantissa and the exponent can be written in either lowercase
or uppercase.
Example: 0.000342 can be represented in exponential form as 3.42e-4
7500000000 can be represented in exponential form as 7.5e9 or75E8
Single Character Constants
It simply contains a single character enclosed within ' and ' (a pair of singlequote).
It is to be noted that the character '8' is not the same as8.
Character constants have a specific set of integer values known as ASCII values
(American Standard Code for InformationInterchange).
Example:
'X' '5' ';'
String Character Constants
These are a sequence of characters enclosed in double quotes, and they may include letters,
digits, special characters, and blankspaces.
Itisagaintobenotedthat"G"and'G'aredifferent-because"G"representsastringasitis
enclosed within a pair of double quotes whereas 'G' represents a single character.
Example:
"Hello!", "2015", "2+1"
Backslash character constant
Although it consists of two characters, it represents singlecharacter.
12
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
DATA TYPES:
Datatypes is a data storage format that can contain a specific type or range ofvalues.
The kind of data that variables may hold in a programming language are called as datatypes.
C data types can be classifies into 3 categories.
1. Primary data types (or fundamental datatypes)
2. Derived datatypes
3. User defined datatypes
All C compiler supports five fundamental data types, namely integer(int), character (char),
floating point (float), double-precision floating point (double),void.
Integer Datatype:
Integer datatype is a set of wholenumbers.
Every integer value does not have the decimal value. We use the keyword "int" to represent integer
data type inc.
We use the keyword int to declare the variables and to specify return type of afunction.
The integer data type is used with different type modifiers like short, long, signed andunsigned.
The following table provides complete details about integer datatype.
13
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
Void Types:
The void data type means nothing or novalue.
Generally, void is used to specify a function which does not return anyvalue.
We also use the void data type to specify empty parameters of afunction.
VARIABLES
Variable is a data name that may be used to store a datavalue.
variables are changeable, we can change value of a variable during execution of aprogram.
A programmer can choose a meaningful variablename.
A variable must be declared before it can bedefined.
Example : average, height, age, total etc….
Datatype of Variable:
A variable in C language must be given a type, which defines what type of data the
variablewill hold.
char: Can hold/store a character init.
Declaration of variables:
Declaration of variables must be done before they are used in theprogram.
Declaration does twothings.
1. It tells the compiler what the variable nameis.
2. It specifies what type of data the variable willhold.
Until the variable is defined the compiler doesn't have to worry about allocating memory space
to thevariable.
Syntax:
Data_type v1,v2, ……… vn;
v1,v2,…..vn are the names ofvariables.
Variables are separated by commas( ,).
A declaration statement must end with a semicolon( ;).
For example:
int number, total;
floatprice;
doubleratio;
Syntax
data_type variable_name = constant/
expression; or
variable_name = constant /expression;
Example
15
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
int a = 10;
int a = b+c;
a = 10;
a = b+c;
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b, sum; //variable declaration
a=10; //variable initialization
b=20; //variable initialization
sum=a+b; // executable part
printf("Sum is %d",sum);
getch();
}
Output:
Sum is 30
Syntax: storage_class_specifierdata_typevariable_name;
16
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
#include<stdio.h>
int main()
{
register int i;
for(i=1; i<=100; i+
+)
printf("n%d",i);
return 0;
Static Variable (static): }
A static variable is declared by using keywordstatic.
The variables declared with static storage class specifier are initialized with zero initial
value if any initial value is not provided at the time of declaration and it can be accessed
from anywhere within the block in which it isdefined.
However, the variables declared with static storage class are not destroyed even after
program control exits from the block. Thus, the value of the variable persists between
different functioncalls.
#include<stdio.h>
increment()
{
static int i=1;
printf("%dn",i);
i++;
}
17
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
main()
{
increment();
increment();
increment();
return 0;
}
Output
1
2
3
#include<stdio.h>
int i;
main()
{
printf("ni=%d",i);
increment();
increment();
decrement();
decrement();
}
increment()
{
i++;
printf("nOn increment, i=%d",i);
}
decrement()
{
i--;
printf("nOn decrement, i=%d",i);
}
Output
i=0
On increment, i=1
On increment, i=2
On decrement,
i=1 On
decrement, i=0
18
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
a = 100.0000
b=1000.0000
c= 900.0000
PI= 3.14
19
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
Types Of C Operators:
C language offers many types of operators. They are,
1. Arithmeticoperators
2. Assignmentoperators
3. Relationaloperators
4. Logicaloperators
5. Bit wiseoperators
6. Conditional operators (ternaryoperators)
7. Increment/decrementoperators
8. Specialoperators
Arithmetic Operators:
C programming language provides all basic arithmetic operators: +, -, *, / and%.
20
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
i) IntegerArithmetic:
When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operations is called
integerarithmetic.
Example, if a and b are integers, a=14 andb=4,
a + b=14 a – b=10 a * b=56 a / b=3 a % b = 2 (remainder ofdivision)
ii) RealArithmetic:
An arithmetic operation involving only real operands is called realarithmetic.
A real operand may assume values either in decimal or exponentialnotation.
The modulo division operator % cannot be used with realoperands.
Example: x= 6.0 / 7.0=0.857143 and y = 1.35 + 2.0 =3.35
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 12, b = 3;
int addition, subtraction, multiplication, division, modulus;
clrscr( );
getch( );
21
}
22
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
Relational Operator:
Relational operators are commonly used to check the relationship between twovariables.
If the relation is true then it will return value 1 or if the relation is false then it will return value0.
C programming offers 6 relationaloperators.
#include<stdio.h> OUTPUT:
#include<conio.h>
void main()
{
int a = 9, b=4;
clrscr( );
getch( );
}
Logical Operators:
Logical operators are used when more than one conditions are to be tested and based on
thatresult, decisions have to bemade.
C programming offers three logical operators. Theyare:
23
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
Forexample: a <18 || a>60 a > b && a>c a = b && x==10
An expression which combines two or more relational expressions is known as logicalexpression.
Assignment Operators:
Assignment operators are used to assign result of an expression to avariable.
‘ = ’ is the assignment operator inC.
Furthermore, C also allows the use of shorthand assignmentoperators.
Shorthand operators take theform:
var op = exp;
where var is a variable, op is arithmetic operator, exp is an expression.
In this case, ‘op=’ is known as shorthand assignment operator.
The above assignment
var op = exp;
is the same as the assignment
var =var opexp;
Consider an example:
24
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
Increment and Decrement Operators:
C programming allows the use of ++ and – operators which are increment and decrement
operators respectively.
Both the increment and decrement operators are unaryoperators.
The increment operator ++ adds 1 to the operand and the decrement operator – subtracts 1 from the
operand.
The general syntax of these operatorsare:
IncrementOperator: m++ or ++m;
Decrement Operator: m- - or - - m;
In the example above, m++ simply means m=m+1; and m-- simply meansm=m-1;
Increment and decrement operators are mostly used in for and whileloops.
Conditional Operator
The operator pair “?” and “:” is known as conditionaloperator.
These pair of operators are ternaryoperators.
The general syntax of conditional operatoris:
25
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
if (a > b)
x=a;
else
x=b;
Now, this if else statement can be written by using conditional operator as:
x = (a > b) ? a : b ;
Exampleprogram:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int a=10, b=20,c ; int a=40, b=20;
clrscr( ); clrscr( );
BitwiseOperators:
In C programming, bitwise operators are used for testing the bits or shifting them left orright.
The bitwise operators available in Care:
26
PROGRAMMING IN C | A HEMAPRIYA, M.Sc. M.Phil., ASST.PROF
Special Operators
C programming supports special operators like comma operator, sizeof operator, pointer
operators (& and *) and member selection operators (. and->).
The comma operator and sizeof operator are discussed in this section whereas the pointer
and member selection operators are discussed in latersections.
1. CommaOperator
The comma operator can be used to link the related expressionstogether.
A comma linked expression is evaluated from left to right and the value of the right
most expression is the value of the combinedexpression.
In this example, the expression is evaluated from left to right. So at first, variable a is
assigned value 2, then variable b is assigned value 4 and then value 6 is assigned to the
variablex.
Comma operators are commonly used in for loops, while loops, while exchanging values,etc.
2 .Sizeof( ) operator
The sizeof operator is usually used with an operand which may be variable, constant or a data
type qualifier.
This operator returns the number of bytes the operandoccupies.
Sizeof operator is a compile timeoperator.
x = sizeof (a);
y =sizeof(float);
The sizeof operator is usually used to determine the length of arrays and structures when their
sizes are not known. It is also used in dynamic memoryallocation.
ARITHMETIC EXPRESSIONS:
Arithmetic expression in C is a combination of variables, constants and operators written in
a propersyntax.
C can easily handle any complex mathematical expressions but these mathematical
expressions have to be written in a propersyntax.
Some examples of mathematical expressions written in proper syntax of Care:
27
Evaluation of Expressions:
Expressions are evaluated using an assignment statement of theform:
Expressions are evaluated based on operator precedence and associativity rules when
anexpression contains more than oneoperator.
C Operator Precedence
At first, the expressions within parenthesis areevaluated.
If no parenthesis is present, then the arithmetic expression is evaluated from left toright.
There are two priority levels of operators inC.
High priority :* /%
Low priority :+ -
The evaluation procedure of an arithmetic expression includes two left to right passes through
the entireexpression.
In the first pass, the high priority operators are applied as they are encountered and in the
second pass, low priority operations are applied as they areencountered.
x = 9 – 12 / 3 + 3 *2 – 1
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets changed.
25
For example,
x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are evaluated first from left to
right. The expression is now evaluated in three passesas:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7
There may even arise a case where nested parentheses are present (i.e. parenthesis inside parenthesis). In
such case, the expression inside the innermost set of parentheses is evaluated first and then the outer
parentheses are evaluated.
x = 9 – ((12 / 3) + 3 * 2) – 1
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2
26
Types of conversions
There are two type of conversions inC.
Implicit typeconversion
Explicit typeconversion
Implicit type conversion:
C performs automatic conversions of type in order to evaluate theexpression.
This is called implicit typeconversion.
For example, if we have an integer data type value and a double data type value in an expression
then C will automatically convert integer type value to double in order to evaluate
theexpression.
27
If we downgrade from a higher data type to a lower data type then it causes lose ofbits.
For example: Moving from double to float causes rounding ofdigits.
Downgrading from float to int causes truncation of the fractionalpart.
#include <stdio.h>
int main(void)
{
//variables
float
x = 24.5,
y = 7.2;
//output
printf("Result = %d\n", result);
printf("End of code\n");
return 0;
}
Output
Result = 3
End of code
In the above code (int) x converts the value 24.5 into 24 and (int) y converts the value 7.2 into 7
so, we get 24/7 i.e., 3 as result because result is of type int and hence the decimal part is truncated.
UNIT-I COMPLETED
28
UNIT-II
MANAGING INPUT AND OUTPUT OPERATIONS
INTRODUCTION:
Reading, processing, and writing of data are the three essential functions of a computer program.
The input function scanf which can read data from a keyboard.
The output function printf which sends results out to a terminal.
All input/output operations are carried out through function calls such as printf and scanf.
printf() and scanf() functions are inbuilt library functions in C programming language which are
available in C library by default.
These functions are declared and related macros are defined in “stdio.h” which is a header file in C
language.
We have to include “stdio.h” file as shown in below C program to make use of these printf() and scanf()
library functions in C language.
READING A CHARACTER:
WRITING A CHARACTER:
The putchar() function displays the character passed to it on the screen and returns the same
character.
This function too displays only a single character at a time.
In case you want to display more than one characters, use putchar() method in a loop.
Syntax:
putchar (variable_name);
Where variable_nameis a type char variable containing a character.
Example:
answer= ‘Y’;
putchar (answer);
will display the character Y on the screen.
The another example ,
29
putchar (‘ \n ‘); where the cursor on the screen move to the beginning of the next line.
Example Program:
#include<stdio.h>
#include<conio.h>
void main() Output:
{ a
char ch='a';
putchar(ch);
getch();
}
FORMATTED INPUT:
Formatted input refers to an input data that has been arranged in a particular format.
For example:
15.75 123 rithish
This line contains three pieces of data arranged in a particular form. The first part of the data should be
read into a variable float, the second into int, and the third part into char.
Syntax:
scanf (“control string”, arg1, arg2, ……, argn);
The control string specifies the field format in which the data is to be entered and the
arguments arg1, arg2, ……argn specify the address of the locations where the data is stored.
Control string and arguments are separated by commas.
30
b) Inputting Real Numbers:
The field width of real numbers is not to be specified and therefore scanf read real numbers using
the simple specification %ffor both the notations, namely, decimal point notations and
exponential notation.
For example:scanf( “ %f %f %f “, &x, &y, &z);
With the input data 475.89 2.156e2 678
Will assign the value 475.89 tox 215.6 to y 678.0 to z.
If the number to be read is of double type, then the specification should be % lf instead of simple % f.
c) Inputting Character Strings:
A scanf function can input strings containing more than one character.
The specification for reading character strings: % ws or % wc
FORMATTED OUTPUT:
The function printf() is used for formatted output to standard output based on a format specification.
The format specification string, along with the data to be output, are the parameters to the printf()
function.
Syntax:
printf( “control string “ arg1, arg2, ……. , argn);
Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t, and \b.
Examples:
printf( “ Programming in c “); printf( “ %d “, a);
printf( “**************** “ ); printf( “ X = %d \n Y= %f “, x, y );
printf( ““); printf( “Sum= %d “, x );
printf( “ \n “);
31
a) Outputting Integer Numbers:
The format specification for printing an integer number %w d
is: Where w specifies the minimum field width for the output.
d specifies that the value to be printed is an integer.
Example:
Format Output
printf( “ %d “, 9876) 9 8 7 6
printf( “ %6d “, 9 8 7 6
9876) printf( “ %2d 9 8 7 6
“, 9876) 9 8 7 6
printf( “ % -6d “, 0 0 9 8 7 6
9876) printf( “ % 06d
“, 9876)
printf( “ % 7.4f “, y) 9 8 . 7 6 5 4
printf( “ % 7.2f “, y) 9 8 . 7 7
printf( “ % -7.2f “, y) 9 8 . 7 7
printf( “ % f “, y) 9 8 . 7 6 5 4
%18.10s N E W D E L H I
% .5s N E W D
% -18.10s N E W D E L H I
C language possesses such decision making capabilities by supporting the following statements.
1. if statement.
2. Switch statement
3. Conditional operator statement.
4. goto statement
The expression is evaluated and depending on whether the value of the expression is true (non
zero) or false (zero) it transfers the control to a particular statement.
Some example of decision making, using if statement,
1) if ( room is dark)
Put on lights
The if statement may be implemented in different forms depending on the complexity of conditions to be
tested. The different forms are:
1. simple if statement
4.else if ladder
Simple If Statement :
The general form of simple if statement is
if(test expression)
{
33
statement-block;
}
statement-x;
Flow chart :
Example:
#include <stdio.h>
#include <conio.h>
void main ( ) Output:
{ a is less than 20
int a = 10; value of a is : 10
if (a <20 )
{
printf(“ a is less than 20 \n”);
}
printf( “ value of a is : %d ” , a);
getch( );
}
If –Else Statement :
The If statement is an extension of the simple If statement.
Syntax:
if (test expression)
{
true-block statements;
}
else
{
false-block statements;
}
statement – x;
34
If the test expression is true then true-block statement are executed, otherwise the false –block statement
are executed.
In both cases either true-block or false-block will be executed not both.
Flow chart :
Example:
#include <stdio.h>
#include <conio.h>
void main ( ) Output:
{ y is greater than x
int x, y ;
x=15;
y=18;
if (x >y )
{
printf(“ x is greater than y \n”);
}
else
{
printf(“ y is greater than x \n”);
}
getch( );
}
35
Here, if the condition 1 is false then it skipped to statement 3.
But if the condition 1 is true, then it tests condition 2.
If condition 2 is true then it executes statement 1 and if false then it executes statement 2.
Then the control is transferred to the statement x.
Flow chart:
Example:
#include <stdio.h>
void main ( )
{
int a, b, c;
printf( “ Enter 3 numbers : ”);
scanf( “ %d %d %d”, &a, &b, &c); Output:
if ( a> b ) Enter 3 numbers : 3 8 4
{ B is greater
if (a > c)
{
36
printf( “ \n A is greater ”);
}
else
{
printf(“ \n C is greater ”);
}
else
{
if (b > c)
{
printf( “ \n B is greater ”);
}
else
{
printf(“ \n C is greater ”);
}
getch( );
}
Else-If ladder :
When a multipath decision is involved then we use else if ladder.
A multipath decision is a chain of ifs in which the statement associated with each else is an
if. Syntax:
Flow chart:
37
This construct is known as the else-if ladder.
The conditions are evaluated from the top (of the ladder) down wards. As soon as a true condition is
found, the statement associated with it is executed and the control is transferred to the statement-X (i.e..,
skipping the rest of the ladder).
When all the n-conditions become false, then the final else containing the default-statement will be
executed.
Example:
#include <stdio.h>
#include <conio.h>
void main ( ) Output:
{ y is greater than x
int mark ;
char grade;
printf( “\n Enter your mark: ”);
scanf( “ %d ” , &mark);
if (mark >79 )
grade = “Honour”;
else if (mark >59)
grade = “First Class”;
else if( mark>49)
grade = “Second Class”;
else if( mark>39)
grade = “Third Class”;
else
38
grade = “ FAIL”;
printf(“\n %s ”, grade);
getch( );
}
SWITCH STATEMENT :
The switch statement is a multiway branch statement.
It provides an easy way to dispatch execution to different parts of code based on the value of the
expression.Switch is a control statement that allows a value to change control of execution.
Syntax:
switch (expression)
{
case value1 :
block1;
break;
case value 2 :
block 2;
break;
default :
default block;
break;
……….
……….
}
statement – x;
Flow Chart:
39
We don't use those expressions to evaluate switch case, which may return floating point values or strings
or characters.
break statements are used to exit the switch block. It isn't necessary to use break after each
block, but if you do not use it, then all the consecutive blocks of code will get executed after the matching
block.
`Rules for using switch statement
i. The expression (after switch keyword) must yield an integer value i.e the expression should be an
integer or a variable or an expression that evaluates to an integer.
ii. The case label values must be unique.
iii. The case label must end with a colon(:)
iv. The next line, after the case statement, can be any valid C statement.
Example :
switch (number)
{
case 1 :printf(“Monday”);
break;
case 2 :printf(“Tuesday”);
break;
case 3 :printf(“Wednesday”);
break;
case 4 :printf(“Thursday”);
break;
case 5 :printf(“Friday”);
break;
default :printf(“Saturday”);
break;
}
Conditional Operator
The operator pair “?” and “:” is known as conditional operator.
These pair of operators are ternary operators.
The general syntax of conditional operator is:
expression1 ? expression2 : expression3 ;
The conditional operator works as follows:
The first expression conditionalExpression is evaluated first. This expression evaluates to 1 if it's true
and evaluates to 0 if it's false.
If conditionalExpression is true, expression1 is evaluated.
If conditionalExpression is false, expression2 is evaluated.
This syntax can be understood as a substitute of if else
statement. For example,a = 3 ;b = 5 ;
Consider an if else statement as:
if (a > b)
x=a;
else
x=b;
Now, this if else statement can be written by using conditional operator as:
x = (a > b) ? a : b ;
40
Example program:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int a=10, b=20,c ; int a=40, b=20;
clrscr( ); clrscr( );
GOTO STATEMENT :
The goto statement is used to transfer the control of the program from one point to another.
It is something referred to as unconditionally branching.
The goto is used in the form
Goto label;
Label statement :
A lable is any valid variable name and must be followed by a colon.
We can precode any statement by a label in the form
Label :statement ;
This statement immediately transfers execution to the statement labeled with the label
identifier. A gotobreaks the normal sequential execution of the program.
Forward Jump: If the label : is placed after thegoto label; some statements skipped and the jump is
known as a forward jump.
Backward Jump: If the label : is before the statement goto label; a loop will be formed and some
statements will be executed repeatedly. Such a jump is known as abackward jump.
Example:
/* Goto Statement in C Programming example */
#include <stdio.h>
intmain()
41
{
intmark;
if(mark>=50)
{
gotoPass;
}
else
gotoFail;
Pass:
printf(" \n \n Congratulation! You made it \n");
Fail:
printf(" \n \n Better Luck Next Time \n");
return0;
}
OUTPUT:
Please enter your Mark: 35
When the control statement is placed before the body of the loop then such loops are called
as entry controlled loops.
If the test condition in the control statement is true then only the body of the loop is executed.
42
If the test condition in the control statement is not true then the body of the loop will not be
executed.
If the test condition fails in the first checking itself the body of the loop will never be
executed.
When the control statement is placed after the body of the loop then such loops are called as exit
controlled loop.
In this the body of the loop is executed first then the test condition in the control statement is checked.
If it is true then the body of the loop is executed again.
If the test condition is false, the body of the loop will not be executed again. In exit controlled loops even
if the test condition fails in the first attempt itself the body of the loop is executed at least once.
43
WHILE STATEMENT:
This is an entry controlled loop.
In this the test condition is placed before the body of the loop.
If the test expression is true (nonzero), codes inside the body of while loop are executed. The
test expression is evaluated again. The process goes on until the test expression is false.
When the test expression is false, the while loop is terminated.
Syntax:
void main( )
Flow Chart: {
int x=1;
clrscr( );
while ( x< = 10 )
{
printf("%d\t", x);
x++;
}
getch( );
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10
DO - WHILE STATEMENT:
The do..while loop is similar to the while loop with one important difference.
The body of do...while loop is executed once, before checking the test expression.
Hence, the do...while loop is executed at least once.
The conditional expression appears at the end of the loop, so the statement(s) in the loop
executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
executes again. This process repeats until the given condition becomes false.
Syntax:
44
do
{ Example:
body of the loop; #include<stdio.h>
} #include<conio.h>
while (test condition);
void main( )
{
Flow Chart: int x=0;
clrscr( );
do
{
printf("%d\t", x);
x++;
}
while ( x< = 5 )
getch( );
}
OUTPUT:
012345
FOR STATEMENT:
Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
int i;
clrscr( );
45
Flow Chart:
for ( i= 1; i<=5; i++)
{
printf("%d \t", i);
getch( );
}
OUTPUT:
12345
Another example:
The increment section may also have more than one part.
for(n=1 , m= 50 ; n< = m; n = n+1, m = m-1)
{
p=m/n;
46
printf( %d %d %d \n ” , n, m, p);
}
It has two variables in increment part. Note: Should be separated by comma.
Syntax:
statement(s);
}
Flow Chart:
Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
int i, j ;
clrscr( );
47
ample 1: Program to print half pyramid using * Example 2: Inverted half pyramid using *
#include<stdio.h> #include<stdio.h>
void main( ) Output: void main( ) Output:
{ * { * * * *
#include<stdio.h>
void main( ) Output:
48
printf("\n");
n--;
}
}
Break Statement:
The break statement is used inside loop or switch statement.
When break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop.
Syntax : Example:
#include<stdio.h>
break; #include<conio.h>
getch( );
}
OUTPUT:
Statement 1
Statement 2
End of Program.
49
Continue Statement:
The continue statement is used inside loops, it skips some statements inside the loop.
When compiler finds the break statement inside a loop, compiler will skip all the following statements in
the loop and resume the loop.
Syntax :
continue; Example:
#include<stdio.h>
Flowchart : #include<conio.h>
void main( )
{
int a=0;
while(a<5)
{
a++;
if(a= = 3)
continue;
OUTPUT:
Statement 1
Statement 2
Statement 4
Statement 5
End of Program.
50
UNIT-II COMPLETED
UNIT-III
ARRAYS
INTRODUCTION:
C Array is a collection of variables belongings to the same data type. You can store group of data
of same data type in an array.
o Array might be belonging to any of the data types
o Array size must be a constant value.
o Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
o It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any
values to array.
Example where arrays are used,
to store list of Employee or Student names,
to store marks of students,
or to store list of numbers or characters etc.
ADVANTAGES: Array variable can store more than one value at a time where other variable can store one
value at a time.
51
Types of C Arrays:
There are 2 types of C arrays. They are,
1. One dimensional array
2. Two dimensional array
3. Multi dimensional array
Three dimensional array
Four dimensional array etc…
mark[0]= 40; mark[1] = 65; mark[2] = 89; mark[3] = 75; mark[4] = 90;
Example:
int salary[10];
float height[5];
char name[15];
Declares the salary as an array to contain a maximum of 10 integer constants, any subscripts 0
to 9 are valid.
52
int a[5]={10,20,30,100,5}
Declares the heightto be an array containing 50 real elements.
Declares the name as a character array(string) variable that can hold a maximum of 15 characters
.
Suppose we read the following string constant into the string variable name
“WELL DONE”
Each character of the string is treated as an element of the array name and is stored in the
memory as follows:
‘W’ ‘E’ ‘L’ ‘L’ ‘ ’ ‘D’ ‘O’ ‘N’ ‘E’ ‘\0’
Syntax:
int a[3]={9,2,4,5,6}; //error: no. of initial vales are more than the size of array.
53
Partial array initialization is possible in c language.
If the number of values to be initialized is less than the size of the array, then the elements will be
initialized to zeroautomatically.
54
Ex:-
charb[9]="COMPUTER"; //
correct
charb[8]="COMPUTER";
//wrong
2. Run TimeInitialization
An array can be explicitly initialized at run time.
This approach is usually applied for initializing large arrays.
Ex:- scanf can be used to initialize an array.
int x[3]; scanf(“%d%d
%d”,&x[0],&x[1],&x[2]);
The above statements will initialize array elements with the values entered through the key board.
(Or)
for(i=0; i<10; i++)
{
printf(“\n %d” , i);
}
TWO – DIMENSIONAL ARRAYS:
An array consisting of two subscripts is known as two-dimensional array.
Syntax: data_typearray_name[row_size][column_size];
55
The initialization is done row by row.
If the values are missing in an initialize, they are automatically set to zero.
MULTI-DIMENSIONAL ARRAYS
Multidimensional arrays are often known as array of the arrays.
In multidimensional arrays the array is divided into rows and columns, mainly while
considering multidimensional arrays we will be discussing mainly about two dimensional
arrays and a bit about three dimensional arrays.
Syntax: data_typearray_name[size1][size2][size3] – [sizeN];
Example: int d[10][20][30];
Example program:
/*ADDITION OF TWO MATRICES*/
#include <stdio.h>
#include<conio.h>
56
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]); Enter the number of rows and columns of matrix
printf("Enter the elements of second matrix\n"); 2
2
for (c = 0; c < m; c++) Enter the elements of first matrix
1 2
for (d = 0 ; d < n; d++) 3 4
scanf("%d", &second[c][d]); Enter the elements of second matrix
5 6
printf("Sum of entered matrices:-\n"); 2 1
for (c = 0; c < m; c++) Sum of entered matrices:-
6 8
{ for (d = 0 ; d < n; d++) 5 5
{
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}
Syntax:-
char string_name[size];
The size determines the number of characters in the string name
Example:-
char city[10];
char name[30];
Initializing strings: -
There are several methods to initialize values for string variables.
For convenience and ease, both initialization and declaration are done in the same step.
Example:
char c[] = "abcd"; OR,
58
Example:
NEW YORK
Reads only NEW (from above example).
(b) Unformatted input functions:
(1) getchar():-
o It is used to read a single character from keyboard. Using this function repeatedly we may read
entire line of text
Example:
char ch=‟z‟;
ch=getchar();
(2) gets():-
o It is more convenient method of reading a string of text including blank spaces.
Example:
char line[100];
gets(line);
(a) putchar():-
o It is used to print a character on the screen.
Example:
putchar(ch);
(b) puts():-
o It is used to print strings including blank spaces.
Example:
char line[15]=”Welcome to lab”;
puts(line);
STRING-HANDLING FUNCTIONS
C supports a number of string handling functions. Most commonly used string handlings functions are
following below.
Function tion
strcat( ) ncatenates two strings.
strcmp( ) mpares two strings.
59
strcpy( ) pies one string over another.
strlen( ) ds the length of a string
All of these built- in functions are aimed at performing various operations on strings and they are defined
in the header file string.h .
i. strcat( )
This function is used to concatenate two strings. i.e., it appends one string at the end of the specified
string.
Its syntax as follows:
strcat(string1, string2);
where string1 and string2 are one-dimensional character arrays.
This function joins two strings together.
In other words, it adds the string2 to string1 and the string1 contains the final concatenated string. E.g.,
string1 contains Progand string2 contains ram, then string1 holds programafter execution of the strcat()
function.
Example:
char str1[10 ] = “VERY”;
char str2[ 5] =”GOOD”;
strcat(string1,string2);
strcat(str1,str2);
ii. strcmp( )
This function compares two strings character by character (ASCII comparison) and returns one of three
values {-1,0,1}.
The numeric difference is “0‟ifstrings are equal .
If it is negative string1 is alphabetically above string2 .
Ifit is positive string2 is alphabetically above string1.
60
char str1[ ] = “WELCOME”;
char str2[ ] =”HELLO”;
strcpy(str1,str2);
Syntax:
strcmp(string1, string2);
Example:
char str1[ ] = “ROM”;
char str2[ ] =”RAM”;
strcmp(str1,str2);
(or)
strcmp(“ROM”,”RAM”);
Syntax:
strcpy(string1, string2);
where string1 and string2 are one-dimensional character arrays.
This function copies the content of string2 to string1.
E.g., string1 contains master and string2 contains madam, then string1 holds madam after execution of the strcpy
(string1,string2) function.
Example:
61
#include<string.h>
main( ) Output:
strcpy(string1,string2); Enter first string: Welcome
{ Enter second string: Hello
char string1[30],string2[30]; First string = Hello
printf(“\n Enter first string:”); Second string = Hello
gets(string1);
printf(“\n Enter second string:”);
gets(string2);
strcpy(string1,string2);
printf(“\n First string=%s”,string1);
printf(“\n Second string=%s”,string2);
}
iv. strlen( ) Function:
This function is used to find the length of the string excluding the NULL character.
In other words, this function is used to count the number of characters in a string.
Syntax:
n=strlen(string)
Example:
char str1[ ] = “WELCOME”;
int n;
n = strlen(str1);
USER-DEFINED FUNCTIONS
C functions are basic building blocks in a program. All C programs are written
using functions to improve re-usability, understandability and to keep track on
them.
What is C function?
A large C program is divided into basic building blocks called C function.
62
C function contains set of instructions enclosed by “{ }” which performs specific operation in a
C program.
Actually, Collection of these functions creates a C program.
b) Improves the reusability of the code, same function can be used in any program rather
than writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by function calls.
63
Example Program:
#include<stdio.h>
#include<conio.h>
int add( int x, inty); // function prototype
void main( )
{
int a, b, c;
clrscr( );
64
c = add(a, b); // function
call printf("Addition of two number is %d", c);
getch( );
}
Types of Function in C:
1) Library Functions in C:
C provides library functions for performing some operations.
These functions are present in the c library and they are predefined.
For example :sqrt( ) is a mathematical library function which is used for finding the square root
of any number .The function scanf( ) and printf( ) are input and output library function
similarly we have strcmp() and strlen() for string manipulations.
To use a library function we have to include some header file using the preprocessor directive
#include.
For example to use input and output function like printf( ) and scanf( ) we have to include
stdio.h, for math library function we have to include math.h for string library string.h should
be included.
65
Syntax:
returntypefunctionName(type1 parameter1, type2 parameter2,...);
Example:
int add (int x, int y);
Function Definition:
The function definition consists of the whole description and code of a function.
It tells that what the function is doing and what are the input outputs for that.
A function is called by simply writing the name of the function followed by the argument list inside
the parenthesis.
1. Function Header:
The first line of code is called Function Header.
int sum( int x, int y)
It has three parts:
i. Function name
ii. Function type
iii. List of Parameters
Function name: It is Unique Name that identifies function. All Variable naming conversions are
applicable for declaring valid function name. E.g: add, sum, etc….,
Function type: Return Type is Type of value returned by function. Return Type may be “Void” if
function is not going to return a value. E.g., int, float.
List of Parameters: Comma-separated list of types and names of parameters. Parameter injects external
values into function on which function is going to operate. Parameter field is optional. If no parameter is
passed then no need to write this field. E.g: int add( int x, int y)
2. Function Body:
The Function Body contains the declarations and statements necessary for
performing the required task.
66
The body enclosed in braces { }, contains three parts in the order.
i) Local variable declaration
ii) Function statement
iii) A return statement
Local variable declaration: That specify the variables needed by the function.
Function statement: That perform the task of the function.
A return statement: That returns the value evaluated by the function.
Function Calls:
A function can be called by simply using the function name followed by a list of
actual parameters(or arguments).
Example:
main( )
{
int c;
c = add(10 , 5); // function
calls printf("%d\n", c);
}
CATEGORY OF FUNCTIONS:
A function depending on whether arguments are present or not and whether a value is returned or not may
belong to any one of the following categories:
(i) Functions with no arguments and no return values.
(ii) Functions with arguments and no return values.
(iii) Functions with arguments and return values.
(iv) Functions with no arguments and return values.
(v) Functions that return multiple values.
(i) Functions with no arguments and no return values:-
67
When a function has no arguments, it does not return any data from calling function.
When a function does not return a value, the calling function does not receive any data from the
called function. That is there is no data transfer between the calling function and the called function.
Example
#include <stdio.h>
Output :
#include <conio.h> Hello ! I Am A Function .
void printmsg()
{
printf ("Hello ! I Am A Function .");
}
int main()
{
printmsg( );
return 0;
}
68
printf ("\n The sum =%d",z);
}
void main()
{
int a, b, c;
printf(“Enter two values:
”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf ("The sum =%d",c);
}
int add (int x, int y)
{
int z;
z=x+y;
return z;
}
(iv) Functions with no arguments but return types:-
When function has no arguments data cannot be transferred to called function.
But the called function can send some return value to the calling function.
Example:
#include<stdio.h> Output :
#include <conio.h> Enter two values: 5 4
void add(int,int); The sum = 9
void main( )
{
int c;
c=add( );
printf ("The sum =%d",c);
}
int add ( )
{
int x,y,z;
69
printf(“Enter two values: ”);
scanf(“%d%d”,&a,&b);
z=x+y;
return z;
}
NESTING OF FUNCTIONS :
It provides a facility to write one function with in another function.
There is no limit as to how deeply functions can be nested. This is called nesting of function.
Syntax:
main( )
{
………..
function1( );
……….
}
function1( );
{
………..
function2( );
……….
}
function2( );
{
………..
……….
}
main () can call Function 1() where Function1 calls Function2() which calls Function3() and so on .
Example:
70
RECURSION:
A function that calls itself is known as a recursive function.
71
Another useful example of recursion is the evaluation of factorials of a given numbers.
The factorial of a number n is expressed as a series of repetitive multiplications as shown below.
Factorial of n = n(n-1)(n-2) …….1.
For example: Factorial of 4 = 4*3*2*1 = 24
#include<stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
else
return (factorial(n-1)*n);
}
int main()
{
int num,f;
printf("Enter a number: ");
scanf("%d",&num);
f=factorial(num);
printf("Factorial of %d = %d",num,f);
return 0;
}
72
Syntax:storage_class_specifierdata_typevariable_name;
Syntax: registerdata_typevariable_name;
Example:
#include<stdio.h>
int main()
{
registerinti;
for(i=1; i<=100; i+
+)
printf("n%d",i);
return0;
Static Variable (static): }
73
The variables declared with static storage class specifier are initialized with zero initial
value if any initial value is not provided at the time of declaration and it can be accessed
from anywhere within the block in which it is defined.
However, the variables declared with static storage class are not destroyed even after
program control exits from the block. Thus, the value of the variable persists between
different function calls.
Syntax:static data_typevariable_name;
Example:
#include<stdio.h>
increment()
{ Output
staticinti=1; 1
printf("%dn",i); i+ 2
+; 3
}
main()
{
increment();
increment();
increment();
return0;
}
The variable declared using extern storage class are stored in memory with by default
zero initial value and continue to stay within the memory until the program’s execution is
not terminated.
Moreover, variables declared as extern can be accessed by all functions in the program,
thus avoiding unnecessary passing of these variables as arguments during function call.
It should be noted that the variables declared outside any function definition are treated
as variables with extern storage class.
Example:
74
#include<stdio.h>
inti;
main() i=0
{ On increment, i=1
printf("ni=%d",i); On increment, i=2
increment(); On decrement, i=1
increment(); On decrement, i=0
decrement();
decrement();
}
increment()
{
i++;
printf("nOn increment,
i=%d",i);
}
decrement()
{
i--;
printf("\nOn
decrement, i=%d",i);
}
There are two ways by which we can pass the parameters to the functions:
1. Call by value:
Here the values of the variables are passed by the calling function to the called function.
If any value of the parameter in the called function has to be modified the change will
be reflected only in the called function.
This happens as all the changes are made on the copy of the variables and not on the actual
ones.
#include <stdio.h>
int sum (int n);
void main( ) {
int a = 5;
printf("\n The value of 'a' before the calling function is = %d", a);
a = sum(a);
printf("\n The value of 'a' after calling the function is = %d", a);
75
}
int sum (int n)
{ n = n + 20;
printf("\n Value of 'n' in the called function is = %d", n);
return n;
}
Output:
The value of 'a' before the calling function is = 5
Value of 'n' in the called function is = 25
The value of 'a' after calling the function is = 25
2. Call by reference
Here, the address of the variables are passed by the calling function to the called function.
The address which is used inside the function is used to access the actual argument used in the call.
If there are any changes made in the parameters, they affect the passed argument.
For passing a value to the reference, the argument pointers are passed to the functions just like any
other value.
Output:
The value of 'a' before the calling function is = 5
value of 'n' in the called function is = -1079041764
The value of 'a' after calling the function is = 25
UNIT-III COMPLETED
76
UNIT-IV
STRUCTURES AND UNIONS
DEFINITION:
A structure is a collection of one or more variables of different data types, grouped together under a single
name. By using structures variables, arrays, pointers etc can be grouped together.
A Structure is a convenient tool for handling a group of logically related data items.
For example, it can be used to represent a set of attributes, such as student_name, roll_no& marks.
DEFINING A STRUCTURE:
The structure definition associated with the structure name is referred as tagged structure.
It doesn’t create an instance of a structure and does not allocate any memory.
Where,
- struct is the keyword which tells the compiler that a structure is being defined.
- Tag_name is the name of the structure.
- variable1, variable2 … are called members of the structure.
- The members are declared within curly braces.
- The closing brace must end with the semicolon.
77
Declaring Structure variables with structure definition:
struct student
{
char name[50];
int age;
float height;
} stu1, stu2, stu3; // declaring variable of struct student
Here stu1 and stu2 are variables of structure Student
STRUCTURE INITIALIZATION:
C language does not permit the initialization of individual structure members within the template.
The initialization must be done only in the declaration of the actual variables..
Syntax:
struct tag_name variable = {value1, value2,… value-n};
Structure initialization can be done in any one of the following ways.
Example:
struct student
{
char name[10];
int age;
float height;
78
};
struct studentstu = { “Dhars”, 22, 6.0 } ;
ARRAYS OF STRUCTURES:
An array is a collection of elements of same data type that are stored in contiguous memory locations.
A structure is a collection of members of different data types stored in contiguous memory locations.
An array of structures is an array in which each element is a structure.
This concept is very helpful in representing multiple records of a file, where each record is a collection of
dissimilar data items.
As we have an array of integers, we can have an array of structures also.
Syntax:
struct tag_namearrayofstructure[size];
Let’s take an example, to store the information of 3 students, we can have the following structure definition and
declaration,
struct student
{
char
name[10]; int
age;
float height;
};
79
struct student stu[3];
Defines an array called stu, which contains three elements. Each element is defined to be of type struct
student.
For the student details, array of structures can be initialized as follows,
80
outer_structure_variable .inner_structure_variable.member_name
(ii) The syntax of another method for the nesting of the structure is as follows
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
----------------------
<data-type> element n;
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
----------------------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Example :
struct stud_Res
{
int rno;
char nm[50];
char std[10];
struct stud_subj
{
char subjnm[30];
int marks;
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a structure with two
members. Structure stud_Res is called as 'outer structure' while stud_subj is called as 'inner structure.'
The members which are inside the inner structure can be accessed as follow :
result.subj.subjnm
result.subj.marks
81
Most C compilers, will allow you to pass entire structures as parameters and return
entire structures.
As with all C parameters structures are passed by value and so if you want to allow a function
to alter a parameter you have to remember to pass a pointer to a struct.
Given that you can pass and return structs the function is fairly easy:
struct comp add(struct comp a , struct comp
b)
{
struct comp c;
c.real=a.real+b.real;
c.imag=a.imag+ b.imag;
return c;
}
After you have defined the add function you can write a complex addition as:
x=add(y,z)
which isn't too far from the x=y+z that you would really like to use. Finally notice that passing
a struct by value might use up rather a lot of memory as a complete copy of the structure is made for the
function.
UNIONS:
A union is one of the derived data types. Union is a collection of variables referred under a single name.
The syntax, declaration and use of union is similar to the structure but its functionality is different.
82
A union definition and variable declaration can be done by using any one of the following
We can access various members of the union as mentioned: a.ca.ia.f and memory organization is shown
below,
a.c
a.i
a.f
POINTERS
DEFINITION:
Pointer is a user defined data type that creates special types of variables which can hold the
address of primitive data type like char, int, float, double or user defined data type like function,
pointer etc. or derived data type like array, structure, union, enum.
Examples:
int *ptr;
In c programming every variable keeps two types of value.
1. Value of variable.
2. Address of variable where it has stored in the memory.
83
About variable ―a‖ :
1. Name of variable: a
2. Value of variable which it keeps: 5
3. Address where it has stored in memory: 1025 (assume)
About variable ―ptr‖ :
4. Name of variable: ptr
5. Value of variable which it keeps: 1025
6. Address where it has stored in memory: 5000 (assume)
Pictorial representation:
Variable
Pointers are built on three underlying concepts which are illustrated below:-
Memory addresses within a computer are referred to as pointer constants. We cannot change
them. We can only use them to store data values. They are like house numbers.
We cannot save the value of a memory address directly. We can only obtain the value
through the variable stored there using the address operator (&). The value thus obtained is known as
pointer value. The pointer value (i.e. the address of a variable) may change from one run of the
program to another.
Once we have a pointer value, it can be stored into another variable. The variable that contains
a pointer value is called a pointer variable.
Pointer Constants Pointer Values Pointer Variables
Pointe
rs
Benefits of using pointers are:-
1) Pointers are more efficient in handling arrays and data tables.
2) Pointers can be used to return multiple values from a function via function arguments.
3) The use of pointer arrays to character strings results in saving of data storage space in memory.
4) Pointers allow C to support dynamic memory management.
5) Pointers provide an efficient tool for manipulating dynamic data structures such as structures
, linked lists , queues , stacks and trees.
6) Pointers reduce length and complexity of programs.
7) They increase the execution speed and thus reduce the program execution time.
84
INITIALIZATION OF POINTER VARIABLES:
The process of assigning the address of a variable to a pointer variable is known as initialization.
Once apointer variable has been declared we can use assignment operator to initialize the variable.
Example:
int quantity ;
int *p; //declaration
p=&quantity; //initialization
We can also combine the initialization with the declaration:
int *p=&quantity;
Always ensure that a pointer variable points to the corresponding type of data.
It is also possible to combine the declaration of data variable, the declaration of pointer variable and the
initialization of the pointer variable in one step.
int x, *p=&x;
ACCESSING THE ADDRESS OF A VARIABLE:
The actual location of a variable in the memory is system dependent and therefore the address of a
variable is not known to us immediately.
In order to determine the address of a variable we use & operator in c. This is also called as the address
operator.
The operator & immediately preceding a variable returns the address of the variable associated with it.
Syntax: p=&x;
would assign the address 5000 to the variable p. The & operator can be remembered as address of.
Example program:
main( ) Output:
{
int a = 5 ; Address of a=1444
printf( "\nAddress of a = %u", &a ); Value of a=5
printf( "\nValue of a = %d", a );
}
The expression &a returns the address of the variable a, which in this case happens to be 1444.
Hence it is printed out using %u, which is a format specified for printing an unsigned integer.
CHAIN OF POINTER:
A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
Normally, a pointer contains the address of a variable.
When we define a pointer to a pointer, the first pointer contains the address of the second
pointer, which points to the location that contains the actual value as shown below.
85
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name.
For example, the following declaration declares a pointer to a pointer of type int –
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example –
#include<stdio.h>
int main () OUTPUT:
{ Value of var = 3000
intvar; Value available at *ptr = 3000
int*ptr; Value available at **pptr =
3000
int**pptr;
var=3000;
return0;
}
POINTERS EXPRESSIONS:
We can use pointer variables in expression.
86
Example:
int x = 10, y = 20, z;
int *ptr1 = &x;
int *ptr2 = &y;
z = *ptr1 * *ptr2 ;
Will assign 200 to
variable z.
We can perform addition and subtraction of integer constant from pointer variable.
Example:
ptr1 = ptr1 + 2;
ptr2 = ptr2 – 2;
We can not perform addition, multiplication and division operations on two pointer variables.
Example:
ptr1 + ptr2 is not valid
However we can subtract one pointer variable from another pointer variable.
We can use increment and decrement operator along with pointer variable to increment or
decrement the address contained in pointer variable.
Example:
ptr1++;
ptr2--;
We can use relational operators to compare pointer variables if both pointer variable points to the
variables of same data type.
POINTER INCREMENT AND SCALE FACTOR
We can use increment operator to increment the address of the pointer variable so that it points to
next memory location.
The value by which the address of the pointer variable will increment is not fixed. It depends
upon the data type of the pointer variable.
For Example:
int *ptr;
ptr++;
It will increment the address of pointer variable by 2. So if the address of pointer variable
is 2000 then after increment it becomes 2002.
Thus the value by which address of the pointer variable increments is known as scale factor. The
scale factor is different for different data types as shown below:
Char 1 Byte
Int 2 Byte
Short int 2 Byte
Long int 4 Byte
Float 4 Byte
87
Double 8 Byte
Long double 10 Byte
value 1 2 3 4 5
Base address
The name x is defined as a constant pointer pointing to the first element, x[0], and therefore the value x is
1000, the location where x[0] is stored.
That is x=&x[0]=1000;
If we declare p as an integer pointer, then we can make the pointer p to the array x by the
following assignment
p=x;
which is equivalent to p=&x[0];
Now we can access every value of x using p++ to move from one element to another.
The relationship between p and x is shown below
p=&x[0]=1000
p+1=&x[1]=1002
p+2=&x[2]=1004
p+3=&x[3]=1006
p+4=&x[4]=1008
Note:- address of an element in an array is calculated by its index and scale factor of the datatype.
Address of x[n] = base address + (n*scale factor of type of x).
Eg:- int x[5]; x=1000;
Address of x[3]= base address of x+ (3*scale factor of int)
= 1000+(3*2)
= 1000+6
=1006
88
POINTERS AND CHARCTERS STRINGS:
String is an array of characters terminated with a null character. We can also use pointer to access the
individual characters in a string .this is illustrated as below
Note :- In `c` a constant character string always represents a pointer to that string and the following statement
is valid
char *name;
name = “delhi”;
these statements will declare name as a pointer to a character and assign to name the constant character string
“Delhi”.
This type of declarations is not valid for character string .
Like:-
char name [20];
name =”delhi” ; //invalid
ARRAY OF POINTER:
We have studied array of different primitive data types such as int, float, char etc. Similarly C supports
array of pointers i.e. collection of addresses.
Example :-
void main( )
{
int *ap[3]; Output:
int al[3]={10,20,30}; Address Element
int k; 4060 10
for(k=0;k<3;k++) 4062 20
ap[k]=al+k; 4064 30
printf(“\n address element\n”);
for(k=0;k<3;k++)
{
printf(“\t %u”,ap[k]);
printf(“\t %7d\n”,*(ap[k]));
}
}
In the above program , the addresses of elements are stored in an array and thus it represents array of
pointers.
A two-dimensional array can be represented using pointer to an array. But, a two-dimensional array can
be expressed in terms of array of pointers also. The conventional array definition is,
data_type array name [exp1] [exp2];
Using array of pointers, a two-dimensional array can be defined as,
data_type *array_name [exp1];
Where,
- data_type refers to the data type of the array.
- array_name is the name of the array.
- exp1 is the maximum number of elements in the row.
Note that exp2 is not used while defining array of pointers. Consider a two-dimensional vector initialized with 3
rows and 4 columns as shown below,
int p[3][4]={{10,20,30,40},{50,60,70,80},{25,35,45,55}};
The elements of the matrix p are stored in memory row-wise (can be stored column-wise also).
Using array of pointers we can declare p as,
int *p[3];
Here, p is an array of pointers. p[0] gives the address of the first row, p[1] gives the address of the second
89
row and p[2] gives the address of the third row.
Now, p[0]+0 gives the address of the element in 0th row and 0th column, p[0]+1 gives the address of the
elements in 0th row and 1st column and so on.
In general,
- Address of ith row is given by a[i].
- Address of an item in ith row and jth column is given by, p[i]+j.
- The element in ithrow and jth column can be accessed using the indirection operator * by
specifying, *(p[i]+j).
90
if(*a<*b)
return a;
else
return b;
}
In this example, “return a” implies the address of “a” is returned, not value .So in order to hold
the address, the function return type should be pointer.
POINTERS TO FUNCTIONS
A function, like a variable has a type and address location in the memory.
It is therefore possible to declare a pointer to a function, which can then be used as an argument in
another function. A pointer to a function can be declared as follows.
type (*fptr)();
This tells the complier that fptr is a pointer to a function which returns type value the
parentheses around *fptr is necessary.
Because type *gptr(); would declare gptr as a function returning a pointer to type.
We can make a function pointer to point to a specific function by simply assigning the name of the
function to the pointer.
Example:
double mul(int,int);
double (*p1)();
p1=mul();
It declares p1 as a pointer to a function and mul as a function and then make p1 to point to the function
mul.
To call the function mul we now use the pointer p1 with the list of parameters.
i,e (*p1)(x,y); //function call equivalent to mul(x,y);
Program:
double mul(int ,int);
void main()
{
int x,y;
double (*p1)();
double res;
p1=mul;
printf("\n enter two numbers:");
scanf("%d %d",&x,&y);
res=(*p1)(x,y);
printf("\n The Product of X=%d and Y=%d is res=%lf",x,y,res);
}
double mul(int a,int b)
{
double val;
val=a*b;
return(val);
}
Output:
91
POINTERS AND STRUCTURES:
A pointer can also point to a structure.
Example :
struct student
{
int sno;
char sname[20], course[20];
float fee;
};
struct student s;
struct student *p;
FILE MANAGEMENT IN C
File management in C, File operation functions in C, Defining and opening a file, Closing a file,
The getw and putw functions, The fprintf&fscanf functions, Random access to files and fseek
function.
C supports a number of functions that have the ability to perform basic file operations,
which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
Real life situations involve large volume of data and in such cases, the console oriented I/O operations
pose two major problems
It becomes cumbersome and time consuming to handle large volumes of data through terminals.
The entire data is lost when either the program is terminated or computer is turned off therefore it is
necessary to have more flexible approach where data can be stored on the disks and read whenever
necessary, without destroying the data. This method employs the concept of files to store data.
92
File operation functions in C:
Function Name Operation
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File
is a structure that is defined in the I/O Library.
The second statement opens the file named filename and assigns an identifier to the FILE type
pointer fp. This pointer, which contains all the information about the file, is subsequently used as
a communication link between the system and the program.
The second statement also specifies the purpose of opening the file. The mode does this job.
93
In these statements the p1 and p2 are created and assigned to open the files data and results
respectively the file data is opened for reading and result is opened for writing. In case the results file
already exists, its contents are deleted and the files are opened as a new file. If data file does not exist
error will occur.
CLOSING A FILE:
The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);
A file must be closed as soon as all operations on it have been completed.
This would close the file associated with the file
pointer. Observe the following program.
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….
…
fclose(p1);
fclose(p2)
The above program opens two files and closes them after all operations on them are completed, once a
file is closed its file pointer can be reversed on other file.
94
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}
95
printf(“nnContents of the odd filenn”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“nnContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}
Where fp id a file pointer associated with a file that has been opened for writing. The
control string is file output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here name is an array variable of type char and age is an int variable
Example: fscanf(f2,”5s%d”,item,&quantity”);
Like scanf, fscanf also returns the number of items that are successfully read.
96
fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality); fprintf(fp,”%s%d%f
%d”,itemnumber,price,quality);
}
fclose (fp);
fprintf(stdout,”nn”);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(I=1;I< =3;I++)
{
fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality);
value=price*quantity”); fprintf(“stdout,”%s%d%f%d
%dn”,item,number,price,quantity,value);
}
fclose(fp);
}
There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.
1. fseek( )
2. ftell( )
3. rewind( )
97
We use the fseek( ) function to move the file position to a desired location.
Syntax:
fseek(fptr, offset, position);
Following are the list of operations we can perform using the fseek() function.
Operation Description
fseek(fptr, N, 1) This will take us N bytes forward from the current position in the
file.
fseek(fptr, -N, This will take us N bytes backward from the current position in the
1) file.
fseek(fptr, -N, This will take us N bytes backward from the end position in the file.
2)
98
4. Trying to perform an operation on a file, when the file is opened for another type of operations
.
5. Opening a file with an invalid filename.
6. Attempting to write a write protected file.
If we fail to check such read and write errors, a program may behave abnormally when an error occurs.
An unchecked error may result in a premature termination of the program or incorrect output.
In C we have two status - inquiry library functions feof and ferrorthat can help us detect I/O errors in the
files.
a). feof():
The feof() function can be used to test for an end of file condition.
It takes a FILE pointer as its only argument and returns a non zero integer value if all of the data
from the specified file has been read, and returns zero otherwise.
If fp is a pointer to file that has just opened for reading, then the statement
if(feof(fp))
printf(“End of data”);
would display the message “End of data” on reaching the end of file condition.
b).ferror():
The ferror() function reports the status of the file indicated.
It also takes a file pointer as its argument and returns a nonzero integer if an error
has been detected up to that point, during processing.
It returns zero otherwise. The statement
if(ferror(fp)!=0)
printf(“an error has occurred\n”);
would print an error message if the reading is not successful.
c). fp==null:
We know that whenever a file is opened using fopen function, a file pointer is returned.
If the file cannot be opened for some reason, then the function returns a null pointer.
This facility can be used to test whether a file has been opened or not.
Example
if(fp==NULL)
printf(“File could not be opened.\n”);
d) perror( ):
It is a standard library function which prints the error messages specified by the compiler.
Example:
if(ferror(fp))
perror(filename);
99
while(!feof(fp))
{
ch=getc(fp);
if(ferror(fp))
perror(“problem in the file”);
else
printf(“\n file cannot be opened”);
putchar(ch);
}
fclose(fp);
}
UNIT-IV COMPLETED
10
UNIT-V
DYNAMIC MEMORY ALLOCATION
DEFINITION:
The process of allocating memory at runtime is known as dynamic memory allocation.
Library routines known as memory management functions are used for allocating and freeing
memory during execution of a program. These functions are defined in stdlib.h header file.
Function Description
malloc() allocates requested size of bytes and returns a void pointer pointing to the first byte of the
allocated space
calloc() allocates space for an array of elements, initialize them to zero and then returns a void pointer to
the memory
10
void*malloc(byte-size)
Example: malloc()
int *x;
x =(int*)malloc(50*sizeof(int));//memory space allocated to variable
x
free(x);//releases the memory allocated to variable x
10
ptris the pointer that is points to allocated memory by malloc( ), calloc( ) or realloc().
Passing an uninitialized pointer, or a pointer to a variable not allocated by malloc( ), calloc()
or realloc()could be dangerous and disastrous.
Example:
int *a;
a=(int *) malloc(30); //first 30 bytes of memory is allocated.
free(a); //de-allocates 30 bytes of memory.
calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with garbage
value. values.
LINKED LISTS
A linked list is a way to store a collection of elements. Like an array these can be character or
integers. Each element in a linked list is stored in the form of a node.
Node:
A node is a collection of two sub-elements or parts. A data part that stores the element
and a next part that stores the link to the next node.
Linked List:
A linked list is formed when many such nodes are linked together to form a chain. Each node points to
the next node present in the order. The first node is always used as a reference to traverse the list and is
called HEAD. The last node points to NULL.
Declaring a Linked list :
In C language, a linked list can be implemented using structure and pointers
10
ii. Linked lists have efficient memory utilization. Memory is allocated whenever it is required
and it is de-allocated (removed) when it is no longer needed.
iii. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a
data item at a specified position and deletion of the data item from the given position.
iv. Many complex applications can be easily carried out with linked lists.
10
Doubly circular linked list can be conceptualized as two singly linked lists formed from the same data
items, but in opposite sequential orders.
THE PREPROCESSOR
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process.
In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to
do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as
CPP.
All preprocessor commands begin with a hash symbol (#).
It must be the first nonblank character, and for readability, a preprocessor directive should begin
in the first column.
The following section lists down all the important preprocessor directives −
Sr.No. Directive & Description
10
These directives can be classified into three categories:
1. Macro Substitution
2. File Inclusion Directives.
3. Compiler Control Directives.
MACRO SUBSTITUTION:
It is a process where an identifier in a program is replaced by a predefined string composed of one or
more tokens.
The preprocessor accomplishes this task under the direction of #define statement.
Syntax:
#define identifier string
There are different forms of macro substitutions. The most common forms are:
1. Simple macro substitutions.
2. Argumented macro substitutions.
3. Nested macro substitutions.
Example,
#define MAX(a,b) (((a)>(b))?(a) : (b))
#define MIN(a,b) (((a)<(b))?(a) : (b))
10
3) Nesting of Macros:
o It can use also one macro in the definition of another macro. That is, macro definitions may
be nested.
o Example:
#define M 5
#define N M+1
#define SQUARE(x) ((x)*(x))
#define CUBE(x) (SQUARE (x)
*(x))
Undefining a Macro:
o A defined macro can be undefined, using the statement
#undef identifier
o This is useful when we want to restrict the definition only to a particular part of the program.
FILE INCLUSION:
File inclusive Directories are used to include user define header fileinside C Program.
File inclusive directory checks included header file inside same directory (if path is not mentioned).
File inclusive directives begins with #include
If Path is mentioned then it will include that header file into current scope.
Instead of using triangular brackets we use “Double Quote” for inclusion of user defined header file.
It instructs the compiler to include all specified files.
#include"FILENAME"
Example :
Explanation :
1. In order to include user defined header file inside C Program , we must have to create one user defined
header file. [Learn How to Create User Defined Header File]
2. Using double quotes include user defined header file inside Current C Program.
10
3. “myfunc.h” is user defined header file .
4. We can combine all our user defined functions inside header file and can include header file whenever
require.
The C Preprocessor offer a feature known as conditional compilation, which can be used to switch on or off a
particular line or group of lines in a program.
Conditional selection of code using #ifdef,#endif.The preprocessor has a conditional statement similar to' C 's if
else.
It can be used to selectively include statements in a program. This is often used where two different computer
types implement a feature in different ways. It allows the programmer to produce a program which will run on
either type.
The keywords for conditional selection are; #ifdef, #else and #endif.
#ifdef: -takes a name as an argument, and returns true if the name has a current definition. The name may be
defined using a #define, the -d option of the compiler.
#else:-is optional and ends the block beginning with #ifdef. It is used to create a 2 way optional selection.
Where the #ifdef is true, statements between it and a following #else or #endif are included in the program.
Where it is false, and there is a following #else, statements between the #else and the following #endif are
included.
This is best illustrated by an example.Using #ifdef for Different Computer Types.Conditional selection is rarely
performed using #defined values.
UNIT-V COMPLETED
10