You are on page 1of 156

K L University

ACADEMIC DIVISION
COURSE HANDOUT FORMAT FOR UNDERGRADUATE COURSES
2015-16 L-T-P
2 4 2

COURSE NAME : C Programming & Data Structures


COURSE CODE : 15ES102
YEAR OF OFFERING THE COURSE : I/IV B.Tech
SEMESTER OF OFFERING THE COURSE : I semester
ACADEMIC YEAR : 2015-16
COURSE COORDINATOR : Dr. D. Haritha

COURSE INSTRUCTORS : Dr. D Haritha, P.V.Vara Prasad, N.Satya


Krishna, E. Sridevi, Zelan Basha, T. Rajesh,
L.Sridhar Rao, Uday Kumar, P. Siva Kumar.
COURSE TEACHING ASSOCIATES (If any) : Sk. Razia, NVS Pavan Kumar, B.Krishna
Mohan, Uday Bhaskar, D. Anand, Vamsidhar

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.

COURSE OUTCOMES (COs):

1. Illustrate how problems are solved using computers and programming.


2. Interpret & Illustrate user defined C functions and different operations on list of data.
3. Implement Linear Data Structures and compare them.
4. Implement the linked representation of BST.
5. Apply the knowledge obtained by the course to solve real world problems.
COURSE OUTCOME INDICATORS (COIs):
Course COI-1 COI-2 COI-3 COI-4 COI-5
Outcome
Number
CO-1 Describe problem Understanding Illustrate
solving and how to basic concepts decision
translate a of C. control and
flowchart to a C looping
program. statements.
CO-2 Interpret user Solving Illustrate Illustrate sorting &
defined C problems different searching
functions, and using operations on techniques.
understanding of recursion list of data
storage classes and
scope of variables
CO-3 Understanding Design and Design and
pointers and user implement implementatio
defined data types Algorithms for n of SLL.
in C language different
applications
using linear
data structures.
CO-4 Design and Implementatio Design and ----
implementation of n of stacks and implementatio
DLL. queues using n of BST with
LL and create, insert,
Circular delete, and
Linked List. tree traversals.
CO-5 Identify the Analysis of the Design Implementation
problem problem

MAPPING OF COURSE OUTCOMES TO PROGRAM OUTCOMES AND COIs TO


TEACHING-LEARNING-EVALUATION PLAN
S.No. Course Outcome Program Blooms Course Teaching- Evaluati
Outcom Taxonom Outcom Learning on
e y level of e Methods Patterns
mapping* Indicato
rs
1 Illustrate how problems E Apply Chalk and TEST 1
are solved using computers talk, PPT/
and programming. hands on
practice
2 Interpret & Illustrate user B Apply and Chalk and TEST 2
defined C functions and analyze talk, PPT/
different operations on list problem
solving.
of data.
3 Implement Linear Data B Analyze Chalk and TEST 3
Structures and compare talk, PPT/
them. analogy
4 Implement the linked A,B,E Analyze Chalk and Compreh
representation of BST, and talk, PPT/ ensive
file handling in C. hands on exam
practice
5 Apply the knowledge A,B,E Apply & Review1
obtained by the course to Analyze &
solve real world problems. Review2

COURSE DELIVERY PLAN:


SESSIO Topic 1/ COI Topic 2/ COI Topic 3/ COI Topic 4/ Topic 5/ COI
N Intro. To C C Functions Searching & COI DLL ,Trees
Number sorting Stacks , & files in C
queues &
SLL
Session 1 Program
development
steps: Algorithm
and flowchart
development
Session 2 Program
development
steps: Algorithm
and flowchart
development
Session 3 Practice on
Algorithm,
flowchart and
Types of
programming
languages,
Definition of
compiler and
interpreter
Session 4 History of C,
Structure of C
program, Data
types, Input and
output statements
Session 5 Operators and its
precedence,
Expression
Evaluation, Type
conversions
Session 6 Evaluating
expressions,
Sequence and
selection
statements(if-
else)
Session 7 If-else statement,
Else-if ladder
and nested
conditional
statements.
Session 8 selection
statements
(switch-case),
Iterations
statements(while,
do-while)
Session 9 Iterations
statements(while,
do-while, for)
Session Practice on
10 iterative
statements
Session Introduction to
11 functions
(function calling,
prototype
statements )
Session Passing
12 parameters to
functions,
Recursive
functions
Session Recursive
13 functions,
Storage classes
and scope of
variables
Session Practice session
14 on functions
Session Introductions
15 to arrays
Session Passing arrays
16 to functions,
Strings
Session String
17 Operations
Session Practice
18 session on
arrays
Session Multi-
19 dimensional
arrays-matrix
multiplication
Session Practice
20 session on
Multi-
dimensional
arrays
Session Searching-
21 linear search,
binary search
Session Introduction
22 to sorting,
bubble sort
Session Quick sort
23
Session Introduction
24 about
pointers,
Pointers to
arrays
Session Array of
25 pointers,
Pointers to
strings
Session Pointers to
26 functions ,
Returning
pointers from
function
Session Pointers to
27 pointer, Void
pointers
Session Call by value
28 and call by
reference
Session Dynamic
29 memory
allocation,
structures,
nested
structures
Session Structures
30 vs arrays
and Array
of structures
and
functions
Session Pointers to
31 structure
variables
and stacks
Session Implementa
32 tion of
stack using
arrays,
Introduction
to queues
Session Implementa
33 tion of
queues
using rrays,
circular
queue
Session Implementa
34 tion of
circular
queue ,
Conversion
from infix
to postfix
Session Conversion
35 from infix
to postfix
and
evaluation
of an
Expression
using stack
Session Imple-
36 mentation
of SLL
Session Implemen-
37 tation of
SLL, DLL
node
definition &
its function
prototypes
Session Imple-
38 mentation of
DLL
Session Imple-
39 mentation of
stacks using
LL
Session Implementati
40 on of queue
using LL
Session Introduction
41 to Binary
Search Tree,
Tree
traversals
Session Imple-
42 mentation of
BST
COI Course Outcome Indicators

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
10 What is an algorithm?
25 Sub-topic-1 (Lecture)
What is a flowchart. How to draw flow
charts?
15 Sub-topic-2 (Lecture)
Explain algorithm and flow chart for
addition of two numbers.
20 Practice-session-1:
There are three boxes. One is labeled
"APPLES" another is labeled
"ORANGES". The last one is labeled
"APPLES AND ORANGES". You know
that each is labeled incorrectly. You may
ask me to pick one fruit from one box
which you choose.
How can you label the boxes correctly?
Write algorithm & draw the flowchart?
25 Practice-session-2:
Draw a flowchart to describe the process of
solving the following problem.
Rahul went to the grocery store and bought
1kg maida for 65Rs., 1 litre milk for 50Rs.,
and a dozen eggs for 35Rs. He paid for the
groceries 500Rs.bill. What was his
change?
05 Conclusion & Summary
Algorithm: step-by-step representation of a problem solution is called an algorithm.
Flowchart: A pictorial representation of an algorithm is called flowchart.
Program: A set of executable instructions which will perform a particular task is known as program.
Ex: algorithm to preparation of tea:
1. Start
2. Take a bowel and ingredients (milk, tea powder, water, sugar,) required to prepare tea in different
bowels.
3. Put bowel on stove.
4. Take water, tea powder and milk into bowel and then heat it 5mts.
5. Add sugar into milk
6. Take this tea into a cup
7. Stop
The following list of symbols are used in flowcharts:

1. Start or stop symbol

2. Processing step symbol

3. Input or output step symbol

4. Decision making step

5. control flow symbol

Start

Result<- 500-
(65+50+35)

Display result
value

stop
Start

Take a Fruit from a


box labeled as A& O

T F
Is it
Apple

Change in correct Change in correct


label A& O as A label A& O as O

Change in correct Change in correct


label O as A&O label A as A&O

Change in correct Change in correct


label A as O label O as A

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
20 Practice-session-1
Ask students to Write an algorithm to find
the roots of a quadratic equation.
25 Practice-session-2
Ask students to Draw flow chart for
finding the roots of a quadratic equation.
20 Practice-session-3
Roberta wants to grow spaghetti in her
back yard. She has cleared a rectangular
patch of land with a width of one inch and
a length of sixty inches. How much
fertilizer does she need to cover the area of
her garden. Draw the Flowchart .
25 Practice-session-4
Write algorithm & flow chart for the
following problrm:
You have a store that sells lemons and
oranges. Oranges are Rs.30 each and

lemons are Rs.15 each. Your program
should get from the user the number of
oranges and lemons he/she wants to buy
and outputs the total amount of money they
owe you.
05 Conclusion & Summary

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
5 Recap
25 Practice-session-1
Write an algorithm and flow chart for the
following problem: Given 2 numbers,
determine whether or not their sum is
greater than 100.

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:

TABLE FILE ENROLLMENT


SUM STUDENTS BY SEMESTER BY CLASS
The only down side of a 4GL is that it does not make efficient use of machines resources.
However, the benefit of executing a program fast and easily far outweighs the extra costs of
running it.
Fifth-generation programming language:
5GLs are centered on solving problems using constraints given to the program, rather than using
an algorithm written by a programmer.
Most constraint-based and logic programming languages and some declarative languages form a
part of the fifth-generation languages.
5GLs are widely used in artificial intelligence research.
Typical examples of a 5GL include Prolog, OPS5, and Mercury.
Another aspect of a 5GL is that it contains visual tools to help develop a program. A good
example of a fifth generation language is Visual Basic.
With 5GL, the programmer only needs to worry about what problems need to be solved and what
conditions need to be met, without worrying about how to implement a routine or algorithm to
solve them.

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

Display yes Display no

Start

Stop

Read d
value

D0

Td0

Td<-td+3;
days++

T F
Td>
=d

Td=td- Read days


2

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

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
10 Recap / Introduction:
Explain brief history and characteristics of
C programming
10 Sub-topic-1(lecture):
Explanation of structure of C program with

one example program- to find the area of a
circle.
15 Sub topic-2(Lecture):
Explanation of C character set, tokens,

identifiers, keywords, operators, constants
with possible examples.
10 Sub-topic-3(Lecture):
Explanation of different data types in C
language and its ranges.
10 Practice session - 2:
Students will verify the ranges of different
data types on their laptops.
10 Sub-topic-4(Lecture):
Explanation of I/O statements,
tokens(keywords, identifiers, operators and

constants)
Explanation of input and output
statements.
15 Practice-session-1:
Students will practice three more
programs-
1. To print digit at 1s place of a
number.
2. To find square root of a given +ve
integer.
15 Practice session-3:
Students will practice few programs-
1. To find simple Interest.
2. To find damped frequency of an
electrical ckt.
05 Conclusion & Summary
DATA TYPES
C language provides a rich set of data types. In C language these data types are classified as:
1. Primary data types( or Fundamental data types or Basic data types or Built-in data types).
2. User defined data types
3. Derived data types.
Primary data types:-
Primary data types are those which are already available in C compiler. These are defined by the
compiler developer. These primary data types are classified into two categories based on the type of data.
They are i. Integral data ii. Floating-point data. Once again this data is classified as shown in the
following tree hierarchy structure.
Based on the size of the floating point data once again it is classified into 3 types of data. i)
Floating-point data type. ii) Double precision floating point data type. iii) Extended Double
precision floating point data type.
PRIMARY DATA TYPES
INTEGRAL DATA TYPE
Integer data type Character data type
Signed data Unsigned data Signed character
Integer data type Unsigned integer data type data type
Short integer data type Unsigned short integer data type Unsigned character
Long integer data type Unsigned long integer data type data type

FLOATING-POINT DATA TYPE


Floating point data type Double precision floating- Extended double precision
point data type floating-point data type

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.

DATA TYPE SIZE RANGE KEYWORD


Signed character data type 1 byte -128 to 127 char / signed char
Unsigned character data type 1 byte 0 to 255 unsigned char
Signed short integer data type 1 byte -128 to 127 signed short int / short int / short
Unsigned short integer data type 1 byte 0 to 255 unsigned short int / unsigned short
Signed integer data type 2 bytes -215 to 215-1 signed int / int
Unsigned integer data type 2 bytes 0 to 216-1 unsigned int / unsigned
Signed long integer data type 4 bytes -231 to 231-1 signed long int / long int / long
Unsigned long integer data type 4 bytes 0 to 232-1 unsigned long int / unsigned long
Floating point data type 4 bytes 3.4E-38 to Float
3.4E+38
Double precision floating point 8 bytes 1.7E-308 to Double
data type 1.7E+308
Extended double precision 10 bytes 3.4E-4932 to long double
floating point data type 1.1E+4932

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.

INPUT AND OUTPUT STATEMENTS:


INPUT FUNCTION- scanf()
We can assign values to variable through assignment statements such as x = 5 a = 0 ; and so on.
Another method is to use scanf() function which can be used to read data from a key board. It is the
general input function available in C Language. The general format of scanf() is as follows:
scanf(control string,&variable1,&variable2,.);
The control string contains format of the data being received. The ampersand symbol (&)before each
variable name is the operator that specifies variable names address. The use of & is must in scanf()
function.
Example: scanf(%d,&x);
When this statement is encountered, the execution of program stops and waits for the value of the variable
x to be typed in .The format %d specifies that an integer value is to be read from the terminal, we have to
type in the value in integer form. Once number typed and return key pressed, the next statement in the
program is executed.
Commonly used format specifications:
%c read a single character.
%d read a decimal Integer.
%e read a floating point value in exponential form.
%f read a floating point value.
%i read a decimal, hexadecimal or octal Integer.
%h read a short integer.
%x read a hexadecimal integer (unsigned) using lower case a f.
%X read hexadecimal integer (unsigned) using upper case A F.
%o read an octal integer.
%s read a string
%u read unsigned decimal integer.
%[ character set] reads only the characters specified with in brackets when inputting string.
%[^character set] The characters specified after ^(circumflex) are not permitted in the input .

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!);

printf (Welcome to the world of Engineering!);


}
Both the messages appear in the output as if a single line. If you wish to print the second message to the
beginning of next line, a new line character must be placed inside the quotation marks.
Program:
main()
Output:
{
Hello!
printf(Hello!\nWelcome to the world of Engineering);
Welcome to the world of Engineering
}

General format of printf() is as follows :


printf(control string,exp1,exp2,exp3,);

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.

Program: Program to read and print integer,float and character values


#include<stdio.h>
main() a x ch
{ int a;
float x; 56 65.8 y
char ch;
printf(Enter value of a);
scanf(%d,&a); Output:
printf(Enter value of x); Enter value of a
scanf(%f,&x); 56
printf(Enter any character ); Enter value of x
scanf(%c,&ch); 65.8
printf( \n a is %d,a); Enter any character
printf(\n x is %f,x); y
printf(\n ch is %c,ch); a is 56
}
x is 65.800000
ch is y

Program Program to read and display octal &hexadecimal integers


#include <stdio.h>
main() Output:
{ Enter any octal integer
int i ,j; 34
printf("Enter any octal integer"); Enter any Hexadecimal integer
scanf(" %o",&i); E
printf("Enter any Hexadecimal integer"); Output values
scanf(" %x",&j); octal integer i is 34
printf("\nOutput values\n"); octal integer i equivalent decimal value 28
printf("\n octal integer i is %o ", i); hexadecimal integer is E
printf("\n octal integer i equivalent decimal hexadecimal integer j equivalent decimal value 14
value %d ", i);
printf("\n hexadecimal integer is %x", j);
printf("\n hexadecimal integer j equivalent decimal value %d ", j);
}

Program: Using printf() to display numerical values.


#include <stdio.h>
main()
{
int a = 2, b = 10, c = 50;
float f = 1.05, g = 25.5, h = -0.1;
printf("\nDecimal values without tabs: %d %d %d", a, b, c);
printf("\nDecimal values with tabs: \t%d \t%d \t%d", a, b, c);
printf("\nThree floats on 1 line: \t%f\t%f\t%f", f, g, h);
printf("\nThree floats on 3 lines: \n\t%f\n\t%f\n\t%f", f, g, h);
printf("\nThe rate is %f%%", f);
printf("\nThe result of %f/%f = %f\n", g, f, g / f);
}
Output: Decimal values without tabs: 2 10 50
Decimal values with tabs: 2 10 50
Three floats on 1 line: 1.050000 25.500000 -0.100000
Three floats on 3 lines:
1.050000
25.500000
-0.100000
The rate is 1.050000%
The result of 25.500000/1.050000 = 24.285715

Program: C program for simple interest calculation


#include<stdio.h>
main()
{ Output:
int p,n,; Enter values of p,n,and r
float r,si;
printf("\n Enter values of p,n,and r"); 200 2 2
scanf("%d %d %f",&p, &n, &r); simple interest =rs.
si=(p * n * r )/ 100; 8.000000
printf("simple interest =rs. %f",si);
}
Program: C program to add two integers
#include<stdio.h>
main()
{ Output:
int a,b,c;
Enter value of a 5
printf("\n Enter value of a");
scanf("%d ",&a); Enter value of b 6
printf("\n Enter value of b");
sum is 11
scanf("%d ",&b);
c=a+b;
printf("sum is %d ",c);
}
One of the essential operations performed in a C language program is to provide input values to the
program and output the data produced by the program to a standard output device. We can assign values
to variable through assignment statements such as x = 5; a = 0; or initialize variables in the type
declaration statement like
int a= 10; float b=25.4;
Another method is to use scanf() function which can be used to read data from the key board. For
outputting results we have used extensively the function printf() which sends results out to a terminal.
There exists several functions in C language that can carry out input output operations. These functions
are collectively known as standard Input/Output Library.
SINGLE CHARACTER INPUT OUTPUT
The basic operation done in input/output is to read characters from the standard input device such as the
keyboard and to output or writing it to the output unit usually the screen.
getchar() function
The getchar() function can be used to read a character from the standard input device. The scanf()
function can also be used to achieve the purpose.. The getchar() function has the following form

variable _name = getchar();

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

Program: Program to test the type of input character

#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

putchar(variable /constant /expression);

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:

(a) char ch;


ch=y; would print character constant y
putchar(ch);
(b) putchar(f); //prints single character constant f on the screen
(c) putchar(65); // prints A whose ASCII value is 65.
(d) putchar(65+35); // prints d whose ASCII value is 65+35(i.e.,100)
(e) putchar(65.2); // cause an error as floating point type is not allowed.

Program: Program to read and display a single character


#include<stdio.h>

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));
}

STRING INPUT AND OUTPUT


gets() function
The gets() function reads string from standard input device. A string is an array or set of characters. The
function gets( ) accepts the name of the string as a parameter, and fills the string with characters that are
input from the keyboard till newline character is encountered (that is till we press the enter key). At the
end function gets( ) appends a null character as must be done to any string and returns.
The standard form of the gets function is
gets (str)

Here str is a string variable. For example,


char str[15];
puts(enter any string:);
gets(str);
If the string entered is GREEN FIELDS ,it is stored as

G R E E N F I E L D S \0

The character \0 is appended automatically, indicating termination of string.


puts() function
puts() is a function that copies a string to the standard output device, usually the display screen. When we
use puts(), we include the standard input/output header file (stdio.h). puts() also appends a newline
character to the end of the string that is printed. The format string can contain escape sequences.
The standard form for the puts function is
puts (str)
Where str is a string variable.
Example puts("This is printed with the puts( ) function!");

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!

Program: Program to read and display a string


#include<stdio.h> Output:
main() Type a string less than 80
characters
{ the string typed is
char s[80];
K L UNIVERSITY
printf (Type a string less than 80 characters);
gets(s);
printf(\n the string typed is\n);
puts(s);
}

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

Read P,T,R Value

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

Display Display Odd


Even

Start

Stop
Read Y Value

T (y%400==0)or N

(y%4==0 AND y
%100!=0)

Flow chart 8:Display Leap Year Display Not Leap Year


SESSION NO: 05
At the end of this session on OPERATORS, students will be able to:
1. Implement different operators in C.
2. Evaluate expressions in C.
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction:

Explain the use of operators in C
10 Sub topic-1(Lecture):
Explanation of arithmetic and relational
operators with example programs.
10 Practice session:
Students will verify above explained
programs.
10 Sub topic-2(Lecture)

Explain logical and bitwise operators
15 Practice session:
We will ask student to write a program on

performing logical and bitwise operations
on numbers
10 Sub task-1(Lecture):
Explain the assignment, increment and

decrement operators with small expression
statements.
15 Practice session:
We will ask student to write a program on

performing increment and decrement
operations on numbers.
10 Sub task-2(Lecture):
Explanation about conditional and special
operators with small example expressions.
10 Practice session:
We will ask student to write a program on
conditional and special operators.
We will ask student to write a program to
find largest of 3 numbers using ternary
operator.
05 Conclusion & Summary
Increment and decrement operators(++ and--)
These two operators are unary operators. They exists in two forms i.e. pre and post(prefix and
postfix)
i) Increment operator(++)
Increment operator is used to increment the value of its operand by 1.General form for pre incrimination
is
++ operand
and post incrimination is
operand ++
where the operand must be a variable but cannot be constant or expression..++operand is called pre
increment or prefix increment and operand++ is called post increment or postfix increment
Example: pre incrementation
int i=20;
++i;
printf(i=%d,i);
output: i=21
Example: post incrementation
int i=20;
i++;
printf(i=%d,i);
output:i=21;
In the above example prefix and postfix operation results in the same output. The prefix and postfix
operations differ in the value used for the operand when it is embedded inside expressions
Example: int x=10,y;
y=++x;
printf(x=%d,y=%d,x,y);
output: x=11,y=11
Here x value is incremented before it is assigned to y. So the expression y = ++x is equivalent to the two
expressions x=x+1 and y=x
Example: int a=5,b;
b=++a*4;
printf(a=%d,b=%d,a,b)
output: a=6,b=24
Example: int x=10,y;
y=x++;
printf(x=%d,y=%d);
output: x=11,y=10
Here value of x is incremented after it is assigned to y, thus the expression y=x++ is equivalent to the
expressions y=x and x=x+1;
Example: int a=5,b;
b=a++*4;
printf(a=%d,b=%d,a,b);
output: a=6,b=20

Note: ++4 and ++(x+y) are invalid expressions.

ii) Decrement operator ( - - )


This operator is used to decrement the value of the operand by 1.

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.

Example: int a=10,b;


b= -- a*3;
printf(a=%d,b=%d\n,a,b);
output: a=9,b=27
Example: int a=10,b;
b=a--*3;
printf(a=%d,b=%d\n,a,b);
output: a=9,b=30

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.

ii) Multiple assignment


This is used to assign the value of an expression to two or more variables.

The general form is v1=v2=v3=expression;

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.

iii) Compound assignment


Compound assignment is a short hand notation for a simple assignment.The compound assignment
operators are
+ =, - =, * =, / =, % =.
To evaluate a compound assignment expression, first change it to a simple expression.

Compound assignment Equivalent simple expression


x+=expression x=x+expression
x-=expression x=x-expression
x*=expression x=x*expression
x/=expression x=x/expression
x%=expression x=x%expression

Example: a*=b+3 is evaluated as a=a*(b+3)


sum+=x is evaluated as sum=sum+x
a%=10 is evaluated as a=a%10.

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

This is called conditional expression.


First, expression1 is evaluated, if the result is non-zero, the expression2 is evaluated and its value is the
final result. Otherwise, expression3 is evaluated and its value is the final result.

Example: To find the biggest of two numbers


big= (a>b)? a: b;
This is equivalent to the if else statement
if (a>b)
big=a;
else
big=b;

Example: To check an integer is even or odd


(n%2)? printf (Given integer is odd\n): printf(Given integer is even\n);
This is equivalent to the statement
if(x%2)
printf(given integer is odd\x);
else
printf(given integer is even\x);

Example:To find absolute value of an expression


y=(x>=0)? x: -x;

Example: To evaluate the function defined by


F(x)= x2-x+1 of x>=0
x2+x+1 of x<0
fx=(x>=0)?(x*x-x+1):(x*x+x+1);
Note:Conditional expression may be nested

Example: To find the biggest of three numbers


big=(a>b)?((a>c)?a:c):((b>c)?b:c);
Although conditional expression is nested, it is not recommended.

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.

Example: int m=5,n;


n=(m+=5,m%3);
n is assigned the value1.
Example: swapping of two integer variable using the comma operator
temp=a , a=b , b=temp;
The comma operator is most often used in for statement expressions to combine two or more expressions
in initial expression. And to combine increment or decrement in the third expression

Example: for(i=1 , j=10 ; i<j ; ++i , --j)


{
statements;
}
ii) size of operator
This operator is used to determine the number of bytes required to store a particular data type item in the
memory.
General form is sizeof(operand)

where the operand may be name of the data type or constant or variable or expression.

Example: printf(char size is %d bytes\n , sizeof (char));


printf(long int size is %dbytes\n , sizeof(double));
printf(double size is %dbyte\n,sizeof(double));

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.

Example: int x=10,*p;


p=&x;

&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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap/Introduction:
Recap all previous class operators
15 Sub-task-1(Lecture):
We will explain precedence and

associativity of all operators in C. we will
explain rules for expression evaluation.
10 Practice session:
Students will evaluate few expression
manually to find output.
10 Sub-task-2(Lecture):
Explain implicit and explicit type
conversion.
10 Practice session:
We will ask student to practice implicit and
explicit type conversions.
10 Sub topic-1(Lecture):
Explanation of if Syntax, flowchart of If
statement and Explain a program to check
a given number is positive OR NOT
10 Practice session:
We will give a task to students to write a
program to print whether a given number is
even or odd.
15 Sub-topic-2(Lecture):
Syntax of if-else statement, explanation of
control flow of if-else statement with a
program to print a given number is even or
odd.
10 Practice session:
We will ask students to print whether the
given year is leap year or not.
05 Conclusion & Summary
CONDITIONAL STATEMENTS
Usually a processor (machine) will execute its instructions in a sequential order only. But in real
time problems we need to execute a set of instructions whenever a particular condition satisfies otherwise
we want to skip that set of instructions which indicates a small sub task. i.e. we want to change the
execution flow of a processor from its sequential flow. To solve this type of problems C language
provides few programming constructs which are called as conditional statements or decision making
and branching statements. They are
1. Simple if statement
2. If-else statement
3. else-if ladder statement
4. Nested if statements.
5. Switch-case statement.
The syntaxes (grammar rules or generic statement) of these statements its execution flowcharts are shown
below.
Simple if statement:-
Syntax:-
if(expression)
Beginning of the if { body
Statement1
------------
------------
------------
Ending of the if body Statement-n
}

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;


}

Program: Write program to check a given number is positive

#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.

Program: Print a given number is even or odd.


Void main()
{
Int I;
Printf(enter integer value);
Scanf(%d,&i);
If(i%2==0)
Printf(Given number is even);
Else
Printf(Given number is odd);
}
Program: print whether the given year is leap year or not
#include <stdio.h>
void main()
{
int year;
printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);
if ( year%400 == 0 && year%4 == 0)
printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);
}
Practice Program:
1. What would be the output of each of the following code segments?
void main ( )
{
int a,b=0;
if(a=b=1)
printf (hello);
else
printf (world);
}
2. What would be the output of each of the following code segments?

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: program to display grades of student


#include<stdio.h>
void main()
{
int m1,m2,m3,total;
float per;
clrscr();
printf("Enter 3 Nos.");
scanf("%d%d%d",&m1,&m2,&m3);
total=m1+m2+m3;
per=total*100/300;
if(per>=60&&per<=100)
printf("You are 1st :");
else if(per>=50&&per<=60)
printf("You are 2nd");
else if(per>=40&&per<=50)
printf("You are 3rd");
else
printf("You are Fail");
getch();
}

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction:
Recalling previous lecture.
10 Sub topic-1(Lecture):
Syntax, flowchart of Switch-case
statement with an example program to
create an arithmetic calculator.
10 Practice session1:
Students will practice a program to find the
given character is a consonant or a vowel or
a digit or a white space or a special symbol.
10 Sub task-2(Lecture):
Explanation of importance of goto and break
statements with example programs.
15 Practice session-2:
Students will practice above program
arithmetic calculator with menu driven to
understand goto and break concepts.
15 Sub task-3(Lecture):
Syntax and flowchart of while and write a
program to print even numbers between
1 to 10.
15 Sub topic-3(lecture):
Explain a program to print and ask lerner to
write a program.
******
******
******
******
15 Practice session-4
Give a task to students to print
******
*****
****
***
**
*
05 Conclusion & Summary
A while loop statement in C programming language repeatedly executes a target statement as long as a given
condition is true.
Syntax:
The syntax of a while loop in C programming language is:

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.

Program: write a program to print numbers from 1 to 10.


#include <stdio.h>

int main ()
{
/* local variable definition */
int a = 1;

/* while loop execution */


while( a < =10 )
{
printf("value of a: %d\n", a);
a++;
}

return 0;
}
Program: Print first 10 even numbers

int main ()
{
/* local variable definition */
int a = 1, i=1;

/* while loop execution */


while( a < =10 )
{
If(i%2==0)
{
Printf(%d\n,i);
a++;
}
i++;
}

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);
}

Program: A program to print


******
******
******
******
Void main()
{
Int i=0, j;
While(I<4)
{
J=0;
While(j<6)
{
Printf(*);
J++;
}
Printf(\n);
I++;
}
}

Program: task to students to print


******
*****
****
***
**
*
Void main()
{
Int i=0, j;
While(I<4)
{
J=i;
While(j<6)
{
Printf(*);
J++;
}
Printf(\n);
I++;
}
}
Practice Program:
1. What is the output when the following program is executed?
#include<stdio.h>
main()
{
int i=1;
while(i<=10)
{
printf(%d,--i);
++i;
}
}
2. What is the output when the following program is executed?
#include<stdio.h>
main()
{
int x=1;
while()
{
printf(%d,x);
++x;
}
}
3. What is the output when the following program is executed?
#include<stdio.h>
main()
{
int a=5;
while(a-- >0)
printf(%d\t,a);
}
4. What is the output when the following program is executed?
#include<stdio.h>
main()
{
int p=5;
while(p<8)
{
printf(%d,p);
p=9;
}
}
5. What will be the output when the following code is executed?
#include<stdio.h>
main()
{
int a = 6;
while (a)
{ printf(%d\t, a);
a -= 2;
}
}

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

10 Syntax and flowchart of do while and


explain a program to add all the numbers
entered by a user until user enters 0.
10 Practice session-1:
We will give a task to students to print
values from 10 to 1 using do-while
10 Explain a menu driven program using
do-while, switch statements.
15 Practice session-2:
We will give a task to students to practice
menu driven program
10 Sub task-1(Lecture):
Syntax and flowchart of for loop and
explain a program to print numbers from 1
to 10 using for
10 Practice session-3:
Students will write a program to print first
10 even numbers using for.
10 Sub task-2(lecture):
Explain the syntax of nested for and explain
a program to print
11
12
13
21
22
23
31
32
33
15 Practice session-4:
Task to students to print
*
**
***
****
*****
05 Conclusion & Summary
For:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
Syntax:
The syntax of a for loop in C++ is:

for ( init; condition; increment )


{
statement(s);
}

Here is the flow of control in a for loop:


The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body
of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to
theincrement statement. This statement allows you to update any loop control variables. This
statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, the
for loop terminates.

Flow Diagram:

Program: to print values from 1 to 10


Void main()
{
Int I;
for(i=0;i<n;i++)
{
Printf(%d ,i);
}
}

Program: to print first 10 even numbers


Void main()
{
Int I, count;
for(i=1,count=0; count< 10; i++)
{
If(i%2==0)
{
Printf(%d\n,i);
Count++;
}
}
}

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);
}
}

Program: Task to learners to print


*
**
***
****
*****
Void main()
{
Int I,j;
For(i=1;i<=5;i++)
{
For(j=1;j<=I;j++)
Printf(*);
Printf(\n);
}
}

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap/introduction:
10 Practice session-1:
Students will practice program-1. To print
fibanocci sequence upto N terms.
15 Practice session-2:
Students will write program-2. To print all
possible co-prime numbers between 1 to N.
10 Practice session-3:
Students will execute program-1.
10 Practice session-4:
Students will execute program-2.
10 Practice session-5:
Students will write program-3. To print
Lucas sequence upto N terms.
10 Practice session-6:
Students will write program-4. To print
multiplication table upto N multiples.
10 Practice session-7:
Students will write a program to reverse the
given number.
15 Practice session-8:
Students will practice program-4. To find
given number is a strong number or not.
05 Conclusion:
Fibonacci Sequence:

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:

Consider main function


void main()
{
area();
}

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);
}

functions with argument and without return type

In this category of function


Function accepts argument but it does not return a value back to the calling Program .
It is Single ( One-way) Type Communication
Generally Output is printed in the Called function
Here area is called function and main is calling function.
Program :
#include<stdio.h>
void add(int,int);
void main()
{
int a=10,b=20;
void add(a,b);
}
void add(int x,int y)
{
printf(%d,x+y);
}
Functions without argument and with return type
In this category of functions,functions can be called without arguments but it returns a value

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction:
Recalling previous topic.
15 Subtask-1(Lecture):
Syntax of Passing parameters to functions.
15 Subtask-2(Lecture):
Explanation of the program to find whether
the given number prime or not on Passing
parameters to functions
15 Practice session-1:
Students will practice the program to find
whether the given number prime or not on
Passing parameters to functions
10 Sub topic-3(Lecture):
Explanation of recursion and recursion
functions with program to find factorial of a
number.
10 Practice session-2
We will ask students to write a program to
find factorial of a number.
15 Sub topic-4(Lecture):
Write a recursive function to find GCD of a
number
10 Practice session-3:
Students will write program to find GCD of
a number
05 Conclusion & Summary
Recursive functions:
Recursion is the process of repeating items in a self-similar way. Same applies in programming languages as
well where if a programming allows you to call a function inside the same function that is called recursive
call of the function as follows.
void recursion()
{
recursion(); /* function calls itself */
}

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>

int factorial(unsigned int i)


{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
Find gcd of a number using recursion in c program

#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;
}

int findgcd(int x,int y)


{
if(x!=y)
{
if(x>y)
return findgcd(x-y,y);
else
return findgcd(x,y-x);
}
return x;
}

SESSION PLAN 13:


At the end of this session, on Recursive 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.

Time Topic Blooms Blooms Blooms


in Taxonom Taxonom Taxonom
Minut y Level-1 y Level-2 y Level-3
es
05 Recap / Introduction:
Recalling previous topic.
10 Sub topic-1(Lecture):
Explanation of recursion and recursion functions
with program to calculate XY
20 Practice session-1:
Students will practice Fibonacci series and writing
recursive function to display first n-Fibonacci
numbers.
20 Practice session-2:
We will ask students to write a program to display
Fibonacci numbers.
10 Sub topic-2(Lecture):
Explanation of different types of storage
classes(auto,register) with programs
1.program to perform addition of two numbers
using auto keyword
2.program to perform addition of two numbers
using registers keyword
10 Practice session-3:
Students will practice the programs
1.program to perform addition of two numbers
using auto keyword
2.program to perform addition of two numbers
using registers keyword
10 Sub topic-3(Lecture):
Explanation of different types of storage
classes(static,extern) with programs
1.To print the series of integer numbers upto using
static keyword
2.program to read and display the values using
extern keyword
10 Practice session-4:
We will ask students to write programs
1.To print the series of integer numbers upto 10
using static keyword
2.program to read and display the values using
extern keyword
05 Conclusion & Summary

Recursive function for X5:

Long int pow(long int x, int n)


{
If(n==0)
Return(1);
If(n==1)
Return(x);
If(n%2==0)
Return(pow(x*x,n/2));
Else
Return(pow(x*x,n/2)*x);
}

Storage class of variable Determines following things


1. Where the variable is stored
2. Scope of Variable
3. Default initial value
4. Lifetime of variable
A. Where the variable is stored :
Storage Class determines the location of variable , Where it is declared. Variables declared with auto
storage classes are declared inside main memory whereas variables declared with keyword register are
stored inside the CPU Register.

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);
;
}

SESSION PLAN 14:

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.

Time Topic Blooms Blooms Blooms


in Taxonom Taxonom Taxonom
Minut y Level-1 y Level-2 y Level-3
es
05 Recap / Introduction:
Recalling previous topic.
20 Ask students to write an algorithm & flow chart to
generate all permutation of 1, 2 and 3.
20 Implement C function to generate all permutation
of 1, 2 and 3.
10 Write a program to fill the entire screen with a
smiling face. The smiling face has an ascii value 1.

20 Ask students to write an algorithm & flow chart to


produce the following output.
A B C D E F G F E D C B A
A B C D E F F E D C B A
A B C D E E D C B A
A B C D D C B A
A B C C B A
A B B A
A A
20 Ask students to write a function which produces
the above output
05 Conclusion & Summary
program to print all permutations of 1,2 and 3.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k;
clrscr();
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
for(k=1;k<=3;k++)
{
if(i==j||j==k||i==k)
continue;
printf("\n%d\t%d\t%d",i,j,k);

}
}
}
getch();
}

program to fill the entire screen with a smiling face

#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

Student practice the following two programs:

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;
}
}

printf(position of the given value is %d,pos);


}

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
10 Sub topic(lecture):
Explanation about passing
arrays to functions with the
program to find the largest
value from the list of values.
10 Practice session:
We will ask students to define a
function to return largest value
from a list of values and call
this function in main to find
largest value of a given list of
values.
10 Sub topic(Lecture):
Explanation about reversing the
values of an array with the
program to reverse the elements
of the array.
15 Practice session:
We will ask students to define a
function to reverse the elements
of an array. Use this in main to
display the given list in reverse
order. Write separate function to
read values to the array
10 Sub topic(lecture):
Explanation about strings
declaration and initialization
with the program
to read and print a line of text.
15 Practice session:
Students will write a Program
to count number of vowels
,consonants ,words ,digits and
symbols in a line of text.
10 Sub topic(lecture):
Explanation about string
functions with the program to
calculate length of the given
string.
10 Practice seesion:
Students will practice the
execution of the program to
calculate length of the string by
using the string function strlen()
05 Conclusion on strings
Explination of passing arrays to functions with the following program:
Arrays can be passed to a function through arguments when an array is passed through argument,
base address of the array is passed. Therefore passing array is always call by reference. To pass one-dimensional
array to a called function,simply write the name of array as actual argument without any subscripts, and size of
array.

1. program to find the frequency of a given number in the list


int frequency(int a[ ],int n , int key);
void main( )
{
int a[10],n,key,count,i;
printf(enter n value);
scanf(%d,&n);
printf(enter values for array);
for(i=0;i<n;i++)
{
scanf(%d,&a[i]);
}
printf(enter key value);
scanf(%d,&key);
count=frequency(a,n,key);
printf(frequency of the given %d number is %d times,key,count);
}
int frequency(int a[10],int n,int key)
{
int count=0,i;
for(i=0;i<n,i++)
{
if(a[i]==key)
count++;
}
return(count);
}

Student practice the following program:

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.

Explanation of string declaration and initialization:

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:

Reading strings from keyboard:


There are different methods to read a string
Using %s control with scanf()
The familiar input function scanf ( ) can be used with %s conversion specification to read string of characters.
Using gets() function:
gets() function is useful to read strings from the keyboard. The general syntax is

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).

Writing strings to the screen:


Using %s control with printf():
We can use printf ( )function with %s conversion to print string. The string is taken from the memory until the
occurrence of null character and is displayed. For example,
char str[ 20];
printf(%s,str);
Unlike scanf() even if the string contains white space characters entire string is displayed
Using puts() function :
puts() function is useful to print/display string on the screen. The general syntax is

puts(st
r)
Where str is any valid string variable name.

1. Program to read and print a line of text


void main( )
{
chat str[20];
printf(enter line of text);
gets(str);
printf(line of text what you entered is %s ,str);
}

Student practice the following program:

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.

strrev(): This function reverses the string. The general syntax is


strrev(str1)
Student practice the following program:

1. Program to find length of the string using strlen() function


Void main()
{
char str[20];
int i;
printf(enter a string);
gets(str);
l=strlen(str);
printf(length of the string is %d,l);
}

SESSION PLAN 17: Operation on Strings


At the end of this session, students will be able to:
1. Implement real time problems to handle text data.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
05 Sub topic(lecture):
Explanation about strings functions
strcmp() with the program to compare
two strings.
20 Practice session:
Studetns will write a program to check
the given string is palindrome or not.
10 Sub topic(lecture):
Explanation about two dimensional
strings with the program to read and
print n strings
05 Sub topic(lecture):
Explanation about strings functions
strcpy() with the program to compare
two strings.
20 Practice session:
Students will practice a program to copy
one string in to another string by using
string function strcpy()
10 Sub topic(lecture):
Execution about string function strcat()
with the program to join one string at the
end of another string
20 Practice session:
Students will write a program to insert a
word before a given word in the text.
05 Conclusion .

Explanation of the following program:


1. Program to compare two strings
void main()
{
char str1[20],str2[20];
int n;
printf(enter first string);
gets(str1);
printf(enter second string);
gets(str2);
n=strcmp(str1,str2);
if(n==0)
printf(two strings are equal);
else
printf(two strings are not equal);
}
Student practice the following program:

2. program to check the given string is palindrome or not


void main()
{
char str1[20],str2[20];
int n;
printf(enter first string);
gets(str1);
strcpy(str2,strrev(str1));
n=strcmp(str1,str2);
if(n==0)
printf(Given string is a palindrome);
else
printf(Given string is not a palindrome);
}
Explanation of two dimensional strings with the following program:

Two dimensional strings:


Strings what we declared above in that we can store only one string at a time. when we want to store
multiple strings we should declare that variable as two dimensional string. The declaration syntax is
as follows:

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]);
}
}

Explanation of the strcpy() function:

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.

Student practice the following program:


1. Program to copy one string into another string by using strcpy().
void main()
{
char str1[20],str2[20];
int n;
printf(enter a string);
gets(str1);
strcpy(str2,str1);
printf(after copying the string is %s,str2);
}
Explanation of the strcat() function:
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.

Student practice the following program:

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);
}

SESSION PLAN 18:


At the end of this session, on Practice session on arrays, Students will be able to:
1. Solve computer applications using list data.
2. Think in logical way to solve real-time applications using recursion.

Time Topic Blooms Blooms Blooms


in Taxonom Taxonom Taxonom
Minut y Level-1 y Level-2 y Level-3
es
05 Recap / Introduction:
20 Draw the flow chart and algorithm that accepts an
integer value from 0 to 999. Display the value of
the number in words. That is, if the user enters 753
then print seven hundred fifty three.
25 Write a program that accepts an integer value from
0 to 999. Display the value of the number red in
words. That is, if the user enters 753 then print
seven hundred fifty three.
20 Draw the flow chart and algorithm. Write a
program to read a name and then display it in
abrvated form. That is, if the user enters All India
Radio then it should be displayed as A.I.R
25 Write a program to read a name and then display it
in abrvated form. That is, if the user enters All
India Radio then it should be displayed as A.I.R
05 Conclusion & Summary
Abbrevation program:

#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();
}

SESSION PLAN 19: Multi-dimensional arrays


At the end of this session, students will be able to:
1. Handle multi-dimensional data in solving problems.
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Introduction types of arrays
10 Sub topic(lecture):
Explanation about two dimensional
arrays with the program to read and print
values of an m*n matrices
15 Practice session:
Ask students to write a program to
perform addition of two matrices
10 Sub topic(lecture):
Explanation about two dimensional
arrays with the program to find transpose
of two matrices.
10 Practice session:
Ask students to write a program to find
transpose of a matrix.
10 Sub topic(lecture):
Explanation of matrix multiplication
15 Sub topic(lecture)
Student will Write a program for matrix
multiplication
20 Practice session:
Students will execute matrix
multiplication routine
05 Conclusion on two dimensional arrays
Introduction:
Two-dimensional array is defined as a set of one dimensional arrays each of same size. Two
dimensional array is declared in the same manner as one-dimensional arrays. It will require two pairs of
square brackets.Syntax for declaring two dimensional arrays is

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:


1.
2. 1. program to read and print values of an m*n matrices.
void main()
{
int a[10][10],r,c,i,j;
printf(enter number of rows and columns);
scanf(%d%d,&r,&c);
printf(enter values for the matrix);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(%d,&a[i][j]);
}
}
printf(values in the matrix are);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(\t %d,a[i][j]);
}
printf(\n);
}
}

Student practice the following program:

3. 2. program to perform addition of two matrices


void main()
{
int a[10][10],b[10][10],c[10][10],r1,c1,r2,c2,i,j;
printf(enter number of rows and columns for a matrix);
scanf(%d%d,&r1,&c1);
printf(enter number of rows and columns for b matrix);
scanf(%d%d,&r2,&c2);
if(r1==r2 && c1==c2)
{
printf(enter values for a matrix);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(%d,&a[i][j]);
}
}
printf(enter values for b matrix);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf(%d,&b[i][j]);
}
}
printf(Resultant matrix is);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(\t %d,c[i][j]);
}
printf(\n);
}
}
else
printf(addition is not possible);
}

Explanation of the following program:

4. program to find transpose of two matrices.


void main()
{
int a[10][10],b[10][10]r,c,i,j;
printf(enter number of rows and columns);
scanf(%d%d,&r,&c);
printf(enter values for the matrix);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(%d,&a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
b[i][j]=a[j][i];
}
}

printf(Transpose of matrix is);


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(\t %d,b[i][j]);
}
printf(\n);
}
}

Explanation of the following program, and student practice the same program:

1. program to perform matrix multiplication.


void main()
{
int a[10][10],b[10][10],c[10][10],r1,c1,r2,c2,i,j,k;
printf(enter number of rows and columns for a matrix);
scanf(%d%d,&r1,&c1);
printf(enter number of rows and columns for b matrix);
scanf(%d%d,&r2,&c2);
if(c1==r2)
{
printf(enter values for a matrix);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(%d,&a[i][j]);
}
}
printf(enter values for b matrix);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf(%d,&b[i][j]);
}
}
for(i=0;i<c2;i++)
{
for(j=0;j<r1;j++)
{
C[i][j]=0;
For(k=0;k<c1;k++)
{
C[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(Resultant matrix is);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(\t %d,c[i][j]);
}
printf(\n);
}
}
else
printf(multiplication is not possible);
}

SESSION PLAN 20:


At the end of this session, on Practice session on Multi-dimensional arrays, Students will be able to:
1. Solve computer applications using multi-dimensional data.
2. Think in logical way to solve real-time applications using recursion.

Time Topic Blooms Blooms Blooms


in Taxonom Taxonom Taxonom
Minut y Level-1 y Level-2 y Level-3
es
05 Recap / Introduction:
20 In a small company there are 5 salesmens. Each
sales man is supposed to sell three products. Draw
flow chart & algorithm to print
a. The total sales by each salesman.
b. Total sales of each item.
25 In a small company there are 5 salesmens. Each
sales man is supposed to sell three products. Write
a program using 2D array to print
a. The total sales by each salesman.
Total sales of each item.

20 Draw flow chart & algorithm to read 2D array


marks which stores marks of five students in 3
subjects and also display highest marks in each
subject.
25 Write a program to read 2D array marks which
stores marks of five students in 3 subjects and also
display highest marks in each subject.
05 Conclusion & Summary

/*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();
}
}

/*student marks report*/

#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);
}
}

SESSION PLAN 21: Linear Search & Binary search


At the end of this session, Students will be able to:
1. How to search an element using linear search and Binary search?
2. Analyze the performance of linear search?

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
10 Introduction to searching and
lecture on linear search.
10 Learner will Search a given value
from the list .
10 Ask Students to draw flowchart for
Linear Search Routine.
20 Students will write & execute
Linear Search Routine
10 Explain Concepts of binary search
15 Searching the given value using
binary search
10 Ask Students to draw flow chart for
Binary Search Routine
15 Students will write & execute
Binary Search Routine
05 Conclusion & Summary
#include<stdio.h>
void main()
{
int key,a[30],i,n;
clrscr();
printf("enter number of values\n:");
scanf("%d",&n);

printf("enter %d values\n:",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("enter value to be searched\n:");


scanf("%d",&key);

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:

Search 35 in the following values using binary search

12,24,27,32,34,35,48,69

SESSION PLAN 22:


Bubble sort
At the end of this session, Students will be able to:
1. Sort data using bubble sort.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
20 Introduction to sorting and
explanation of bubble sort
procedure
20 Sorting of given numbers
10 Ask student to draw flowchart for
bubble sort Routine
20 Ask students to write bubble sort
Routine
20 Students will execute Bubble sort
Routine
05 Conclusion & Summary
Large Elements are sorted like rabbit & small elements towards the end move
like turtle towards beginning
void bubble(int a[ ],int n)
{
int i,j,temp;
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(a[j+1]<a[j])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
Example:6,5,3,1,8,7,2,4
6 5 3 1 8 7 2 4
1.Pass 5 3 1 6 7 2 4 8
2.Pass 3 1 5 6 2 4 7 8
3.Pass 1 3 5 2 4 6 7 8
4.Pass 1 3 2 4 5 6 7 8
5.Pass 1 2 3 4 5 6 7 8

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
20 Explain Quick sort procedure
10 Ask students to draw flow chart
for quick sort Routine.
20 Ask students to write quick sort
Routine
20 Students will practice quick sort
with the given example
20 Students will execute Quick sort
recursive Routine
05 Conclusion & Summary
As its name implies, quicksort is the fastest known sorting algorithm in practice.
Its average running time is O(N log N). It has O(N2) worst-case performance,
quicksort is a divide-and-conquer recursive algorithm. The basic algorithm to
sort an array S consists of the following four easy steps:

1. If the number of elements in S is 0 or 1, then return.

2. Pick any element v in S. This is called the pivot.

3. Partition S - {v} (the remaining elements in S) into two disjoint groups:

S1 ={x S ={v}| x v}, and S2 = {x S -{v}| x v}.


4. Return { quicksort(S1) followed by v followed by quicksort(S2)}.
The Steps of Quick sort illustrated by example
#include<stdio.h>
#include<conio.h>
void quicksort(int[],int);
void qsort(int[],int,int);
int median3(int[],int,int);
void main()
{
int a[50],n,i;
clrscr();
printf("enter size of array\n");
scanf("%d",&n);
printf("enter values\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Sorted o/p:\n");
quicksort(a,n);
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
void quicksort(int a[50],int n)
{
qsort(a,0,n-1);
}
int median3(int a[50],int left,int right)
{
int temp;
int center = (left+right)/2;
if(a[center]>a[right])
{
temp=a[right];
a[right]=a[center];
a[center]=temp;
}

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]);
}

void qsort(int a[50], int left, int right)


{
int i,j,temp;
int pivot;
if(left<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

1. The first element as the pivot.


2. A safe course is merely to choose the pivot randomly.
3. Median-of-Three Partitioning: The median of a group of N numbers is
the th largest number. The best choice of pivot would be the
median of the array. A good estimate can be obtained by picking three
elements randomly and using the median of these three as pivot. Using
median-of-three partitioning clearly eliminates the bad case for sorted
input (the partitions become equal in this case) and actually reduces the
running time of quicksort by about 5 percent.
SESSION PLAN :24
At the end of this session, Students will be able to:
1. Write expressions using pointers.
2. Perform arithmetic operations on pointers.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
10 Sub task-1(Lecture):
What are pointers and pointer
operators with examples?
15 Ask student to draw flow chart for
the below problem.
20 Practice session-1:
Students will execute a program to
access and display values of
different types of variables using
pointers.
10 Sub task-2(Lecture):
Explanation about how to use
pointers in expressions and possible
arithmetic operations on pointers.
15 Ask student to draw flow chart for
the below problem
20 Practice session-2:
We will ask students to write a
program to perform arithmetic
calculations using pointers.
05 Conclusion on pointers
Introduction to Pointers

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.

Benefit of using pointers

Pointers are more efficient in handling Array and Structure.


Pointer allows references to function and thereby helps in passing of function as arguments to
other function.

It reduces length and the program execution time.

It allows C to support dynamic memory management.


Concept of Pointer

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.

Declaring a pointer variable

General syntax of pointer declaration is,

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

Pointer variable always points to same type of data.

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;

printf("%d",*p); //this will print the value of a.

printf("%d",*&a); //this will also print the value of a.

printf("%u",&a); //this will print the address of a.

printf("%u",p); //this will also print the address of a.

printf("%u",&p); //this will also print the address of p.

Code for Program to illustrate the use of pointers in arithmetic


operations in C Programming
1. main()
2. {
3. int a, b, *p1, *p2, x, y, z;
4. a = 12;
5. b = 4;
6. p1 = &a;
7. p2 = &b;
8. x = *p1 * *p2 - 6;
9. y = 4* - *p2 / *p1 + 10;
10. printf("Address of a = %u\n", p1);
11. printf("Address of b = %u\n", p2);
12. printf("\n");
13. printf("a = %d, b = %d\n", a, b);
14. printf("x = %d, y = %d\n", x, y);
15. *p2 = *p2 + 3;
16. *p1 = *p2 - 5;
17. z = *p1 * *p2 - 6;
18. printf("\na = %d, b = %d,", a, b);
19. printf(" z = %d\n", z);
20. }

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

Declaration of a pointer variable:

- Syntax:- data_type *pointer_variable_name;


In the above syntax pointer_variable_name is an indentifier.

In the above declaration operator * is called as indirect address operator or dereferencing


operator. But usually we read as value at

- Examples to declare a pointer variable is


int *iptr;
char *cptr;
float *fptr;
void *vptr;
- In the above examples iptr is called integer pointer in which we can store address of any other
integer variable.
- In the above examples cptr is called character pointer in which we can store address of any
other character variable.
- In the above examples fptr is called float pointer in which we can store address of any other
float variable.
- In the above examples vptr is called void pointer or generic pointer in which we can store
address of any other variable of any type either built-in type or user defined type.
Like above pointers we have another pointers in C. they are

- 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;

/* take the address of var */


ptr = &var;

/* take the address of ptr using address of operator & */


pptr = &ptr;

/* take the value using pptr */


printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);

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.

Void Pointer Basics :


1. In C General Purpose Pointer is called as void Pointer.
2. It does not have any data type associated with it

3. It can store address of any type of variable

4. A void pointer is a C convention for a raw address.

5. The compiler has no idea what type of object a void Pointer really points to ?

Declaration of Void Pointer :


void * pointer_name;

Void Pointer Example :


void *ptr; // ptr is declared as Void pointer

char cnum;
int inum;
float fnum;

ptr = &cnum; // ptr has address of character data


ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data
Explanation :
void *ptr;
1. Void pointer declaration is shown above.
2. We have declared 3 variables of integer,character and float type.

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.

6. It is capable of storing address of any data type

Accessing value of a variable through 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;

printf("\ni value =%d, i address = %u",*iptr,iptr);


printf("\ni value =%d, i address = %u",i,&i);

printf("\nc value =%c, c address = %u",*cptr,cptr);


printf("\nc value =%c, c address = %u",c,&c);

printf("\nf value =%f, f address = %u",*fptr,fptr);


printf("\nf value =%f, f address = %u",f,&f);
}
Cw-program-2: analyze the output of the following simple program and why?

#include<stdio.h>
void main()
{
int *iptr=&i,i=90;
char c,*cptr = &c,c='a';
float f=23.34, *fptr = &f;

printf("\ni value =%d, i address = %u",*iptr,iptr);


printf("\ni value =%d, i address = %u",i,&i);

printf("\nc value =%c, c address = %u",*cptr,cptr);


printf("\nc value =%c, c address = %u",c,&c);

printf("\nf value =%f, f address = %u",*fptr,fptr);


printf("\nf value =%f, f address = %u",f,&f);
}
Pointer expressions:
- Like normal variables, we can use pointer variables also in expressions which are called as
pointer expression.
- If we considered p1 and p2 are two pointer variables and also assume they are initialized with
proper addresses of two variables then the following statements are valid statements.
1. A = *p1+*p2 ;
2. A = *p1* *p2; Note:- gap is mandatory between product operator(*) and pointer
operator(*) otherwise it considers as multipointer operator
3. A = *p1/ *p2; Note:- gap is mandatory between division operator(/) and pointer
operator(*) otherwise it considers as comment paragraph
operator(/* */).
4. A = *p-*p2;
5. A = *p +x; A=*p*x; A=*p/x; A = *p-x;
6. A= *p+5; A = *p*3; A=*p/3; A = *p - 8;
Example program2:

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;

9. printf("\n sum of x,y is : %d",*p1+*p2);


10. printf("\n difference of x,y is : %d",*p1-*p2);
11. printf("\n product of x,y is : %d",*p1 * *p2);
12. printf("\n division of x,y is : %d ",*p1 / *p2);
13. printf("\n reminder of x,y is : %d ",*p1 % *p2);
14.
15. printf("\n %u",p1+p2); // Error
16. printf("\n %u",p1-p2); // Error
17. printf("\n %u",p1 * p2); // Error
18. printf("\n %u ",p1 / p2); // rrror
19. printf("\n %u ",p1 % p2); // Error
20.}
Pointer arithmetic operations:

- The following arithmetic operations can b performed on pointers.


1. An integer constant or variable can be added to a pointer or subtracted from a pointer,
Example:
int x,*p1,i;
p1 = &x;
p1 = p1+3; valid statement.
p1 = p1+i; valid statement.
P1 = p1 - 5; valid statement.
P1 = p1 - i; valid statement.
But adding of two pointers, subtracting of two pointers, product of two pointers, division
of two pointers are not allowed in C programming.
Subtraction of two pointers is allowed whenever they are pointing the same array.
Example:
p1+p2; p1-p2; p1*p2; and p1/p2; are invalid in C programming.
0 1 2 3 4 5 6 7

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;

then p1>p2; p1<p2; p1<=p2; p1>=p2; p1==p2; p1!=p2; are allowed.

Pointer and Arrays

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.

Suppose we declare an array arr,

int arr[5]={ 1, 2, 3, 4, 5 };

Assuming that the base address of arr is 1000 and each integer requires two byte, the five element
will be stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the element,
arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.

arr is equal to &arr[0] // by default

We can declare a pointer of type int to point to the array arr.

int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.

Now we can access every element of array arr using p++ to move from one element to another.

NOTE : You cannot decrement a pointer once incremented. p-- won't work.

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.

Reading and printing an array of data using pointers:-

- 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.}

Pointer to Multidimensional Array

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.

*(*(ptr + i) + j) is same as a[i][j]

Pointer and Character strings

Pointer can also be used to create strings. Pointer variables of char type are treated as string.

char *str = "Hello";

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.

Program to sort N strings using an array of pointers

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main() {
char *str[5], *temp;
int i, j, n;

printf("\nHow many names do you want to have?");


scanf("%d", &n);

for (i = 0; i < n; i++) {


printf("\nEnter the name %d: ", i);
flushall();
gets(str[i]);
}

for (i = 0; i < n; i++) {


for (j = 0; j < n - 1; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
}
}
}

flushall();

printf("\nSorted List : ");


for (i = 0; i < n; i++)
puts(str[i]);

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

Sorted List : pra pri prq prt

SESSION PLAN 26: Pointers to functions


At the end of this session, students will be able to:
1. Use pointers in solving problems using C language.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
10 Explanation about pointer to strings with
the program to read and print string
using pointers
10 Ask students to write a program that
replaces two or more consecutive blanks
in a string by a single blank.
10 Discussion on the above program .
10 Ask learner to execute the program that
replaces two or more consecutive blanks
in a string by a single blank.
15 Explanation about pointer to function
with a program to call a user defined
function int Armstrong(int )
10 Students will execute the above program
15 Ask students to write a program to check
whether the given positive number is a
strong number or not.
10 Students will execute the above program
05 Conclusion
Pointer to functions

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.

int sum(int, int);


int (*s)(int, int);
s=sum;

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);

Example of Pointer to Function

#include< stdio.h>
#include< conio.h>

int sum(int x, int y)


{
return x+y;
}

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;
}

char *process(char *text) {


int length, c, d;
char *start;

c = d = 0;

length = strlen(text);

start = (char*)malloc(length+1);

if (start == NULL)
exit(EXIT_FAILURE);

while (*(text+c) != '\0') {


if (*(text+c) == ' ') {
int temp = c + 1;
if (*(text+temp) != '\0') {
while (*(text+temp) == ' ' && *(text+temp) != '\0') {
if (*(text+temp) == ' ') {
c++;
}
temp++;
}
}
}
*(start+d) = *(text+c);
c++;
d++;
}
*(start+d)= '\0';

return start;
}

Write a c program to check whether a number is strong or not

#include<stdio.h>
void Strong(int *);
int main(){
int num,a;

printf("Enter a number: ");


scanf("%d",&num);
a=&num;
strong(a)
getch();
}
void strong(int *p)
{
int temp=*p,num=*p,i,f,sum=0,r;
while(num){
i=1,f=1;
r=num%10;

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);
}

Complicated Function Pointer Example

You will find a lot of complex function pointer examples around, lets see one such example and try to
understand it.

void *(*foo) (int*) ;

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.

SESSION PLAN 27: pointers to pointers & void pointers


At the end of this session, students will be able to:
1. Implement functions with pointers.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
15 Explanation about pointer function using
a program to call int* sum(int,int)
function to find sum of given two
numbers.
10 Students will execute the above program.
15 Ask students to write a main function
that calls int* factorial(int) which
calculates factorial of a given positive
number.
10 Students will execute the above program
10 Explanation about pointer to pointer
with the program to perform arithmetic
calculations by using pointer to pointer
10 Ask students to write a program to
perform arithmetic calculations by using
pointer to pointer
10 Explanation about void pointer with the
program to read and write values into
any type of variable using void pointer
10 Ask students to write a program to read
and write values into any type of
variable using void pointer
05 Conclusion
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;

/* take the address of var */


ptr = &var;

/* take the address of ptr using address of operator & */


pptr = &ptr;

/* take the value using pptr */


printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);

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
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.

Void Pointer Basics :


6. In C General Purpose Pointer is called as void Pointer.
7. It does not have any data type associated with it

8. It can store address of any type of variable

9. A void pointer is a C convention for a raw address.

10. The compiler has no idea what type of object a void Pointer really points to ?

Declaration of Void Pointer :


void * pointer_name;

Void Pointer Example :


void *ptr; // ptr is declared as Void pointer

char cnum;
int inum;
float fnum;

ptr = &cnum; // ptr has address of character data


ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data

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.

12. It is capable of storing address of any data type

SESSION PLAN 28: Call by value and call by reference


At the end of this session, students will be able to:
1. Use functions effectively in writing programs.
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
10 Explanation about call by value
with the program to swap values of two
variables by using call by value
procedure.
10 Ask Studetns to write a program for
swapping of two variables .
10 Explanation about call by reference with
the program to swap values of two
variables by using call by reference.
10 Students will write a program to swap
values of two variables by using call by
reference concept.
20 Explanation on call by value and call by
reference.
20 Draw flowchart for swapping 2 values
using both call by value & call by
reference.
20 Students will practice program to swap
2 values using both call-by-value and
call-by-reference.
05 Conclusion on call by value and call by
reference concept.
Types of Function calls in C

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);


int main()
{
int x = 10;
calc(x);
printf("%d", x);
}

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);


int main()
{
int x = 10;
x = calc(x);
printf("%d", x);
}

int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20

Program to swap values of two variables by using call by value concept

#include<stdio.h>
#include<conio.h>

int swap(int , int); // Declaration of function

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();
}

int swap( int x, int y ) // x and y are formal parameters


{
int t ;
t=x;
x=y;
y=t;
printf ( "\nx = %d y = %d", x, y ) ;
}

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.

void calc(int *p);


int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}

void calc(int *p)


{
*p = *p + 10;
}

Output : 20

C Program to swap two numbers using pointers and function.

#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

Types of Function calls in C

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);


int main()
{
int x = 10;
calc(x);
printf("%d", x);
}

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);


int main()
{
int x = 10;
x = calc(x);
printf("%d", x);
}

int calc(int x)
{
x = x + 10 ;
return x;
}
Output : 20

Program to swap values of two variables by using call by value concept

#include<stdio.h>
#include<conio.h>

int swap(int , int); // Declaration of function

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();
}

int swap( int x, int y ) // x and y are formal parameters


{
int t ;
t=x;
x=y;
y=t;
printf ( "\nx = %d y = %d", x, y ) ;
}

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.

void calc(int *p);


int main()
{
int x = 10;
calc(&x); // passing address of x as argument
printf("%d", x);
}

void calc(int *p)


{
*p = *p + 10;
}

Output : 20

C Program to swap two numbers using pointers and function.


#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

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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3

05 Introduction about dynamic memory


allocation

10 Explain sizeof() ,malloc(),


calloc(),realloc(),and free()

10 Ask students to write a program to read


and print list of values

10 Explanation about memory allocation


functions with the program to find sum
of the list values .

10 Ask students to write a program to find


the sum of the list of values , allocating
the memory by using memory allocation
functions.

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.

Students will write the following


program .Create a structure for 3
10 students with 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.

As the name indicates, memory can be allocated dynamically whenever required.

Dynamic Memory Allocation is the phenomenon of allocationof memory during run time. Allocated
memory can be released during runtime.

Memory Management Functions with DMA

C library has the following built-in-functions to manage dynamic memory allocation.

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:

ptr_variable=(cast type) malloc(size of block);

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.

Example: ptr=(int *)malloc(10*sizeof(int));

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.

If sufficient memory is not available malloc() returns a null pointer.

Explination of the following program:

1. program to read and print n values using memory allocation function.


void main()

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);

Example: free (ptr);


Where ptr is a pointer which points to the block which is to be released/de-allocated.
It is not the pointer that is being released but what it points to.

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 .

The general form of calloc() function is

ptr_variable=(cast type) calloc(no of blocks, size of block);

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().

The general form of realloc() function is:

ptr_variable=(cast type) realloc(old_ptr, new size of block);

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.

Explanation and practice of the following program.


2. Program calculate sum of the list of values using memory allocation function.
void main()
{
int *p,n,i,sum=0;
printf(enter n value);
scanf(%d,&n);
p=(int)malloc(n*sizeof(2));
printf(enter list of values);
for(i=0;i<n;i++)
{
scanf(%d, (p+i));
}
for(i=0;i<n;i++)
{
sum=sum+*(p+i);
}
printf(sum=%d,sum);
}

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:

complex : real part, imaginary part

fraction : numerator, denominator

date : day, month, year

student : roll number, name, age, marks in three subjects

address : name, door number, street, locality, city, pin code

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.

STRUCTURE TYPE DECLARATION

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

data type field1;

data type field2;

.
.;

data type fieldn;

}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;
}

SESSION PLAN 30:


At the end of this class on Introduction to structures students will be able to:
1. Array of structure variables
2. Applying the concepts of array of structure variables to sort the list of records.
3. Structures and functions.
Blooms Blooms Blooms
Time Topic Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3

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);
}

SESSION PLAN 31:


At the end of this class hour on structure my students will be able to:
1. Implement a LIFO Data Structure STACK.

Blooms Blooms Blooms


Time Topic Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3

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(LIFO) : Array Implementation

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.

* Push(x) Inserting an element into the stack.


* Pop()- deleting an element from the stack.

Stack Applications:

1. To implement the function calls/Recursion


2. To convert the given infix expression into postfix exp
3. To evaluate the postfix expressions.
4. To check whether the symbols are balanced or not.
5. DFS

SESSION PLAN 32: Implementation of stacks using arrays


At the end of this session, Students will be able to:
1. Implement stacks using arrays?
2. Identify uses and applications of stacks?

3.Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
10 Ask students to drae flowchart for
push() and pop() functions
20 Ask students to write push() and
pop() functions.
20 Students will execute the stack
program.
10 What are linear queues?
15 Basic operations of queues?
15 Explanation of Insert() , delete()
routines with suitable examples.
05 Conclusion & Summary
Implementation of stack using arrays:
#include<stdio.h>
#define max 5
typedef struct stack stack;
struct stack
{
int a[50];
int tos;
};
void push(stack*,int);
int pop(stack*);
void main()
{
int x,n;
stack *s;
s->tos=-1;
printf("enter your choice :\n1.push\n2.pop\n3.exit\n");
scanf("%d",&n);
while(n!=3)
{
switch(n)
{
case 1:
printf("enter a value\n");
scanf("%d",&x);
push(s,x);
break;
case 2:
x=pop(s);
if(x!=-1)
printf("popped value is %d\n",x);
break;
}
printf("enter your choice:\n1.push\n2.pop\n3.exit\n");
scanf("%d",&n);

}
}

void push(stack *s,int x)


{
if(s->tos==max-1)
{
printf("stack full\n");
return;
}

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(FIFO)-Linear Data Structure :


The information in queue is processed in the same order as it was received that is on a first-in ,first-
out(FIFO) or a first come,first served(FCFS) basis.

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;
};

typedef struct queue* queue;


queue q;
In main() function do the following Initializations:
Rear=front=-1;
q=(queue) malloc(sizeof(struct queue);
Types of Queues:

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.

SESSION PLAN 33: Implementation of queues using arrays


At the end of this session, Students will be able to:
1. Implement Queues using arrays?

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
20 Ask students to draw flowchart for
Insert() & delete() routines
20 Ask students to write Insert() ,
delete() routines
20 Students will execute Insert() ,
delete() routines?
5 Discuss applications of queues..
05 What is Circular queue ?
20 Explain Operations on Circular
queue?
05 Conclusion & Summary
Implementation of Linear Queue:

Void enqueue( int x)


{

If(qrear==max)
{
Printf(Q FULL);
Return;
}
qa[++qrear] =x;

if(qfront==-1 || qfront == qrear+1)


qfront=0;
}
Int dequeue()
{

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)

SESSION PLAN 34: Implementation of circular queue


At the end of this session, Students will be able to:
1. Implement circular queues using arrays.
2. Convert an arithmetic expression from one form to other form?
3 . Convert an infix expression to postfix expression using a stack data structure.
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
15 Ask student to draw flow chart for
circular queue.
10 Students will write Circular queue
routines.
15 Students will execute Circular
queue operations.
15 Converting an arithmetic
expression from infix to postfix and
postfix.
10 Ask student to draw flow chart for
conversion.

25 Ask student to Convert the given


infix expression to postfix
expression using stacks
05 Conclusion & Summary
Implementation of Circular Queue using Arrays:

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.

Items can inserted and deleted from a queue in O(1) time.

#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);
}
}

SESSION PLAN: 35 Converting an infix expression to postfix expression


At the end of this session, Students will be able to:
1. Write and execute infix expression to postfix expression conversion.
2. Evaluate an arithmetic Expression using stack
.Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
20 Ask students to write a program
to convert the given infix
expression to postfix
expression.
20 Students will practice / Trace
the above program with an
example.
15 Lecture on how to evaluate an
arithmetic Expression using
stack.
10 Ask students to draw flowchart
for arithmetic Expression
evaluation using stack.
15 Ask students to write function
to evaluate an arithmetic
Expression using stack.
10 Students will execute the
function
05 Summary
Converting an infix expression to postfix expression:

I/p char STACK Contents Postfix Expression

(
_

(
_
(
(

(
( _

(
(
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.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
15 Explain linked lists Vs Arrays.
15 Define node structure
10 Explain create() function
15 Explain Insert() & find() functions.
15 Ask students to draw flowchart for
create(), insert() and find()
routines?
20 Ask students to write create(),
insert() and find() routines?
05 Summary
Single Linked List:

#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;
}

SESSION PLAN 37: Implementing operations on SLL


At the end of this session, Students will be able to:
1. Implement linear data structures like linked lists.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
15 Explain deletion & display
operations on SLL.
25 Students will execute the SLL
operations
20 Draw flow chart for DLL
operations
15 Explain DLL along with create (),
Insert() & find() functions.
15 Ask students to write insert() and
find() routines?
05 Summary
SLL Deletion and display:
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");
}

SESSION PLAN 38: Implementing operations on DLL


At the end of this session, Students will be able to:
1. To write delete() operation on DLL.
2. Implement Circular Linked List
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
10 Explain deletion & display
operations on DLL.
15 Ask students to write delet() and
display() routines?
20 Students will practice execution of
DLL operations
15 Explain circular linked list
30 Ask students to write operations on
CLL.
05 Summary
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");

}
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;

newnode=(list) malloc(sizeof(struct node));


newnode->data=x;
newnode->next=l->next;
l->next=newnode;
} //end of insert

list deletenode(list l)
{
l=l->next;
return l;
}

position find(list l, int x)


{
position p;
p=l->next;
while((p!=l) && (p->data!=x))
p=p->next;
return(p);
}

position findprev(list l, int x)


{
position p;
p=l->next;
while((p!=l) && (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=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;
}
}

SESSION PLAN 39: Implementing stacks using LL


At the end of this session, Students will be able to:
1. Implement stacks using SLL.
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap
15 Explain push() operation
10 Ask learner to draw flow chart for
stack operations.
15 Write push() using SLL
10 Students will Execute the push()
function
15 Explain pop() & display()
operations
15 Ask students to write pop() using
SLL
10 Students will execute the pop() and
display() functions
05 Summary
Implementation of stacks using LL:

// stack push is insert at begin


// stack pop is delete at begin
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
typedef struct node* list;
list tos=NULL;
void push(int);
int pop();

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);
}

SESSION PLAN 40: Implementing Queues using LL


At the end of this session, Students will be able to:
1. Implement queues using linked list.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
15 Explain insert() operation using
SLL
10 Ask learner to draw flow chart for
Insert()
10 We will ask students to write
insert() using SLL
10 Explain delete() operation using
SLL
10 Students will execute the insert()
function
10 Ask learner to draw flow chart for
Delete()
15 Ask students to write delete ()
using SLL
10 Students will practice Execution of
delete () function
05 Summary
Implementation of Queues using LL:

/ /queue insert is insert at end


// queue delete is delete at begin
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
typedef struct node* list;
list front=NULL,rear=NULL;
void insert(int);
int delet();

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);
}

SESSION PLAN 41:Introduction to Trees


At the end of this session, Students will be able to:
1. Create BST
Time in Topic Blooms Blooms Blooms
Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
15 Introduction to trees , tree def.
15 Binary tree properties
10 Explain creating binary tree with
the given values.
15 Explain BST
15 Creating BST
20 Students will practice constructing
BST with the given values.
05 Summary
TREES

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

*In a tree with N nodes ,the no of edges will be N-1.


*Root is a node without a parent.
*Leaves: Nodes without children are known as leaves.
*Siblings: Nodes with the same parent.
*Path : A path from node n1 to nk is defined as a sequence of nodes n1, n2, nk ,such that ni is the
parent of ni+1 for, 1i k.
*Path Length : It is the no of edges on the path .If you have k nodes in the
path,path length will be k-1.
*Depth:- Depth of a node is the path length from the root to the given node.
*Depth of the tree is the maximum path length that is existing in the tree.
*Depth of the root is zero.
*Height :- Height of a node is the maximum path length from a leaf to the given node.
Height of a tree is the maximum path length that is existing in the tree.
*Height of the leaf is Zero.
*The Height of the tree is equal to the depth of the tree.
*Ancestors : All nodes in the path from the root to the parent of a given node.
*Descendants :- All the children ,grand children etc are called as descendants
of the node.

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.

*In a binary tree,with n nodes there exists (n+1) NULL Links.

BINARY TREE DIAGRAM WITH NODE STRUCTURE:

5
4

4 8
8 5

3 5 7 9
2 0 7 2

2 7 7
8 0 9

2
9

SESSION PLAN 42: Implementing insert and find operations on BST


At the end of this session, Students will be able to:
1. To write programs using tree data structure.

Time in Topic Blooms Blooms Blooms


Minutes Taxonomy Taxonomy Taxonomy
Level-1 Level-2 Level-3
05 Recap / Introduction
15 Explain Insert() of BST.
15 Ask students to write Insert() of
BST
10 Students will practice execution of
insert() function.
05 Summary
05 Recap / Introduction
15 Explain Delete() of BST.
15 Ask students to write Delete () of
BST
10 Students will practice execution of
Delete () function.
05 Summary

BINARY SEARCH TREE:


struct treenode
{
int data;
struct treenode *left;
struct treenode *right;
};
typedef struct treenode *tnode;
tnode makeempty( tnode t )
{
if( t != NULL )
{
makeempty( t->left );
makeempty( t->right );
free( t );
}
return NULL;
}
tnode find( int x, tnode t )
{
if( t == NULL )
return NULL;
if( x < t->data )
return find( x, t->left );
else
if( x > t->data )
return find( x, t->right );
else
return t;
}
tnode findmin( tnode t )
{
if( t == NULL )
return NULL;
else
if( t->left == NULL )
return t;
else
return findmin( t->left );
}
tnode findmax( tnode t )
{
if( t != NULL )
while( t->right != NULL )
t = t->right;
return t;
}
tnode insert( int x, tnode t )
{
/* 1*/ if( t == NULL )
{
/* Create and return a one-node tree */
/* 2*/ t = malloc( sizeof( struct treenode ) );
/* 3*/ if( t == NULL )
/* 4*/ printf( "Out of space!!!" );
else
{
/* 5*/ t->data = x;
/* 6*/ t->left = t->right = NULL;
}
}
else
/* 7*/ if( x < t->data )
/* 8*/ t->left = insert( x, t->left );
else
/* 9*/ if( x > t->data )
/*10*/ t->right = insert( x, t->right );
/* Else x is in the tree already; we'll do nothing */
//printf("\nlast statement in insert\n");
/*11*/ return t; /* Do not forget this line!! */
}
tnode delete( int x, tnode t )
{
tnode tmpCell;
if( t == NULL )
printf( "data not found" );
else
if( x < t->data ) /* Go left */
t->left = delete( x, t->left );
else
if( x > t->data ) /* Go right */
t->right = delete( x, t->right );
else /* Found data to be deleted */
if( t->left && t->right ) /* two children */
{
/* Replace with smallest in right subtree */
tmpCell = findmin( t->right );
t->data = tmpCell->data;
t->right = delete( t->data, t->right );
}
else /* One or zero children */
{
tmpCell = t;
if( t->left == NULL ) /* Also handles 0 children */
t = t->right;
else if( t->right == NULL )
t = t->left;
free( tmpCell );
}
return t;
}
int retrieve({
return p->data;
}
/* traverse a binary search tree in a LDR (Left-Data-Right) fashion */
void inorder (tnode sr )
{
if ( sr != NULL )
{
inorder ( sr -> left ) ;
/* print the data of the node whose leftchild is NULL or the
path has already been traversed */
printf ( "\t%d", sr -> data ) ;
inorder ( sr -> right ) ;
}
else
return ;
}
main( )
{
tnode t,p;
int i;
int j = 0;
t = makeempty( NULL );
for( i = 0; i < 10; i++, j = ( j + 7 ) % 10 )
t = insert( j, t );
inorder (t);
for( i = 0; i < 10; i += 2 )
{
printf( " \n delete %d from BST tree \n", i );
t = delete( i, t );
}
inorder (t);
for( i = 1; i < 10; i += 2 )
if( ( p = find( i, t ) ) == NULL || retrieve( p ) != i )
printf( "Error at %d\n", i );
for( i = 0; i < 10; i += 2 )
if( ( p = find( i, t ) ) != NULL )
printf( "Error at %d\n", i );
printf( "\nMin is %d, Max is %d\n", retrieve( findmin( t ) ),
retrieve( findmax( t ) ) );
return 0;}
EVALUATION PLAN:

CO-1 CO-2 CO-3 CO-4 CO-5


Title
Test-1 Algorithm, flow
chart, Decision
control &
looping
Statements.
Test-2 Functions, Review 1
recursion,
storage
classes, arrays.
Test-3 Pointers,
stacks and
their
applications,
queues, SLL.
End-Semester TOPICS TOPICS TOPICS DLL, Review 2
Exam Trees, BST,
Files in C.

Wieghtage Of Marks Vs Course Outcomes:

% %
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:

1. Brian W. Kernighan, Dennis M. Ritchie, The C Programming Language: ANSI C


Version, 2/e, Prentice-Hall/Pearson Education-2005.
2. E. Balagurusamy , Programming in ANSI C 4th ed., Tata McGraw-Hill Education, 2008 .
3. R. F. Gilberg, B. A. Forouzan, Data Structures, 2nd Edition, Thomson India Edition-2005.

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.

Supplementary Note / Remarks (if any):

Endorsement Signatures of:


Teaching Associates:

Course Team:

COURSE COORDINATOR
GROUP HEAD

HEAD OF DEPARTMENT
Approved By: DEAN-ACADEMICS (Sign with
Office Seal)

You might also like