C Programming Notes
C Programming Notes
C Programming Notes
Programming
Notes
Topperworld
Contents
1 Introduction to Programming 4
3 Arrays 55
4 Functions 67
5 Recursion 83
6 Pointers 89
7 Structure 94
8 Union 102
3
Chapter-1
INTRODUCTION
Computer
that is designed to accept data as input, perform the required mathematical and logical
operations and output the result. It is now a days used for variety of uses ranging from
house hold works to space technology. The credit of invention of this machine goes to the
Types of Computers:
Based on nature, computers are classified into Analog computers and Digital
computers. The former one deals with measuring physical quantities ( concerned with
continuous variables ) which are of late rarely used. The digital computer operates by
counting and it deals with the discrete variables. There is a combined form called Hybrid
general computers. As the name tells special computers are designed to perform certain
specific tasks where as the other category is designed to cater the needs of variety of users.
4
Basic structure of a digital computer
The main components of a computer are Input unit (IU), Central Processing unit
(CPU) and Output unit (OU). The information like data ,programs etc are passed to the
computer through input devices. The keyboard, mouse, floppy disk, CD, DVD, joystick etc
are certain input devices. The output device is to get information from a computer after
processing. VDU (Visual Display Unit), Printer, Floppy disk, CD etc are output devices.
The brain of a computer is CPU. It has three components- Memory unit, Control
unit and Arithmetic and Logical unit (ALU)- Memory unit also called storage device is to
store information. Two types memory are there in a computer. They are RAM (random
access memory) and ROM (read only memory). When a program is called, it is loaded
and processed in RAM. When the computer is switched off, whatever stored in RAM will
data, program etc. are stored for future use. Inside a computer there is storage device called
Hard disk, where data are stored and can be accessed at any time.
5
The control unit is for controlling the execution and interpreting of instructions
stored in the memory. ALU is the unit where the arithmetic and logical operations are
performed.
The length of bit varies from computer to computer, from 8 to 64. A group of 8 bits is
called a Byte and a byte generally represents one alphanumeric (Alphabets and Numerals)
character.
The Physical components of a computer are called hardwares. But for the machine
to work it requires certain programs (A set of instructions is called a program). They are
called soft wares. There are two types of soft wares – System software and Application
software – System software includes Operating systems, Utility programs and Language
processors.
ASCII Codes
American standard code for information interchange. These are binary codes for
alpha numeric data and are used for printers and terminals that are connected to a computer
Operating Systems
The set of instructions which resides in the computer and governs the system are
called operating systems, without which the machine will never function. They are the
medium of communication between a computer and the user. DOS, Windows, Linux,
6
Utility Programs
various tasks. Word, Excel, Photoshop, Paint etc. are some of them.
Language Translators
These are the programs which are used for converting the programs in one language into
This process is presented in a straightforward, linear fashion but you should recognize that
these steps are repeated many times during development to correct errors and make
improvements to the code. The following are the four steps in this process 1) Writing and
Editing the program 2) Compiling the program 3) Linking the program with the required
Compiling Programs
The code in a source file stored on the disk must be translated into machine language. This
is the job of the compiler. The Compiler is a computer program that translates the source code
written in a high-level language into the corresponding object code of the low-level language.
This translation process is called compilation. The executable program is stored in a disk for
future use or to run it in another computer. The compiled programs runs the whole program
7
at time. The Compiler which executes C programs is called as C Compiler. Example Turbo
Linker
case of large program the programmer prefer to break a code into smaller modules as this
simplifies the programming task. Eventually, when the source code of all modules has been
converted into object code, we need to put all the modules together. This is the job of the
linker. Usually, the compiler automatically invokes the linker as the last step in compiling a
program. If a source file references library functions or functions defined in other source files,
the link editor combines these functions (with main ()) to create an executable file. The
Linker assembles all functions, the program’s functions and system’s functions into one
executable program.
Executing Programs
To execute a program we use an operating system command, such as run, to load the program
from a storage device to primary memory and execute it. Getting the program into memory
is the function of an operating system program known as the loader. It locates the executable
program and related files into main memory from where it can be executed by the CPU.
8
Languages.
These programs facilitate the users to make their own programs. User’s programs
are converted to machine oriented and the computer does the rest of works.
Application Programs
Computer Languages
Machine language depends on the hard ware and comprises of 0 and 1 .This is
tough to write as one must know the internal structure of the computer. At the same time
assembly language makes use of English like words and symbols. With the help of special
language. Here also a programmer faces practical difficulties. To over come this hurdles
user depends on Higher level languages, which are far easier to learn and use. To write
programs in higher level language, programmer need not know the characteristics of a
computer. Here he uses English alphabets, numerals and some special characters.
9
Some of the Higher level languages are FORTRAN, BASIC, COBOL, PASCAL,
C, C++, ADA etc. We use C to write programs. Note that Higher level languages can not
into machine coded instructions. These softwares are called Compiler, Interpreter, and
Assembler. The major difference between a compiler and an interpreter is that compiler
compiles the user’s program into machine coded by reading the whole program at a stretch
numerical data, but it does not lend itself very well to organizing large programs. Pascal
can be used for writing well-structured and readable programs, but it is not as flexible as
the C programming language. C++ goes one step a head of C by incorporating powerful
Programming Methodology
Algorithms
algorithm.
Example
To make a coffee
Step1: Take proper quantity of water in a cooking pan Step2: Place the pan on a
Step4: Put out the light and add sufficient quantity of sugar and milk
representation of an algorithm is called a Flow Chart. For this certain pictures are used.
11
Consider a problem of multiplying two numbers
Algorithm
12
Flow chart
In the above example execution is done one after another and straight forward. But such
straight forward problems occur very rarely. Sometimes we have to depend on decision
making at certain stage in a normal flow of execution. This is done by testing a condition
and appropriate path of flow is selected. For example, consider the following problem
Algorithm
compare x and y
Step 3: if x > y then compare x with z and find the greater Step 4: Otherwise
Flow Chart :
13
Exercise: Write Algorithm and flow chart for the solution to the problem
14
A brief history of C
C devolved from a language called B, written by Ken Thompson at Bell Labs in 1970.
Ken used B to write one of the first implementations of UNIX. B in turn was a descendant
of the language BCPL (developed at Cambridge (UK) in 1967), with most of its
instructions removed.
So many instructions were removed in going from BCPL to B, that Dennis Ritchie of Bell
Labs put some back in (in 1972), and called the language C.
The famous book The C Programming Language was written by Kernighan and Ritchie
in 1978, and was the definitive reference book on C for almost a decade.
The original C was still too limiting, and not standardized, and so in 1983 an ANSI
It has taken until now (ten years later) for the ANSI ( American National Standard
compilers.
Structure of a program
section, and one or more modules called functions. One of these functions is called main.
The preprocessor directives contain special instructions that indicate how to prepare the
program for compilation. One of the most important and commonly used preprocessor
commands is include which tells the compiler that to execute the program, some
information is needed from the specified header file. The global declaration statements
can be accessed at any part or block of a program as needed. A C program contains one
or more functions where, a function is defined as a group of C statements that are written
15
in a logical sequence to perform a specific task. The main() function is the most important
function and is a part of every C program . The execution of a C program begins at this
function.
All the functions (including main()) are divided into two parts-the
declaration section and the statement section. The declaration section precedes the
statement section and is used to describe the data that will be used in the function. Note
that data declared within a function are known as local declaration as that data will be
visible only within that function. The life time of the data will be only till the function
ends. The statement section in a function contains the code that manipulates the data to
Preprocessor
directives
Global declarations
main()
Local declarations
Statements
Function1()
16
Local declarations
Statements
…………….
…………….
FunctionsN()
Local declarations
Statements
STRUCTURE OF A C
PROGRAM
write Function1, Function2 etc. but with the exception that every program must contain
To write a C program, we first need to write the code. For this, open a text editor. If you
are a windows user you may use Notepad and if we want to write on UNIX/Linux we can
use emacs or vi. Once the text editor is opened on your screen type the following program
statements.
#include<stdio.h>
17
int main()
return 0;
Output:
After writing the code save the file in any name with a .c or .cpp extension(ex. file1.c or
prog1.c file1 or prog1 are file name that can be chosen by user) To see the output we need
to compile the code in any compiler like TC or DevC or GCC followed by run or execution
of the code. During compilation it show error status. Because before execution the
program should be error free. Compilation can be done by clicking compile option in the
compiler followed by click run option. If you are a Windows user then open the command
prompt by clicking Start->Run and typing ‘command’ and clicking OK. Using command
prompt, change to the directory in which you had saved your file and then type.
c:\>tc file1.c
In case you are working on UNIX/Linux operating system, then exit the text editor and
-o is the output file name. If you have leave out the -o then the file name a.out is used.
After compilation .exe file creates that can be directly run by clicking file1.exe for
Windows and typing ./file1 for UNIX /Linux operating system. When we run .exe file,
18
output of the program will be displayed on the screen i.e.
#include<stdio.h>
This is a preprocessor command that comes as the first statement in our code. All
preprocessor commands start with symbol hash(#). The #include statement tells the
compiler to include the standard input/output library or header file (stdio.h) in the
program. This file has some in-built functions. By simply including this file in our code
we can use these functions directly. The standard input/output header file contains
functions for input and output of data like reading values from the keyboard and printing
int main()
Every C program contains a main() function which is the starting point of the program .
int is the return value of the main(). After all the statement of the program have been
written, the last statement of the program will return an integer value to the operating
system . {} The two curly brackets are used to group all the related statements of the main
function. All the statements between the braces form the function body. The function body
19
printf(“\n This is your First C Program”);
The printf function is defined in the stdio.h file and is used to print the text on the screen.
The message that has to be displayed on the screen is enclosed within double quotes and
put inside the brackets. The message is quoted because in C a text is always put between
inverted commas. ‘\n’ is an escape sequence and represents a newline character. It is used
to print the message on a new line on the screen. Escape Sequences are actually non-
return 0;
This is a return command that is used to return the value 0 to the operating system to give
an indication that there were no errors during the execution of the program.
; (Semicolon)
Example
#include<stdio.h>
#include<conio.h> int
main( )
float r, a;
printf(“radius”);
20
scanf(“%f”, &r);
a=3.145*r*r;
return 0;
Library Function
They are built in programs readily available with the C compiler. These functions perform
certain operations or calculations. Some of these functions return values when they are
accessed and some carry out certain operations like input, output. A library functions
accessed in a used written program by referring its name with values assigned to necessary
arguments.
pow(d,i),
toupper(c), tolower(c).
Note : the arguments i, c, d are respectively integer, char and double type.
Example:
#include<math.h>
21
#include<stdio.h>
#include<conio.h>
int main( )
float x, s;
scanf(“%f ”,&x);
s=sqrt(x);
return 0;
Note that C language is case sensitive, which means ‘a’ and ‘A’ are different.
Before the main program there are statements begin with # symbol. They are called
preprocessor statements. Within the main program “ float r, a;” is a declaration statement.
compiler looking for library functions, which are used in the program, included in the file,
22
Data Input and Output
For inputting and outputting data we use library function. The important of these
functions are getch( ), putchar( ), scanf( ), printf( ), gets( ), puts( ). For using these
stdio.h is a header file that contains the built in program of these standard input
output function.
getchar function
It is used to read a single character (char type) from keyboard. The syntax is
char c;
c = getchar( );
#include<stdio.h> int
main( )
return 0;
Putchar Function
23
putchar(char c);
Example:
char c; c = ‘a’;
putchar(c);
Using these two functions, we can write a very basic program to copy the input, a
#include <stdio.h>
int main()
int c;
c = getchar();
while(c != EOF)
putchar(c);
c = getchar();
return 0;
scanf function
This function is generally used to read any data type- int, char, double, float, string.
The syntax is
The control string consists of group of characters, each group beginning % sign and a
24
conversion character indicating the data type of the data item. The conversion characters
are c,d,e,f,o,s,u,x indicating the type resp. char decimal integer, floating point value in
exponent form, floating point value with decimal point, octal integer, string, unsigned
integer, hexadecimal integer. ie, “%s”, “%d” etc are such group of characters.
#include<stdio.h>
Int main( )
float y;
………
…….…
NOTE:
College” cannot be read in this manner. For reading such a string constant
Example:
char place[80];
25
……………. scanf(“%[^\n]”, place);
……………..
with these statements a line of text (until carriage return) can be input the variable
‘place’.
printf function
This is the most commonly used function for outputting a data of any type.
The syntax is
Here also control string consists of group of characters, each group having %
symbol and
Example:
#include<stdio.h>
` int main()
return 0;
Note that in this list of arguments the variable names are without &symbol unlike in the
case of scanf( ) function. In the conversion string one can include the message to be
displayed. In the above example “The square of the number is” is displayed and is
26
followed by the value of x. For writing a line of text (which include blank spaces) the
There are quite a number of format specifiers for printf. Here are the basic ones :
%c print a character
%s print a string
%% print a single %
"eight", 9);
would print
The call
would print
100 144 64
Successive calls to printf just build up the output a piece at a time, so the calls
27
printf("Hello, ");
printf("world!\n");
While inputting or outputting data field width can also be specified.This is included
in the conversion string.(if we want to display a floating point number convert to 3 decimal
places the conversion string is “%.3f”).For assigning field width,width is placed before
simply “%.2f”.
C Tockens
C tokens are the basic buildings blocks in C language which are constructed together to
write a C program. Each and every smallest individual unit in a C program is known as C
28
The Character Set
C used the upper cases A,B,…….,Z, the lower cases a ,b,…..,z and certain special
Identifiers are used as the general terminology for the names of variables, functions and arrays.
Identities are names given to various program elements like variables, arrays and functions.
The name should begin with a letter and other characters can be letters and digits and also
can contain underscore character ( _ ) . They must consist of only letters, digits, or
No other special character is allowed. It should not be a keyword. It must not contain white
C keywords
These are the words that convey a special meaning to the C compiler. The keywords cannot
Auto, break, case, char, const, continue, default, do, double, else, enum, extern float, for,
goto, if, int, long, register, return, short, signed, sizeof, static, struct , Switch, typedef, union,
29
unsigned, void, volatile, while. (Note that these words should not be used as identities.)
Data Type
The variables and arrays are classified based on two aspects- first is the data type it stores
and the second is the type of storage. The basic data types in C language are int, char, float
and double. They are respectively concerned with integer quantity, single character,
numbers, with decimal point or exponent number and double precision floating point
numbers ( ie; of larger magnitude ). These basic data types can be augmented by using
quantities like short, long, signed and unsigned. ( ie; long int, short int, long double etc ).
Constants
There are 4 basic types of constants. they are integer constants, floating-point
(a) integer constants: It is an integer valued numbers, written in three different number
An octal integer constant consists of digits 0,1,…,7. with 1st digit 0 to indicate that
it is an octal integer.
30
Example :0, 01, 0756, 032, etc…..
32, 083, 07.6 etc ........................ are not valid octal integers.
0x.
Usually negative integer constant begin with ( -) sign. An unsigned integer constant is
identified by appending U to the end of the constant like 673U, 098U, 0xACLFU etc.
( b) floating point constants : It is a decimal number (ie: base 10) with a decimal
(c)character constants : It is a single character enclosed in single quotes like ‘a’. ‘3’,
‘?’, ‘A’ etc. each character has an ASCII to identify. For example ‘A’ has the ASCII
(d)escape sequences: An escape sequence is used to express non printing character like
a new line, tab etc. it begin with the backslash ( \ ) followed by letter like a, n, b, t, v, r,
31
\b : backspace \f : form feed \? : question mark
Only a single data can be stored in a variable. The data stored in the variable is accessed
by its name. before using a variable in a program, the data type it has to store is to be
declared.
Example : int a, b, c,
a=3; b=4;
c=a+b
Note : A statement to declare the data types of the identifier is called declaration statement.
An array is an identifier which is used to store a collection of data of the same type with
the same name. the data stored is an array are distinguished by the subscript. The
With this declaration n, mark is an array of size 100, they are identified by nark[0],
32
Note : along with the declaration of variable, it can be initialized too. For example int x=10;
with this the integer variable x is assigned the value 10, before it is used. Also note that
Declaration
This is for specifying data type. All the variables, functions etc must be declared before
they are used. A declaration tells the compiler the name and type of a variable you'll be
using in your program. In its simplest form, a declaration consists of the type, the name
char c; int i;
float f;
You may wonder why variables must be declared before use. There are two reasons:
1. It makes things somewhat easier on the compiler; it knows right away what kind of storage
to allocate and what code to emit to store and manipulate each variable; it doesn't have to
2. It forces a bit of useful discipline on the programmer: you cannot introduce variables
willy-nilly; you must think about them enough to pick appropriate types for them. (The
compiler's error messages to you, telling you that you apparently forgot to declare a
variable, are as often helpful as they are a nuisance: they're helpful when they tell you that
you misspelled a variable, or forgot to think about exactly how you were going to use it.)
Expression
This consists of a single entity like a constant, a variable, an array or a function name. it
Statements
Statements are the ”steps” of a program. Most statements compute and assign values or
call functions, but we will eventually meet several other kinds of statements as well. By
default, statements are executed in sequence, one after another. A statement causes the
compiler to carry out some action. There are 3 different types of statements – expression
statements compound statements and control statements. Every statement ends with a
semicolon.
(2) {
a=3; b=4;
c=a+b;
(3) if (a<b)
i = 0;
i = i + 1;
Symbolic Constants
With this definition it is a program the values of p, n ,r are assigned the value of
INTEREST is computed.
35
Chapter-2
Arithmetic Operators
The basic operators for performing arithmetic are the same in many computer
languages:
+ addition
- subtraction
* multiplication
/ division
% modulus (remainder)
For exponentiations we use the library function pow. The order of precedence of
results in truncation. i.e.When applied to integers, the division operator / discards any
quantity (type float or double), the division operator yields a floating-point result, with
a potentially nonzero fractional part. So 1 / 2.0 is 0.5, and 7.0 / 4.0 is 1.75.
Example : int a, b, c;
a=5; b=2;
c=a/b;
36
Actual value will be resulted only if a or b or a and b are declared floating type. The
Example : int a, b;
Here c=2.5
Order Preference
addition and subtraction. The term ``precedence'' refers to how ``tightly'' operators
bind to their operands (that is, to the things they operate on). In mathematics,
Unary Operator
operator.
(1) the decrement and increment operators - ++ and -- are unary operators. They increase
Note : in the place of ++x , x++ can be used, but there is a slight variation. In both
int x, y; y=sizeof(x);
The value of y is 2 . the sizeof an integer type data is 2 that of float is 4, that of
37
double is 8, that of char is1.
< ( less than ), <= (less than or equal to ), > (greater than ), >= ( greater than
example ‘b*b – 4*a*c< 0 is a logical expression. Its value is either true or false.
int i, j, k ;
i=2;
j=3 ;
k=i+j ;
k>4 has the value true k<=3 has the value false.
Logical Operator
The relational operators work with arbitrary numbers and generate true/false values. You
can also combine true/false values by using the Boolean operators, which take true/false
values as operands and compute new true/false values. The three Boolean operators are:
&& and
38
|| or
The && (``and'') operator takes two true/false values and produces a
true (1) result if both operands are true (that is, if the left- hand
operator takes two true/false values and produces a true (1) result
true/false value and negates it, turning false to true and true to
&& (and ) and || (or) are logical operators which are used to connect logical
2. (a<=3) || (b>2)
Assignment Operator
These operators are used for assigning a value of expression to another identifier.
Note : 1. if a floating point number is assigned to a integer type data variable, the
value will be
truncated.
It results in storing 5 to b.
Similarly if an integer value is a assigned to a float type like float x=3 the
Conditional Operator
Example:
int a,b,c,d,e
a=3;b=5;c=8;
d=(a<b)? a : b;
e=(b>c) ? b : c;
#include <stdio.h>
int main()
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
40
printf("y value is %d", y);
OUTPUT:
x value is 1
y value is 2
These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits. Bit wise
| (bitwise OR),
~ (bitwise OR),
^ (XOR),
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
(decimal) x^y = 01111000 (binary) = 120 (decimal) x << 1 = 01010000 (binary) = 80 (decimal)
41
is0000000000000000000000000000000000000000000000000010100000000000. So, all 0‘s are
converted into 1‘s in bit wise NOT operation. Bit wise left shift and right shift : In left shift
operation ―x << 1 ―, 1 means that the bits will be left shifted by one place. If we use it as ―x
<< 2 ―, then, it means that the bits will be left shifted by 2 places.
In this example program, bit wise operations are performed as shown above and output is
#include <stdio.h>
int main()
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
OUTPUT:
AND_opr value = 0
42
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
When variables and constants of different types are combined in an expression then they are
converted to same data type. The process of converting one predefined type into another is called
type conversion. Type conversion in c can be classified into the following two types: Implicit
Type Conversion When the type conversion is performed automatically by the compiler without
programmer‘s intervention, such type of conversion is known as implicit type conversion or type
promotion. The compiler converts all operands into the data type of the largest operand. The
sequence of rules that are applied while evaluating expressions are given below: All short and
char are automatically converted to int, then, If either of the operand is of type long double, then
others will be converted to long double and result will be long double. Else, if either of the operand
Else, if either of the operand is float, then others are converted to float. Else, if either of the operand
is unsigned long int, then others will be converted to unsigned long int. Else, if one of the operand
is long int, and the other is unsigned int, then if a long int can represent all values of an unsigned
int, the unsigned int is converted to long int. otherwise, both operands are converted to unsigned
long int. Else, if either operand is long int then other will be converted to long int. Else, if either
operand is unsigned int then others will be converted to unsigned int. It should be noted that the
final result of expression is converted to type of variable on left side of assignment operator before
assigning value to it. Also, conversion of float to int causes truncation of fractional part,
43
conversion of double to float causes rounding of digits and the conversion of long int to int causes
Explicit Type Conversion The type conversion performed by the programmer by posing the data
type of the expression of specific type is known as explicit type conversion. The explicit type
conversion is also known as type casting. Type casting in c is done in the following form:
(data_type)expression; where, data_type is any valid c data type, and expression may be constant,
variable or expression. For example, x=(int)a+b*d; The following rules have to be followed while
converting the expression from one type to another to avoid the loss of information: All integer
types to be converted to float. All float types to be converted to double. All character types to be
converted to integer.
Control Statements
When we run a program, the statements are executed in the order in which they
appear in the program.Also each statement is executed only once. But in many cases we
condition is satisfied. Also we may want to skip some statements based on testing a
Branching
44
Looping
Conditional Branching
1. if else statement
It is used to carry out one of the two possible actions depending on the
The syntax is
Or
if (expression)
statement1;
else
statement2;
45
,they are written as a block using the braces { }
3.if(x<0)
x=-x;
s=sqrt(x);
else
x=sqrt(x);
46
2. nested if statement
Within an if block or else block another if – else statement can come. Such
The syntax is
if (expression1)
statement1
if (expression2)
statement2 else
statement3
3. Ladder if Statement
The syntax is
If (expression1)
statement1
else if (expression2)
statement2
else if (expression3)
47
statement3
……………….
……………
else statementn
printf(“\n good”);
printf(“\n to be improved”);
Switch Statement
switch(expression){
case value1:
statement1;
break;
case value2:
statement2;
48
break;
…………………..
…………………..
default:
statement;
All the option are embedded in the two braces { }.Within the block each group is
written after the label case followed by the value of the expression and a colon.
Each group ends with ‘break’ statement. The last may be labeled ‘default’. This is
to avoid error and to execute the group of statements in default if the value of the
Looping
simple or compound.
49
Example 1: #include<stdio.h>
main()
while(n > 0)
printf("\n"); n = n - 1;
Example2:
#include<stdio.h>
int main()
int i=1;
while(x<=10)
printf(“%d”,i);
++i;
return 0;
2. do while statement
do statement while(expression)
50
Example: #include<stdio.h>
int main()
int i=1; do
printf(“%d”,i);
++i;
}while(i<=10);
Return 0;
1) In the while loop the condition is tested in the beginning whereas in the other
2) In while loop the statements in the loop are executed only if the condition is true.
Whereas in do – while loop even if the condition is not true the statements are
3. for loop
for(expression1;expression2;expression3)
statement;
51
Here expression1 is to initialize some parameter that controls the looping action.
expression2 is a condition and it must be true to carry out the action. expression3
Example: #include<stdio.h>
int main()
return 0;
Here the program prints i starting from 1 to 10.First i is assigned the value 1 and
#include<stdio.h> int
main()
int i;
scanf(“%f”,&x); avg += x;
avg /= 10;
printf(“\n average=%f”,avg);
return 0;
52
}
Example : for(i=1;i<=10;++i)
for(j=1;j<=10;++j);
#include<stdio.h>
int main()
while(n<=10)
sum+=x;
printf(“%d”,sum);
return 0;
53
Example 2 :A program for printing prime numbers between 1 and 100:
#include <stdio.h>
#include <math.h>
int main()
int i, j;
printf("%d\n", 2);
for(j = 2; j < i; j = j + 1)
if(i % j == 0)
return 0;
It is used to bypass the remainder of the current pass through a loop. The loop does
54
not terminate when continue statement is encountered, but statements after
continue are skipped and proceeds to the next pass through the loop. In the above
example of summing up the non negative numbers when a negative value is input,
it breaks and the execution of the loop ends. In case if we want to sum 10
Example : #include<stdio.h>
int main()
scanf(“%d”,x);
if(x<0) continue;
sum+=x;
++n;
} printf(“%d”,sum);
return 0;
goto statement
It is used to alter the normal sequence of program execution by transferring control to some
55
Example :
#include<stdio.h>
int main( )
int n=1,x,sum=0;
while(n<=10)
scanf(“%d” ,&x);
++n;
error:
return 0;
56
Chapter-3
Arrays
An array is an identifier to store a set of data with common name.
Note that a variable can store only a single data. Arrays may be one dimensional or
multi-dimensional.
Definition: Arrays are defined like the variables with an exception that each array
name must be accompanied by the size (i.e. the max number of data it can store).For a
one dimensional array the size is specified in a square bracket immediately after the
The syntax is
int i;
int a[10];
declares an array, named a, consisting of ten elements, each of type int. Simply
speaking, an array is a variable that can hold more than one value. You specify which of
the several values you're referring to at any given time by using a numeric subscript.
57
above with a picture like this:
float mark[50];
char name[30];
Note: With the declaration int x[100],computer creates 100 memory cells with name
Array Initialization
Although it is not possible to assign to all elements of an array at once using an assignment
expression, it is possible to initialize some or all elements of an array when the array is
The list of values, enclosed in braces {}, separated by commas, provides the initial values
If there are fewer initializers than elements in the array, the remaining elements are
would initialize a[7], a[8], and a[9] to 0. When an array definition includes an
initializer, the array dimension may be omitted, and the compiler will infer the dimension
int x[ ] ={0,1,2,3,4,5}; or
int x[6]={0,1,2,3,4,5};
statement is like
int x[3]={0,1,2,3,4,5};
int x[6]={0,1,2};
then the values are stored like x[0]=0, x[1]=1, x[2]=2, x[3]=0, x[4]=0 and x[5]=0.
If we want to read n values to an array name called ‘mark’ , the statements look like
int mark[200],i,n;
for(i=1;i<=n;++i)
scanf(“%d”,&x[i]);
Note: Here the size of array declared should be more than the number of values that are
intended to store.
To store an array to another array. Suppose a and b are two arrays and
we want to store that values of array a to array b. The statements look like
i; for(i=1;i<=100;++i)
59
b[i]=a[i];
#include<stdio.h>
int main( )
int x,i;
float x[100],avg=0;
scanf(“%d”,&n);
for(i=1;i<=n;++i)
scanf(“%f”,&x[i]); avg=avg+x[i];
avg=avg/n;
Ex:
60
Now let us see to use a function program to calculate the average
of a set of values.
#include<stdio.h>
main()
int n;
float x[100],avg;
scanf(“%d”,&n);
for(i=1;i<=n;++i)
scanf(“%f”,&x[i]); avg=average(n,x);
for(i=1;i<=n;++i)
sum=sum+y[i]; sum=sum/n;
return(sum);
Note:
Ex:
#include<stdio.h>
………..
arrange(n,x);
…………..
……….
return;
MULTI-DIMENSIONAL ARRAYS
62
Initiating a two dimensional array we do as int x[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}
Or
int x[3][4]={
{1,2,3,4};
{5,6,7,8};
{89,10,11,12};
NOTE: The size of the subscripts is not essential for initialization. For reading a two
Example
for(i=1;i<=2;++i) for(j=1;j<=3;++j)
scanf(“%f”,&A[i][j]);
NOTE: If x[2][3] is a two dimensional array, the memory cells are identified with name
access specifier in c and c++. A string is always terminated with \0 (Null) character.
Example: Char ar[20] · The above example will store 19 character with I null character.
63
If we want to store many strings(like many names or places) two dimensional array is
used. Suppose we want to store names of 25 persons, then declare name as char name[25][
]. Note that the second square bracket is kept empty if the length of string is not specified.
If the declaration is char name[25][30], 25 names of maximum size 30 can be stored. The
scanf( “%[^\n]”,name(i));
WAP to accept a complete string (first name and last name) and display in
the output.
# include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
char str1[20];
char str2[20];
scanf(“%s”,&str1);
scanf(“%s”,&str2);
puts(str1); puts(str2);
}
64
String Functions in C: Our c language provides us lot of string functions
for manipulating the string. All the string functions are available in
1. strlen().
2.strupr().
3. strlwr().
4. strcmp().
5.strcat().
6.strapy().
7.strrev().
3.strlwr (). This string function is basically used for the purpose of
65
Example: char str = “Gaurav” strlwr(str);
4.strcmp ().
This string function is basically used for the purpose of comparing two
Case 1: if first string > than second string then, result will be true.
Case 2: if first string < than second string then, result will be false.
str3=strcmp(str1,str2); printf(“%s”,str3);
str3=strcat(str1,str2); printf(“%s”,str3);
copying one string into another string. char str1= “Gaurav”; char
66
str2= strrev(str2,str1); printf(“%s”,str2);
string into upper case. 2. To reverse the string . 3. To copy string into
# include<stdio.h>
# include<conio.h>
#include<string.h>
int main() {
char str[20];
char str1[20];
int opt,len;
scanf(“%d”,&opt);
switch(opt) {
case 1: strupr(str);
break;
67
case 2: strrev(str);
break;
case 3: strcpy(str1,str);
break;
case 4: len=strlen(str);
break;
default:
return 0;
68
Chapter-4
FUNCTIONS
functions and programmer written functions. We are familiarised with library functions and
Defining a Function
well defined task. It is written after or before the main function. A function has two
statements return;
If the function does not return any value to the calling point (where the function is
69
{
statements return;
If a value is returned to the calling point, usually the return statement looks like
Note that if a function returns no value the keyword void can be used before the function name.
Example:
printf(“%s”,x); return;
int z ;
z=(x>=y)? x: y ; return(z);
int z;
return ;
Note: In example (1) and (2) the function does not return anything.
Advantage of Function
1. It appeared in the main program several times, such that by making it a function, it can be
written just once, and the several places where it used to appear can be replaced with calls
70
to the new function.
2. The main program was getting too big, so it could be made (presumably) smaller and more
Accessing a Function
The arguments should be of the same data type defined in the function definition.
Example:
y=maximum(a,b);
writecaption(name);
Example:
#include<stdio.h>
int z ;
71
z=(x>=y) ? x : y ; return
(z);
int main( )
c=maximum(a,b);
return 0;
Function Prototype
It is a common practice that all the function programs are written after the
main( ) function. When they are accessed in the main program, an error of prototype
function is shown by the compiler. It means the computer has no reference about the
programmer defined functions, as they are accessed before the definition. To overcome
this, i.e to make the compiler aware that the declarations of the function referred at the
calling point follow, a declaration is done in the beginning of the program immediately
Example1:
1)
#include<stdio.h>
int main( )
72
int a,b,c; scanf(“%d%d”,&a,&b);
c=maximum(a,b);
return 0;
int z;
z=(x>=y) ? x : y ;
return(z);
Example-2
#include<stdio.h>
int main( )
int n;
scanf(“%d”,&n);
factorial(n);
return 0;
int i,p=1;
for(i=1;i<=m;++i)
73
p*=i;
return( );
Note: In the prototype declaration of function, if it return no value, in the place of data-
The values are passed to the function program through the arguments. When a value
is passed to a function via an argument in the calling statement, the value is copied into the
formal argument of the function (may have the same name of the actual argument of the
calling function). This procedure of passing the value is called passing by value. Even if
formal argument changes in the function program, the value of the actual argument does
not change.
Example
#include<stdio.h> void
main( )
int x;
scanf(“%d”,&x);
square(x):
return 0;
74
}
void square(int x)
x*=x ;
return;
Call by Value
In which values of variables are passed by the calling function to the called function. The
programs that we have written so far call functions using call-by-value method of passing
parameters. In call by value method, the called function creates new variables to store the
value of the arguments passed to it. Therefore, the called function uses a copy of the actual
If the called function is supposed to modify the value of the parameters passed to it, then the
change will be reflected only in called function. In the calling function no change will be
made to the value of variables .This is because all the changes were made to copy of the
#include<stdio.h>
Void add(int n)
Int main(){
Int num=2;
Add(num);
75
Return 0;
Void add(int n)
N=n+10;
In this program the add() accepts an integer variable num and adds to it. In the calling
function, the value of num=2. In add(), the value of num is modified to 12 but in the calling
Since the called function uses a copy of num, the value of num in the calling function remains
untouched .
Call by Reference
In which address of variables are passed by the calling function to the called function. When
calling function passes arguments to the called function using call-by-value method, the only
way to return the modified value of the argument to the caller is explicitly using the return
statement. The better option when a function wants to modify the value of the argument is to
function parameters as references rather than normal variables.When this is done by any
change made by function to the arguments it receives are visible in the calling function. To
indicate that an argument is passed using call by reference, an asterisk(*) is placed after the
type in the parameter in the called function will then be reflected in the calling function.
76
Hence, in call-by-reference method, a function receives an implicit reference to the argument,
rather than a copy of its value. Therefore, the function can modify the value of the variable
Example:
#include<stdio.h>
int main()
int num=2;
add(&num);
return 0;
{ *n=*n+10;
Output:
Advantages
The advantages of using the call-by-reference technique of passing arguments are as follows.
Since arguments are not copied into new variables, it provides greater time and space
77
efficiency.
The called function can change the value of the argument and the change is reflected in the
calling function.
A return statement can return only one value. In case we need to return multiple values, pass
Disadvantages
However side effect of using this technique is that when an argument is passed using call by
address, it becomes difficult to tell whether that argument is meant for input, output o
Storage Classes
Storage classes defines the scope(visibility) and lifetime of variables and/or functions declared
within a C program. In addition to this, the storage class gives the following information about
The storage class of a function or a variable determines the part of memory where storage space
will be allocated for that variable or function (whether the variable/function will be stored in a
register or in RAM).
It specifies how long the storage allocation will continue to exit for that function or variable.
It specifies the scope of variable or functions i.e. the storage class indicates the part of the C
program in which the variable name is visible or the part in which it is accessible. In other
words, whether the variable/function can be referenced throughout the program or only within
78
It specifies whether the variable or function has internal, external or no linkage.
It specifies whether the variable or function will be automatically initialized to zero or to any
indeterminate value.
and static. The general syntax for specifying the storage class of a variable can be given
as:
The auto storage class specifier is used to explicitly declare a variable with automatic
storage. It is local and its scope is restricted to that block or function. They are called so
because such variables are created inside a function and destroyed automatically when the
variable unless specified otherwise. So the keyword auto is not required at the beginning
of each declaration.
Here x is an integer that has automatic storage. It is deleted when the block in which x is
declared is exited.
Memory for the variable is automatically allocated upon entry to a block and freed
79
The scope of the variable is local to the block in which it is declared. These variable may be
Every time the block is entered, the variable is initialized with the values declared.
If auto variables are not initialized at the time of declaration, then they contain some garbage
value.
When a variable is declared using registered as its storage class, it is stored in a CPU register
as its storage class, it is stored in a CPU register instead of RAM. Since the variable is stored
in a register, the maximum size of the variable is equal to the the register size. One drawback
of using a register variable is that they cannot be operated using the unary ‘&’ operator
because it does not have a memory location associated with it. A register variable is declared
register int x;
Registered variables are used when quick access to the variable is needed. It also stored in
registered depending on the hardware and implementation restrictions. Like auto variable,
register variables also have automatic storage duration. Each time a block is entered, the
register variables defined in that block are accessible and the moment that block is existed,
Example:
80
Extern Storage Class (Global Variable)
The variables which are alive and active throughout the entire program are called external
variables. It is not centered to a single function alone, but its scope extends to any function
having its reference. The value of a global variable can be accessed in any program which
uses it. For moving values forth and back between the functions, the variables and arrays
are declared globally i.e., before the main program. The keyword external is not necessary
for such declaration, but they should be mentioned before the main program. Incase the
Example:
//FILE1.c
#include<stdio.h>
int x;
void print(void)
int main()
x=10;
print();
return 0;
//End of FILE1.c
81
//FILE2.c
#include<stdio.h>
extern int x;
void print()
Printf(“\n x in FILE2=%d”,x);
main(){
//statements
//end of FILE2.c
Output:
X in FILE1=10
In the program, we have used two files-FILE1 and FILE2.FILE1 has declared a global
variable x. FILE1 also includes FILE2 which has print function that uses the external
automatic variables static variable retains values throughout the life of the program, i.e. if
a function is exited and then re-entered at a later time the static variables defined within the
function will retain their former values. Thus this feature of static variables allows
functions to retain information permanently throughout the execution of the program. Static
variable is declared by using the keyword static. To declare an integer x as static , write
82
When a static variable is not explicitly initialized by the programmer, then it is
automatically initialized to zero when memory is allocated for it. Although static automatic
variables exist even after the block in which they are defined terminates, their scope is local
Static storage class can be specified for auto as well as extern variables.
When we declare a variable as extern static variable, then that variable is accessible from
Look at the following code which clearly differentiates between a static variable and a
normal variable.
#include<stdio.h>
void print(void);
int main()
print();
print();
print();
83
return 0;
void print()
static int x;
int y=0;
x++;
y++;
Output:
84
Chapter-5
RECURSION
satisfied. It is used for repetitive computation (like finding factorial of a number) in which
Example:
#include<stdio.h>
int main( )
int n;
long int m;
scanf(“%d”,&n);
m=factorial(n);
return 0;
if (n<=1)
return(1);
else
return(n*factorial(n-1));
85
In the program when n is passed the function, it repeatedly executes calling the same
#include<stdio.h>
int main(){
scanf(“%d %d”,&num1,&num2);
res=GCD(num1,num2);
return 0;
int rem;
rem=x%y;
if(rem==0)
return y;
else
return GCD(y,rem);
86
Output:
Types of Recursion
Recursion is a technique that breaks a problem into one or more sub-problems that are
similar to the original problem. Any recursive function can be characterized based on:
Whether any operation is pending at each recursive call (tail-recursive or not) , and
Direct Recursion
int fun(int n)
{ if(n==0)
return 0;
else
return (fun(n-1));
Here fun() calls itself for all positive values of n, so it is said to be a directly recursive
function.
Indirect Recursion
87
ultimately calls it. These two functions are indirectly recursive as they both call each other.
int fun1(int n)
{ if(n==0)
return n;
else
return fun2(n);
int fun2(int x)
return fun2(x-1);
Tail Recursion
when the recursive function returns to its caller.When the called function returns, the returned
value is immediately returned from the calling function. Tail recursive functions are highly
desirable because they are much more efficient to use as the amount of information that has
For example , the factorial function that we have written is a non-tail recursive function,
recursive call.
int Fact(int n)
if(n==1)
return 1;
else
88
return (n*Fact(n-1));
recursive. In such a non-tail recursive function, information about each pending operation
must be stored, so the amount of information directly depends on the number calls.
However, the same factorial function can be written a tail-recursive manner as follows.
int Fcat(n)
return Fact1(n,1);
if(n==1)
return(n==1)
else
auxiliary parameter as we did in case of the Factorial function. The auxiliary parameter is
used to form the result. When we use such a parameter, the pending operation is incorporated
into the auxiliary parameter so that the recursive call no longer has a pending operation. We
generally use an auxiliary function while using the auxiliary parameter. This is done to keep
the syntax clean and hide the fact that auxiliary parameters are needed.
89
90
Chapter-6
POINTERS
element.
Uses
1. They are used to pass information back and forth between a function and calling
point.
When we declare a variable say x, the computer reserves a memory cell with name x. the
data stored in the variable is got through the name x. another way to access data is through
the address or location of the variable. This address of x is determined by the expression
&x, where & is a unary operator (called address operator). Assign this expression &x to
another variable px(i.e. px=&x).this new variable px is called a pointer to x (since it points
to the location of x. the data stored in x is accessed by the expression *px where * is a
int *p declares the variable p as pointer variable pointing to a an integer type data. It is
91
The value stored in q is got by *p.
Ex: float a;
Note : here in ‘b’ address of ‘a’ is stored and in ‘*b’ the value of a is stored.
Pointers are also passed to function like variables and arrays are done. Pointers are normally
used for passing arguments by reference (unlike in the case if variable and arrays, they are
passed by values). When data are passed by values the alteration made to the data item with
in the function are not carried over to the calling point; however when data are passed by
reference the case is otherwise. Here the address of data item is passed and hence whatever
changes occur to this with in the function, it will be retained through out the execution of
the program. So generally pointers are used in the place of global variables.
Ex: )
#include<stdio.h>
int main()
int x = 1;
92
int y=2;
f(&X,&y);
return 0;
*px=*px+1;
*py=*py+2;
return;
Note:
An array name is really a pointer to the first element in the array i.e. if x is a one
dimensional array, the name x is &x[0] and &x[i] are x + i for i= 1,2,……. So to read
int x[100],n;
scanf (“%d”, x + i )
93
(in the place of scanf (“%d”,&x[i] ) )
Note : the values stored in the array are got by * ( x + i ) in the place x[i].
Usually when we use an array in C program, its dimension should be more than enough or
may not be sufficient. To avoid this drawback we allocate the proper ( sufficient)
dimensions of an array during the run time of the program with the help of the library
functions called memory management functions like ‘malloc’, ‘calloc’, ‘realloc’ etc. The
Ex;
x= (int *) malloc (n* sizeof (int) ) , for in the place of initial declaration int x[n]
int main()
scanf(“%d”, &n);
94
x=(int *)malloc(n * sizeof(int));
for(i=1;i<=n,++i)
*(x+i);
return 0;
95
Chapter-7
STRUCTURE
We know an array is used to store a collection of data of the same type. But if we want to
deal with a collection of data of various type such as integer, string, float etc we use
tool for handling logically related data items of bio-data people comprising of name, place,
date etc. , salary details of staff comprising of name, pay da, hra etc.
Defining a structure.
Struct structure_name
For example
1 struct account
}customer[20]
Note :1here accountno, name and balance are called members of the tructure
96
2 struct date
year;
}dateofbirth;
In these examples customer is a structure array of type account and dateofbirth is a structural
type of date.
For example
struct date
year;
struct biodata
Date birthdate;
}staff[30];
Note: we can declare other variables also of biodata type structure as follows.
97
Processing a structure
The members of a structure are themselves not variable. They should be linked to the
structure variable to make them meaningful members. The linking is done by period (.)
If staff[] is structure array then the details of first staff say staff[1] is got by
Staff[1].name=”Jayachandran”
staff[1].age=26
staff[1].birthdate.day=11
staff[1].birthdate.month=6
staff[1].birthdate.year=1980
If ‘employee’ is a structure variable of type biodata as mentioned above then the details
biodata employee;
employee.birthdate.year etc.
Structure initialisation
Like any other variable or array a structure variable can also be initalised by using
syntax static
struct record
98
char name[30]; int
age;
int weight;
Here student1 is of record structure and the name,age and weight are initialised as
Write a c program to read biodata of students showing name, place, pin, phone and
grade
#include<stdio.h> int
main()
struct biodata
};
int n;
prinf(“\n no of students”);
scanf(“%d”,n);
for(i=1;i<=n;++i)
99
{
scanf(“%s”,student[i].name);
scanf(“%s”,student[i].place);
scanf(“%d”,student[i].pin); scanf(“%ld”,student[i].phone);
scanf(“%c”,student[i].grade);
}return 0;
This is to define new data type equivalent to existing data types. Once defined a user-
defined data type then new variables can be declared in terms of this new data type. For
Now integer is a new type and using this type variable, array etc can be defined as
integer x;
integer mark[100];
Ex2:
typedef struct
100
int accno; char name[30];
float balance;
}record;
Now record is structure type using this type declare customer, staff as record type
Record customer;
Record staff[100];
Mainly there are two methods by which structures can be transferred to and from a
function.
Example 1
#include<stdio.h>
typedef struct
float balance;
}record;
int main()
…..
Record customer;
101
. . . .
Customer.balance=adjust(customer.name,customer.accn
o,balance)
. . . . .
return 0;
float x;
. . . . . X=
. . . . .
return(x);
Example 2
#include<stdio.h>
typedef struct
float balance;
}record;
int main()
102
record customer;
. . . . . .
adjust(&customer);
printf(“\n %s\t%f”,coustomer.name,customer.balance)
return 0;
float x;
. . . .
cust->balance=...
. . . .
return;
In the first example structure members are passed individually where as in the second
case customer is passed entirely as a pointer named cust. The values of structure
members are accessed by using -> symbol like cust->.name, cust->balance etc.
103
Chapter-8
Union
Union is a concept similar to a structure with the major difference in terms of storage.
In the case of structures each member has its own storage location, but a union may
contain many members of different types but can handle only one at a time. Union is
union var
int m; char c;
float a;
union var x;
Now x is a union containing three members m,c,a. But only one value can be stored either in
104
Chapter-9
FILE HANDLING
Data Files are to store data on the memory device permanently and to access
whenever is required.
Stream oriented data files are either text files or unformatted files. System oriented data
files are more closely related to computer’s operating system and more complicated to
File *fp;
Here fp is the pointer variable to indicate the beginning of the buffer area and called
stream pointer .
The next step is to open a data file specifying the type i.e. read only file, write only file,
read /write file. This is done by using the library function fopen.
The syntax is
fp=fopen(filename,filetype)
2 ‘w’ ( to open a new file for writing only. If file with filename exists, it will be destroyed
105
and a new file is created in its place)
3 ‘a’ ( to open an existing file for appending. If the file name does not exist a new file with
5 ‘w+’ ( to open a new file for reading and writing. If the file exists with that name, it will
6 ‘a+’ ( to open an existing file for reading and writing. If the file does not exist a new file
will be created).
For writing formatted data to a file we use the function fprintf. The syntax is
For example to write the name “rajan” to the file named ‘st.dat’
fprintf(fp,”%[^\n]”,”rajan”);
The last step is to close the file after the desired manipulation. This is done by the library function
Example:1
#include<stdio.h>
#include<string.h>
typedef struct{
int day;
int month;
int year;
}date;
Typedef struct{
106
char name(30);
date birthdate;
}biodata;
int main(){
scanf(“%[^\n]”,student.name);
scanf(“%[^\n]”,student.place);
scanf(“%d”,&student.age);
scanf(“%d”,&student.birthdate.day);
scanf(“%d”,&student.birthdate.month): scanf(“%d”,&student.birthdate.year);
fprintf(fp,”%s%s%d%d%d%d”,student.name,student.place,student.
fclose(fp);
return 0;
#include<stdio.h>
int main(){
file *fp;
int n;
float x ;
fp=fopen(“num.dat”,’w’);
scanf(“%d”,&n);
for(i=1;i<=n;++i)
{ scanf(“%d”,&x);
fprintf(fp,”%f\n”,x);
} fclose(fp);
107
return 0;
To read formatted data from a file we have to follow all the various steps that
discussed above. The file should be opened with read mode. To open the existing file
‘r+’);
For reading formatted data from a file we use the function fscanf
typedef struct
int age;
date birthdate;
}biodata;
typedef struct{
char name[30];
char place[30];
int age;
int birthday;
}biodata;
int main(){
108
student;
fp=fopen(“st.dat”,’r+’); fscanf(fp,”%s”,student.name);
printf(“%s”,student.name); fclose(fp);
return 0;
For reading and writing unformatted data to files we use the library functions fread
The syntax for writing data to file ‘st.dat’ with stream pointer fp is
fwrite(&student, sizeof(record),1,fp);
#include<stdio.h>
typedef struct{
int date;
int month;
int year;
}date;
typedef struct
int age;
date birthdate;
109
}biodata;
int main(){
File *fp;
fp=fopen(“st.dat”,’a+’) biodata
scanf(“%[^\n]”,student.name);
scanf(“%[^\n]”,student.place);
scanf(“%d”,&student.age);
scanf(“%d”,&student.birthdate.day);
scanf(“%d”,&student.birthdate.month):
scanf(“%d”,&student.birthdate.year);
fwrite(&student,sizeof(record),1,fp); fclose(fp);
return 0;
tpedef struct
year;
}date;
typedef struct
int age;
date birthdate;
}biodata;
int main()
110
{
biodata student;
fread(&student,sizeof(record),1,fp);
printf(“%s\n”,student.name); printf(“%s\n]”,student.place);
printf(“%d\n”,&student.age);
printf(“%d\n”,&student.birthdate.day);
printf(“%d\n”,&student.birthdate.month):
printf(“%d\n”,&student.birthdate.year); fclose(fp);
return 0;
111
Chapter-10
BASICS ALGORITHMS
Algorithms are mainly used to achieve software reuse. Once we have an idea or a blueprint of
An algorithm is basically a set of instructions that solve a problem. It is not uncommon to have
multiple algorithms to tackle the same problem, but the choice of a particular algorithm must
An algorithm has a finite number of steps . Some steps may have involve decision-making
and repetition. Broadly speaking an algorithm may employ one of the following control
Sequence:
By sequence we mean that each steps of an algorithm is executed in a specified order. Let us
write an algorithm to add two numbers . This algorithm performs the steps in a purely
Step 5: End
Decision:
Decision statements are used when the execution of a process on the outcome of the
112
condition. For example if x=y, then print EQUAL. So the general form of IF construct can be
given as follows.
A condition in this context is any statement that may evaluate to either a true value or a false
value. In the above example, a variable x can be either equal to yor not equal to y. However,
it cannot be both true or false. If the condition is true , then the process is executed. A
IF condition
Then process1
ELSE process2
This form is populary known as the IF-ELSE constructed. Here, if the condition is true , then
Step 3: IF A=B
PRINT “EQUAL”
ELSE
[END OF IF]
Step 4: END
Repetition
Repetition, which involves execution one or more steps for a number of times can be
implemented using constructs such as while , do-while and for loops. These loops execute
113
Algorithm to print the first 10 natural of two numbers.
Step 3: PRINT I
[END OF LOOP]
Step 5: END
Analysis an algorithm means determining the amount of resources (such as time and memory)
needed to execute it. The time complexity of an algorithm is basically the running time of a
program as a function of the input size. Similarly , the space complexity of an algorithm is the
amount of computer memory that is required during the program executing as a function of the
input size.
In other words, the number machine instructions which a program executes is called its time
complexity. This number is primarily dependent on the size of the program’s input and the
algorithm used.
Fixed Part: It varies from Problem to Problem. It includes the space needed for storing
instructions, constants, variables and structured variables like arrays and structures).
Variable Part: It varies from program to program.It includes the space needed for recursion
stack, and for structured variables that are allocated space dynamically during the runtime of a
program.
114
Worst-case, Average-case, Best-case and Amortized Time Complexity
Worst-case running time: This denotes the behaviour of an algorithm with restpect to the worst
-possible case of the input instance. The worst-case running time of an algorithm is an upper
It is the estimate of the running time of an “average” input. It specifies the expected behavior
of the algorithm when the input is randomly drawn from a given distribution. Average-case
running time assumes that all inputs of a given size are equally likely.
The term “Best-case performance” is used to analyze an algorithm under optimal conditions.
For example, the best case for a simple linear search on an array occurs when the desired
Amortized running time refers to the time required to perform a sequence of operations
averaged over all the operations performed. Amortized analysis guarantees the average
The time and space complexity can be expressed using a function f(n) where n it the input size
for a given instance of the problem being solved. Expressing the complexity is required when
We want to predict the rate of growth of complexity as the input size of the problem increases.
115
There are multiple algorithms that find a solution to a given problem and we need to find the
The most widely used notation to express this function f(n) is the Big O notation.it provides
Algorithm Efficiency:
If a function is linear (without any loop or recursion), the efficiency of an algorithm can be
given as the numbers of instructions it contains. However, if an algorithm contains loops, then
the efficiency of that algorithm may very depending on the number of loops and the running
Big O Notation
It has been seen that the number of statements executed in the program for n elements of the
data is a function of the number of elements , expressed as f(n). Even if the expression derived
for a function is complex, a dominant factor in the expression is sufficient to determine the
order of the magnitude of the result and hence the efficiency of the algorithm. This factor is the
Big O, and expressed as O(n). The Big O notation, where O stands for ‘order of ‘ is concerned
with what happens for very large value of n. For example, if a sorting algorithm performs n 2
operations to sort just n elements , then that algorithm would be described as an O(n)2algorithm.
If (n) and g(n) are the functions defined on a positive integer n, then
f(n)=Og(n).
That is f on n is Big-O of g of n if and only if positive constants c and n exists such that
f(n)<=cg(n). It means that for large amounts of data, f(n) will grow no more than a constant
116
Example:
For(i=0;i<100;i++)
Statement block;
Here 100 is the loop factor. We have already said that efficiency is directly proportional to the
number of iterations. Hence, the general formula in the case of linear loops may be given as
f(n)=n
for (i=0;i<100;i=i+2)
statement block;
hence the number of iterations is half the number of the loop factor. So here the efficiency can
be given as f(n)=n/2.
Omega Notation(Ω)
The omega notation provides a tight lower bound for f(n).This means that the function can
Ω notation is simple written as f(n) ε Ω(g(n)) where n is the problem size and Ω(g(n))={h(n):
ᴲ positive constants c>0, n0 such that 0<=cg(n)<=h(n), for all n>=n0}. Hence we can say that
Ω(g(n)) comprises a set of all the functions h(n) that are greater than or equal to c(g(n)) for all
values of n >=n0.
If cg(n)<=f(n), c>0, for all n>=n0, then f(n) ε Ω(g(n)) and g(n) is an asymptotically tight lower
117
Theta Notation(θ)
Theta notation provides an asymptotically tight bound for f(n).θ notation is simply written as
f(n)ε θ(g(n)), where n is the problem size and θ(g(n) ={h(n):ᴲ positive constants c1,c2 and n0
Hence we can say that θ(g(n)) comprises a set of all the functions h(n) that are between c 1(g(n))
**************END*****************
118