Professional Documents
Culture Documents
ACADEMIC DIVISION
COURSE HANDOUT FORMAT FOR UNDERGRADUATE COURSES
2015-16 L-T-P
2 4 2
COURSE OBJECTIVE : The objective of the course is to equip the student with problem solving
skills using C Language and associated Data Structures to provide the student details about algorithms
used in typically familiar problems, and a few details about the essential ingredients of the programming
language C and fundamental Data Structures.
COURSE RATIONALE : The course takes an imperative view of problem solving through
programming using C programming language.. This necessitates data abstraction, basics of data
structures, and an introduction to the GNU/Linux operating system and programming the medium level
language C. Student is professionally trained in algorithms, flowcharts analysis of a problem and
translating the same into a C program. The students are made to write C programs on their own for sets of
both mathematical and other engineering problems after exposing them to the different constructs of C
language namely Input/output, assignments, iteration and control structures. Finally the student is
acquainted with basic data structures like stacks, queues, lists etc.
SESSION PLAN: 01
At the end of this session on PROGRAM DEVELOPMENT STEPS, Students will be able:
1. To write an algorithm for the given problem.
2. To draw flow chart for the given problems.
Start
Result<- 500-
(65+50+35)
Display result
value
stop
Start
T F
Is it
Apple
Stop
SESSION PLAN: 02
At the end of this session on PROGRAM DEVELOPMENT STEPS, Students will be able:
1. To write an algorithm for the given problem.
2. To draw flow chart for the given problems.
Start
Read
a,b,c
values
d<- b2-
4ac
T F
d=
=0
r<- b/2a T F
d<
0
Display r Display r1(-
value roots are b+d)/2a
complex
r2(-b-
d)/2a
Display r1,r2
Stop
Start
AreA= 1*60
Display Area
Stop
SESSION PLAN: 03
At the end of this session on PROGRAM DEVELOPMENT STEPS, Students will be able:
3. To understand the Necessity of Programming and programming languages.
4. To know what is compiler and interpreter.
5. To write an algorithm
6. To draw flow chart for the given problems.
25 Practice-session-2
Students will practice algorithms and
flowcharts for the following problem.
A frog is at the bottom of a 30 meter
well. Each day he summons enough
energy for one 3 meter leap up the
well. Exhausted, he then hangs there
for the rest of the day. At night, while
he is asleep, he slips 2 meters
backwards. How many days does it
take him to escape from the well?
Note: Assume after the first leap that
his hind legs are exactly three meters
up the well. His hind legs must clear
the well for him to escape.
25 Sub-topic-1 (Lecture)
Generation of Computers:
First, second, third, fourth, fifth generation
languages.
15 Sub-topic-2 (Lecture)
Definition of compiler, interpreter, and
their difference.
05 Conclusion & Summary
Necessity of Programming: Now a days every human being using computers in their daily works. For
example washing machines, tvs, refrigirators, pcs, calculators, cellphones etc every thing was working
based on softwares. So that every human being had necessary to be a programmer.
PROGRAMMING LANGUAGES:
A programming language is a language specifically designed to express computations that can be
performed the computer. Programming languages are used to express algorithms or as a mode of
human communication.
While high-level programming languages are easy for the humans to read and understand, the
computer actually understands the machine language that consists of numbers only.
In between the machine languages and high-level languages, there is another type of language
known as assembly language. Assembly languages are similar to machine languages, but they are
much easier to program in because they allow a programmer to substitute names for numbers.
However, irrespective of what language the programmer use, the program written using any
programming languages has to be converted into machine language so that the computer can
understand it. There are two ways to do this: compile the program or interpret the program
The question of which language is best depends on the following factors:
The type of computer on which the program has to be executed
The type of program
The expertise of the programmer
For ex, FORTRAN is a good language for processing 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
ahead of C by incorporating powerful object-oriented features, but it is complex and difficult to
learn.
First generation: Machine Language:
Machine language is the lowest level of programming language. It is the only language that the
computer understands. All the commands and data values are expressed using 1s and 0s.
In the 1950s each computer had its own native language. Although there were similarities
between each of the machine language but a computer could not understand programs written in
another machine language.
The main advantage of machine language is that the code can run very fast and efficiently, since it
is directly executed by the CPU.
However, on the down side, the machine language is difficult to learn and is far more difficult to
edit if errors occur. Moreover, if you want to add some instructions into memory at some location,
then all the instructions after the insertion point would have to be moved down to make room in
memory to accommodate the new instructions.
Last but not the least, code written in machine language is not portable and to transfer code to a
different computer it needs to be completely rewritten. Architectural considerations make
portability a tough issue to resolve.
Second generation: Assembly Language:
Assembly languages are symbolic programming languages that use mnemonics (symbols) to
represent machine-language instructions. Since assembly language is close to the machine, it is
also called low-level language.
Basically, an assembly language statement consists of a label, an operation code, and one or more
operands.
Labels are used to identify and reference instructions in the program. The operation code
(opcode) is a mnemonic that specifies the operation that has to be performed, such as move, add,
subtract, or compare. The operand specifies the register or the location in main memory from
where the data to be processed is located.
Assembly language is machine dependent. This makes the code written in assembly language less
portable as the code written to be executed on one machine will not run on machines from a
different or sometimes even the same manufacturer.
No doubt, the code written in assembly language will be very efficient in terms of execution time
and main memory usage as the language is also close to the computer.
Programs written in assembly language need a translator often known as the assembler to convert
them into machine language. This is because the computer will understand only the language of
1s and 0s. it will not understand mnemonics like ADD and SUB.
The following instructions are a part of assembly language code to illustrate addition of two
numbers
MOV AX,4 Stores the value 4 in the AX register of CPU
MOV BX,6 Stores the value 6 in the BX register of CPU
ADD AX,BX Add the contents of AX and BX register. Store the result in AX register
Third generation programming language:
The third generation was introduced to make the languages more programmer-friendly.
3GLs spurred the great increase in data processing that occurred in the 1960s and 1970s. in these
languages, the program statements are not closely related to the internal characteristics of the
computer and is therefore often referred to has high-level languages.
3GLs made programming easier, efficient and less prone to errors.
Programs were written in an English-like manner, making them more convenient to use and
giving the programmer more time to address a client's problems.
Most of the programmers preferred to use general purpose high level languages like BASIC
(Beginners' All-purpose Symbolic Instruction Code), FORTRAN, PASCAL, COBOL, C++ or
Java to write the code for their applications.
Again, a translator is needed to translate the instructions written in high level language into
computer-executable machine language. Such translators are commonly known as interpreters
and compilers.
3GLs makes it easier to write and debug a program and gives the programmer more time to think
about its overall logic. The programs written in such languages are portable between machines
Fourth generation : very high-level language:
4GLs is a little different from its prior generation because they are basically nonprocedural so the
programmers define only what they want the computer to do, without supplying all the details of
how it has to be done.
Characteristics of such language include:
the code comprising of instructions are written in English-like sentences;
they are nonprocedural
the code is easier to maintain
4GL code enhances the productivity of the programmers as they have to type fewer lines of code
to get something done. It is said that a programmer become 10 times more productive when he
writes the code using a 4GL than using a 3GL.
A typical example of a 4GL is the query language that allows a user to request information from a
database with precisely worded English-like sentences.
Let us take an example in which a report has to be generated that displays the total number of
students enrolled in each class and in each semester. Using a 4GL, the request would look similar
to this:
COMPILER vs INTERPRETER:
A compiler is a special type of program that transforms source code written in a programming
language (the source language) into machine language comprising of just two digits- 1s and 0s
(the target language). The resultant code in 1s and 0s is known as the object code. The object
code is the one which will be used to create an executable program.
If the source code contains errors then the compiler will not be able to its intended task. Errors
that limit the compiler in understanding a program are called syntax errors. Syntax errors are like
spelling mistakes, typing mistakes, etc. Another type of error is logic error which occurs when the
program does not function accurately. Logic errors are much harder to locate and correct.
Interpreter: Like the compiler, the interpreter also executes instructions written in a high-level
language.
While the compiler translates instructions written in high level programming language directly
into the machine language; the interpreter on the other hand, translates the instructions into an
intermediate form, which it then executes.
Usually, a compiled program executes faster than an interpreted program. However, the big advantage of
an interpreter is that it does not need to go through the compilation stage during which machine
instructions are generated. This process can be time-consuming if the program is long. Moreover, the
interpreter can immediately execute high-level programs.
Start
Read a a,b
values
Y N
c>10
0
Start
Stop
Read d
value
D0
Td0
Td<-td+3;
days++
T F
Td>
=d
Stop
SESSION NO: 04
At the end of this session on INTRODUCTION TO C LANGUAGE, Students will be able to:
1. Understand structure of simple C program.
2. Use character set of C, tokens.
3. Write simple C programs
Integers are whole numbers with a range of values supported by a particular machine.
Generally, integers occupy one word of storage, and since the word sizes of machines vary (like
16-bit processor or 32-bit processor) the size of integer that can be stored depends on the
computer. If we use a 16-bit word length, the size of the integer is 2 bytes. If we use a 32-bit
processor then the size of the integer is 4 bytes. Size and ranges of different basic data types in C
language are given in the following table.
Floating point numbers (real numbers) are stored in 32 bits( in all 16-bit and 32-bit machines),
with 6 digits of precision. When the accuracy provided by a float number is not sufficient then
double can be used. A double data type numbers uses 64 bits giving a precision of 14 digits.
EXERCISE
Q1. Write an algorithm, flowchart and program to print domain set of integer data type
supported by your machine?
Q2. Write an algorithm, flowchart and program to print domain set of floating-point data type
supported by your machine?
Q3. Write an algorithm, flowchart and program to print domain set of character data type
supported by your machine?
Q4. Write an algorithm, flowchart and program to print range of integer data type supported
by your machine?
Q5. Write an algorithm, flowchart and program to print boundary values of unsigned integer
data type.
Q6. Write an algorithm, flowchart and program to print boundary values of long integer data
type.
Q7. Write an algorithm, flowchart and program to print boundary values of character data
type.
OUTPUT FUNCTION-printf()
printf() function in C allows you to display information required to the user and also prints the
values of variables. Output data can be written from computer to standard output device.
Program
#include < stdio.h > Output:
Hello!Welcome to the world of Engineering.
main ( )
{
printf (Hello!);
The control string contains format of the data to be displayed and exp1,exp2,exp3are output
expressions. The function accepts a series of arguments, each applying to a conversion specifier in the
given control string , printf() prints the formatted information to the standard output device, usually the
display screen
Program:
#include<stdio,h>
main()
{
int a;
a=100;
printf(value of a is %d,a);
}
Output:
value of a is 100
Here control string contains format specifier %d indicates a decimal integer to be displayed .a is the name
of the variable. If value of a is 100 the value 100 will be displayed on screen.
where variable_name is any valid C identifier that has been declared as single character type. When this
statement is encountered, the compiler waits until a key is pressed and then assigns this character as a
value to getchar(). Since getchar() is used on the right-hand side of an assignment statement, the character
value of getchar() is in turn assigned to the variable_name on the left-hand side.
For example:
char ch;
ch=getchar();
will assign the character H to the single character variable ch when we press the key H on the
keyboard. Since getchar() is a function, it requires a set of parentheses as shown in the above example. It
accepts no arguments and returns a single character constant.
Ex Program: Program for reading & writing a character
# include < stdio.h >
void main ( )
{
char ch;
printf (Type one character:) ;
ch = getchar () ; // gets a character from key board and stores it in the variable ch.
printf ( \nThe character you typed is = %c, ch) ; // displays value of ch on the screen.
}
Output:
Type one character
K
The character you typed is =K
#include,stdio.h>
#include<ctype.h>
main()
{
char ch;
printf(Press any key \n);
ch=getchar();
if (isalpha(ch)>0)
printf(The character is a letter.);
else if (isdigit(ch)>0)
printf(The character is a digit.);
else
printf(The character is not alphanumeric.);
}
Output:
Press any key
H
The character is a letter.
Press any key
5
The character is a digit
Press any key
&
The character is not alphanumeric
putchar() function:
The putchar() function which is analogus to getchar() function can be used for writing character data one
at a time to the output terminal. The general form is
The only one argument that is specified in the pair of parentheses should be either a single character
variable (or) a single character constant (or) an integer constant (or) any expression whose result should
be of single character type. No other data type is allowed.
variable is any C identifier containing a character declared as a single character type. If variable is used
as an argument to putchar(), the character that is stored in that variable is displayed.
Constant is any single character constant (or) an integer constant. If a single character constant is used as
an argument to the putchar(), it is directly displayed on the output terminal whereas if an integer constant
is used as an argument to putchar(), the character whose ASCII value is equivalent to the specified integer
constant will be displayed on the output terminal.
If an expression is used as an argument to the putchar() function, the result of that expression which is of
single character type will be displayed directly on the output terminal. If the expression whose result is of
integer type is used as an argument, its ASCII character will be displayed on the output terminal.
Example:
main()
{
char in;
printf(please Enter one character);
in = getchar ( ) ; // assign the keyboard input value to in.
putchar(in); // out put in value to screen.
}
Output:
please Enter one character
H
H
Program: Program to read an alphabet from terminal and displaying it after case conversion.(lower case
to upper case & vice versa) .
#include<stdio.h>
#include<ctype.h> Output
main() Enter an alphabet
{ a
char ch; A
printf(Enter an alphabet \n); Enter an alphabet
ch=getchar(); Q
if (islower(ch))
q
putchar(toupper(ch);
else
putchar(tolower(ch));
}
G R E E N F I E L D S \0
Output:
This is printed with the puts() function!
Example
puts("This prints on the first line. \nThis prints on the second line.");
puts("This prints on the third line.");
puts("If we used printf( ) instead of puts( ), all four lines would be on two lines!");
Output
This prints on the first line.
This prints on the second line.
This prints on the third line.
If we used printf( ) instead of puts( ), all four lines would be on two lines!
C supports many other similar functions which are given in the table below .These character functions
are contained in header file ctype.h .Assume ch is declared as character type variable
Function Test Description
isalnum(ch) Is ch an alphanumeric character? Returns value 1 if true or 0 otherwise
isalpha(ch) Is ch an alphabetic character? Returns value 1 if true or 0 otherwise
isdigit(ch) Is ch a digit? Returns value 1 if true or 0 otherwise
islower(ch) Is ch a lowercase letter? Returns value 1 if true or 0 otherwise
isupper(ch) Is ch a uppercase letter? Returns value 1 if true or 0 otherwise
isprint(ch) Is ch a printable character? Returns value 1 if true or 0 otherwise
ispunc(ch) Is ch a punctuation mark? Returns value 1 if true or 0 otherwise
isspace(ch) Is ch a whitespace character? Returns value 1 if true or 0 otherwise
toupper(ch) If the variable ch is assigned with Converts to uppercase
lowercase alphabet converts it to
uppercase alphabet
tolower(ch) If the variable ch is assigned with Converts to lowercase
uppercase alphabet converts it to
lowercase alphabet
Flow Chat 1:
Start
Read r Value
Area
Display Area
Value
stop Start
Read a Number
n
D=n%10
Flow Char 2:
Display D Value
Flow chart 3:
Start
Read a +ve
Number n
Display r Value
stop
Start
Read n
value
i=1
T F
Flow chart 4: i<=
10
Display
i*n
i=i+1
Stop
Flow chart 5:
Start
SI=(P*T*R)/100
Display SI Value
stop
Start
Read L,C,R
Values
F=
Flow chart 6:
Display F Value
stop
Flow chart 7:
Start
Read a
Number n
Y N
N
%2=
=0
Start
Stop
Read Y Value
T (y%400==0)or N
(y%4==0 AND y
%100!=0)
General form is
--operand
or
operand--
where the operand must be a variable but cannot be constant or expression.--operand is called pre
decrement or prefix decrement and operand-- is called post decrement or postfix decrement
Example:
int i=10;
--i;
printf(i=%d,i ) ;
output: i=9
Example: int i=10;
i--;
printf(i=%d,i);
output: i=9;
In the above example both the prefix and postfix operations results in the same value.
Assignment Operators:
There are three forms of assignment: simple assignment, multiple assignment and compound
(short hand) assignment.
i) Simple assignment
The operator used is =.
The general form is
Variable name=expression;
The value of the expression is evaluated first and is assigned to the variable. The evaluation of the
expression is right to left.
Example:
x=10 a=10 && 5
y=12.5 a=x>y
a=A
area=0.5*b*h.
Note:
= is the assignment operator used to assign right side expression value to the left hand side variable.
= = is comparison operator to compare the value of left hand and right hand side expression.
a=b will assign b value to a
a==b will compare the values of a and b for equality.
The value of the expression is assigned to the variables v1, v2, v3 etc. the evaluation is right to left.
Example: a=b=0.
a=b=x+y
The value of x+y is assigned to b and then the value of b is assigned to a.
Conditional operator:
The operator symbol is ?: This is also called ternary operator. The conditional operator has three
expressions.
The general form is
expression1?expression2:expresssion3
Special operators:
The special operators are
i) comma operator(,)
ii) sizeof operator
iii) address operator(&),
iv) indirection operator(*)
v) cast operator
i) Comma operator
The comma operator is used to combine two more expressions into a single expression.
The general form is
expression1,expression2,---,expressi
onN
The expression are evaluated from left to right and the value of the right most expression is the result of
the overall expression.
Example: int i=10,j;
j= ( i+=5, --i , i+20);
j is assigned the value 34.
where the operand may be name of the data type or constant or variable or expression.
Example: sizeof(13.56)
sizeof(239462l)
sizeof(896254ll)
sizeof(*)
sizeof(a+b)
iii) address operator
General form is
&operand
Where the operand must be a variable name. This operator is used to determine the address of the memory
location allotted to a variable.
&x represent the address of the memory location allotted to the variable x and it is assigned to the pointer
p.
p x
347 10
2
347
iv) Indirection operator
General form is
*operand
Where the operand must be a pointer.This operator is used to get the value at the address represented by
the pointer. This operator is also called de-referencing operator or value at address operator.
Example: int x=10,y,*p;
p=&x;
y=*p;
The value 10 of x is assigned to the variable y.
The expression y=*p is equivalent to the expression y=x.
v) Cast operators
These operators are used to convert the data type of operand explicitly to another type.
The general form is
(data type name)expression
Where datatype is int, double, char , pointer etc.
Example:(int)9.3 ,(double)15,(float)327,3/(int)7.2,(int)8.5/(int)4.3
Example: int a=10,b=6;
float x;
x=(float)a / (float)b;
The values of a and b are substituted in the right side expression in floating point mode and the value
assigned to x is1.6666666
Practice Programs:
1. What is the value assigned to a?
int a, x=2;
a = x + 3 * x++;
2. What is the output of the following program?
#include<stdio.h>
main()
{
int x= 5;
printf( %d , %d , %d, ++x, x , x ++);
}
3. What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a = 5, b = 0, c ;
c = a || b ++ ;
printf (b = % d, c = %d, b, c);
}
4. What value is assigned to c when the following code is exectued?
int a=5,b=6,c;
c=(a+b>a-b)?a*b;a%b;
5. What is the output when the following code is executed?
#include<stdio.h>
main()
{
int x=10,y=15,a,b;
a=x++;
b=++y;
printf(%d , %d ,a,b);
}
SESSION NO: 06
At the end of this session on EVALUATING EXPRESSIONS & CONDITIONAL STATEMENTS,
Students will be able to:
1. Evaluate expressions in C.
2. Write C programs using conditional statements.
In the above syntax if is the C keyword, expression is any valid C expression and statements in if
body are any valid C statement i.e. either simple statement, complex statement, compound statement,
expression statement, or any conditional statement or control statement. If the body of if statement
contains only single statement then { (beginning of if body), }(ending of if body) are optional.
The execution flow of the simple-if statement is shown in the following flow chart.
T Expressi F
on
If
body
If the expression is the true expression then if-body will execute and then goes to the next
statement otherwise controller will skip the if-body and directly it goes to execute the next statement in
the program.
void main()
{
Statement;
Statement;
..
..
if(expression)
{ T F
If-body
}
Statement;
Statement;
}
#include<stdio.h>
Void main()
{
Int i;
Printf(enter integer value:);
Scanf(%d, &i);
If(i>0)
Printf(given number is positive);
Printf(end of program);
}
Program: write a program to print whether a given number is even
#include<stdio.h>
void main()
{
Int i;
Printf(enter integer value:);
Scanf(%d, &i);
If( i%2==0)
Printf(Given number is even);
Printf(end of program);
}
If-else statement:-
In an application if we have a task to perform in false case also then we use if-else statement. The
syntax for if-else statement is as follows.
Syntax:
if(expression)
{
Statement-1
Statement-n
}
else
{
Statement-21
Statement-2n
}
In the above syntax if and else are keywords. The execution flow of the if-else statement is shown in the
following flowchart.
T Expressi F
on
If Else
body body
If the expression is a true expression then controller will execute the if-body ( true body) and then
goes to execute next statement in the C program otherwise controller will execute the else-body and then
goes, to execute the next statement in C program.
In the above syntax the if-body and else-body both are contains any valid C statement.
void main()
{
int var1,var2=2,num=100,a;
if(var1=var2%2)
num=2;
a=2;
printf(%d %d,num,var1);
}
3. What is the value of y in the following code?
x=7,y=0;
if(x = 6)
y=7;
else
y=1;
4. What is the value of z after the following statements executed?
int x=2,y=2,z=1;
if(x=y%2)
z+=10;
else
z+=20;
5. What is the output of the following code?
main()
{
int a=300,b=100,c=50;
if(a>400)
b=300;
c=200;
printf(\n b=%d c=%d,b,c);
}
SESSION PLAN: 07
At the end of this session on CONDITIONAL STATEMENTS (if, if-else), Students will be able to:
1. Get good experience in usage of simple-if and else-if statements in C Language programs.
2. Illustrate flow of else-if and nested if statements
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction:
Recalling previous lecture.
10 Practice session-1:
Ask Students to write electricity bill
calculation program.
10 Practice session-2:
Ask Students to write a program to find an
employee salary.
10 Practice session-3:
Ask Students to write a program to find
largest among given five integers.
10 Practice session-4:
Ask Students to write a program to find
week of day for a given integers b/w 1-7
10 Sub topic-1(Lecture):
Explanation of Syntax, flowchart of else-If
ladder statement with example program to
find grade of a student.
10 Practice session:
We will give a task to students to write a
program to print month name of a given
number between 1 to 12.
10 Sub topic-2(Lecture):
Explanation of Syntax, flowchart of
Nested - If statement with example
program to find largest of given three
numbers.
20 Practice session:
1. Ask Students to write a program to
find if a number is power of 2 in C?
2. Ask Students to write a program to
display the grades of students as:
Marks Grade
90 O
80 X
70 A
60 B
50 C
<40 FAIL
05 Conclusion & Summary
else-if ladder statement:-
In any application, if multiple decisions want to take then else-if ladder conditional statement is the best
programming construct to solve these type of problems. The syntax of else-if ladder statement is shown
below.
Syntax:-
if( expression-1){
Statement-1;
..
..
Statement-n;
}
else if( expression-2){
Statement-21;
Statement-2n;
}
else if( expression-3)
{
Statement-31;
....
Statement-3n;
}
else if( expression-n)
{
Statement-n1;
..
..
Statement-nn;
}
else
{
Default-statement-1;
Default-statement-n;
}
Next-statement-x;
This construct is known as the else if ladder. The conditions are evaluated from the top of the ladder to
downwards. As soon as a true condition is found, the statement associated with it is executed and the control
is transferred toExpres
the Next-statement-x (skipping the rest of the ladder). When all the n conditions become
false, then the final else containing the default statement will be executed.
sion1
If This execution flow is shown graphically in the following flow chart.
Expres
body
sion2
1
If
Expres
body
sion3
2
If
Expres
body
sion4
3
If
body
4
T F Expr-n
If Else
body body-n
T F
-n
Next-
sstat
T F
T F
Program: a program to enter the temperature and print the following message according to the given
temperature by using if else ladder statement.
1. T<=0 "Its very very cold".
2. 0 < T < 0 "Its cold".
3. 10 < T < =20 "Its cool out".
4. 20 < T < =30 "Its warm".
5. T>30 "Its hot"
#inlcude<stdio.h>
#include<conio.h>
void main()
{
float temp;
clrscr();
printf("Enter The Temperature");
scanf("%f",&T);
if(T<=0)
{
printf("Its very very cold");
}
else if(T>0 && T<=10)
{
printf("Its cold");
}
else if(T>10 && T < =20)
{
printf("Its cool out");
}
else if(T<=30 && T>20)
{
printf("Its warm");
}
else
{
printf("Its hot");
}
getch();
}
Nested if-else:
Nested if else statment is same like if else statement, where new block of if else statement is defined in
existing if or else block statment. Used when user want to check more than one conditions at a time.
Syntax
if(condition is true)
{
if(condition is true)
{
statement;
}
else
{
statement;
}
}
else
{
statement;
}
Program: Write a program to input three numbers and find the largest number among three.
Solution:
---------------------------------------------------------------------------
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter three number");
scanf("%d%d%d", &a, &b, &c);
if(a>b && a>c)
{
printf("A is largest");
}
else
{
if(b>a && b>c)
{
printf("B is largest");
}
else
{
printf("C is largest");
}
}
getch();
}
SESSION PLAN: 08
At the end of this session on SELECTION STATEMENT (switch), Students will be able to:
1. Implement switch-case & unconditional statements.
2. Apply while and do-while statements to solve the problems.
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression,
and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed.
int main ()
{
/* local variable definition */
int a = 1;
return 0;
}
Program: Print first 10 even numbers
int main ()
{
/* local variable definition */
int a = 1, i=1;
return 0;
}
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
SESSION PLAN: 09
At the end of this session, on ITERATION STATEMENTS DO-WHILE, Students will be able to:
1. Apply for loop to solve the problems.
2. Apply do-while statement to solve the problems
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
Flow Diagram:
Nested-for:
C programming language allows to use one loop inside another loop. Following section shows few examples
to illustrate the concept.
Syntax:
The syntax for a nested for loop statement in C is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
Program: explain a program to print
11
12
13
21
22
23
31
32
33
Void main()
{
Int I,j;
For(i=1;i<=3;i++)
{
For(j=1;j<=3;j++)
Printf(%d %d,I,j);
}
}
SESSION PLAN: 10
At the end of this session, on PRACTICE ON ITERATIVE STATEMENTS, Students will be able to:
1. Apply control loops to solve the real time problems.
void main()
{
int i=0,n0,n1,sum;
n0=0;
n1=1;
printf(%d\n%d\n,n0,n1);
sum=n0+n1;
while(i<10)
{
sum=n0+n1;
printf(%d\n,sum);
n0=n1;
n1=sum;
}
}
Lucas sequence:
void main()
{
int i=0,n0,n1,sum;
n0=2;
n1=1;
printf(%d\n%d\n,n0,n1);
sum=n0+n1;
while(i<10)
{
sum=n0+n1;
printf(%d\n,sum);
n0=n1;
n1=sum;
}
}
Reverse Number:
void main()
{
int n , rem,rev=0;
printf(enter any number\n);
scanf(%d,&n);
while(n!=0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10
}
Printf(the reverse number is %d,rev);
}
Multiplication table:
void main()
{
int n ;
printf(enter any number\n);
scanf(%d,&n);
for(i=1;i10;i++)
printf(%d * %d = %d\n,i,n,i*n);
}
Strong No:
Void main()
{
Int n,temp,fact=1,rem,sum=0;
Printf(enter number\n);
Scanf(%d,&n);
Temp=n;
While(temp!=0)
{
Rem=temp%10;
Fact=1;
For(i=1;irem;i++)
Fact=fact*i;
Sum=sum+fact;
Temp=temp/10;
}
If(sum==n)
Printf(%d is a strong number\n);
}
Co prime no:
void main()
{
int i,j,k,count;
printf(enter any number\n);
scanf(%d,&n);
for(i=2;in;i++)
for(j=2;jn;j++)
{
If(i!=j)
{
Count=0;
For(k=1;k(i>j?j:i);k++)
{
If(i%k==0 && j%k==0)
Count++;
}
If (count==1)
Printf((%d %d)\n, I,j);
}
}
}
SESSION PLAN: 11
At the end of this session, on FUNCTIONS, Students will be able to:
1. Know the benefits of function in computer programming.
2. Apply structured programming concepts in solving problems.
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
5 Recap / Introduction:
Recalling previous session
Sub task-1 :Lecture:
15 What is a function, necessity of function,
function declaration, definition
10 Students will practice on function
prototypes in c
10 Writing a simple C function to display
*****
Klu
*****
10 We will ask students to practice above
function
15 Sub task-1(Lecture):
Categories of functions-without argument
without return type, With argument without
return type- Program on addition of two
numbers.
10 Practice session-1:
We will ask students to write a program that
will display the input text in capital letters.
10 Subtask-2(Lecture):
Functions without argument with return
type, with argument and with return-
program on addition of two numbers.
10 Practice session-2:
Students will practice to write program on
addition of two numbers with above two
categories.
05 Conclusion & Summary
Session will be concluded by the
significance of function
Categories of functions:
There are mainly four categories of functions are there they are
1)functions without argument and without return type
2)functions with argument and without return type
3)functions without argument and with return type
4)functions with argument and with return type.
functions without argument and without return type:
We have just called a function , we can see that there is no variable or anything specified between the pair of
round brackets.
void area();
Now in the prototype definition of the function we can see the return value as Void. Void means it does not
return anything to the calling function.
#include<stdio.h>
void add();
void main()
{
add();
}
void add()
{
int a=10,b=20;
printf(%d,a+b);
}
Program:
#include<stdio.h>
int add();
void main()
{
int c;
c=add();
printf(%d,c);
}
int add()
{
int a=10,b=20;
return x+y;
}
Functions with argument and with return type
In this example we are going to learn function which can accept an argument and return a value.
Function accepts argument and it return a value back to the calling Program thus it can be termed as Two-
way Communication between calling function and called function.
#include<stdio.h>
int add(int,int);
void main()
{
int a=10,b=20,c;
c=add(a,b);
printf(%d,c):
}
int add(int x,int y)
{
return x+y;
}
Practice Programs:
1. What is the output when the flowing program segment is executed?
int a=1,b=2;
int f1(int a,int b);
main()
{
int i=1,c,d;
c=5*(i+1);
d=10*(i-1);
printf(% d, %d ,f1(a,c),f1(b,d));
}
int f1(int x,int y)
{
return(x*y);
}
2. What will be the output when the flowing program segment is executed?
#include<stdio.h>
int i;
void increment(int i)
{
i++;
}
int main()
{
for(i=0;i<10;increment(i))
{}
printf(i=%d\t ,i)
}
SESSION PLAN: 12
At the end of this session, on PASSING PARAMETERS TO FUNCTIONS, Students will be able to:
1. Solve computer applications with recursive concept.
2. Think in logical way to solve real-time applications using recursion.
int main()
{
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go in infinite
loop.
Recursive function are very useful to solve many mathematical problems like to calculate factorial of a
number, generating Fibonacci series, etc.
Number Factorial
Following is an example, which calculates factorial for a given number using a recursive function:
#include <stdio.h>
#include<stdio.h>
int main(){
int n1,n2,gcd;
printf("\nEnter two numbers: ");
scanf("%d %d",&n1,&n2);
gcd=findgcd(n1,n2);
printf("\nGCD of %d and %d is: %d",n1,n2,gcd);
return 0;
}
B. Scope of Variable
Scope of Variable tells compile about the visibility of Variable in the block. Variable may have Block
Scope , Local Scope and External Scope. Wiki has defined variable scope as
In computer programming, a scope is the context within a computer program in which a variable name or
other identifier is valid and can be used, or within which a declaration has effect
C. Default Initial Value of the Variable
Whenever we declare a Variable in C, garbage value is assigned to the variable. Garbage Value may be
considered as initial value of the variable. C Programming have different storage classes which has
different initial values such as Global Variable have Initial Value as 0 while the Local auto variable have
default initial garbage value.
D. Lifetime of variable
Lifetime of the = Time Of - Time of Variable
variable Declaration Destruction
Suppose we have declared variable inside main function then variable will be destroyed only when the
control comes out of the main .i.e end of the program.
C Programming Storage Class
Every variable in C programming has two properties: type and storage class. Type refers to the data type
of variable whether it is character or integer or floating-point value etc. And storage class determines how
long it stays in existence.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Automatic storage class
Keyword for automatic variable
auto
Variables declared inside the function body are automatic by default. These variable are also known as
local variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are rarely used.
External storage class
External variable can be accessed by any function. They are also known as global variables. Variables
declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1 and that
variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in
file 2 to indicate that, the variable specified is global variable and declared in another file.
Example to demonstrate working of external variable
#include
void Check();
int a=5;
/* a is global variable because it is outside every function */
int main(){
a+=4;
Check();
return 0;
}
void Check(){
++a;
/* ----- Variable a is not declared in this function but, works in any function as they are global variable
------- */
printf("a=%d\n",a);
}
Register Storage Class
Keyword to declare register variable
Register
Example of register variable
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register rather
than memory. Value stored in register is much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared register
variables.
Since, there are limited number of register in processor and if it couldn't store the variable in register, it
will automatically store it in memory.
Static Storage Class
The value of static variable persists until the end of the program. A variable can be declared static using
keyword: static. For example:
static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
c++;
printf("%d\t",c);
;
}
At the end of this session, on Practice session on functions, Students will be able to:
1. Solve computer applications using structure programming.
2. Think in logical way to solve real-time applications using recursion.
}
}
}
getch();
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=24;i++)
{
for(j=1;j<=80;j++)
{
printf("%c",char(1));
}
printf("\n");
}
getch();
}
SESSION PLAN:15
At the end of this session on Introduction to arrays, students will be able to:
1. Solve real time problems with list of data
.
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Intrduction:
Introduction about arrays and its
Importance
15 Sub topic1 (Lecture):
Explanation about array declaration,
initialization of arrays with following
program reading and printing array
elements.
15 Practice session:
Students will practice a Program to find
the sum and average of given N integers.
10 Practice session:
Students will write the program to find
the maximum and minimum of given N
positive integers.
15 Practice Session:
Ask students to write a program to print
the position of given element from the
list of values
5 Lecture:
Discussion on the program written by
students.
15 Practice Section:
Students will write the program to print
the position of given element from the
list of values
15 Practice Section:
Ask students to write a program to find
the average of given N positive integers
and then find out the number of
elements exist less than the average and
greater than the average.
05 Conclusion on arrays
1. program to print the position of given element from the list of values
void main( )
{
int a[10],i,n,pos,ele;
printf(enter n value);
scanf(%d,&n);
printf(enter values for the array);
for(i=0;i<n;i++)
{
scanf(%d,&n);
}
printf(enter the value to find position);
scanf(%d,&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
pos=i+1;
}
}
2. program to find the average of given N positive integers and then find out the number of
elements less than the average and greater than the average.
void main( )
{
int a[10],i,n,lcount=0,scount=0,avg,sum=0;
printf( enter n value);
scanf(%d,&n);
printf(enter values for the array);
for(i=0;i<n;i++)
{
scanf(%d,&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i]);
}
avg=sum/n;
for(i=0;i<n;i++)
{
if(a[i]>=avg)
Gcount++;
else
scount++;
}
printf(number of values less than average =%d,scount);
printf(number of values grater than average=%d,lcount);
}
SESSION PLAN:16
At the end of this session on Passing arrays to functions, students will be able to:
1. Think logically how to manage with arrays.
2. Implement programs with huge data.
2. Define a function to reverse the elements of an array and use this function in main to reverse array values.
Write separate function to read array values.
void readvalues(int a[ ],int n);
void reversevalues(int a[ ],int n);
void main( )
{
int a[10],n,i;
printf(enter n value);
scanf(%d,&n);
printf(enter values for array);
readvalues(a,n);
reversevalues(a,n);
printf(values of arrays after reversing);
for(i=0;i<n;i++)
{
printf(%d,&a[i]);
}
}
void readvalues(int a[10],int n)
{
int i;
for(i=0;i<n;i++)
{
scanf(%d,&a[i]);
}
}
void reversevalues(int a[10],int n)
{
int temo,i,j;
for(i=0,j=n-1;i<j;i++,j--)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
Introduction:
String is a sequence of characters treated as a single data item.
Any group of characters(except double quotes) enclosed between double quotation marks is a string
constant.
Vijayawada ,green fields,1234 , 5 ,A are string constants
C does not support string data type . Strings in C are represented by arrays of characters.A string is stored in an
array of characters as shown below.
char str[5]=hello;
h E l L o \0
The end of the string is marked with a special character , the null character \0 whose ASCII value is zero.
Declaring strings:
A string variable is any valid C variable name and it is always declared as an array. Hence to declare a
string variable we use character array. The general format is
char arrayname[size]
Where arrayname is a string variable and the size determines the number of characters in the string. Consider the
following array declarations
char city[10],name[20],address[25];
Where city, name and address are character arrays which can hold strings of length 9,19 and 24
characters respectively.
Initializing strings:
We can initialize a string the same way that we initialize any other variable by assigning a value to it
when it is defined. In this case the value is a string. For example
char city[10] = HYDERABAD;
If we declare city as
char city[9] = HYDERABAD;
then the null character will not be appended automatically to the character array . because , city can hold 9
characters and the string HYDERABAD has already 9 characters filling the 9 spaces. Since a string is stored in a
character array , while initializing through type declaration, size of the array can be omitted as shown below.
char city[ ] = HYDERABAD;
In this case compiler will create an array of 10 bytes and initialize it with HYDERABAD followed by
null character
A string may be initialized as an array of characters.
char city[ ] = {H,Y,D,E,R,A,B,A,D,\0};
A character pointer may be initialized with a string.
char *city = HYDERABAD;
Since a string variable is a character array, one string variable cannot be assigned to another string
variable.
char str1[6 ] = green,str2[6];
str2 = str1;
The above assignment leads to compilation error.
When pointers are initialized with strings we can assign one string to another string.
char *str1=green,*str2;
str2=str1;
The above assignment is valid.
A character array cannot be initialized with a string by an assignment statement.
char city[10];
city = HYDERABAD;
The above assignment is invalid
Explination of string reading and printing with the following program:
gets(st
str is any valid string variable name and it will read r)
a string of characters until enter key is pressed(i.e
until new line character is entered).
puts(st
r)
Where str is any valid string variable name.
2. Program to count number of vowels ,consonants ,words ,digits and symbols in a line of text.
Void main( )
{
char str[20];
int i,vcount=0,wcount=0,ccount=0,scount=0,dcount=0;
printf(enter a line of text);
gets(str);
for(i=0;str[i]!=\0;i++)
{
if((str[i]>=A && str[i]<=Z) | |(str[i]>=a && str[i]<=z))
{
if(str[i]==a || str[i]==e|| str[i]==i || str[i]==o || str[i]==u )
vcount++
else
ccount ++;
}
else if(str[i]== )
wcount++;
else if(str[i]>=0 && str[i]<=9)
dcount++;
else
scount++;
}
printf(vcount=%d,ccount=%d,scount=%d,dcount=%d,wcount=
%d,vcount,ccount,scount,dcount,wcount+1);
}
Explanation of strings functions:
String functions:
C language supports several functions useful for string manipulation. Whenever these functions are used the
header file string.h must be included. Some of the functions are:
strlen(): This function returns length of a string, that is counts no of characters in the string
excluding null character. If the string is empty it returns zero. The general format of this function is
n=strlen(str);
Where n is an integer variable which receives the length of the string str
strcat(): This function is useful to join two strings together. The general format of strcat() function is
strcat(str1,str
2)
str1, str2 are two string variables. When strcat() function is executed str2 is appended to strg1 and str2
remains unchanged.
strcmp(): This function is useful to compare to strings. If the two strings are similar then it returns 0
,otherwise , it returns the difference between the ASCII values of first pair of non-matching characters.
The general syntax is
strsmp(str1,s
tr2)
str1 and str2 may be string variables or string constants. The returned value is
Zero if the strings are identical.
Positive if the strings are not in alphabetical order.
Negative if the strings are in alphabetical order.
strcpy(): This function is useful to copy one string into another string. The general syntax is
strcpy(str1,st
r2)
The content of str2 will be copied into str1.
Char str[row][column]
row represents how many strings we want to store and column represents length of the each string.
Example char str[5][15].
In str we can store 5 strings and each strings can have a length of 15.
Initialization:
Two dimensional string can be initialized as
char str [5][15]={red,blue,green,yellow,white};
1. program to read and print n number of strings.
void main()
{
char str[10][20];
int n;
printf(enter n value);
scanf(%d,&n);
printf(enter your strings);
for(i=0;i<n;i++)
{
gets(str[i]);
}
printf(strings are);
for(i=0;i<n;i++)
{
puts(str[i]);
}
}
strcpy(): This function is useful to copy one string into another string. The general syntax is
strcpy(str1,st
r2)
The content of str2 will be copied into str1.
strcat(str1,str
2)
str1, str2 are two string variables. When strcat() function is executed str2 is appended to strg1 and
str2 remains unchanged.
3. program to join one string at the end of another string by using strcat().
void main()
{
char str1[20],str2[20];
int n;
printf(enter first string);
gets(str1);
strcat(str1,str2);
printf(after concadination the string is %s,str1);
}
#include<stdio.h>
#include<string.h>
void main()
{
char str[100],*ptr,i,l;
clrscr();
printf("Enter any string\n");
gets(str);
l=strlen(str);
ptr=str;
printf("%c",*(ptr+0));
for(i=1;i<l;i++)
{
if(*(ptr+i-1)==' ')
printf(" %c. ",*(ptr+i));
}
getch();
}
NUMBER TO WORD PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
long num,div,n1;
int flag,digit,pos,tot_dig;
clrscr();
printf("\n Enter number: ");
scanf("%ld",& num);
if(num==0)
{
printf("Zero\n\n");
exit(0);
}
if(num>99999)
{
printf("please enter number between 0 and 100000\n\n");
exit(0);
}
tot_dig = 0;
div = 1;
n1 = num;
while ( n1 > 9 )
{
n1 = n1 / 10;
div = div * 10;
tot_dig++;
}
tot_dig++;
pos = tot_dig;
while ( num != 0 )
{
digit= num / div;
num = num % div;
div = div / 10;
switch(pos)
{
case 2:
case 5: if ( digit == 1 )
flag = 1;
else
{
flag = 0;
switch(digit)
{
case 2: printf("twenty ");break;
case 3: printf("thirty ");break;
case 4: printf("forty ");break;
case 5: printf("fifty ");break;
case 6: printf("sixty ");break;
case 7: printf("seventy ");break;
case 8: printf("eighty ");break;
case 9: printf("ninty ");
}
}
break;
case 1:
case 4: if ( flag == 1 )
{
flag = 0;
switch(digit)
{
case 0 : printf("ten ");break;
case 1 : printf("eleven ");break;
case 2 : printf("twelve ");break;
case 3 : printf("thirteen ");break;
case 4 : printf("fourteen ");break;
case 5 : printf("fifteen ");break;
case 6 : printf("sixteen ");break;
case 7 : printf("seventeen ");break;
case 8 : printf("eighteen ");break;
case 9 : printf("ninteen ");
}
}
else
{
switch(digit)
{
case 1 : printf("one ");break;
case 2 : printf("two ");break;
case 3 : printf("three ");break;
case 4 : printf("four ");break;
case 5 : printf("five ");break;
case 6 : printf("six ");break;
case 7 : printf("seven ");break;
case 8 : printf("eight ");break;
case 9 : printf("nine ");
}
}
if ( pos == 4 )
printf("thousand ");
break;
case 3:
if ( digit> 0 )
{
switch(digit)
{
case 1 : printf("one ");break;
case 2 : printf("two ");break;
case 3 : printf("three ");break;
case 4 : printf("four ");break;
case 5 : printf("five ");break;
case 6 : printf("six ");break;
case 7 : printf("seven ");break;
case 8 : printf("eight ");break;
case 9 : printf("nine ");
}
printf("hundred ");
}
break;
}
pos--;
}
if ( pos == 4 && flag == 0)
printf("thousand");
else
if ( pos == 4 && flag == 1)
printf("ten thousand");
if ( pos == 1 && flag == 1 )
printf("ten ");
getch();
}
datatype arrayname[row]
[col]
row represents number of rows and col represents number of columns in array.
example
int a[3][3];
for the above declaration it occupies 3 rows and 3 columns for array a. A 2-dimensional arraya, which
contains three rows and four columns can be shown as below:
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name
of the array, and i and j are the subscripts that uniquely identify each element in a.
Initializing Two-Dimensional Arrays:
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an
array with 3 rows and each row has 4 columns.
int a[3][4]={ {1,2,3,4},{5,6,7,8},{9,10,11,12}};
Explanation of the following program, and student practice the same program:
/*sales report*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,opt;
int a[5][3];
float pr[3]; double total;
printf("\nenter rate of each product");
for(i=0;i<3;i++)
scanf("%f",&pr[i]);
clrscr();
printf("\n*******ENTER NO.OF PRODUCTS SELL BY EACH SELLER IN EACH
PRODUCT TYPE*******\n");
for(i=0;i<5;i++)
{
printf("\n----sales man-%d-----\n",i);
for(j=0;j<3;j++)
{
printf("\n\tenter product no-%d\t:",j);
scanf("%d",&a[i][j]);
}
}
while(1)
{
clrscr();
printf("\n********MENU********\n");
printf("\n1. The total sales by each sales man\n");
printf("\n2. total sales of each item\n");
printf("\n3. exit");
printf("\n***********************\n");
scanf("%d",&opt);
switch(opt)
{
case 1:
clrscr();
for(i=0;i<5;i++)
{
total =(float)0.0;
for(j=0;j<3;j++)
{
total = total + a[i][j]*pr[j];
}
printf("\nsales man-%d total sales is %lf",i,total);
}
break;
case 2:
clrscr();
for(i=0;i<3;i++)
{
total =(float)0.0;
for(j=0;j<5;j++)
{
total = total + a[j][i]*pr[i];
}
printf("\nproduct type-%d total sales is %lf",i,total);
}
break;
case 3:
exit(0);
break;
default:
printf("\nyou entered invalid option\n");
break;
}
getch();
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,max;
int a[5][3];
clrscr();
printf("\n*******ENTER MARKS GAINED BY EACH STUDENT IN EACH
SUBJECT*******\n");
for(i=0;i<5;i++)
{
printf("\n----STUDENT NO-%d-----\n",i);
for(j=0;j<3;j++)
{
printf("\n\tenter marks in subject-%d\t:",j);
scanf("%d",&a[i][j]);
}
}
clrscr();
for(i=0;i<3;i++)
{
max = 0;
for(j=0;j<5;j++)
{
if(max<a[j][i])
max = a[j][i];
}
printf("\nSUBJECT-%d HIGHEST MARKS is %d",i,max);
}
}
printf("enter %d values\n:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]==key)
{
printf("%d is found at %d position",a[i],i+1);
return;
}
}
printf("NOT FOUND");
}
Example:
12,24,27,32,34,35,48,69
Time complexity:
Best Case:O(N)
Average case: O(N2)
Worst Case:O(N2)
Space complexity :In Place or O(1)
SESSION PLAN 23:
At the end of this session, Students will be able to:
1. Sort large volumes of input using divide-and-conquer strategy.
if(a[left]>a[right])
{
temp=a[left];
a[left]=a[right];
a[right]=temp;
}
if(a[left]>a[center])
{
temp=a[left];
a[left]=a[center];
a[center]=temp;
}
temp=a[right];
a[right]=a[center];
a[center]=temp;
return(a[right]);
}
pivot=median3(a,left,right);
i=left;
j=right-1;
while(i<j)
{
while(a[i]<=pivot)
i++;
while(a[j]>pivot)
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[right];
a[right]=a[i];
a[i]=temp;
qsort(a,left,i-1);
qsort(a,i+1,right);
}
}
/Picking the Pivot
Pointers are variables that hold address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language. Although pointer may appear little confusing and complicated in the
beginning, but trust me its a powerful tool and handy to use once its mastered.
Whenever a variable is declared, system will allocate a location to that variable in the memory, to
hold value. This location will have its own address number.
Let us assume that system has allocated memory location 80F for a variable a.
int a = 10 ;
We can access the value 10 by either using the variable name a or the address 80F. Since the memory
addresses are simply numbers they can be assigned to some other variable. The variable that holds
memory address is called pointer variable. A pointer variable is therefore nothing but a variable that
contains an address, which is a location of another variable. Value of pointer variable will be stored
in another memory location.
data-type *pointer_name;
Data type of pointer must be same as the variable, which the pointer is pointing. void type pointer
works with all data types, but isn't used oftenly.
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer
variable contains address of variable of same data type. In C language address operator & is used to
determine the address of a variable. The & (immediately preceding a variable name) returns the
address of the variable associated with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
int *ptr = &a ; //initialization and declaration together
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator *.
int a,*p;
a = 10;
p = &a;
Output
Address of a = 4020
Address of b = 4016
a = 12, b = 4
x = 42, y = 9
a = 2, b = 7, z = 8
=====================================================================
Definition of a pointer: pointer is a variable which contains the address of another same type of
variable.
Name of the
x location
iptr
1000 Value at location
100
1500
1000
Address of location
- Pointer to an array.
- Pointer to a function. We will discuss in later sessions.
Accessing address of a variable and Initialization of a pointer variable:
- We can initialize a pointer variable by using assignment operator either compilation time(at
the time of declaration) or execution time as shown in the following example.
- Example program-1:-
1. #include<stdio.h>
2. void main()
3. {
4. int *iptr , i;
5. //char *cptr = &c, c; //this is invalid statement. Error: undefined
symbol c
6. char c, *cptr = &c; //this is compilation time initialization.
7. float *fptr, f
8. void *vptr
9. iptr = &i
10. fptr = &f
11. vptr = &i; // these are execution time initialization.
12. vptr = &f;
13. vptr = &c;
14. printf(%d %f %c,*iptr,*fptr,*cptr
15. printf(%u %u %u, iptr,fptr,cptr);
16. }
- In the above example program & operator will gives the address.
- In line number 9, &i will returns the base address of integer variable i.
- In line number 10, &f will gives the base address of float variable f.
- & is unary operator.
- & operator will give the address of its operand.
- Its operand should be a variable but not an expression or not a constant.
- Ex:- ptr = &x; is valid but ptr = &5; and ptr = &(x+y*z); are not valid.
- Usually we read this as address of
- In the above example iptr is integer pointer. Which is initialized with the address of integer
variable i in line no 9 with intr = &i statement. Similarly float pointer fptr with float variable f
address, character pointer cptr with character variable address c are initialized.
- But void pointer vptr is initialized with integer variable i address in line no. 11, with float
variable f address in line no. 12 and also initialized with character variable c base address in
line no. 13 because void pointer is a generic pointer.
- NOTE:- void pointer is nothing but generic pointer in which we can store address of any type
variable as shown in the above example.
Multi pointer:-
Pointer to 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.
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, following is the declaration to declare 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 ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Void Pointers in C:
Definition
1. Suppose we have to declare integer pointer,character pointer and float pointer then we need to
declare 3 pointer variables.
2. Instead of declaring it is feasible to declare single pointer variable which can act as integer
pointer,character pointer.
5. The compiler has no idea what type of object a void Pointer really points to ?
char cnum;
int inum;
float fnum;
3. When we assign address of integer to the void pointer, pointer will become Integer Pointer.
4. When we assign address of Character Data type to void pointer it will become Character
Pointer.
5. Similarly we can assign address of any data type to the void pointer.
- By using * operator and pointer variable name we can access the value of a variable which is
pointed by a pointer.
- In the above example program-1 line number 14,15, *iptr will gives the i value and iptr will
gives i addres.
- Similarly *fptr, *cptr will gives values of f, c variables and fptr, cptr will gives addresses of f,
c variables.
Cw-program-1: analyze the output of the following simple program and why?
#include<stdio.h>
void main()
{
int i,*iptr=&i;
char c='a',*cptr = &c;
float f=23.34, *fptr = &f;
#include<stdio.h>
void main()
{
int *iptr=&i,i=90;
char c,*cptr = &c,c='a';
float f=23.34, *fptr = &f;
1. #include<stdio.h>
2. void main()
3. {
4. int *p1,*p2;
5. int x,y;
6. x=10,y=20;
7. p1 = &x;
8. p2 = &y;
A
200 202 204 206 208 210 212 214
p1 p2
here p1-p2 allowed. Here p1-p2 will gives the number of elements b/w p1 and p2.
2. Increment and decrement operations on pointer value are allowed in C programming.
Whenever we increment a pointer by one then its value will be incremented by size of its
data type. In the above figure if p1 is incremented by 2 then its value becomes 206,
nothing but it will points A[3].
Example:
++p1; p1++; --p1; p1--; all are valid statements in C programming.
3. We can use pointers in relational expressions to compare two pointers if those two are of
same type.
Example: int *p1,*p2;
int x=10,y=20;
p1 = &x; p2 = &y;
When an array is declared, compiler allocates sufficient amount of memory to contain all the elements
of the array. Base address which gives location of the first element is also allocated by the compiler.
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five element
will be stored as follows
Here variable arr will give the base address, which is a constant pointer pointing to the element,
arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
As studied above, we can use a pointer to point to an Array, and then we can use that pointer to access
the array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the aboce program, the pointer *p will print all the values stored in the array one by one. We can
also use the Base address (a in above case) to act as pointer and print all the values.
- We can read elements into an array and we can access data from an array
by using a pointer like index variable.
- Updating (reading or accessing or modifying) on array elements should
possible with pointer whenever the type of pointer is equal to the type of
element.
- Whenever we increment an integer pointer by 1 then it will goes to point
next integer in that array.
Example program-1: program to read and print an array of integers using integer
pointer.
#include<stdio.h> 0 1 2 3 4 5
6 7 8 9 10 11 12 14
void main() a a
1. { 200 202 204 206 208
210 212 214 216 218 220 222 224 226
2. int a[15],*ptr,i,n;
3. 200
4. printf("\nenter n value\n"); ptr
5. scanf("%d",&n); 500
6. ptr = a;
7.
8. for(i=0;i<n;i++)
9. {
10. printf("\nenter a n element :");
11. scanf("%d",ptr++);
12. }
13. ptr = a;
14. for(i=0;i<n;i++)
15. {
16. printf("\n %d",*ptr);
17. ptr++;
18. }
19.}
- In above example program-1 first an integer pointer ptr initialized with the
base address of an array a and then it was incremented by 1 in each
iteration. Whenever it was incremented by 1 then ptr value will be
incremented by the size of integer, usually size of integer is 2 bytes.
- In above example program-1 we used separate loop index variable to
traverse array a. We can also implement without using separate loop index
variable i. This is explained in the following example program.
- In C language array name itself will gives the base address of that array,
which is equal to the base address of a[0] element. So if we consider the
expression a+n then it will gives the (n-1)th element (indexed as n in
array) base address. This is used in the following code which is similar to
the above program.
#include<stdio.h>
void main()
{
int a[15],*ptr,n;
printf("\nenter n value\n");
scanf("%d",&n);
ptr = a;
while(ptr<(a+n))
{
printf("\nenter a n element :");
scanf("%d",ptr++);
}
ptr = a;
while(ptr<(a+n))
{
printf("\n %d",*ptr);
ptr++;
}
}
We know that array name itself will give the base address of that array. So
that, shell we use array name as index pointer to traverse the array in the
above program? The answer for this question is given by the following
program.
#include<stdio.h>
void main()
{
int n,a[15],i,*ptr;
printf("\nenter n value\n");
scanf("%d",&n);
ptr = a+n;
while(a<ptr)
{
printf("\nenter an element ");
scanf("%d",a);
a++; //Error: L-value required
}
a = a-n; //Error: L-value required
while(a<ptr)
{
printf("\n %d",*a);
a++; //Error: L-value required
}
}
In the above program we get 3 errors i.e. L-value required. Because, array
name is we can use array name as an array pointer.
Cw- program-1:
#include<stdio.h>
void main()
{
int x1,x2,x3,x4,x5,x6,i;
int *iap[10],j,*temp;
x1 = 10; x2 = 20;
x3 = 12; x4 = 32;
x5 = 22; x6 = 43;
iap[0] = &x1; iap[1] = &x2;
iap[2] = &x3; iap[3] = &x4;
iap[4] = &x5; iap[5] = &x6;
for(i=0;i<6;i++)
{
printf("\n %dth element is %d",i,*iap[i]);
}
for(i=0;i<6-1;i++)
{
for(j=0;j<6-1-i;j++)
{
if(*iap[j]>*iap[j+1])
{
temp = iap[j];
iap[j] = iap[j+1];
iap[j+1] = temp;
}
}
}
printf("\n******ELEMENTS AFTER SORTING*****\n");
for(i=0;i<6;i++)
{
printf("\n %dth element is %d",i,*iap[i]);
}
}
Cw-program-2:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int *iap[20],n,i,j,*temp;
printf("\nenter n value\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
iap[i] = (int*)malloc(sizeof(int));
printf("\nenter %dth element :",i);
scanf("%d",iap[i]);
}
printf("\narray elements\n");
for(i=0;i<n;i++)
{
printf("\n %dth element is %d",i,*iap[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(*iap[j]>*iap[j+1])
{
temp = iap[j];
iap[j] = iap[j+1];
iap[j+1] = temp;
}
}
}
printf("\n******ELEMENTS AFTER SORTING*****\n");
for(i=0;i<n;i++)
{
printf("\n %dth element is %d",i,*iap[i]);
}
for(i=0;i<n;i++)
{
free(iap[i]);
}
}
SESSION PLAN:25
Pointer to arrays(pointers to strings)
At the end of this session, students will be able to:
1. Implement computer programs for different real-time applications which are having list of data
using pointers.
2. Implement computer programs for different real-time applications which are having list of data
using pointers.
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
15 Explanation about pointer to an array
with the Program to read an array of N
strings.
15 We will ask students to write a C
program to read an array of strings and
then sort them using pointer to an array.
15 Students will execute the above
program.
15 Explanation about an array of pointers
with the Program to read and print an
array of n strings.
15 We will ask students to write a program
to sort N strings using an array of
pointers.
15 Students will execute the above
program.
05 Conclusion on array of pointers
Program-1: reading and printing an array of n strings using array of pointers.
#include<stdio.h>
#include<string.h>
void main()
{
char *p[10],str[100];
1. int i,n;
2. printf("\nenter n value");
3. scanf("%d",&n);
4. for(i=0;i<n;i++)
5. {
6. printf("\nenter %dth string",i);
7. fflush(stdin);
8. scanf("%s",str);
9. p[i] = (char*)malloc((strlen(str)+1)*sizeof(char));
10. strcpy(p[i],str);
11. }
12. for(i=0;i<n;i++)
13. {
14. printf("\n%s",p[i]);
15. }
16.}
Example program-2:
Write a program to sort N number of strings using array of pointers concept.
1. #include<stdio.h>
2. #include<string.h>
3. void main()
4. {
5. char *p[10],*tp,str[100];
6. int i,j,n;
7. printf("\nenter n value");
8. scanf("%d",&n);
9. for(i=0;i<n;i++)
10. {
11. printf("\nenter %dth string",i);
12. fflush(stdin);
13. scanf("%s",str);
14. p[i] = (char*)malloc((strlen(str)+1)*sizeof(char));
15. strcpy(p[i],str);
16. strcat(p[i],"\0");
17. }
18. for(i=0;i<n-1;i++)
19. {
20. for(j=0;j<n-i-1;j++)
21. {
if(strcmp(p[j],p[j+1])>0)
{
tp = p[j];
p[j] = p[j+1];
p[j+1] = tp;
}
}
}
for(i=0;i<n;i++)
{
printf("\n%s",p[i]);
}
22.}
A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to such an array.
As we know now, name of the array gives its base address. In a[i][j], a will give the base address of this
array, even a+0+0 will also give the base address, that is the address of a[0][0] element.
Here is the generalized form for using pointer with multidimensional arrays.
Pointer can also be used to create strings. Pointer variables of char type are treated as string.
This creates a string and stores its address in the pointer variable str. The pointer str now points to the
first character of the string "Hello". Another important thing to note that string created using char pointer
can be assigned a value at runtime.
char *str;
str = "hello"; //Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to use
indirection operator *.
Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character array with rows of
varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};
In the second approach memory wastage is more, hence it is prefered to use pointer in such cases.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
char *str[5], *temp;
int i, j, n;
flushall();
return (0);
}
Output
How many names do you want to have? 4
Enter the name 0: pri
Enter the name 1: prt
Enter the name 2: prq
Enter the name 3: pra
It is possible to declare a pointer pointing to a function which can then be used as an argument in another
function. A pointer to a function is declared as follows,
type (*pointer-name)(parameter);
Example :
int (*sum)(); //legal declaraction of pointer to function
int *sum(); //This is not a declaraction of pointer to function
A function pointer can point to a specific function when it is assigned the name of the function.
s is a pointer to a function sum. Now sum can be called using function pointer s with the list of parameter.
s (10, 20);
#include< stdio.h>
#include< conio.h>
int main( )
{
int (*fp)(int, int);
fp=sum;
int s = fp(10, 15);
printf("Sum is %d",s);
getch();
return 0;
}
Output : 25
Program that replaces two or more consecutive blanks in a string by a single blank.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SPACE ' '
char *process(char*);
int main()
{
char text[1000], *r;
printf("Enter a string\n");
gets(text);
r = process(text);
printf("\"%s\"\n", r);
free(r);
return 0;
}
c = d = 0;
length = strlen(text);
start = (char*)malloc(length+1);
if (start == NULL)
exit(EXIT_FAILURE);
return start;
}
#include<stdio.h>
void Strong(int *);
int main(){
int num,a;
while(i<=r){
f=f*i;
i++;
}
sum=sum+f;
num=num/10;
}
if(sum==temp)
printf("%d is a strong number",temp);
else
printf("%d is not a strong number",temp);
}
You will find a lot of complex function pointer examples around, lets see one such example and try to
understand it.
It appears complex but it is very simple. In this case (*foo) is a pointer to the function, whose return type
is void* and argument is of int* type.
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.
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, following is the declaration to declare 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 ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Void Pointers in C:
Definition
3. Suppose we have to declare integer pointer,character pointer and float pointer then we need to
declare 3 pointer variables.
4. Instead of declaring different types of pointer variable it is feasible to declare single pointer
variable which can act as integer pointer,character pointer.
10. The compiler has no idea what type of object a void Pointer really points to ?
char cnum;
int inum;
float fnum;
Explanation :
void *ptr;
7. Void pointer declaration is shown above.
8. We have declared 3 variables of integer,character and float type.
9. When we assign address of integer to the void pointer, pointer will become Integer Pointer.
10. When we assign address of Character Data type to void pointer it will become Character
Pointer.
11. Similarly we can assign address of any data type to the void pointer.
Functions are called by their names. If the function is without argument, it can be called directly using its
name. But for functions with arguments, we have two ways to call them,
1. Call by Value
2. Call by Reference
Call by Value
In this calling technique we pass the values of arguments which are stored or copied into the formal
parameters of functions. Hence, the original values are unchanged only the parameters inside function
changes.
void calc(int x)
{
x = x + 10 ;
}
Output : 10
In this case the actual variable x is not changed, because we pass argument by value, hence a copy of x is
passed, which is changed, and that copied value is destroyed as the function ends(goes out of scope). So
the variable x inside main() still has a value 10.
But we can change this program to modify the original x, by making the function calc() return a value,
and storing that value in x.
int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20
#include<stdio.h>
#include<conio.h>
main( )
{
int a = 10, b = 20 ; // call by value
swap(a,b); // a and b are actual parameters
printf ( "\na = %d b = %d", a, b ) ;
getch();
}
Call by Reference
In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as
a reference or a pointer, in both the case they will change the values of the original variable.
Output : 20
#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */
printf("Number1 = %d\n",num1);
printf("Number2 = %d",num2);
return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output
Number1 = 10
Number2 = 5
Functions are called by their names. If the function is without argument, it can be called directly using its
name. But for functions with arguments, we have two ways to call them,
1. Call by Value
2. Call by Reference
Call by Value
In this calling technique we pass the values of arguments which are stored or copied into the formal
parameters of functions. Hence, the original values are unchanged only the parameters inside function
changes.
void calc(int x)
{
x = x + 10 ;
}
Output : 10
In this case the actual variable x is not changed, because we pass argument by value, hence a copy of x is
passed, which is changed, and that copied value is destroyed as the function ends(goes out of scope). So
the variable x inside main() still has a value 10.
But we can change this program to modify the original x, by making the function calc() return a value,
and storing that value in x.
int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20
#include<stdio.h>
#include<conio.h>
main( )
{
int a = 10, b = 20 ; // call by value
swap(a,b); // a and b are actual parameters
printf ( "\na = %d b = %d", a, b ) ;
getch();
}
Call by Reference
In this we pass the address of the variable as arguments. In this case the formal parameter can be taken as
a reference or a pointer, in both the case they will change the values of the original variable.
Output : 20
Number1 = 10
Number2 = 5
SESSION PLAN: 29
At the end of this session on Dynamic Memory Allocation, students will be able to:
1. Allocate memory dynamically.
2. Write programs using user defined data types by thinking logically.
Introduction
Need of structures, structure definition
and declaration of structure with
15 examples.
program to read and display the data of a
student consisting of id_number,
name,age and cgpa.
10 Participative session: Students will
practice
Define a structure COMPLEX whose
fields are the real and imaginary parts of
a complex number. Write a program to
read two complex numbers through
keyboard and find their sum
Explanation on the following program
Create a structure for 3 students with
5 RollNo, Name and Age. Display the
required student details by having input
as RollNo.
Conclusion
05
Introduction:
Variables are named memory locations and they are to hold data to be manipulated by the programs.
Memory allocation for the variables used so far is static memory allocation. Staticmemory allocation
is the phenomenon of allocation of memory during compilation time. The Allocated memory is released at
the end of program execution.
The declaration
int a;
allocates 2 bytes of memory to the variable a at compilation time where as the array declaration
int b[6];
allocates 12 bytes of memory space at compilation time. In such a declaration there are few
shortcomings.
If we want to deal with more memory than size of the array during runtime of the program, we
cannot increase the size of array at runtime.
Many a times all the memory allocated during compile time are not used; we cannot decrease the
wastage of memory at runtime.
To overcome the above problems we have the concept of Dynamic Memory Allocation.
Dynamic Memory Allocation is the phenomenon of allocationof memory during run time. Allocated
memory can be released during runtime.
malloc()
calloc()
realloc()
free()
The above functions are available in alloc.h, and stdlib.h. Either of the header files can be included.
1. malloc()
The general form of malloc is:
The function allocates a block of memory. On successful memory allocation the function returns a pointer
to the first byte of the block. Allocated space is initialized with garbage.
In the above syntax size of block is block size to be allocated. (cast type) is the cast expression which
indicate the type of data that will be stored in the allocated block. ptr_variableis a pointer of the cast-type
which holds the address of the first byte of the block.
Allocates 20 bytes of space and returns a pointer to the block which is assigned to the pointer ptr of type
int. This is illustrated in the following figure.
ptr
Size of the block= (10 *2)
bytes
200
0
2000
The storage space allocated will have no name and hence must be accessed through the pointer only. If the
allocation fails, malloc() function returns a null pointer. Therefore check whether the allocation is
successful before using the pointer.
int *p,i,n;
printf(enter n value);
scanf(%d, &n);
p=(int *)malloc(n*sizeof(2));
printf(enter %d number of values,n);
for(i=0;i<n;i++)
scanf(%d,(p+i));
printf(values are);
for(i=0;i<n;i++)
printf(%d\n);
1. free( )
The free()is used to release(free) the block of memory which has already been allocated by malloc or
calloc functions
This is done for reusability.
The general form of free() function is:
free (ptr_variable);
2. calloc( )
calloc is used to allocate multiple blocks of memory, all of which are of same size and returns a pointer
to the first byte of the first block. Initialize the allocated space with 0s .
callochas two parameters first is the no. of blocks to be allocated and the second is the size
ofblock.
ptr_variable is a pointer, which stores the address of the first byte of the first block allocated. If the
function is unable to allocate the requisite space, null pointer is returned and is assigned to the ptr
variable.
3. realloc()
malloc() and calloc() are functions used to dynamically allocate memory for storage. But in some
circumstances we need to alter the memory allocated by the above functions during runtime. This is
achieved with the help of realloc().
Here old_ptr is the pointer to the block which has been allocated and is to be altered (increased/
decreased).
On successful reallocation the function returns a pointer to the first byte of the reallocated block. If the
functionis unable to allocate the additional size a NULL pointer is returned and the original block is freed.
new size of blockmay be smaller or larger than the original block size. The location of old block and
new block may be same or different. If different data of old block will be copied to the new block. The
function will guarantee that the old data is intact.
INTRODUCTION:
We have seen that arrays can be used to represent logically related data items that belong to the same data
type using a single name. However, array cannot be used to represent a collection of logically related
items belonging to different data types using a single name. To tackle this suitably, C supports a user
defined data type known as structure that can store related information of same data type or different data
types together under a single name. For example, it can be used to store the related items of different data
types : employee number, name, basic pay, da, hra, gross pay and net pay together under a single name.
Some other examples of structure are:
Each element in a structure is called a field. It has many of the characteristics of the variables that have
been used in the programs so far. It has a type, and it exists in memory. It can be assigned values, which
in turn can be accessed for selection or manipulation. The primary difference between a field and variable is
field is part of a structure.
The difference between an array and a structure is that all elements in an array must be of the same type,
while the elements in a structure can be of the same or different types.
There are two ways to declare a structure : tagged structure and type - defined structures.
Tagged structure
A tagged structure can be used to define variables, parameters, and return types. The general syntax is
struct TAG
{
data type field1; data type
field2; . .;
data type fieldn;
};
A tagged structure begins with the key word struct followed by TAG. The TAG is the identifier for the
structure, and it allows us to declare structure variables, function parameters and return type. Field1
,field2, fieldn can be variables ,arrays, pointers or other structure variables. After the closing brace, if semicolon is
there no variables are declared.
Example :
struct student
{
long int id_no; char
name[20];
int age;
float cgpa;
};
Type declaration with typedef
The more powerful way to declare a structure is to use a type definition typedef . The general syntax is
typdef struct
.
.;
}TYPE;
An identification TYPE is required at the end of the block , The identifier is the type definition name.
Example :
typedef struct
{
long int id_no;
char name[20];
int age;
float cgpa;
}STUDENT;
Declaring structure variables
After a structure has been declared, we can declare variables using it. The structure variable declaration is
similar to the declaration of any other data type. The following examples will demonstrate the declaration
of structure type and the variables that use it.
Example:
struct student
{
long int id_no;
char name[20];
int age;
float cgpa;
};
typedef struct
{
long int id_no;
lhar name[20];
int age;
float cgpa;
}
Recap:
05
Definition, significance of structures.
Introduction (Lecture)
Define a student structure with members sno,sname
10
and three subject marks and write a program to store n
student details.
Participative session: Students will practice
Define a student structure with members sno,sname
10 and three subject marks and write a program to store n
student details. Sort the student data base on total
marks.
Sub-topic-1 (Lecture)
Define a customer structure with members
10 cname,ccode,iname and price and write a program to
store n customer details and sort the records based on
price of the item.
10 Participative session : Students will practice
Define a customer structure with members
cname,ccode,iname and price and write a program to
store n customer details and sort the records based on
price of the item.
Sub-topic-1 (Lecture)
Program to pass the structure individual members to a
10
function and display the values. Pass the two integer
values and display.
Participative session
Students will practice a program to pass the entire
15
structure to a function and display the values. The
structure having two integer member variables..
Sub-topic-2 (Lecture)
Explain a program to create a structure student,
5 containing name and roll. Ask user the name and roll of
a student in main function. Pass this structure to a
function and display the information in that function.
Participative session
Students will practice program to create a structure
student, containing name and roll. Ask user the name
20
and roll of a student in main function. Pass this
structure to a function and display the information in
that function.
05 Conclusion
1. Define a student structure with members sno, sname and three subject marks and write a program
to store n student details.
#include<stdio.h>
struct student
{
int sno;
char sname[15];
int m1,m2,m3;
};
void main()
{
int n;
struct student s[10];
printf(Enter number of student details you want to enter );
scanf(%d,&n);
printf(Enter student details);
for(i=0;i<n;i++)
{
printf(Enter student number);
scanf(%d,&s[i].sno);
printf(Enter student name);
scanf(%s,s[i].sname);
printf(Enter student marks);
scanf(%d%d%d,&s[i].m1,&s[i].m2,&s[i].m3);
}
printf(\n Student Details);
printf(\nSno \t Sname \t M1 \tM2\tM3);
for(i=0;i<n;i++)
{
printf(\n%d\t%s\t%d\t%d\t%d,s[i].sno,s[i].sname,s[i].m1,s[i].m2,s[i].m3);
}
}
2. Define a student structure with members sno, sname and three subject marks and write a program
to store n student details. Sort the student data base on total marks.
#include<stdio.h>
struct student
{
int sno;
char sname[15];
int m1,m2,m3,tot;
};
void main()
{
int n,i;
struct student s[10],temp;
printf(Enter number of student details you want to enter );
scanf(%d,&n);
printf(Enter student details);
for(i=0;i<n;i++)
{
printf(Enter student number);
scanf(%d,&s[i].sno);
printf(Enter student name);
scanf(%s,s[i].sname);
printf(Enter student marks);
scanf(%d%d%d,&s[i].m1,&s[i].m2,&s[i].m3);
}
for(i=0;i<n;i++)
{
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
}
for(p=1;p<n;p++)
{
for(i=0;i<n-p;i++)
{
if(s[i].tot>s[i].tot)
{
temp=s[i];
s[i]=s[I+1];
s[i+1]=temp;
}
}
}
printf(\n Student Details);
printf(\nSno \t Sname \t M1 \tM2\tM3\tTotal);
for(i=0;i<n;i++)
{
printf(\n%d\t%s\t%d\t%d\t%d\t
%d,s[i].sno,s[i].sname,s[i].m1,s[i].m2,s[i].m3,s[i].tot);
}
}
3. Define a customer structure with members cname,ccode,iname and price and write a program to
store n customer details and sort the records based on price of item.
#include<stdio.h>
sturct customer
{
char cname[15] ,iname[15];
int ccode;
float price;
};
void main()
{
struct customer c[10],temp;
int n,I,p;
printf(Enter number of details);
scanf(%d,&n);
printf(\nEnter Details);
for(i=0;i<n;i++)
{
printf(Enter customer name);
scanf(%s,c[i].cname);
printf(Enter item name);
scanf(%s,s[i].iname);
printf(Enter customer code);
scanf(%d,&s[i].ccode);
printf(Enter item price);
scanf(%f,&s[i].price);
}
for(p=1;p<n;p++)
{
for(i=0;i<n-p;i++)
{
if(c[i].price>c[i].price)
{
temp=c[i];
c[i]=c[I+1];
c[i+1]=temp;
}
}
}
printf(\nCustomer Details);
prinntf(\nCname\tIname\tCcode\tPrice);
for(i=0;i<n;i++)
{
printf(\n%s\t%s\t%d\t%f,s[i].cname,s[i].iname,s[i].ccode,s[i].price);
}
}
4. Program to pass the structure individual members to a function and display the values. Pass the
two integer values and display.
#include<stdio.h>
struct data
{
int a,b;
};
void display(struct data a, struct data b);
void main()
{
struct data d;
printf(\nEnter Two integer values);
scanf(%d%d,&d.a,&d.b);
display(d.a,d.b);
}
void display(struct data a,struct data b)
{
printf(\na= %d,b=%b,d.a,d.b);
}
5. Program to create a structure student, containing name and roll. Ask user the name and roll of a
student in main function. Pass this structure to a function and display the information in that
function.
struct student
{
char sname[15];
int sno;
};
void display(struct student s);
void main()
{
struct student s;
printf(Enter student name);
scanf(%s,s[i].sname);
printf(Enter student number);
scanf(%d,&s[i].sno);
display(s);
}
void display(struct student s)
{
printf(\n sname =%s\n Sno=%d,s[i].sname,s[i].sno);
}
05 Recap:
Sub-topic-1 (Lecture)
10 Program to read the roll number and date births of a list
of students and display the output sorted on date of birth
Participative session: Students will practice
20 Program to read the roll number and date births of a list
of students and display the output sorted on date of birth
Sub-topic-2 (Lecture)
Lernen is asked to write a Program to perform
10 multiplication of 2 complex numbers, reading and
product of 2 complex numbers should be performed by
using functions. Use pointer to structure method.
Participative session : Students will practice
Program to perform multiplication of 2 complex
20 numbers, reading and product of 2 complex numbers
should be performed by using functions. Use pointer to
structure method.
15 Explanation of basic operations of stacks
15 Push(), POP() routines explanation
05 Conclusion & Summary
Introduction to stacks:
Stack is a linear data structure on which the insert and delete operations can be performed at the same end.(OR)
stack is a linear data structure into which the elements are inserted and deleted in such a way that the last element
inserted is to be deleted first.
The most and least accessible elements in a stack are known as the top and bottom of the stack, respectively.
Stack operations: only through top of the stack we can perform these operations.
Stack Applications:
}
}
s->a[++s->tos]=x;
}
int pop(stack *s)
{
if(s->tos==-1)
{
printf("under flow\n");
return(-1);
}
else
return(s->a[s->tos--]);
}
Analysis:
Push(): O(1)
Pop(): O(1)
Introduction to queues:
Queue is also an abstract data type or a linear data structure, in which the first element is inserted from
one end called REAR(also called tail), and the deletion of exisiting element takes place from the other
end called as FRONT(also called head). This makes queue as FIFO data structure, which means that
element inserted first will also be removed first.
The process to add an element into queue is called Enqueue and the process of removal of an element
from queue is called Dequeue.
#define max 5
struct queue
{
int a[20];
int front, rear;
};
1. Linear queue.
2. Circular queue.
3. Dequeue.
Queue Applications:-
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as
they arrive, First come first served.
4. Queue is a checkout line at a Super market cash register. The first person inline is the first to
be Checked out.
5. Queue can be found in a time sharing computer system where many users share the system
simultaneously.
6. In multi program concept the os has to maintain different processes in ready queue ,
Waiting queue.etc.
7. In simulation:- Simulation is the process of forming an abstract model from a real situation
inorder to understand the impact of modifications and the effect of introducing various
strategies on the situation. Simulation allows the user to experiment with real and proposed
situations otherwise impossible or impractical. The major advantage of simulation is that it
permits experimentation without modifying the real situation.
8. Military operations ,pilot training programme etc.
9. Queuing theory.
If(qrear==max)
{
Printf(Q FULL);
Return;
}
qa[++qrear] =x;
If (qfront==-1)
{
Printf(UNDERFLOW\n);
Return;
}
Return(qa[qfront++]);
}
void display()
{
int i;
for( i = qfront; i <=q rear; i++)
{
Printf(%d , a[i]);
}
}
Analysis of Queue
Enqueue : O(1)
Dequeue : O(1)
Size : O(1)
Circular Queue:
Circular queue c is also implemented as same as simple queue, the main difference is that in circular
queue last element will again points to first element.
#include<stdio.h>
#include<conio.h>
#define size 4
typedef struct
{
int front;
int rear;
int count;
int a[50];
}queue;
void enqueue(int x, queue *q)
{
if(q->count==size)
{
printf("Q FULL\n");
return;
}
q->rear=(q->rear+1)%size;
q->a[q->rear]=x;
q->count++;
}
int dequeue(queue *q)
{
int x;
if(q->count==0)
{
printf("Q EMPTY\n");
return(-1);
}
x=q->a[q->front];
q->front=(q->front+1)%size;
q->count=q->count-1;
return(x);
}
void main()
{
int ch,x,y;
queue q;
clrscr();
q.rear= size-1;
q.front= 0;
q.count= 0;
printf("\n 1. enqueue \n 2. dequeue\n 3. exit\n");
scanf("%d",&ch);
while(ch!=3)
{
switch(ch)
{
case 1: printf("enter value to insert\n");
scanf("%d",&x);
enqueue(x,&q);
break;
case 2: y=dequeue(&q);
if(y!=-1)
printf("the deleted value is %d\n",y);
break;
}
printf("\n 1. enqueue \n 2. dequeue\n 3. exit\n");
scanf("%d",&ch);
}
}
(
_
(
_
(
(
(
( _
(
(
A a
((
* (
* *+ +
*+
( (+ (+
_( ((((_ A
(((( (
* (_ _((((
((( (
((((
( ( (__/
SESSION PLAN 36: SLL node structure definition
At the end of this session, Students will be able to:
1. Implement operations on SLL.
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
};
typedef struct node* list;
typedef struct node* position;
list create();
void display(list);
position find(list,int);
void insert(list,int);
position findprev(list,int);
list deletenode(list);
void main()
{
list l;
int ch,insch,x;
clrscr();
printf("enter 1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
while(ch!=5)
{
switch(ch)
{
case 1:
l=create();
break;
case 2:
printf("enter element to insert\n");
scanf("%d",&x);
insert(l,x);
break;
case 3:
l=deletenode(l);
break;
case 4:
display(l);
break;
}
printf("enter \n1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
}
}
void insert(list l , int x)
{
int insch,c=0,c1=0;
position p;
list newnode,temp;
printf("\nenter ur choice \n 1.At Begin\n 2.At Middle \n3.At end \n4.After any
node\n");
scanf("%d",&insch);
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL;
temp=l->next;
if(insch==1) //insert at begin
{
newnode->next=l->next;
l->next=newnode;
}
else if(insch==2) //inser at middle
{
while(temp)
{
temp=temp->next;
c++;
}
c=c/2;
temp=l->next;
while(temp&&c1!=c)
{
c1++;
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;
}
else if(insch==3) //at end
{
while(temp->next!=NULL)
temp=temp->next;
temp->next=newnode;
}
else if(insch==4) //after a position
{
int key;
printf("After which key u want to insert\n");
scanf("%d",&key);
p=find(l,key);
newnode->next=p->next;
p->next=newnode;
}
} //end of insert
list deletenode(list l)
{
int delch,c=0,x,c1=0;
position temp,p;
temp=l->next;
printf("\nenter ur choice \n 1.At Begin\n 2.At Middle \n3.At end \n4.A specific
node\n");
scanf("%d",&delch);
if(delch==1)
{
l=l->next;
}
else if(delch==2)
{
while(temp)
{
temp=temp->next;
c++;
}
c=c/2;
temp=l->next;
while(temp&&c1+1!=c)
{
c1++;
temp=temp->next;
}
temp->next=temp->next->next;
}
else if(delch==3)
{
while(temp->next->next!=NULL)
temp=temp->next;
temp->next=NULL;
}
else if(delch==4)
{
printf("enter element to delete\n");
scanf("%d",&x);
p=findprev(l,x);
p->next=p->next->next;
}
return l;
}
position find(list l, int x)
{
position p;
p=l->next;
while((p!=NULL) && (p->data!=x))
p=p->next;
return(p);
}
position findprev(list l, int x)
{
position p;
p=l->next;
while((p!=NULL) && (p->next->data!=x))
p=p->next;
return(p);
}
list create()
{
list temp,newnode,l;
int x;
l=(list) malloc(sizeof(struct node));
l->data=0;
l->next=NULL;
temp=l;
printf("enter 999 to exit\n");
scanf("%d",&x);
while(x!=999)
{
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
temp=temp->next;
printf("enter 999 to exit\n");
scanf("%d",&x);
}
return l;
}
void display(list l)
{
list temp;
temp=l->next;
printf("\nThe list is:\n");
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
DLL Operations:
Double Linked List:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
typedef struct node* list;
typedef struct node* position;
list create();
void display(list);
position find(list,int);
void insert(list,int);
position findprev(list,int);
list deletenode(list);
void main()
{
list l;
int ch,insch,x;
clrscr();
printf("enter 1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
while(ch!=5)
{
switch(ch)
{
case 1:
l=create();
break;
case 2:
printf("enter element to insert\n");
scanf("%d",&x);
insert(l,x);
break;
case 3:
l=deletenode(l);
break;
case 4:
display(l);
break;
}
printf("enter \n1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
}
}
void insert(list l , int x)
{
int key;
position p;
list newnode;
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL;
newnode->prev=NULL;
//after a position
printf("After which key u want to insert\n");
scanf("%d",&key);
p=find(l,key);
newnode->next=p->next;
p->next->prev=newnode;
newnode->prev=p;
p->next=newnode;
} //end of insert
list deletenode(list l)
{
l->next=l->next->next;
l->next->next->prev=l;
return l;
}
position find(list l, int x)
{
position p;
p=l->next;
while((p!=NULL) && (p->data!=x))
p=p->next;
return(p);
}
list create()
{
list temp,newnode,l;
int x;
l=(list) malloc(sizeof(struct node));
l->data=0;
l->next=NULL;
l->prev=NULL;
temp=l;
printf("enter 999 to exit\n");
scanf("%d",&x);
while(x!=999)
{
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
newnode->prev=temp;
temp=temp->next;
printf("enter 999 to exit\n");
scanf("%d",&x);
}
return l;
}
void display(list l)
{
list temp;
temp=l->next;
if(temp!=NULL)
{
printf("\nThe list is:\n");
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
else
printf("List empty\n");
}
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
typedef struct node* list;
typedef struct node* position;
list create();
void display(list);
position find(list,int);
void insert(list,int);
position findprev(list,int);
list deletenode(list);
void main()
{
list l;
int ch,insch,x;
clrscr();
printf("enter 1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
while(ch!=5)
{
switch(ch)
{
case 1:
l=create();
break;
case 2:
printf("enter element to insert\n");
scanf("%d",&x);
insert(l,x);
break;
case 3:
l=deletenode(l);
break;
case 4:
display(l);
break;
}
printf("enter \n1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
}
}
void insert(list l , int x)
{
int key;
position p;
list newnode;
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL;
newnode->prev=NULL;
//after a position
printf("After which key u want to insert\n");
scanf("%d",&key);
p=find(l,key);
newnode->next=p->next;
p->next->prev=newnode;
newnode->prev=p;
p->next=newnode;
} //end of insert
list deletenode(list l)
{
l->next=l->next->next;
l->next->next->prev=l;
return l;
}
position find(list l, int x)
{
position p;
p=l->next;
while((p!=NULL) && (p->data!=x))
p=p->next;
return(p);
}
list create()
{
list temp,newnode,l;
int x;
l=(list) malloc(sizeof(struct node));
l->data=0;
l->next=NULL;
l->prev=NULL;
temp=l;
printf("enter 999 to exit\n");
scanf("%d",&x);
while(x!=999)
{
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
newnode->prev=temp;
temp=temp->next;
printf("enter 999 to exit\n");
scanf("%d",&x);
}
return l;
}
void display(list l)
{
list temp;
temp=l->next;
if(temp!=NULL)
{
printf("\nThe list is:\n");
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
else
printf("List empty\n");
}
Circular DLL:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
typedef struct node* list;
typedef struct node* position;
list create();
void display(list);
position find(list,int);
void insert(list,int);
position findprev(list,int);
list deletenode(list);
void main()
{
list l;
int ch,insch,x;
clrscr();
printf("enter 1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
while(ch!=5)
{
switch(ch)
{
case 1:
l=create();
break;
case 2:
printf("enter element to insert\n");
scanf("%d",&x);
insert(l,x);
break;
case 3:
l=deletenode(l);
break;
case 4:
display(l);
break;
}
printf("enter \n1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
}
}
void insert(list l , int x)
{
int key;
position p;
list newnode;
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
//after a position
printf("After which key u want to insert\n");
scanf("%d",&key);
p=find(l,key);
newnode->next=p->next;
p->next->prev=newnode;
newnode->prev=p;
p->next=newnode;
} //end of insert
list deletenode(list l)
{
l->next=l->next->next;
l->next->next->prev =l;
return l;
}
position find(list l, int x)
{
position p;
p=l->next;
while((p!=l) && (p->data!=x))
p=p->next;
return(p);
}
list create()
{
list temp,newnode,l;
int x;
l=(list) malloc(sizeof(struct node));
l->data=0;
l->next=NULL;
l->prev=NULL;
temp=l;
printf("enter 999 to exit\n");
scanf("%d",&x);
while(x!=999)
{
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
newnode->next=l;
temp->next=newnode;
newnode->prev=temp;
temp=temp->next;
printf("enter 999 to exit\n");
scanf("%d",&x);
}
return l;
}
void display(list l)
{
list temp;
temp=l->next;
if(temp!=l)
{
printf("\nThe list is:\n");
while(temp!=l)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
else
printf("List empty\n");
}
Circular SLL:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
typedef struct node* list;
typedef struct node* position;
list create();
void display(list);
position find(list,int);
void insert(list,int);
position findprev(list,int);
list deletenode(list);
void main()
{
list l;
int ch,insch,x;
clrscr();
printf("enter 1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
while(ch!=5)
{
switch(ch)
{
case 1:
l=create();
break;
case 2:
printf("enter element to insert\n");
scanf("%d",&x);
insert(l,x);
break;
case 3:
l=deletenode(l);
break;
case 4:
display(l);
break;
}
printf("enter \n1.create \n2.insert \n3. delete \n4. display \n5. exit\n");
scanf("%d",&ch);
}
}
void insert(list l , int x)
{
list newnode;
list deletenode(list l)
{
l=l->next;
return l;
}
list create()
{
list temp,newnode,l;
int x;
l=(list) malloc(sizeof(struct node));
l->data=0;
l->next=NULL;
temp=l;
printf("enter 999 to exit\n");
scanf("%d",&x);
while(x!=999)
{
newnode=(list) malloc(sizeof(struct node));
newnode->data=x;
newnode->next=l;
temp->next=newnode;
temp=temp->next;
printf("enter 999 to exit\n");
scanf("%d",&x);
}
return l;
}
void display(list l)
{
list temp;
temp=l->next;
printf("\nThe list is:\n");
while(temp!=l)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
void main()
{
int ch,x;
clrscr();
printf("enter \n 1. push \n 2. pop \n 3. exit\n");
scanf("%d",&ch);
while(ch!=3)
{
switch(ch)
{
case 1:
printf("enter element to be pushed\n");
scanf("%d",&x);
push(x);
break;
case 2:
x=pop();
if(x!=-1)
printf("the popped val is: %d\n",x);
break;
}
printf("enter \n 1. push \n 2. pop \n 3. exit\n");
scanf("%d",&ch);
}
}
void push(int x)
{
list newnode;
if (tos==NULL)
{
tos=(node*)malloc(sizeof(struct node*));
tos->data=x;
tos->next=NULL;
}
else
{
newnode=(node*)malloc(sizeof(struct node*));
newnode->data=x;
newnode->next=tos;
tos=newnode;
}
}
Implementation of stacks using LL:
int pop()
{
int x;
if(tos==NULL)
printf("stack is empty\n");
else
{
x=tos->data;
tos=tos->next;
return(x);
}
return(-1);
}
void main()
{
int ch,x;
clrscr();
printf("enter \n 1. insert \n 2. delete \n 3. exit\n");
scanf("%d",&ch);
while(ch!=3)
{
switch(ch)
{
case 1:
printf("enter element to be inserted\n");
scanf("%d",&x);
insert(x);
break;
case 2:
x=delet();
if(x!=-1)
printf("the popped val is: %d\n",x);
break;
}
printf("enter \n 1. insert \n 2. delet \n 3. exit\n");
scanf("%d",&ch);
}
}
void insert(int x)
{
list newnode;
if (rear==NULL)
{
rear=(node*)malloc(sizeof(struct node*));
rear->data=x;
rear->next=NULL;
front=rear;
}
else
{
newnode=(node*)malloc(sizeof(struct node*));
newnode->data=x;
newnode->next=NULL;
rear->next=newnode;
rear=newnode;
}
}
Implementation of Queues using LL:
int delet()
{
int x;
if(front==NULL)
printf("queue is empty\n");
else
{
x=front->data;
front=front->next;
return(x);
}
return(-1);
}
Trees
Binary search tree is a simple data structure for which running time of most operations is O(logN) on
average.
*Trees are used to implement the file system of several popular operating systems.
*Trees can be used to support searching operations in O(log N) average time.
*Trees can be used to implement symbol table.
Tree(Recursive definition): A tree is a collection of nodes.The collection can be
empty;otherwise, a tree consists of a distinguished node r,called the root,and
zero or more nonempty(sub) trees T1,T2, T k, each of whose roots are
connected by a directed edge from r .
Roo
t
T T2 Tr
T3
1
TREE DIAGRAM
BINARY TREE
DIAGRAM
A
B C
D H F
E G
*The Depth of a binary tree may vary from (N-1) worstcase to log 2 N Best Case .
* The average depth of a binary tree is O(square root(N)).
Perfectly Balance Binary tree:-
If the height of the left subtree is equal to the height of the right subtree at all
the nodes it is called as the perfectly balanced binary tree.
PERFECT BINARY TREE DIAGRAM
B C
D E E F
*The maximum no of nodes in a binary tree of height H is 2H+1 1. If D is the depth of the tree then
N = 2D+1 - 1
*Full node : A full node is a node with two children.
*The number of full nodes plus one is equal to the no of leaves in a nonempty binary tree.
*If the height of the left subtree is greater than the height of the right subtree the tree is called as left
heavy.
*If the height of the right is greater than the height of the left subtree it is called as right heavy tree.
*Any nodes which has outdegree 0 is called a terminal node or a leaf ,all other nodes are called branch
nodes/Internal-nodes.
*Level: The level of any node is the length of its path from the root.
*Ordered tree: If in a(directed) tree an ordering of the nodes at each level is prescribed ,then such a
tree is called an ordered tree.
*Degree of a node: The no. of subtrees of a node is called the degree of the node.
*A set of disjoint trees is a forest.
*If the outdegree of every node is exactly equal to m or 0 and the no of nodes at level i is m i-1
(assuming the root is at level 1) then the tree is called a full or complete m-ary tree
.
*No of ordered trees with n nodes is (1/n+1)(2n)Cn.
Storage Representation of Binary Trees.
1.Sequential /Array representation
2.Linked storage representation.
3.Threaded storage representation.
5
4
4 8
8 5
3 5 7 9
2 0 7 2
2 7 7
8 0 9
2
9
% %
Description CO 1 CO 2 CO 3 CO 4 CO 5
L-T Practical
Test 1 5% 4% 5% - - - 4%
/Review1
5% - - 5% - - -
Test 2
6% - - - 6% - -
Test 3
4% 1% - - - - 1%
Attendance
End
Semester 30% 20% 7% 6% 6% 11% 20%
Exam/
Review2
100%
Total:
LTC Component is going to be assessed in every session and the weitage is 25% ( min.
of 35 sessions)
Syllabus:
Introduction to C language, Control structures, Functions, recursive functions. storage classes and scope
of variables. Arrays- passing arrays as parameters to functions. Searching- linear search, binary search,
Sorting- Bubble sort, quick sort. Strings, operations on strings and Multidimensional arrays. Pointers,
call by value Vs call by reference. Structures and Unions. Dynamic memory allocation. Stack and
Queue- implementation of Stack, Queue, circular Queue. Infix, post-fix and prefix notations, Stack
Applications - Evaluation of infix expression, conversion of infix to post-fix expressions using stacks.
Linked List- Linked List vs Arrays, Creation, insertion, deletion of Singly linked list, Doubly linked list
and Circular linked list . Linked list representation of Stack and Queues. Trees- Tree, Binary trees,
Binary search tree:- Creation, Insertion, Deletion and Tree traversals.
Text Books:
Reference Books:-
1. Mark Allen weiss, Data Structures and Algorithm Analysis in C, 2008, Third Edition, Pearson
Education.
2. Horowitz, Sahni, Anderson Freed, Fundamentals of Datastructures in C, 2nd Edition-2007.
3. Robert Kruse, C. L. Tondo, Bruce Leung, Shashi Mogalla, Data structures and Program Design
in C, 4th Edition-2007.
4. C for Engineers and Scientists An Interpretive Approach by Harry H. Cheng, Mc Graw Hill
International Edition-2010.
5. Jeri R. Hanly, Elliot B. Koffman, Problem Solving and Program Design in C, 7/e, Pearson
Education-2004.
6. Jean Paul Trembly Paul G.Sorenson, An Introduction To Data Structures with applications, 2 nd
Edition.
Course Team:
COURSE COORDINATOR
GROUP HEAD
HEAD OF DEPARTMENT
Approved By: DEAN-ACADEMICS (Sign with
Office Seal)