PPS Course Fie R18
PPS Course Fie R18
1. Course Description
5
Implement basic operations on binary trees
UNIT – I
Data Structures: Introduction, classification of Data structures, ADT and applications, Overview of
List and its operations.
Linked Lists: Representation in memory, Operations of Singly Linked List: Traversing, Searching,
Insertion, Deletion and Reverse, Doubly Linked List and its Operations, Circular Linked Lists and its
Operations.
UNIT – II
Stacks: Stack ADT and its implementations, Applications of Stacks: Infix to Postfix Conversion and
Postfix evaluation – Corresponding algorithms.
Queues: Queue ADT and its implementations, Types of Queue: Simple Queue, Circular Queue,
Priority Queue; Operations on each type of Queues- Corresponding Algorithms.
UNIT – III
Trees: Basic Tree Terminologies, Representations, types of Binary Trees: Threaded Binary Tree,
Binary Search Tree, AVL Tree and their operations: Insertion Deletion, Traversal.
UNIT – IV
Graphs: Basic Terminologies, Representations, Graph traversal algorithms.
Dictionaries: Dictionary as a linear list and its operations-Insertion, Deletion, Searching, Hash tables,
Hash Functions, Collision Resolution Techniques-Linear Probing, Quadratic Probing, and Double
Hashing.
UNIT V
Text books:
1. Ellis Horowitz, Sartaj Sahni, Fundamentals of Data Structures in C, Second Edition
Universities Press.
2. Thomas H. Cormen Charles E. Leiserson, Introduction to Algorithms, PHI Learning Pvt.
Ltd. Third edition.
Reference books:
1. Algorithms, Data Structures, and Problem Solving with C++”, Illustrated Edition by Mark
Allen Weiss, Addison-Wesley Publishing Company
2. E.Balagurusamy Data Structures Using C, McGraw Hill Education; First edition
COURSE OUTCOMES
3 -
Develop
algorithms,
operations on
queues,
CO3 3 2 3 - 1 - - - - - - 1
stacks and
Linked Lists.
3 -
Demonstrate
the
representation
and traversal
techniques of
CO4 graphs and 3 3 3 - 1 - - - - - - 1
their
applications
3 -
Implement
basic
CO5 operations on 3 3 3 - 1 - - - - - - 1
binary trees.
3 -
LIST OF BOOKS
Text books:
Reference books:
1. Algorithms, Data Structures, and Problem Solving with C++”, Illustrated Edition by
Mark Allen Weiss, Addison-Wesley Publishing Company
2. E.Balagurusamy Data Structures Using C, McGraw Hill Education; First edition
SESSION PLANNER
TIME TABLE
1 2 3 4 6
5
Day/Time 9:10 10.10- 11.10 12.10-1.00 1.00 - 3.00-
2.00-3.00
10.10 11.10 12.10 2.00 4.00
MON AP ODE DS&A ODE ED SPORTS
L
TUE EEP ED AP AP LAB
U
WED DS&A ED M2 EDP
N
THU M2 DS&A ODE IOT LAB
C
FRI ODE AP LIB DS&A LAB
H
SAT ED DS&A AP ODE EDP AP
COORDINATOR: Mr.Naresh
TIME TABLE
TIME TABLE
1 2 3 4 6
5
Day/Time 9:10 10.10- 11.10 12.10-1.00 1.00 - 3.00-
2.00-3.00
10.10 11.10 12.10 2.00 4.00
DS&A DS&A
MON
(A) (B)
L DS&A LAB
TUE (B)
U
DS&A DS&A
WED
(B) N (A)
DS&A DS&A
THU C
(B) (A)
DS&A DS&A LAB
FRI H
(A) (A)
DS&A
SAT
(B)
Student List
S.No R.No Name of the Candidate P02 SEC
BNC
1 19H51A0501 ABRABOINA SOWMYA CSE S03
2 19H51A0502 BEMILIGAY MUKESH CSE S03
3 19H51A0503 BIJJAM GREESHMA REDDY CSE S03
4 19H51A0504 GAJENDRULA HARSHITHA CSE S03
5 19H51A0505 KARAKALA LOKESH REDDY CSE S03
6 19H51A0506 KATEPOGU DARSHITH RAJ CSE S03
7 19H51A0507 RANABOTU RAKSHITH REDDY CSE S03
8 19H51A0508 RANGA SATYA RAJ CSE S03
9 19H51A0509 SHABANA KHAN CSE S03
10 19H51A0510 SHEVAKULA MADHURI CSE S03
11 19H51A0511 DASARI SAHITHI CSE S03
12 19H51A0512 KANUGANTI PAVAN CSE S03
13 19H51A0513 MEGHANA JONNALAGADDA CSE S03
14 19H51A0514 MOHAMMED AYAZ AHMED CSE S03
15 19H51A0515 NAKKALA THOMAS REDDY CSE S03
16 19H51A0516 NOOTHI SAHITHI CSE S03
17 19H51A0517 POOSA JAGADISH CSE S03
18 19H51A0518 SADINENI SREE CSE S03
19 19H51A0519 SILVERI ABHINAV CSE S03
20 19H51A0520 BHEEMIREDDY VISHNU VARSHITHA CSE S03
21 19H51A0521 GONELA KIRAN DEEPAK CSE S03
22 19H51A0522 GUNTAKA KEERTHI CSE S03
23 19H51A0523 K V S S S R H SRI HARSHA CSE S03
24 19H51A0524 POLAPELLY SAHANA CSE S03
25 19H51A0525 VODELA AKSHAY MURARI CSE S03
26 19H51A0526 APPIDI SAI DEEPA CSE S03
27 19H51A0527 AVINASH SHARMA CSE S03
CSE S04
28 19H51A0528 BHAVYA SREE ANUMOLU
CSE S04
29 19H51A0529 CHILIVERI HARSHITHA
CSE S04
30 19H51A0530 GOKA VAMSHI REDDY
CSE S04
31 19H51A0531 KONDAM ROHAN
CSE S04
32 19H51A0532 PRAVEEN CHOWDHARY
CSE S04
33 19H51A0533 YELLARAM ARCHANA
CSE S04
34 19H51A0534 ANOOP KUMAR JHA
CSE S04
35 19H51A0535 DHANUSH KV
CSE S04
36 19H51A0536 GARLAPATI CHANDANA SRI
CSE S04
37 19H51A0537 GOLLAPALLY SREEPRIYA
CSE S04
38 19H51A0538 GONE VINAY
CSE S04
39 19H51A0539 KOTA VENKATA SRI DIVYA
CSE S04
40 19H51A0540 LINGAMPALLI BHARGAVI
CSE S04
41 19H51A0541 PODUTURI SAVAN REDDY
CSE S04
42 19H51A0542 DOSAPATI SAI TEJA
CSE S04
43 19H51A0543 GODALLA SUSHMA
CSE S04
44 19H51A0544 GONELA PRANAY KUMAR
CSE S04
45 19H51A0545 JAKKALA SIVA VENKATA DEEPESH
CSE S04
46 19H51A0546 KOKKONDA RAJANI
CSE S04
47 19H51A0547 KOLUKULA Naga Pavan Madhur
CSE S04
48 19H51A0548 LOKINENI SAHITHI
CSE S04
49 19H51A0549 MADALA NAVYA
CSE S04
50 19H51A0550 PULI SHABARISH
CSE S04
51 19H51A0551 VANGARI BHUVANA SRI
ANKSAPURAM VIJAY VARDHAN CSE S04
52 19H51A0552 REDDY
CSE S04
53 19H51A0553 BELDHE MANIKANTA
CSE S04
54 19H51A0554 BALLA SAI TANUJA
CSE S05
55 19H51A0555 CHITTALURI USHA
CSE S05
56 19H51A0556 GELLU MANASA
CSE S05
57 19H51A0557 GURIJALA GANENDHAR
CSE S05
58 19H51A0558 MANDLA POOJITHA
CSE S05
59 19H51A0559 T MURALI KRISHNA
CSE S05
60 19H51A0560 POTHUGANTI SHIVA SAI
CSE S05
61 19H51A0561 TANVI KALVA
CSE S05
62 19H51A0562 ACHANA SREELATHA
CSE S05
63 19H51A0563 ANKIT TRIPATHY
CSE S05
64 19H51A0564 G KRANTHI KUMAR GOUD
CSE S05
65 19H51A0565 GUDIMETLA SURYA SAI VIKAS REDDY
CSE S05
66 19H51A0566 KARAKAVALASA VINAY BHARGAV
CSE S05
67 19H51A0567 MADHAM MOUNIKA
CSE S05
68 19H51A0568 MOIN ASHIQ
CSE S05
69 19H51A0569 NANGE RAVALIKA
CSE S05
70 19H51A0570 BOLLAMPALLI KARTHIK REDDY
CSE S05
71 19H51A0571 DAGGULA NAVEEN
CSE S05
72 19H51A0572 GADDAM MANIRATNA PRASAD
CSE S05
73 19H51A0573 GODALA VENKATESH
CSE S05
74 19H51A0574 J.SAI RAKESH
CSE S05
75 19H51A0575 MARTALA SHARVAANI
CSE S05
76 19H51A0576 NAGANNAGARI NARSIMHA REDDY
CSE S05
77 19H51A0577 NALLI SHARATH RAJ
CSE S05
78 19H51A0578 SUFYAN AZAR
CSE S05
79 19H51A0579 TEJAVATH RAJU NAYAK
CSE S05
80 19H51A0580 JANGITI SHYAM KUMAR
CSE S05
81 19H51A0581 POTLA SAI PRASAD
CSE S05
82 19H51A0582 BANTU NAVYA
CSE S06
83 19H51A0583 DAPPU SAI PRASANNA
CSE S06
84 19H51A0584 NETHIKOUPULA ARUN KUMAR
CSE S06
85 19H51A0585 PABBU MANIDEEP
CSE S06
86 19H51A0586 SIKHA MADHU KIRAN MAI
CSE S06
87 19H51A0587 JANVI SAINI
CSE S06
88 19H51A0588 ANANTHULA ANNAPURNA
CSE S06
89 19H51A0589 ANDE ARAVIND
CSE S06
90 19H51A0590 BYRU GANGADHAR
CSE S06
91 19H51A0591 IFFAT MARIA
CSE S06
92 19H51A0592 KANDIKATLA DIVYA
CSE S06
93 19H51A0593 MAMDYAL ABHISHEK ANIL
CSE S06
94 19H51A0594 VELURI SRIHARSHA
CSE S06
95 19H51A0595 CHERIVIRALA KARTHIK
CSE S06
96 19H51A0596 CHOKKARAPU AKANKSHA
CSE S06
97 19H51A0597 DUDYALA AJAY KUMAR
CSE S06
98 19H51A0598 MACHIDI SAI NEERAJ
CSE S06
99 19H51A0599 NEELA RAJU
CSE S06
100 19H51A05A0 PADAKANTI SAI CHARAN
CSE S06
101 19H51A05A1 PARINITHA PEMBARTHI
CSE S06
102 19H51A05A2 RACHAKONDA ADITHYA
CSE S06
103 19H51A05A3 RUDRABHATLA TARUN KUAR
CSE S06
104 19H51A05A4 TIRAMBAK THANUJA
CSE S06
105 19H51A05A5 JANASWAMY AISHWARYA
CSE S06
106 19H51A05A6 JASTHI PRANEETH SAI
CSE S06
107 19H51A05A7 KOLLIPARA NIKHIL
CSE S06
108 19H51A05A8 MANCHIPPA ISHITHA
CSE S06
109 19H51A05A9 RATHOD ARCHANA
110 19H51A05B0 SAHISTHA UNNISA CSE S07
PROGRAMME I B.TECH (COMMON TO CIV, MEC, EEE, ECE, CSE & IT)
YEAR I SEM I/II Academic Year 2019-20 BATCH 2019-2023
Course Code A30503 Course Name DSA
ARTICULATION
S.No COs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
1 CO1 3 2 3 - 1 - - - - - - 1 3 -
2 CO2 3 2 3 - 1 - - - - - - 1 3 -
3 CO3 3 2 3 - 1 - - - - - - 1 3 -
4 CO4 3 3 3 - 1 - - - - - - 1 3 -
5 CO5 3 3 3 - 1 - - - - - - 1 3 -
Average 3.0 2.0 3.0 - 1.0 - - - - - - 1.0 3.0 -
Final Attainment (70% of Ext + 30% of Int) 3.00 3.00 3.00 3.00 3.00
COs Attainment PO1 PO2 PO3 PO4 PO5 PO6 P07 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
##
CO1 3.00 3 2 3 - 1 - - - - - - 1 3 -
##
CO2 3.00 3 2 3 - 1 - - - - - - 1 3 -
##
CO3 3.00 3 2 3 - 1 - - - - - - 1 3 -
##
CO4 3.00 3 3 3 - 1 - - - - - - 1 3 -
##
CO5 3.00 3 3 3 - 1 - - - - - - 1 3 -
A.Y:2020-21
SEM: II
INTRODUCTION
Computer technology plays an increasing role in the information revolution. Today,
the application of computers is all-pervasive in everybody’s life. Sound knowledge
of how computers process data and information has, therefore, become indispensable
for anyone who seeks employment not only in the area of IT but also in any other
field.
COMPUTER PROGRAMMING
C PROGRAMMING LANGUAGE
The book covers the basic anatomy of a computer system, input devices, processor,
output devices, memory management, algorithms, flowcharts, and programming in
C language, which talks about the basic structure of C programs and their execution,
how to declare constants, variables and data types, details the input and output
operations, built-in operators and how to build expressions using them also covered
in Unit-I. Unit II covers decision making and looping structures and arrays. Unit-III
provides a detailed exposition of functions. Pointers and basic concepts of strings are
covered in Unit-IV in a user-friendly manner. Unit-V covers the concepts of
structures, unions and files.
1
PROGRAMMING FOR PROBLEM SOLVING
2
PROGRAMMING FOR PROBLEM SOLVING
COURSE CONTENTS
UNIT -II
Control Statements 54 - 73
Arrays 74 – 83
LAQ 84 - 85
SAQ 85 – 87
UNIT -III
Functions 89 – 98
Program Structure 103 – 112
Recursion 112 – 114
Header Files 115 - 117
Strings 118 - 134
LAQ 135
SAQ 135
UNIT -IV
Pointers 120 - 154
Structures and Unions 155 - 176
LAQ 177
SAQ 178
UNIT -V
Data Files 179 – 201
Searching and Sorting 202 - 210
LAQ 211
SAQ 212
3
PROGRAMMING FOR PROBLEM SOLVING
UNIT-I
4
PROGRAMMING FOR PROBLEM SOLVING
INTRODUCTION TO COMPUTER
Input Output
(raw data / Instructions) (Information i.e. processed)
data)
1. Computer Hardware:
ALU CU
Input Output
Devices Devices
Primary Memory
Secondary Memory
5
PROGRAMMING FOR PROBLEM SOLVING
Input Devices
➢ These are used to enter data and programs into the computer
➢ These are for man to machine communication
➢ E.g.: Keyboard, mouse, scanner, touch screen, audio input.
Output Devices
➢ These are used to get the desired output from the computer
➢ These are for the machine to man communication
➢ E.g.: Printer, Monitor, Speakers
➢ If the output is shown on the monitor, then it is called “Soft copy”
➢ If the output is printed on paper using the printer, then it is called “hard copy”
CPU (Central Processing Unit)
➢ It is responsible for processing the instructions
➢ It consists of 3 parts
1) ALU – Arithmetic & Logic Unit
2) CU- Control Unit
3) Memory
➢ ALU performs arithmetic operations like
addition, subtraction, multiplication, division and logical operations like
comparisons among data
➢ CU is responsible for the movement of data inside the system
➢ Memory is used for the storage of data and programs. It is divided into 2 parts.
1) Primary Memory/ Main Memory
2) Secondary Memory/ Auxiliary Memory
1) Primary Memory
➢ It is also called main memory
➢ Data is stored temporarily i.e.; data gets erased when the computer is turned off
➢ E.g.: RAM
2) Secondary Memory
➢ It is also called auxiliary memory
➢ Data is stored permanently so that users can reuse the data even after power loss.
➢ E.g.: Hard disk, CD, DVD, Floppy, etc.
2. Computer Software:
➢ The software is used to make the hardware of the computer to function
➢ Software is a collection of programs (or) instructions
6
PROGRAMMING FOR PROBLEM SOLVING
Hard
ware
1. System Software
➢ They constitute a set of programs that manage the hardware resources of a computer
➢ It is divided into 3 classes
Operating System
➢ It acts as an interface between the user and the hardware
➢ It makes the system to operate in an efficient manner
➢ Ex: MS-DOS, Windows, UNIX, LINUX, etc.
System Support
➢ They provide some utilities and other operating services
➢ E.g.: Sort utilities, disk formatting utilities, Security monitors
7
PROGRAMMING FOR PROBLEM SOLVING
System Development
➢ It includes
a) Language translators – Used for converting programs into machine language
b) Debuggers – for error-free programs
c) CASE tools – Computer Assisted Software Engineering Tools
2. Application Software
➢ It contains programs for performing tasks
➢ It is divided into 2 classes
8
PROGRAMMING FOR PROBLEM SOLVING
COMPUTING ENVIRONMENTS
➢ In t h e early days, there was only one environment i.e., the mainframe
computer. Itoccupies much space and consumed a large amount of power.
➢ With the invention of t h e transistor and IC (Integrated Circuits)
technology, minicomputers were introduced in which many components are fused.
➢ After the invention of microprocessor technology, the environment changed
resultingin mini-computers and personal computers
➢ The computing environments are classified into 4 types. They are
1) Personal computing environment
2) Time sharing environment
3) Client-server environment
4) Distributed computing environment
1) Personal computing environment
➢ In a personal computer, all the basic elements of the CPU are combined into the
microprocessor and all the hardware components are tied together.
➢ The whole computer can be used by the user to perform his task independently
Advantage:
The computer is busy always reducing CPU idle time
9
PROGRAMMING FOR PROBLEM SOLVING
Disadvantage:
The response becomes slow as the number of users connected to the central computer
increases
Terminals
Fig: Time-sharing environment
3) Client-Server environment
➢ This environment splits the computing function between a central computer and a
user computer
➢ Users are given personal computers (PC’s) on workstations so that some of the
computation responsibility can be moved from a central computer and assigned
to the workstation
➢ User’s workstations (or) micro computers are called “Clients”
➢ The powerful central mainframe (or) microcomputer is known as “Server”
Advantages:
- Response time is faster
- Users are more productive
10
PROGRAMMING FOR PROBLEM SOLVING
11
PROGRAMMING FOR PROBLEM SOLVING
COMPUTER LANGUAGES
➢ Computer programming languages are used to give instructions to the computer in
a language which the computer understands
➢ Computer languages are classified into 3 types
1) Machine languages
2) Symbolic languages
3) High-level languages
1) Machine languages
➢ A computer is a machine and since its memory can store only 1’s and 0’s,
instructions must be given to the computer in streams of 1’s and 0’s i.e., binary code.
➢ These are easily understandable by the machine
➢ Programs written in binary code can be directly fed to the computer for execution
andit is known as machine language.
Advantage:
➢ Execution is very fast since there is no need for conversion
Disadvantage:
➢ Writing and reading programs in machine language is very difficult
➢ Machine instructions are difficult to remember
2) Symbolic Languages
➢ It is also called as assembly language
➢ An assembly program contains “Mnemonics”
➢ “Mnemonic” means information can be memorized easily and is generally in the
form of abbreviations.
Advantage:
➢ Easy to read and write programs in assembly language when compared to machine
language
➢ Mnemonics are easy to remember
Disadvantage:
➢ Assembly programs are machine dependent
➢ Execution is slow since it needs conversion into machine language
➢ “Assembler” is used to convert assembly language programs into machine language.
12
PROGRAMMING FOR PROBLEM SOLVING
3) High-level languages
➢ A set of languages that are very close to our native languages are called “high-
level languages”.
➢ High-level languages have control structures, I/O facilities, hardware independence
E.g.: FORTRAN, COBOL, PASCAL, C, C++ etc.,
Advantage:
➢ Machine independence i.e., programs are “Portable” i.e., programs can be
movedfrom one system to another
➢ Easy to learn and understand
➢ Takes less time to write programs
Disadvantage:
➢ High-level language programs need a translator for conversion into machine
language
➢ ‘Compilers’ (or) ‘Interpreters’ are used for converting high level language
programsinto machine language.
Compiler /
High level language program Machine Language code
Interpreter
13
PROGRAMMING FOR PROBLEM SOLVING
1) Requirements
➢ Information about the problem must be stated clearly and unambiguously
➢ The main objective of this phase is to eliminate unimportant aspects and identify the
root problem
2) Analysis
➢ It involves identifying the problem inputs, outputs, that the program must produce.
➢ It also determines the required format in which results should be displayed.
3) Design
➢ It involves designing algorithms, flowcharts (or) GUI’s (Graphical User Interfaces).
➢ Designing the ‘algorithm’ is to develop a list of steps called an algorithm to solve
theproblem and then verify that the algorithm solves the problem intended.
➢ “Top- down design” is followed i.e. list the major steps (or) sub problems that
need to be solved.
➢ “Flow charts” are used to get the pictorial representation of the algorithm.
➢ Algorithm for a programming problem consists of at least the following sub
problems
1. Get the data
2. Perform the computations
3. Display the results
4) Coding / Implementation
➢ This step involves writing algorithm as a program by selecting any one of the high
– level languages that are suitable for the problem.
➢ Each step of the algorithm is converted into one (or) more statements in a
programming language.
5) Testing
➢ Checking / verifying whether the completed program works as desired is called
“Testing”
➢ Running the program several times using different sets of data verifies whether a
program works correctly for every situation provided in the algorithm.
➢ After testing, the program must be free from the following errors.
a) Syntax errors
b) Logical errors
c) Run-time errors
14
PROGRAMMING FOR PROBLEM SOLVING
6) Maintenance
➢ It involves modifying a program to remove previously undetected errors and to
keep it up-to-date as government regulations (or) company policies change.
➢ Many organizations maintain a program for some time i.e., 5 years
System
requirements
Analysis
Design
Coding
Testing
−b + b2 − 4ac
Procedure: r1 =
2a
−b − b2 − 4ac
r2 =
2a
15
PROGRAMMING FOR PROBLEM SOLVING
3) Design
Algorithm
1. start
2. Read a,b,c values
3. Compute d = b2 4ac
4. if (d > 0) then
(i) a) compute r1 = b+ sqrt (d)/(2*a)
r2 = b sqrt(d)/ (2*a)
b) print r1, r2 values
(ii)otherwise if (d == 0) then
a) compute r1 = -b/(2*a)
r2=-b/(2*a)
b) print r1, r2 values
(iii) otherwise, if d < 0 then
a) print roots are imaginary
5. Stop
16
PROGRAMMING FOR PROBLEM SOLVING
Flowchart
Start
Read a,b,c
Compute d = ((b*b)-(4*a*c))
True IS False
(d>0)
Compute
r1 🢪 -b+sqrt(d)/ (2*a) False True
r2 🢪 -b- sqrt(d)/ (2*a) Is
(d==0)
False
IS (d<0)
Compute
True r1🢪 -b/(2*a)
r2 🢪 -b/(2*a)
Print r1, r2 values
Print roots are imaginary
Stop
4. Implementation
C-code for finding roots of quadratic equation
# include<stdio.h>
# include<conio.h>
# include<math.h>
Void main ( )
{
float a,b,c,r1,r2,d;
clrscr ( );
17
PROGRAMMING FOR PROBLEM SOLVING
if (d>0)
{
r1 = -b+sqrt (d) / (2*a);
r2 = -b-sqrt (d) / (2*a);
printf (“\nRoots are real and the values are= %f %f”, r1, r2);
}
else if (d= =0)
{
r1 = -b/(2*a);
r2 = -b/(2*a);
printf (“\nRoots are equal and the values are = %f %f”, r1, r2);
}
else
if (d<0)
{
printf(“\nRoots are imaginary”);
}
getch ( );
}
5) Testing
Case 1: Enter a,b,c values : 1 4 3
r1 = -1
r2 = -3
Case 2: Enter a,b,c values : 1 2 1
r1 = -1
r2 = -1
Case 3: Enter a,b,c values : 1 1 4
Roots are imaginary
18
PROGRAMMING FOR PROBLEM SOLVING
ALGORITHM:
➢ It is a step–by–step procedure for solving a problem
Properties of an Algorithm
An algorithm must possess the following 5 properties. They are
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
1. Input: An algorithm must have zero (or) a greater number of inputs
2. Output: Algorithm must produce one (or) a greater number of outputs
3. Finiteness: An algorithm must terminate in a countable number of steps
4. Definiteness: Each step of the algorithm must be stated clearly
5. Effectiveness: Each step of the algorithm must be easily convertible into program
statements
Example
Algorithm for finding the average of 3 numbers
1. start
2. Read the 3 variables of a,b&c
3. Compute sum = a+b+c
4. compute avg = sum/3
5. Print sum & avg values
6. Stop
Pseudocode
➢ If a n algorithm is written in English like sentences, then it is called as
‘PSEUDOCODE’
19
PROGRAMMING FOR PROBLEM SOLVING
FLOW CHART
Graphical representation of an algorithm is called a flow chart.
Advantages of flow chart
➢ It is very easy to understand because the reader follows the process quickly from
the flowchart instead of going through the text.
➢ Arrows are used for connecting the symbols and show the flow of execution.
20
PROGRAMMING FOR PROBLEM SOLVING
Oval
Input / output Input/output of data
Parallelogram
Process Any processing to be
performed can be
represented
Rectangle
Decision box Decision operations that
determine which of the
alternative paths to be
Diamond followed
Connector Used to connect different
parts of flowchart
Circle
Flow Joins 2 symbols and also
represents flow of
Arrows execution
Pre-defined process Modules (or)subroutines
specified else where
Pentagon
For loop symbol Shows initialization,
condition and
incrementation of loop
Hexagon variable.
Document Shows the data that is
ready for printout
Printout
21
PROGRAMMING FOR PROBLEM SOLVING
Example
Flowchart for finding the average of 3 numbers
Start
Read a,b,c
Stop
22
PROGRAMMING FOR PROBLEM SOLVING
23
PROGRAMMING FOR PROBLEM SOLVING
Example:
//Aim: Program for finding circumference of circle
#include<stdio.h>
#include<conio.h>
#define PI 3.1415
void main ( )
{
float c, r;
clrscr ( );
printf (“enter radius of circle”);
scanf (“%f”, &r);
c = 2 * PI * r;
printf (“Circumference = %f”, c);
getch ( );
}
Program Development (or Creating and Running Program)
➢ Program consists of a set of instructions written in a programming language
➢ The job of a programmer is to write and test the program.
➢ There are 4 steps for converting a ‘C’ program into machine language.
1) Writing and editing the program
2) Compiling the program
3) Linking the program
4) Executing the program
1) Writing and editing the program
➢ ‘Text editors’ are used to write programs.
➢ Users can enter, change and store character data using text editors.
➢ Special text editor is often included with a compiler.
➢ After writing the program, the file is saved to disk. It is known as ‘source file’ .
➢ This file is input to the compiler.
Linker
Object file executable file
24
PROGRAMMING FOR PROBLEM SOLVING
4) Executing Programs
➢ ‘Loader’ is the software that gets the program that is ready for execution into the
memory.
➢ When everything is loaded, the program takes control and the ‘Runner’ begins its
execution.
➢ In the process of execution, the program reads the data from the user, processes the
data and prepares the output.
Special Characters:
Some of the special characters in ‘C’ are:
25
PROGRAMMING FOR PROBLEM SOLVING
, ; $ “ : /
? < > # ~ `
Keywords in C Language
Identifiers
In C programming, identifiers are names given to C entities , such as variables ,
functions, structures, etc. Identifiers are created to give a unique name to C entities to
identifythem during the execution of a program.
For example: money, mango tree, etc.,
Rules for writing identifier
1. An identifier can be composed of letters (both uppercase and lowercase letters), digits
and underscore '_' only.
2. The first letter of the identifier should be either a letter or an underscore. But it is
discouraged to start an identifier name with an underscore though it is legal. It is because
26
PROGRAMMING FOR PROBLEM SOLVING
an identifier that starts with an underscore can conflict with system names. In such
cases,thecompiler will complain about it. Some system names that start with
underscore
are _fileno , _iob, _wfopen, etc.,
3. There is no rule for the length of an identifier. However, the first 31 characters of an
identifier are discriminated by the compiler. So, the first 31 letters of two identifiers in a
program should be different.
Variables
❖ It is the name given to a memory location that may be used to store a data value
❖ A variable may take different values at different times during execution
❖ A variable name may be chosen by the programmer in a meaningful way toreflect
its function (or) nature in the program
E.g., sum, avg, total etc.
int num;
Here, num is a variable of integer type.
Rules for naming a variable
1) They must begin with a letter.
2) The length of the variable must not exceed 31 characters in ANSI standard. But
first eight characters are treated as significant by many compilers.
3) Upper and lowercase characters are different
E.g.: total, TOTAL, Total are 3 different variables.
4) The variable name should not be a keyword.
Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
For example:
Decimal constants: 0, -9, 22 etc.
Octal constants: 021, 077, 033 etc.
Hexadecimal constants: 0x7f, 0x2a, 0x521etc.
Notes:
You can use small caps a, b, c, d, e, f instead of uppercase letters while writing a
hexadecimal constant.
Every octal constant starts with 0 and hexadecimal constant starts with 0x in C
programming.
➢ Floating-point constants
Floating point constants are numeric constants that has either fractional form or
exponent form. For example: -2.0, 0.0000234, -0.22E-5
Note: Here, E-5 represents 10-5. Thus, -0.22E-5 = -0.0000022.
➢ Character constants
Character constants are the constants that use single quotations around characters. For
example: 'a', 'l', 'm', 'F' etc.
Escape Sequences
Sometimes, it is necessary to use newline(enter), tab, quotation mark, etc. in the
programwhich either cannot be typed or has special meaning in C programming. In such
cases, escape sequences are used. For example: \n is used for newline. The backslash (\ )
causes "escape" from the normal way the characters are interpreted by the compiler.
Escape
Sequences Character name
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
28
PROGRAMMING FOR PROBLEM SOLVING
Escape
Sequences Character name
\\ Backslash
\? Question mark
\0 Null character
String constants
String constants are the constants that are enclosed in a pair of double-quote marks.For
example:
• “good” ->string constant
• “” ->null string constant
• “ “ ->string constant with 6 white spaces
• “x” ->string constant having a single character
29
PROGRAMMING FOR PROBLEM SOLVING
Data Types
❖ Data type specifies the set of values and the type of data that can be stored in a variable.
❖ They allow the programmer to select the type appropriate to the needs of the
application.
Types:
1) Primary data types
2) Derived data types
1. Primary data types
‘C’ compilers support 4 fundamental data types
They are
1) integer
2) character
3) Floating – point
4) Double precision floating point
Primrary Data Types
Integral Type
Integer character
30
PROGRAMMING FOR PROBLEM SOLVING
31
PROGRAMMING FOR PROBLEM SOLVING
32
PROGRAMMING FOR PROBLEM SOLVING
OPERATORS
❖ Operator performs an operation on data
❖ Operators are classified into
1. Arithmetic operators.
2. Relational operators.
3. Logical operators.
4. Assignment operators.
5. Increment and decrement operators.
6. Bitwise operators.
7. Conditional operators.
8. Special operators.
1). Arithmetic operator
❖ These operators are used for numerical calculations (or) to perform arithmetic
operations like addition, subtraction, etc.
33
PROGRAMMING FOR PROBLEM SOLVING
34
PROGRAMMING FOR PROBLEM SOLVING
3. Logical Operators
❖ These are used to combine 2 (or) more expressions logically
❖ They are logical AND (&&) logical OR (||) and logical NOT (!)
Logical AND (&&)
exp1 exp2 exp1&&exp2
T T T
T F F
F T F
F F F
Logical OR (|| )
exp1 exp2 exp1||exp2
T T T
T F T
F T T
F F F
35
PROGRAMMING FOR PROBLEM SOLVING
Program:
#include<stdio.h>
#include<conio.h>
void main()
{ Input: enter the values of a&b= 10 20
int a,b; Output:
clrscr(); (a>b) && (a<b) =0
(a>b) || (a<b) =1
printf(“Enter the values of a&b=”); !(a>b)=1
scanf(“%d%d”,&a,&b);
printf (“\n(a>b) && (a<c)=%d”, (a>b) && (a<b));
printf (“\n(a>b) || (a<b)%d”, (a>b) || (a<b));
printf (“\n! (a>b) =%d”!(a>b));
getch();
}
4. Assignment operators
❖ It is used to assign a value to a variable
Types
1) simple assignment 2) compound assignment
36
PROGRAMMING FOR PROBLEM SOLVING
Program:
#include<stdio.h>
#include<conio.h>
void main()
{ Output:
a=10
int a= 10; (a+=10) =20
clrscr(); (a-=10)=10
(a*=10)=100
printf (“ \na=%d”, a); (a/=10)=10
printf (“ \n(a+=10)=%d”, a+ =10); (a%=10)=0
printf (“ \n(a-=10)=%d”, a- =10);
printf (“ \n(a*=10)=%d”, a* =10);
printf (“ \n(a/=10)=%d”, a/ =10);
printf (“ \n(a%=10)=%d”, a% =10);
getch();
}
❖ Increment operator is placed after the operand in post increment and the value is
incremented after the operation is performed
eg: z = a++; z=a
a= a+1
37
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h>
void main()
{ Output:
a=10
int a= 10; ++a=11
clrscr(); a=11
a++=11
printf (“\na= %d”,a); a=12
printf (“ \n(++a)=%d”,++ a);
printf (“\na= %d”,a);
printf (“\n(a++)= %d”,a++);
printf (“\na= %d”,a);
getch();
}
b) Decrement operator: (- -)
❖ It is used to decrement the values of a variable by 1.
2 types: i) pre decrement
ii) post decrement
❖ decrement operator is placed before the operand in pre-decrement and the value
is first decremented and then operation is performed on it.
E.g.: z = - - a; a= a-1
z=a
❖ decrement operator is placed after the operand in post decrement and the value is
decremented after the operation is performed
E.g.: z = a--; z=a
a= a-1
38
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h>
void main()
{ Output:
a=10
int a= 10; --a=9
clrscr(); a=9
a--=9
printf (“\na= %d”,a); a=8
printf (“ \n--a=%d”,-- a);
printf (“\na= %d”,a);
printf (“\na--= %d”,a--);
printf (“\na= %d”,a);
getch();
}
6. Bitwise Operator
Unlike other operators, bitwise operators operate on bits (i.e., on binary values of
onoperand).
Operator Description
a b a &b a b a|b A b a ^b
0 0 0 0 0 0 0 0 0
0 1 0 0 1 1 0 1 1
1 0 0 1 0 1 1 0 1
1 1 1 1 1 1 1 1 0
39
PROGRAMMING FOR PROBLEM SOLVING
a&b a|b
8 4 2 1 8 4 2 1
a =12 1 1 0 0 a =12 1 1 0 0
b =10 1 0 1 0 b =10 1 0 1 0
a &b 1 0 0 0 a|b 1 1 1 0
a&b = 8 a | b = 14
a^b
8 4 2 1
a =12 1 1 0 0
b =10 1 0 1 0
a ^b 0 1 1 0
a^b=6
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a= 12, b = 10;
Output:
clrscr();
a&b=8
printf (“\n(a&b)= %d”,(a&b)); a|b=14
a^b=6
printf (“ \n(a|b)=%d”,(a|b));
printf (“\n(a^b)= %d”,(a^b));
getch();
}
40
PROGRAMMING FOR PROBLEM SOLVING
Left Shift
❖ If the value of a variable is left shifted one time, then its value gets doubled
❖ eg: a = 10 then a<<1 = 20
32 16 8 4 2 1
a=10
1 0 1 0
a<<1 = 20
Right shift
If the value of a variable is right shifted one time, then its value becomes half the original
value.
❖ eg: a = 10 then a>>1 = 5
8 4 2 1
a=10
1 0 1 0
a>>1 0 Discard it
1 0 1
a>>1 = 5
One’s complement
❖ It converts all ones to zeros and zeros to ones
❖ E.g.: a = 5 then ~a=2 [only if 4 bits are considered]
8 4 2 1
a=5
1 0 1
~a
0 1 0
~a = 2
41
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h> Output
void main() (a<<1)= 40
{
(b>>1)=5
int a= 20, b = 10,c=10;
(~c)=11
clrscr();
printf (“ \n(a<<1)=%d”, a<<1);
printf (“ \n(b>>1)=%d”, b>>1);
printf (“\n(~c)= %d”, ~c);
getch();
}
Signed
1’s complement = - [ give no +1]
E.g.: ~10 = - [10+1] = -11
~-10 = - [-10+1] = 9
unsigned
1’s complement = [65535 – given no]
7. Conditional operator (? :)
❖ It is also called ternary operator
❖ Syntax:
exp1? exp2: exp3
❖ if exp1 is true exp2 is evaluated, otherwise exp3 is evaluated.
❖ it can also be represented in if – else form
if (exp1)
exp2;
else
exp3;
42
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h>
void main ( )
{
int z; Output
clrscr(); Z=1
z = (5>3) ? 1:0;
printf (“z=%d”,z);
getch();
}
8) Special operations
Some of the special operations are comma, ampersand (&), size of operators.
a) Comma: ( , )
It is used as separator for variables
E.g.; a=10, b=20
b) Address:(&)
It is used to get the address of a variables.
c) Size of ( ) ;
It is used to get the size of a data type of a variable in bytes.
43
PROGRAMMING FOR PROBLEM SOLVING
Program:
main ( )
{
int a=10;
float b=20;
printf (“\n a= %d b=%f”, a,b );
printf (“ \nAddress of a =%u “ , &a ) ;
printf (“ \nAddress of b =%u” ,&b ) ;
printf (“\nSize of a = %d ” , sizeof (a) ) ;
printf ( “\nSize of b = %d ”, sizeof (b) ) ;
} a b
Output: 10 20.00
a=10 b=20.00 1234 5678
Address of a =1 2 3 4
Address of b = 5 6 7 8 Only for this example
Size of a = 2 bytes
Size of b = 4 bytes
EXPRESSIONS
❖ Def: An expression is a combination of operators and operands which reduces to a
single value
❖ An operand is a data item on which an operation is performed.
❖ An operator indicates an operation to be performed on data.
E.g.; z = 3+2*1
z=5
Types Expression
1. Primary expressions
The operand in the primary expression can be a name, a constant or any parenthesized
expression
44
PROGRAMMING FOR PROBLEM SOLVING
E.g.: c = a+ (5*b);
2. Postfix expressions:
The operator will be after the operands in a postfix expression.
E.g.: ab+
3. Prefix expressions
The operator is before the operand in a prefix expression.
E.g.: +ab
4. unary expression:
It contains one operator and one operand.
E.g.: a++, --b
5. Binary expression
It contains 2 operands and one operator.
E.g.: a+b, c-d
6. Ternary expression
It contains 3 operands and one operator.
E.g.; Exp1? Exp2: Exp3
If Exp1 is true, Exp2 is executed. otherwise Exp3 is executed.
Expression Evaluation, Precedence And Associativity
❖ Expressions are evaluated by the ‘C’ compiler based on precedence and
associativity rules.
❖ If an expression contains different priority operators, then precedence rules
areconsidered.
45
PROGRAMMING FOR PROBLEM SOLVING
Primary Expression
() [] . -> expr++ expr-- left-to-right
Operators
* / %
+ -
>> <<
== !=
&&
||
Comma , left-to-right
46
PROGRAMMING FOR PROBLEM SOLVING
E.g.: C = 30 - 10 * 2
20
2
10
3
Here, 10*2 is evaluated first since ‘*’ has more priority than ‘-‘and ‘=’
➢ If an expression contains same priority, then associativity rules are considered
i.e.,left right (or right to left)
E.g.: z= a*b/c
z = 40 * 20 / 10 Here ‘*’ and ‘/’ have same priority so, left
to right associativity is
considered.
800
2
80
3
E.g.: x =5 *4 + 8/2 x = 5 * 4 + 8 / 2
1 2
x = 24
Parenthesis has the highest priority and comma has the least priority among operators.
47
PROGRAMMING FOR PROBLEM SOLVING
Type Conversions
Converting one data type into another is the concept of type conversion
2 types
1. Implicit type conversion
2. Explicit type conversion
❖ Implicit type conversion is automatically done by the compiler by converting
smaller data type into a larger data type.
E.g.: int i,x;
float f;
double d;
long int l;
x = l / i + x - f - d
long float
long float
float
`
Float
Double
int double
48
PROGRAMMING FOR PROBLEM SOLVING
int float
float
int
Here, the resultant of ‘a+b’ is converted into ‘int’ explicitly and then assigned to ‘C’
Program:
#include<stdio.h>
#include<conio.h>
Void main ( )
{
Output
printf (“\nval1=%d”, 5/2); 2
printf (“\nval2=%f”, 5.5/2); 2.75
printf (“\nval3=%f”, (float) 5/2); 2.5
getch();
Comment lines in C
❖ In ‘C’, comment lines are placed in “ /* */”.
❖ Single line and multiple lines are enclosed in /* and */.
❖ Comment lines are ignored by the compiler.
❖ The documentation section is enclosed in comment lines.
❖ Documentation section consists of a set of comment lines giving the name of the
program, the author and other details, which the programmer would like to use later.
49
PROGRAMMING FOR PROBLEM SOLVING
LIBRARY FUNCTIONS IN C
❖ These functions are already defined in the system libraries.
❖ Programmer can reuse the existing code in the system libraries to write error-
freecode.
❖ But to use the library functions, user must be aware of syntax of the function.
Some of the library functions are:
• printf()
• scanf()
• clrscr()
• sqrt()
E.g.: 1) sqrt() function is available in math.h library and its usage is
:y= sqrt (x)
number must be positive
eg: y = sqrt (25)
then ‘y’ = 5
2 printf ( ) and scanf() functions are available in stdio.h library.
3) clrscr ( ) function is available in conio.h library.
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
main ( )
{
int x,y;
clrscr ( );
printf (“enter a positive number”);
scanf (“ %d”, &x)
y = sqrt(x);
printf(“squareroot = %d”, y);
getch();
}
Output
Enter a positive number 25
Squareroot = 5
50
PROGRAMMING FOR PROBLEM SOLVING
Long answers:
51
PROGRAMMING FOR PROBLEM SOLVING
Short answers:
1. What are various computer languages?
2. Write a “C” statement to find the value of “n” when divided by 32 Without using
arithmetic operator and store the result in variable “a”
3. What are the various phases of SDLC?
4. What is printed by the following program
void main()
{
int x=5, y=10,z=10;
x=y==z;
printf(“%d”, x);
getch();
}
5. What is the difference between application software and system software?
6. If x=-2, y=5 & z=0 calculate the value of expression x-2*y+z/y*2%3 step by step.
7. Write a C statement to multiply the given number ‘n’ by 4 and store in another
variable ‘a’ without using arithmetic operator.
8. What is the value of x when the following program fragment is executed?
int x=10,y=15;
x=(x<y) ? (y+x) : (y-x);
printf(“%d”,x);
9. Difference between compiler and interpreter
10. Write short notes on type cast operator.
11. Distinguish between variables and constants.
12. Explain SDLC.
13. Write an algorithm to find whether the given number is even or odd?
14. What is an identifier? Write the rules for writing identifier.
52
PROGRAMMING FOR PROBLEM SOLVING
UNIT II
53
PROGRAMMING FOR PROBLEM SOLVING
CONTROL STATEMENTS
There are 3 types of control statements.
➢ Decision control statements
➢ Looping control statements
➢ Jump statements
Decision statements:
These are used to make a decision among the alternative paths.
They are
1. simple – if statement
2. if – else statement
3. nested – if else statement
4. else – if ladder
5. switch statement
1. Simple – if statement
➢ ‘if’ keyword is used to execute a set of statements when the logical condition is
true.
Syntax:
if (condition)
{
Statement block;
}
Statement-X;
Flow chart
True False
Condition?
Statement block
Statement X
54
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a;
clrscr();
printf (“enter a number”);
scanf (“%d”, &a);
if (a>50)
{
a=a*10;
}
printf(“a=%d”,a);
}
Input: Input:
enter a number 60 enter a number 20
Output: Output:
a=600 a=20
2. if else statement
➢ If –else statement takes care of true as well as false conditions.
➢ ‘Statement block-1’ is executed when the condition is true and ‘Statement block-2’
(or) ‘else block’ is executed when the condition is false.
Syntax:
if (condition)
{
Statement block-1;
}
else
{
Statement block-2;
}
Statement-x;
55
PROGRAMMING FOR PROBLEM SOLVING
Flow chart
True False
Cond
ition?
Statement-X
Program
/* checking for even (or) odd number */
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf (“enter a number”);
scanf (“%d”, &n);
if (n%2 ==0)
{
printf (“%d is even number”, n);
}
else
{
printf( “%d is odd number”, n);
}
printf(“n=%d”,n);
getch();
}
56
PROGRAMMING FOR PROBLEM SOLVING
Input
1) enter a number 10 2) enter a number 5
output
10 is even number 5 is odd number
n=10 n=5
3. Nested if - else statement
➢ A ‘nested if’ is an if statement that is the object of either if (or) an else.
➢ ‘if’ is placed inside another if (or) else.
Syntax:
if (condition1)
{
if (condition2)
{
Statement block-1;
}
else
{
Statement block-2;
}
}
else
{
if (condition3)
{
Statement block-3;
}
else
{
Statement block-4;
}
}
Statement-x;
57
PROGRAMMING FOR PROBLEM SOLVING
Flow chart
True False
Cond
ition1
Statement-X
Program
/* largest of 3 numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf (“enter the values of a,b,c=”);
scanf (“%d%d%d”, &a, &b, &c);
if (a>b)
{ if (a>c)
printf (“%d is largest”, a);
else
printf (“%d is largest”, c);
}
else
{
if (b>c)
58
PROGRAMMING FOR PROBLEM SOLVING
59
PROGRAMMING FOR PROBLEM SOLVING
flow chart
Stmt n Stmt x
Program
/* finding roots of quadratic equation */
#include<stdio.h>
#include<conio.h>
#include <math.h>
void main ( )
{
int a,b,c,d;
float r1, r2;
clrscr();
printf (“enter a,b,c values”);
scanf (“%d%d%d”, &a, &b, &c);
d=( b*b) – (4*a*c );
if (d>0)
{
r1 = (-b+sqrt(d)) / (2*a);
r2 = (-b-sqrt(d)) / (2*a);
printf(“roots are real”);
60
PROGRAMMING FOR PROBLEM SOLVING
61
PROGRAMMING FOR PROBLEM SOLVING
5. Switch statement
➢ It is used to select one among multiple decisions.
➢ ‘switch’ successively tests a value against a list of integers (or) character constant.
➢ When a match is found, the statement (or) statements associated with that value are
executed.
Syntax:
switch (expression)
{
case value1: stmt1;
break;
case value2: stmt2;
break;
------
default: stmt;
}
Statement-x;
62
PROGRAMMING FOR PROBLEM SOLVING
Flow chart
Switch
(expressionon)
Exp =value2
Stmt2
default Stmt
Program
#include<stdio.h>
#include<conio.h>
Statement-X
void main()
{
int n;
clrscr();
printf (“enter a number”);
scanf (“%d”, &n);
switch (n)
{
case 0: printf (“zero”)
break;
case 1: printf (‘one”);
break;
default: printf (‘wrong choice”);
}
}
63
PROGRAMMING FOR PROBLEM SOLVING
Input:
enter a number 1
Output
one
Flow chart
False
Initialization Increment/
condition decrement
True
Statement-X
64
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h>
void main()
{ Input:
enter the value of n=5
int n,i; Output
clrscr(); i=1
scanf(”%d”,&n); i=3
{ i=5
printf (”\ni=%d”,i);
}
getch();
}
65
PROGRAMMING FOR PROBLEM SOLVING
2) while loop
Syntax
while (condition)
{
body of the loop;
(or)
group of statements;
}
Statement-x;
Flow chart
initialization
while False
(condition)
True
Incr/ dec
Statement-X
66
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h> Input:
void main() enter the value of n=5
{ Output
int i=1,n; i=1
clrscr(); i=2
printf(”enter the value of n=”);
scanf(”%d”,&n); i=3
while(i<=n) i=4
{
printf (”\ni=%d”,i); i=5
i++;
}
getch();
}
3) do-while loop
Syntax
Initialization
do
{
body of the loop;
(or)
group of statements;
} while (condition);
Statement-x;
67
PROGRAMMING FOR PROBLEM SOLVING
Flow chart
initialization
Incr/ dec
True while
(condition)
False
Statement-X
Program
#include<stdio.h>
#include<conio.h> Input:
void main() enter the value of n=5
{ Output
int i=1,n; i=1
clrscr(); i=2
printf(”enter the value of n=”);
scanf(”%d”,&n); i=3
do i=4
{
printf (”\ni=%d”,i); i=5
i++;
}while(i<=n);
getch();
}
68
PROGRAMMING FOR PROBLEM SOLVING
69
PROGRAMMING FOR PROBLEM SOLVING
JUMP STATEMENTS
1) break
2) continue
3) goto
1) break
➢ It is a keyword used to terminate the loop (or) exit from the block.
➢ The control jumps to next statement after the loop (or) block.
➢ ‘break’ is used with for, while, do-while and switch statement.
➢ When break is used in nested loops then only the innermost loop is
terminated.
➢ It is protected by an if statement.
Syntax
{ Stmt1;
Stmt2;
break;
Stmt3;
Stmt4;
}
Program
#include<stdio.h>
#include<conio.h> Output
void main() 1 2 3 4 5
{ hai
int i;
clrscr();
for (i=1; i<=10; i++)
{
if (i= =5)
{
break;
}
else
{
printf (”\t%d”, i);
}
}
Printf(“\nhai”);
getch();}
70
PROGRAMMING FOR PROBLEM SOLVING
2) continue
➢ It is a keyword used for continuing the next iteration of the loop.
➢ It skips the statements after the continue statement.
➢ It is used with for, while and do-while.
➢ It is protected by an if statement.
Syntax
{
Stmt1;
Stmt2;
continue;
Stmt3;
Stmt4;
}
Program
#include<stdio.h>
#include<conio.h> Output
void main() 1 2 3 4 6 7 8 9 10
{ hai
int i;
clrscr();
for (i=1; i<=10; i++)
{
if (i= =5)
{
continue;
}
else
{
printf (”\t%d”, i);
}
}
Printf(“\nhai”);
getch();
}
71
PROGRAMMING FOR PROBLEM SOLVING
3) goto
➢ It is an unconditional statement
➢ It is used to change the normal sequence of program execution by transferring the
control to some other part of program
label:
group of statements;
Where the label is unique identifier used to specify where the control will be
transferred in a program.
The general form of goto statement can be classified in to two types.
72
PROGRAMMING FOR PROBLEM SOLVING
Program
Forward jump
#include<stdio.h>
#include<conio.h> Output
void main() Hello
{
hi
clrscr();
you
printf(’Hello”);
printd(“hi”);
goto x;
printf(”How are”);
x: printf(”you”);
getch();
Program
Backward jump
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(’Hello”);
printf(“hi”);
x:
printf(”How are”);
goto x;
printf(”you”);
getch();
}
73
PROGRAMMING FOR PROBLEM SOLVING
ARRAYS
❖ Array: An array is a group of related data items that share a common name.
(or) Homogenous collection of data items that share a common name.
❖ A particular value in an array is identified using its “index number” or “subscript”.
Advantage
❖ The ability to use a single name to represent a collection of items and to refer to an
item by specifying the item number enables the user to develop concise andefficient
programs.
Declaring for declaring array
Syntax: for declaring array:
E.g.:
1. float height [50]
This declares ‘height’ to be an array containing 50 float elements.
2. int group [10]
❖ This declares the ‘group’ as an array to contain a maximum of 10 integer constants.
❖ Individual elements are identified using “ array subscripts”.
❖ While complete set of values are referred to as an array, individual values are
called “elements”.
E.g.: To represent a set of 5 numbers by an array, it can be declared as
followsint a[5];
❖ Then computer reserves 5 storage locations each of 2 bytes.
a[0]
a[1]
a[2]
a[3]
a[4]
❖ First element is identified by subscript ‘zero’ i.e., a[0] represents first element of
the array.
❖ If there are ‘n’ elements in array then subscripts range from 0 to n-1
74
PROGRAMMING FOR PROBLEM SOLVING
Initialization
To store values into an array it can be done as follows.
a[0] = 10; 10 a[0]
a[1] = 20; 20 a[1]
a[2] = 30; 30 a[2]
a[3] = 40; 40 a[3]
a[4] = 50; 50 a[4]
75
PROGRAMMING FOR PROBLEM SOLVING
Program for compile time initialization and sequential access using for loop
#include<stdio.h> storing
#include<conio.h>
void main ( )
{
getch ( );
}
accessing
Output: Elements of the array are
10 20 30 40 50
Program for runtime initialization and sequential access using for loop
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[10],i,n;
clrscr ( );
printf (“enter the size of array=\n”);
scanf(”%d”,&n);
printf(”\nenter the array elements=\n”);
for ( i=0; i<n; i++)
Storing/assigning values to an element of
scanf(”%d”, &a[i]);
an array
printf(“the given elements of the array are”);
for (i=0; i<n; i++)
Accessing the elements of the aray
printf(”\t%d ”, a[i]);
getch ( );
}
76
PROGRAMMING FOR PROBLEM SOLVING
Input:
enter the size of array=5
enter the array elements= 10 20 30 40 50
Output:
❖ The output of compile time initialized program will not change during different runs of
the program.
❖ The output of run time initialized program will change for different runs because user
is given a chance of accepting different values during execution.
2. Two – dimensional arrays
❖ These are used in situations where a table of values have to be stored (or) in
matrices applications.
❖ Syntax:
datatype array_ name [rowsize] [column size];
❖ E.g.: int a[5] [5];
❖ No of elements in array = rowsize *columnsize = 5*5 = 25
77
PROGRAMMING FOR PROBLEM SOLVING
Initialization:
Program for compile time initialization and sequential access using nested for loop
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[3][3] = {10,20,30,40,50,60,70,80,90};
a[0] [0] a[0] [1] a[0] [2]
int i,j;
10 20 30
clrscr ( );
a[1] [0] a[1] [1] a[1] [2]
printf (“the given elements of the array are=\n”);
40 50 60
for ( i=0; i<3; i++)
a[2] [0] a[2] [1] a[2] [2]
{
70 80 90
for (j=0;j<3; j++)
{
printf(“%d \t”, a[i] [j]);
}
printf(“\n”);
}
getch ( );
}
Output:
78
PROGRAMMING FOR PROBLEM SOLVING
Program for runtime initialization and sequential access using nested for loop
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[10][10] ,i,j,n,m;
clrscr ( );
printf(“enter the size of m&n=\n”);
scanf(“%d%d”,&m,&n);
printf (“enter the elements of an array=\n”);
for ( i=0; i<m; i++)
{
for (j=0;j<n; j++)
{
scanf(“%d ”, &a[i] [j]);
}
}
printf(“the given elements of the array are”);
for ( i=0; i<m; i++)
{
for (j=0;j<n; j++)
{
printf(“%d\t ”, a[i] [j]);
}
printf(“\n”)
}
getch( );
}
79
PROGRAMMING FOR PROBLEM SOLVING
Input:
enter the size of m & n =3 3
enter the elements of an array=
1 2 3 4 5 6 7 8 9
Output:
the given elements of the array are
1 2 3
4 5 6
7 8 9
80
PROGRAMMING FOR PROBLEM SOLVING
81
PROGRAMMING FOR PROBLEM SOLVING
Array applications:
82
PROGRAMMING FOR PROBLEM SOLVING
Long answers:
1. A) Distinguish between while and do-while statements? Write a C program to
generate prime numbers from 1 to n.
2. What are type qualifiers? Write a program to find Fibonacci series of a given number
using recursive and non-recursive approaches.
3. Discuss array applications? Write a C program to find product of n*n matrices?
4. A) Explain while, for, do- while and switch statements with an example?
B) Write a C program to generate all the prime numbers between 1 and n, where n
is a value supplied by the user?
5. Write a C program to find product of two n X n matrices.
6. Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user.
7. Write a C program to find product of two n X n matrices.
8. A(i) Illustrate features of For loop, with flow chart and example.
(ii) Compare If- Else – If Ladder with Switch statement.
9. B(i) Explain switch statement with syntax, write a C-Program to perform arithmetic
operations using switch statement.
(ii) Write a C program to print multiplication tables from ‘m’ to ‘n’ using while loop.
10. A(i) Explain array of pointers and pointer to array with example.
(ii) Write a C program to perform Matrix Multiplication which must read size of the
matrix- A and matrix – B and verify the possibility.
11. Explain the else-if ladder with syntax and flowchart?
Write a “C” program to find the average of 3 subjects marks and display the result
as follows
Average Result
>=40 and <=50 Third class
>50 and <=60 Second class
>60 and <=75 First class
>75 and <=100 Distinction
If marks in any subject is less than 40 then fail.
12. What is the difference between while and do-while loops? Write a “c” program to
calculate the following sum
Sum=1-x+ x2-x3+x4 ........................ n terms.
13. Explain the various unconditional statements with example programs.
14. Explain the nested if else with syntax and flowchart? Write a C program to find the
smallest of three numbers using nested if else.
83
PROGRAMMING FOR PROBLEM SOLVING
Short answers:
1. Distinguish between if-else-if ladder and switch statements.
2. What is an array? Explain run time initialization of an array?
3. Differentiate between while and do-while?
4. Differentiate between break and continue?
5. What is an array? How to initialize two-Dimensional array?
6. Write the importance of ‘break’ and ‘continue’ keywords.
7. Write the syntax of while-loop and do-while loop with suitable example.
8. Declare an array a1 to initialize “Hyderabad” and a2 to initialize 3 x 3 array with
all zeroes.
9. What is the output of the following program?
void main()
{
int m=1;
if(m==1)
{
Printf(“Delhi”);
if(m==2)
printf(“Chennai”);
else
printf(“Banglore”);
}
else
printf(“end”);
getch();
}
10. What would be the o/p of the following program fragment
for(i=1; i<=10; i++);
{
printf(“%d”, i);
}
printf(“%d”, i);
11. (a) In an entry-controlled loop if the body is executed “n” times, the test
conditionis evaluated ----------- times.
(b) Draw the flowchart of do-while loop.
12. What would be the output of the following program fragment?
84
PROGRAMMING FOR PROBLEM SOLVING
int i;
for (i=1; i<=10; i++)
{
if(i<5)
continue;
else
break;
printf(“CMR”);
}
16. Assuming that y=1 initially, what will be their values after executing the
following code segments.
switch(y)
{
case 0: x=0;
y=0;
printf(“%d%d”,x,y);
case 2: x=2;
y=2;
printf(“%d%d”,x,y);
default: x=1;
y=2;
printf(“%d%d”,x,y);
}
85
PROGRAMMING FOR PROBLEM SOLVING
{
int a[]={10,20,30,40,50};
printf("%d\n",a[3]);
getch();
}
19. What is the difference b/w two-dimensional and multi-dimensional array?
20. What is the o/p of the following program?
#include<stdio.h>
#include<conio.h>
void main()
{
int m[]={1,2,3,4,5};
intx,y=0;
clrscr();
for(x=0;x<5;x++)
{
y=y+m[x];
printf("%d\n", y);
}
getch();
}
86
PROGRAMMING FOR PROBLEM SOLVING
UNIT III
87
PROGRAMMING FOR PROBLEM SOLVING
FUNCTIONS
DEFINITION:
➢ The number of statements grouped into some logical unit is called a function.
➢ C is a collection of programs. Every c program must have one main() function
section because execution starts from there only.
Types of functions
Functions are broadly classified into 2 types. They are
1) predefined functions (or standard/library functions)
2) user defined functions
1) predefined (or) library functions
❖ These functions are already defined in the system libraries
❖ Programmer can reuse the existing code in the system libraries to write error free
code.
❖ But to use the library functions, user must be aware of syntax of the function.
E.g.: 1) sqrt() function is available in math.h library and its usage is :
y= sqrt (x)
number must be positive
eg: y = sqrt (25)
then ‘y’ = 5
2 printf ( ) function is available in stdio.h library.
3) clrscr ( ) function is available in conio.h library.
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main ( )
input
{ int x,y; clrscr ( );
printf (“enter a positive number”); Enter a positive number 25
scanf (“ %d”, &x) Output
y = sqrt(x); Squareroot = 5
printf(“squareroot = %d”, y);
getch();
}
88
PROGRAMMING FOR PROBLEM SOLVING
89
PROGRAMMING FOR PROBLEM SOLVING
STRUCTURE OF C FUNCTION:
According to c language function mechanism contains 5 parts. They are
➢ Function declaration
➢ Function definition
➢ Function call
➢ Function return value
➢ Elimination of function declaration.
FUNCTION DECLARATION:
A function can be declared before it is used in the program. The function can be
declared inside of the main function or outside of the main function.
A function can be declared inside of the main function then it is called as local
function.
A function can be declared outside of the main function then it is called as global
function.
Syntax:
Where return type represents which type of value is return by the function definition to the
calling function. Where return type is any data type.
E.g.:
Function definition:
It is used to define the function that describes what is the operation to be done by
the function.
Syntax:
return type fnname(arguments)
90
PROGRAMMING FOR PROBLEM SOLVING
Function call:
It is also called a calling function. It is an operational statement which sends
program control to the function definition.
Syntax:
fnname (arguments);
E.g.:
Sum(a,b);
Sub(c,d)
Mul(e,f);
Ex: return(c);
#include<stdio.h>
#include<conio.h>
void sum(int,int);
void main()
{ input
int a,b; Enter the values of a & b=5 7
clrscr();
printf(“enter the value of a & b=”); Output
sum(a,b); Sum = 12
getch();
}
void sum(int c, int d)
{
int e;
e = c+d;
printf(“sum = %d’,e);
}
91
PROGRAMMING FOR PROBLEM SOLVING
Advantages of function:
➢ We can decrease the complexity of a program and we can improve the
understandability of the program by using function.
➢ A program is divided into some functional parts and each part is separately coded
and later combined into a single unit.
➢ These independent coded parts are known as sub programs.
➢ We can decrease the length of the program by eliminating the program code into
individual parts.
➢ It is easy to locate the errors by using functions.
➢ Testing and debugging become easy.
➢ By using functions, we can get the advantages of usability of existing code.
i.e., we can use one function in another function (or) another program with slight (or) no
modifications.
Characteristics of functions:
1) A function can have no. of arguments these arguments depend on the purpose of a
function.
2) A function can define with return type or without return type.
3) A function returns only one value at a time
4) The default return value from any function is an integer.
5) If you want to return a non-integer value then mention the return type.
6) I f a function doesn’t return any value then mention the return as void.
Actual parameters:
The arguments [variable] which are used in calling function [function call] is
called as “actual parameters”.
Formal (or) Dummy Parameters:
The arguments [variable] which are used in called function [function definition]
is called as “Formal (or) Dummy Parameters”.
92
PROGRAMMING FOR PROBLEM SOLVING
Categories of functions
❖ Depending on whether arguments are present (or) not and whether a value is
returned (or) not, functions are categorized into:
1) functions without arguments and without return values
2) functions without arguments and with return values
3) Functions with arguments and without return values
4) Functions with arguments and with return values.
93
PROGRAMMING FOR PROBLEM SOLVING
c= fun ( ); return c;
values are sent back
----- }
}
94
PROGRAMMING FOR PROBLEM SOLVING
getch ( ); Sum = 12
}
int sum ( )
{
int a,b,c;
printf(“enter the values of a&b=”);
scanf (“%d%d”, &a, &b);
c = a+b;
return c;
}
3) Functions with arguments and without return values
95
PROGRAMMING FOR PROBLEM SOLVING
---
value are sent back
c= fun ( a,b ); return c;
--- }
---
}
96
PROGRAMMING FOR PROBLEM SOLVING
97
PROGRAMMING FOR PROBLEM SOLVING
Enter 5 elements
10 20 30 40 50
98
PROGRAMMING FOR PROBLEM SOLVING
Output:
Elements of the array are
10 20 30 40 50
2. Sending individual elements as argument to function.
❖ If individual elements are to be passed as arguments, then array elements
along with their subscripts must be given in function call.
❖ To receive the elements, simple variables are used in function definition
#include<stdio.h>
#include<conio.h>
void main ( )
{
void display (int, int);
int a[5], i;
clrscr( );
printf (“enter 5 elements”);
for (i=0; i<5; i++)
scanf(“%d”, &a[i]);
display (a [0], a[4]);
getch( );
}
void display (int a, int b)
{
print f (“first element = %d”,a);
printf (“last element = %d”,b);
}
input
Enter 5 elements
10 20 30 40 50
Output
First element = 10
Last element = 50
99
PROGRAMMING FOR PROBLEM SOLVING
Scope:
❖ “scope” of a variable determines the part of the program where it is visible
2 types
1. local scope 2. global scope
1. Local scope:
❖ Local scope specifies that variables defined within the block are visible only in that
block and invisible outside the block.
Program code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main ( )
Input:
{
enter a positive number=
int x,y;
25
clrscr ( );
Output:
printf (“enter a positive number=\n”);
Squareroot = 5
scanf (“ %d”, &x)
y = sqrt(x);
printf(“squareroot = %d”, y);
getch();
}
100
PROGRAMMING FOR PROBLEM SOLVING
2. Global scope
❖ Global scope specifies that variables defined outside the block are visible upto end
of the program.
E.g.:
#include<stdio.h>
#include<conio.h>
int c= 30; /* global area */
void fun();
void main ( )
{
int a = 10;
printf (“a=%d, c=%d” a,c);
fun ( );
getch(); Local function area
}
void fun ( )
{
printf (“c=%d”,c);
}
output
a =10, c = 30
c = 30
Scope rules
❖ Scope rules relate to the accessibility, period of existence and boundary of usage of
variables.
Scope rules related to statement Blocks:
❖ Block is set of statement enclosed in curly braces.
❖ Variables declared in a block are accessible and usable within that block and
does not exist outside it.
101
PROGRAMMING FOR PROBLEM SOLVING
#include<stdio.h>
#include<conio.h>
void main()
{
‘i' is available within this
int i = 1;
block only
printf (“\ni=%d”,i);
{
int i=2; ‘i' is available within this
getch();
}
Output:
i=1
i=2
Storage classes:
There are 4 storage classes (or) storage class specifiers supported in ‘C’ They are:
1) auto
2) extern
3) static
4) register
1. automatic variables / Local variables.
➢ Keyword: auto
➢ These are also called local variables.
➢ Scope:
❖ Scope of a local variable is available within the block in which they are
declared.
❖ These variables are declared inside a block.
➢ Default value: garbage value
102
PROGRAMMING FOR PROBLEM SOLVING
E.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
auto int i=1; ‘i' is available within this
{ block only
auto int i=2;
{
auto int i=3; Output:
printf (“\ni=%d”,i) i=3
} i=2
printf(“\ni=%d”, i); i=1
}
printf(“\ni=%d”, i);
getch();
}
2. Global Variables / external variables
➢ Keyword: extern
➢ These variables are declared outside the block and so they are also called global
variables
➢ Scope:
Scope of a global variable is available throughout the program.
➢ Default value: zero
103
PROGRAMMING FOR PROBLEM SOLVING
E.g.:
#include<stdio.h>
#include<conio.h>
extern int i =1; /* this ‘i’ is available throughout program */
void fun( );
void main ( ) Output:
{ i=3
int i = 3; /* this ‘i' available only in main */ i=1
clrscr();
printf (“\ni=%d”, i);
fun ( );
getch( );
}
void fun ( )
{
printf (“\ni=%d”, i);
}
3) Static variables
➢ Keyword: static
➢ Scope
Scope of a static variable is that it retains its value throughout the program and in
between function calls.
❖ Static variables are initialized only once.
➢ Default value: zero
104
PROGRAMMING FOR PROBLEM SOLVING
E.g.:
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main ( ) void main()
{ {
clrscr(); clrscr();
inc ( ); inc ( );
inc ( ); inc ( );
inc ( ); inc ( );
getch(); getch();
} }
void inc ( ) void inc ( )
{ {
static int i =1; auto int i=1;
printf (“\ni=%d”, i); printf (“\ni=%d”, i);
i++; i++;
} }
Output Output
i=1 i=1
i=2 i=1
i=3 i=1
105
PROGRAMMING FOR PROBLEM SOLVING
4. Register variables
➢ Keyword: register
❖ Register variable values are stored in CPU registers rather than in memory
where normal variables are stored.
❖ Registers are temporary storage units in CPU.
❖ They allow faster access time for register variables than normal variables.
E.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
register int i;
clrscr();
for (i=1; i< =5; i++)
printf (”\ni=%d ”,i);
getch();
}
Output:
i=1
i=2
i=3
i=4
i=5
106
PROGRAMMING FOR PROBLEM SOLVING
107
PROGRAMMING FOR PROBLEM SOLVING
Call by reference:
The process of passing the variables’ addresses from calling function to
calledfunction is called as call by reference.
According to call by value mechanism the modification is done in the function
definition (called function) it must affect the arguments of the calling function.
E.g.:
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
int a,b;
clrscr( );
printf(“enter the valuesof a&b=”);
scanf(“%d%d”,&a,&b);
printf (“before swapping a=%d, b=%d”, a,b);
swap (&a,&b);
printf (“after swapping a=%d, b=%d”, a,b);
getch();
}
void swap (int *a, int *b)
{
*a=(*a+*b)-(*b=*a);
}
Input:
enter the values of a & b=10 20
Output:
Before swapping a=10, b=20
After swapping a = 20, b=10
108
PROGRAMMING FOR PROBLEM SOLVING
Type Qualifiers:
Type qualifiers add special attributes to existing datatypes.
1. Const
There are 3 types of constants
a) Literal constants
b) Defined constants
c) Memory constants
a) Literal constants
❖ unnamed constants are used to specify data.
E.g.:
a=b+5 Here ‘5’ is literal constant.
b) defined constants
❖ They use preprocessor command ‘define” with #
E.g.: #define PI 3.1415
c) Memory constants
❖ It uses ‘C’ type qualifier ‘const’ to indicate that the data cannot be changed.
❖ Syntax: const type identifier = value.
❖ E.g.:
const float pi = 3.1415
❖ it is simply giving a literal name.
Program
#include<stdio.h>
#include<conio.h>
#define PI 3.1415
void main ( )
{
const float cpi = 3.14
clrscr();
printf (“literal constant = %f”,3.14);
printf (“defined constant = %f”, PI);
109
PROGRAMMING FOR PROBLEM SOLVING
Output:
literal constant = 3.14
defined constant = 3.1415
memory constant = 3.14
2. volatile
❖ ‘volatile’ type qualifier is used to tell the compiler that a variable is shared.
❖ That is, a variable may be referenced and changed by other programs (or) entities
if it is declared as volatile.
E.g.: volatile int x;
3. restrict
❖ This is used only with pointers.
❖ It indicates that the pointer is only the initial way to access the different data.
❖ It provides more help to the compiler for optimization.
E.g.;
int *ptr
int a= 0;
ptr = &a;
*ptr+=4;
Cannot be replaced with
*ptr+=9
*ptr+=5;
❖ Here the compiler cannot replace the two statements *ptr+=4 and *ptr+=5 by one
statement *ptr+=9, because it does not know if the variable ‘a’ can be accessed
directly (or) through other pointers.
❖ Same program fragment using ‘restrict’ qualifier is as follows
E.g.:
restrict int *ptr
110
PROGRAMMING FOR PROBLEM SOLVING
int a= 0;
ptr = &a;
*ptr+=4;
❖ Here the compiler can replace the 2 statements by one statement, *ptr+=9 because
it is sure that variable cannot be accessed through any other resources.
Recursive Functions
❖ “recursion” is the process of defining something in terms of itself.
❖ “Recursive function” is a function that calls itself again in the body of the function.
Advantages:
i. Usually simplicity.
ii. Although atmost of the times a problem can be solved without recursion, but in some
situations in programming, it is a must to use recursion. For example, a program to display
a list of all files of the system cannot be solved without recursion.
iii. The recursion is very flexible in data structure like stacks, queues, linked list and quick
sort.
iv. Using recursion, the length of the program can be reduced.
Disadvantages:
i. It requires extra storage space. The recursive calls and automatic variables are stored on
the stack. For every recursive call separate memory is allocated to automatic variables
with the same name.
ii. Often the algorithm may require large amounts of memory if the depth of the recursion
is very large.
iii. If the programmer forgets to specify the exit condition in the recursive function, the
program will execute out of memory.
iv. The recursion function is not efficient in execution speed and time.
v. Some function calls inside recursion are repeated or duplicated just like Fibonacci
E.g.:
❖ A function fact ( ), which computes the factorial of an integer ‘N’ ,which is the
product of all whole numbers from 1 to N
111
PROGRAMMING FOR PROBLEM SOLVING
112
PROGRAMMING FOR PROBLEM SOLVING
Limitations of Recursive:
1. Recursive solutions may involve extensive overhead because they use function
calls. Each function call requires push of return memory address, parameters, returned
result, etc., and every function return requires that many pops.
2. Each time you call a function you use up some of your memory allocation may be in
stack or heap. If there are large number of recursive calls – then you may run out of
memory.
Infinite recursion occurs if the recursion step An infinite loop occurs with iteration if
does not reduce the problem in a manner that the loop-condition test never becomes
Recursion terminates when a base case is Iteration terminates when the loop-
Recursion is usually slower than iteration due Iteration does not use stack so it's faster
Recursion uses more memory than iteration Iteration consumes less memory
Infinite recursion can crash the system infinite looping uses CPU
cycles repeatedly
113
PROGRAMMING FOR PROBLEM SOLVING
HEADER FILES IN C
114
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h> Program
#include<stdio.h>
#include<conio.h>
#define wait getch( ) #define wait getch( )
void main ( ) void main ( )
{ {
clrscr ( ); #undef wait;
printf (“Hello”); clrscr ( );
wait ; printf (“Hello”);
} wait;
Output: }
Hello Output:
Error since wait is undefined before
using it
2. File inclusion directives:
❖ An external file containing functions (or) macro definitions can be included using
#include directive.
Syntax :
# include <filename> (or) #include “filename”
E.g.:
#include <stdio.h>
Output:
void main ( )
Hello
{
printf (“hello”);
getch();
}
The definition of the function printf ( ) is present in <stdio.h>header file.
115
PROGRAMMING FOR PROBLEM SOLVING
#else
printf(‘This is line number two”);
#endif
}
116
PROGRAMMING FOR PROBLEM SOLVING
STRINGS
Definition of Strings:
Here the datatype represents only character the compiler automatically assigns a NULL
character at the end of the string. The size of the string must be equal to maximum number
of characters “+1”
Initialization:
During declaration:
We can initialize the character array at the time of declaration by using the
following:
Syntax:
datatype stringname[size]={set of characters};
Or
datatype stringname[size]={“total string”};
E.g.:
Char a[]={‘s’,’a’,’i’};
(or)
Char a[]={“sai”};
With the help of keyboard:
input and output functions
117
PROGRAMMING FOR PROBLEM SOLVING
getchar():
It is a single character input function.
It returns a single character.
It does not require any arguments.
Syntax:Charactervariable=getchar();
Syntax:
putchar(char variable);
Program code:
#include<stdio.h>
#include<conio.h>
void main()
{
char b;
clrscr();
printf(“enter a single character=\n”);
b=getchar();
printf(“the given character=”);
putchar(b);
getch();
}
Input:
Enter a single character=f
Output:
The given character=f
The getchar() type function can also be used to read multiple characters by reading one
character at a time with the help of keyboard.
Putchar() is also used to display multiple character at a time by using for loop.
Program code:
#include<stdio.h>
#include<conio.h>
void main()
{
char a[20];
int n;
printf(“Enter the size of the string=\n”);
scanf(“%d”,&n);
printf(“enter the string=\n”);
for(i=0;i<n;i++)
{
a[i]=getchar(); }
118
PROGRAMMING FOR PROBLEM SOLVING
a[i]=’\0’;
printf(“the given string =\n”);
for(i=0;i<n;i++)
{
putchar(a[i]);
}
getch();
}
input:
enter the size of a string=3
enter the string= sai
output:
the given string= sai
scanf() function:
The input function is a scanf function. it can be used to read any data type.
That isint, char, float.
Printf() function:
The output function is a printf function. It can be used to display any data type. That
is int, char, float.
Program code:
#include<stdio.h>
#include<conio.h>
void main ( )
{
char a ;
clrscr();
printf(“Enter a single character=\n”);
scanf(“%c”,&a);
printf (“The given character =%c”,a);
getch ( );
}
Input:
Enter a single character= k
Output:
The given character = k
119
PROGRAMMING FOR PROBLEM SOLVING
Program code:
#include<stdio.h>
#include<conio.h>
void main ( )
{
char a[20] ;
clrscr();
printf(“Enter a string=\n”);
scanf(“%s”,&a);
printf (“The given string =%s”,a);
getch ( );
}
Input:
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a[30] ;
clrscr();
printf(“Enter the string=\n”);
gets(a);
printf (“The given string =\n”);
puts(a);
getch ( );
}
Input:
Enter the string=raj kumar
Output:
The given string =raj kumar
120
PROGRAMMING FOR PROBLEM SOLVING
1). strlwr ( )
It is used to convert the given string into lowercase.
Syntax:
strlwr (string name);
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a[30] ;
clrscr();
printf(“Enter the string=\n”);
gets(a);
strlwr(a);
printf (“The given string in lowercase =\n”);
puts(a);
getch ( );
}
Input:
Enter the string=RAJ
Output
The given string in lowercase =raj
121
PROGRAMMING FOR PROBLEM SOLVING
2). strupr ( )
It is used to convert the given string into uppercase.
Syntax:
strupr (string name);
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a[30] ;
clrscr();
printf(“Enter the string=\n”);
gets(a);
strupr(a);
printf (“The given string in uppercase =\n”);
puts(a);
getch ( );
}
Input:
Enter the string=raj
Output:
The given string in uppercase =RAJ
3). strlen ( )
This function gives the length of the string i.e. the number of characters in a string.
Syntax:
Integer variable=strlen (string name);
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a[30] ;
int b;
printf(“enter the string=\n”);
gets(a);
b= strlen (a);
printf (length of the string = %d”, b);
getch ( );
}
Input:
Enter the string=sai
Output:
Length of the string = 3
Note: “\0” will not be counted as a character.
122
PROGRAMMING FOR PROBLEM SOLVING
4). strcpy ( )
This function is used for copying source string into destination string.
The length of the destination string must be greater than (or) equal to that of the source
string
Syntax:
strcpy (Destination string, Source String);
E.g.:
1) char a[50]; 2) char a[50];
Strcpy (“Hello”,a); strcpy ( a,”hello”);
o/p: error o/p: a= “Hello”
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a[50], b[50]; H E l l o \o
clrscr ( ) ;
printf (“enter a source string”); E l l o \o
gets(a);
strcpy ( b,a);
printf (“copied string =”);
puts(b);
getch ( );
}
Input:
Enter a source string: Hello
Output:
Copied string = Hello
123
PROGRAMMING FOR PROBLEM SOLVING
5) strncpy ( )
This function is used for copying ‘n’ characters of source string into destination string.
The length of the destination string must be greater than (or) equal to that of the source
string.
Syntax:
strncpy (Destination string, Source String, n);
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
a
{
char a[50], b[50]; H E l l o \o
clrscr ( ) ; b
printf (“enter a string”);
gets (a); H E l \o
strncpy (b,a,3);
b[3] = ‘\0’;
printf (“copied string = ”);
puts(b);
getch ( );
}
Input:
Enter a string: Hello
Output:
Copied string = Hel
124
PROGRAMMING FOR PROBLEM SOLVING
6) strcat ( ):
This is used for combining or concatenating two strings.
The length of the destination string must be greater than the source string.
The resultant concatenated string will be in the source string.
Syntax:
strcat (String1, string2);
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a[50], b[20];
clrscr ( );
printf (“enter THE string A=”);
gets (a);
printf (“enter the string B=”);
gets (b);
strcat (a,b);
printf(“concatenated string = %s”, a);
getch ( );
}
Input:
ENTER THE STRING A= Hello
ENTER THE STRING B= GoodMorning
Output:
Concatenated string = HelloGood Morning
125
PROGRAMMING FOR PROBLEM SOLVING
7) strncat ( ):
This is used for combining or concatenating n characters of one string into another.
The length of the destination string must be greater than the source string.
The resultant concatenated string will be in the source string.
Syntax:
strncat (String1, string2,n);
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a [30] = “Hello”;
char b [20] = “Good Morning”;
clrscr ( );
strncat (a,b,4);
a [9] = ‘\0’;
printf(“concatenated string = %s”, a);
getch ( );
}
Output
Concatenated string = HelloGood.
126
PROGRAMMING FOR PROBLEM SOLVING
String comparison
8) strcmp()
This function compares 2 strings
It returns the ASCII difference of the first two non – matching characters in both the
strings.
Syntax:
strcmp (string1, string2);
If the difference is equal to zero string1 = string2
If the difference is positive string1> string2
If the difference is negative string1 <string2
E.g,:
char a[10]= “there”
char b[10] = “their” t h e r e \0
strcmp (a,b);
t h e i \0
Output: ‘r’ > ‘i’
string1 >string2
char a[10]= “their”
char b[10] = “there” t h e i \0
strcmp (a,b);
t h e e \0
Output: string1 <string2
‘i’< ‘r’
char a[10]= “there”
char b[10] = “there”
strcmp (a,b);
Output: t h e e \0
string1 =string2
t h e e \0
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a[50] b [50];
int d;
clrscr( );
printf (“enter 2 strings”);
scanf (“%s %s”, a,b);
d = strcmp (a,b);
if (d==o)
printf(“%s is equal to %s”, a,b);
else if (d>0)
prinft(“%s is greater than %s”,a,b);
else if (d<0)
printf(“%s is less than %s”, a,b);
getch ( );
}
127
PROGRAMMING FOR PROBLEM SOLVING
9. strncmp ( )
This function is used for comparing first ‘n’ characters of 2 strings.
Syntax:
strncmp ( string1, string2, n);
E.g.: char a[10] = “the”;
char b[10] = “there”
strncmp (a,b,3);
Output: Both strings are equal.
10. strrev( )
The function is used for reversing a string.
The reversed string will be stored in the same string
Syntax:
strrev (string);
Program code:
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char a[50] ;
clrscr( );
printf (“enter a string”);
gets (a);
strrev (a);
printf(“reversed string = %s”,a)
getch ( );
}
Input:
enter a string Hello
Output:
Reverstring = olleH
128
PROGRAMMING FOR PROBLEM SOLVING
Arrays of strings
Arrays of pointers: (to strings)
It is an array whose elements are pointers to the base address of the string.
It is declared and initialized as follows
char *a[ ] = {“one”, “two”, “three”};
Here, a[0] is a pointer to the base address of the string “one”.
a[1] is a pointer to the base address of the string “two”.
a[2] is a pointer to the base address of the string “three”.
o n e \0 t w o \0 t h r e e \0
a[0] 1234
a[1] 1238
a[2] 1242
Array of pointers
Advantage:
Unlike the two dimensional array of characters. In (array of strings), in array of pointers
to strings there is no fixed memory size for storage.
The strings occupy only as many bytes as required hence, there is no wastage of space.
Program
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char *a[5] = {“one”, “two”, “three”, “four”, “five”};
int i;
clrscr ( );
printf ( “the strings are”);
for (i=0; i<5; i++)
printf (“%s”, a[i]);
getch ( );
}
Output:
The strings are : one two three four five
129
PROGRAMMING FOR PROBLEM SOLVING
Character operations
Character: it can be a character (A-Z(or) a- z); digit
(0-9), a white space, special symbol
Declaration
char a= ‘A’; using a ouput functions character constant.
Character input / ouput functions
input functions printf ( )
scanf ( ) putchar ( )
getchar ( ) putch ( )
getch ( )
getche ( )
E.g.: char a;
scanf(“%c”, &a); printf (“%c”, &a);
a = getchar ( ); putchar (a);
a = getch ( ); putch (a);
Character analysis and conversion functions
There are some predefined functions available in “ctype.h” library for analyzing the
character input and converting them.
Analysis functions
Function Checks whether entered character is
1. isalpha ( ) An alphabet (or) not
2. isdigit ( ) A digit (or) not
3. isspace ( ) A space, a newline (or) tab
4. ispunct ( ) A special symbol (or) not
5. islower ( ) A lower case letter of alphabet
6. isupper ( ) An upper case letter of alphabet
Converting functions
Function
tolower ( ) Converts an upper case alphabet to lower case
130
PROGRAMMING FOR PROBLEM SOLVING
Program
#include<stdio.h>
#include<conio.h>
#include <ctype.h>
Void main ( )
{
char a = ‘D’;
clrscr ( );
if ( isalpha (a))
printf ( “%c is an alphabet”,a);
else
printf (“%c is not an alphabet”,a);
getch ( );
}
Output:
D is an alphabet
131
PROGRAMMING FOR PROBLEM SOLVING
02 01 2010
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ( )
{
char a[20] = “02 01 2010”;
int day, mon, yr;
clrscr( );
sscanf (a, “%d%d %d”, &day, &mon, &yr);
printf ( “Day =%d”, day);
printf ( “Month = %d”, mon);
printf ( “Year = %d”, yr);
getch ( );
}
Output:
Day = 02
Month = 01
Year = 2010
132
PROGRAMMING FOR PROBLEM SOLVING
o/p
%s
Program 02/01/2010
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ( )
{
char a[50];
int day = 11, mon = 12, yr = 2014;
clrscr( );
sprintf (a, “%d/%d/%d”, day, mon, yr);
printf ( “today’s date =%s”, a);
getch ( );
}
133
PROGRAMMING FOR PROBLEM SOLVING
Long answers:
1. What are type qualifiers? Write a program to find Fibonacci series of a given number
using recursive and non-recursive approaches.
2. What is recursion? Write a C program to find GCD (greatest common devisor) of
two given integers.
3. Differentiate between call by value and call by reference with an example?
4. I) Explain about types of parameters passing mechanisms in C.
5. II) Illustrate command line arguments with example.
6. Explain various categories of function using an example program?
7. What is recursion? Write a C program to find the factorial of a given number using
recursion.
8. Define string? What are string manipulation functions? Explain with example.
9. What is string? Explain string handling functions?
10. Explain various string manipulation function with examples.
Short answers:
1. What is inter function communication.
2. What is Function? What are the types of functions?
3. Distinguish between function prototype and function definition
4. What is recursion? What are its limitations?
5. What are the different storage classes? Write the keywords.
6. What is scope? What are the different types of scope?
7. What are the different types of functions?
8. Distinguish between automatic and static variable.
9. Describe array of strings?
134
PROGRAMMING FOR PROBLEM SOLVING
UNIT IV
135
PROGRAMMING FOR PROBLEM SOLVING
POINTERS
Pointer: Pointer is a variable that stores the address of another variable.
Features of Pointers
❖ Pointer saves the memory space.
❖ Execution time with pointer is faster because data is manipulated with the address
i.e. direct access to memory location.
❖ The memory is accessed efficiently with the pointer i.e. dynamically memory is
allocated and deallocated.
❖ Pointers are used with data structures.
Pointer declaration, initialization and accessing.
Consider the following statement:
value
179
5000 Address
Declaring a pointer:
datatype *pointervariable;
int *p;
It means ‘p’ is a pointer variable that holds the address of another integer variable.
Initialization of a pointer
❖ Address operator (&) is used to initialize a pointer variable.
E.g.: int qty = 175;
int *p; Variable value Address
qty 175 5000
p= &qty;
p 5000 5048
136
PROGRAMMING FOR PROBLEM SOLVING
p = &qty;
n = *p;
#include<stdio.h>
#include<conio.h>
Void main ( )
{
int x;
int *p;
clrscr ( );
x= 10;
p = &x;
printf (“\nValue of x = %d”, x);
printf (“\nx is stored at address %u”, &x);
printf (“\nValue of x using pointer = %d”, *p);
printf (“\naddress of x using pointer = %u”, p);
getch ( );
}
Output:
Value of x = 10
x is stored at address = 5000
value of x using pointer = 10
Address of x using pointer = 5000
137
PROGRAMMING FOR PROBLEM SOLVING
❖ Continuous memory locations are allocated for all the elements of the array by the
compiler
❖ The base address is the location of the first element (index 0) of the array.
E.g.: int a [5] = {10, 20,30,40,50};
The five elements are stored as follows
Elements a[0] a[1] a[2] a[3] a[4]
Value 10 20 30 40 50
Address 1000 1002 1004 1006 1008
base address
a= &a[0]=1000
if ‘p’ is declared as integer pointer, then the array ‘a’ can be pointed by the following
assignment
(P+i) =&( a+i);
(or) p = &a[0];
(or) P=a
❖ Every value of ‘a’ can be accessed by using p++ to move from one element to
another. When a pointer is incremented, its value is increased by the size of the
datatype that it points to. This length is called the “scale factor”
❖ The relationship between ‘p’ and ‘a’ is shown below
P = &a[0] = 1000
P+1 = &a[1] = 1002
P+2 = &a[2] = 1004
P+3 = &a[3] = 1006
P+4 = &a[4] = 1008
❖ Address of an element is calculated using its index and the scale factor of the
datatype.
138
PROGRAMMING FOR PROBLEM SOLVING
For e.g.:
❖ instead of using array indexing, pointers can be used to access array elements.
❖ *(p+3) gives the value of a[3]
*(p+i) = a[i]
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[10],n;
int *p,i;
clrscr ( );
printf(“enter the size of array=\n”);
scanf(“%d”,&n);
printf (”Enter %d elements=”,n);
for (i=0; i<n; i++)
scanf (“%d”, &a[i]);
p = &a[0];
printf (“Elements of the array are”);
for (i=0; i<n; i++)
printf(“%d”, *(p+i));
getch( );
}
Input:
Enter the size of array=5
Enter 5 elements: 10 20 30 40 50
Output:
Elements of the array are: 10 20 30 40 50
139
PROGRAMMING FOR PROBLEM SOLVING
140
PROGRAMMING FOR PROBLEM SOLVING
141
PROGRAMMING FOR PROBLEM SOLVING
Initialization:
‘&’ is used for initialization
E.g.: int a[3] = {10,20,30};
int *p[3], i;
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i];
p[i]= a+i;
a p[0] p[1] p[2]
1236 1238
a[0] a[1] a[2]
10 20 30
1234 1236 1238
p
1234
Accessing
Indirection operator (*) is used for accessing
E.g.: for (i=0, i<3; i++)
printf (”%d”, *p[i]);
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[3] = {10,20,30};
int *p[3],i;
for (i=0; i<3; i++)
p[i] = &a[i];
printf (elements of the array are”)
for (i=0; i<3; i++)
printf (”%d \t”, *p[i]);
getch();
}
Output: elements at the array are: 10 20 30
142
PROGRAMMING FOR PROBLEM SOLVING
Note: returns the no. of elements in between p1 and p2 if both of them point tosame array
h) p1++
i) – – p2
j) sum + = *p2
j) p1 > p2
k) p1 = = p2
l) p1 ! = p2
143
PROGRAMMING FOR PROBLEM SOLVING
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a,b,x,y,z;
int *p1, *p2;
a =12;
b = 4;
p1= &a;
a b x y
p2 = &b; 42
12 4 14
x = *p1 * * p2 – 6; y= 1234 5678 Pointers
4 - *p2 / *p1+10;
printf (“Address of a = %u”, p1);
p1 1234 5678 p2
printf (“Address of b = %u”, p2);
printf (“a= %d b =%d”, a,b);
printf (“x= %d y =%d”, x,y);
}
Output:
Address of a = 1234
Address of b = 5678
a = 12 b= 4
x = 42 y= 14
Pointer to pointer:
❖ Pointer to pointer is a variable that holds the address of another pointer
Declaration:
datatype ** pointer_name;
Eg : int **p; p is a pointer to pointer
Initialization:
‘&’ is used for initialization
E.g.: int a = 10;
144
PROGRAMMING FOR PROBLEM SOLVING
int *p;
a
int **q;
10
p = &a;
q =&p; 1234
P
1234
5000
Accessing:
q
❖ Indirection operator (*) is used for
5000
accessing
Program:
#include<stdio.h>
#include<conio.h>
Void main ( )
{
int a = 10;
int *p;
int **q;
p = &a;
q = &p;
printf(“a =%d”,a);
printf(“a value through pointer = %d”, *p);
printf(“a value through pointer to pointer = %d”, **q);
getch();
}
Output:
a=10
a value through pointer = 10
a value through pointer to pointer = 10
Void pointers: (Generic pointer)
❖ It is a pointer that can hold the address of any datatype variable (or) can point to
any datatype variable.
Declaration
void *pointername;
E.g.: void *vp;
145
PROGRAMMING FOR PROBLEM SOLVING
Accessing
❖ Type cast operator is used for accessing the value of a variable through its pointer.
Syntax:
* ( (type cast) void pointer)
E.g.:
int i=10;
void *vp;
vp = &i;
printf (“%d”, * ((int*) vp));
type cast
Program:
#include<stdio.h>
#include<conio.h>
Void main ( )
{
int i =10;
float f = 5.34;
void *vp;
clrscr ( );
vp = &i;
printf (“i = %d”, * ((int*)vp));
vp = &f;
printf ( “f = %f”, * ((float*) vp));
getch ( );
}
Output:
i = 10
f = 5.34
146
PROGRAMMING FOR PROBLEM SOLVING
#include<stdio.h>
#include<conio.h>
Void main ( )
{
void swap(int,int);
int a,b;
clrscr();
printf(“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping a=%d b=%d”,a,b);
swap(a,b);
getch();
}
void swap(int a,int b)
{
int t; all these statements is equivalent to
t=a; a = (a+b) – (b =a);
a=b; or
b=t;
printf(“after swapping a=%d, b=%d”,a,b);
}
Input:
enter 2 numbers 10 20
Output:
Before swapping a=10 b=20
After swapping a=20 b=10
147
PROGRAMMING FOR PROBLEM SOLVING
#include<stdio.h>
#include<conio.h>
Void main ( )
{
void swap(int *,int *);
int a,b;
clrscr();
printf(“enter 2 numbers”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping a=%d b=%d”,a,b);
swap(&a, &b);
printf(“after swapping a=%d, b=%d”,a,b);
getch();
}
Input:
enter 2 numbers 10 20
Output:
Before swapping a=10 b=20
After swapping a=20 b=10
148
PROGRAMMING FOR PROBLEM SOLVING
Pointer to functions:
❖ It holds the base address of function definition in memory.
Declaration
❖ datatype (*pointername) ( );
❖ The name of the function itself specifies the base address of the function. So,
initialization is done using function name.
❖ E.g.: int (*p) ( );
p = display; if display ( ) is a function that is defined.
Program for calling a function using pointer to function
Program:
#include<stdio.h>
#include<conio.h>
Void main ( )
{
int (*p) ( );
clrscr ( );
p = display;
*(p) ( );
getch ( );
}
display ( )
{
printf(“Hello”);
}
Output:
Hello
149
PROGRAMMING FOR PROBLEM SOLVING
150
PROGRAMMING FOR PROBLEM SOLVING
3. realloc ( ) :
❖ It is used for reallocating already allocated memory.
❖ It can either reduce (or) extend the allocated memory.
❖ It returns a void pointer that points to the base address of reallocated memory.
Syntax:
151
PROGRAMMING FOR PROBLEM SOLVING
arguments
Here, argc = 5
argv[0] = sample.exe argv[3] = are
argv[1] = hello argv[4] = you
argv [2] = how
Program:
#include<stdio.h>
#include<conio.h>
void main ( int argc, char *argv[ ])
{
int i;
clrscr( );
printf (“ no. of arguments given at command prompt = %d”, argc);
printf (“ arguments given at command prompt are \n”);
for ( i =1; i<argc; i++)
printf (”%s\n ”, argv[i]);
getch( );
}
152
PROGRAMMING FOR PROBLEM SOLVING
Output:
Steps:
1) compile the program
2) Run the program
3) Go to command prompt and give the input
c:|> sample.exe hello how are you.
No. of arguments given at command prompt is = 5
arguments given at command prompt are:
hello
How
Are
You
153
PROGRAMMING FOR PROBLEM SOLVING
datatype datamember n;
};
Here, struct - keyword
structurename - specifies name of structure
datamember1, datamember2 -- specifies the data items that make up
structure.
154
PROGRAMMING FOR PROBLEM SOLVING
Eg:
struct book
{
int pages;
char author [30];
float price;
};
object:
an object is used for
(i) accessing all data members of a structure.
(ii)allocating memory for data members of a structure.
Structure variables
There are 3 ways of declaring structure variables
1) struct book
{
int pages;
char author[30];
float price;
}b;
2) struct
Note : Tagname can be ignored if the
{
variable is declared of the time of defining
int pages;
structure
char author[30];
float price;
}b;
3) struct book
{
int pages;
char author[30];
float price;
};
struct book b;
155
PROGRAMMING FOR PROBLEM SOLVING
156
PROGRAMMING FOR PROBLEM SOLVING
clrscr ( );
printf(“ Details of book are”);
printf(“\npages =%d\n author = %s\n price = %f”, b.pages, b.author, b.price);
getch();
}
program code for declare the values in the main program:
#include<stdio.h>
#include<conio.h>
struct book
{
int pages;
char author[30];
float price;
} b;
void main ( )
{
Struct book b={100, “balu”, 325.75};
clrscr ( );
printf(“ Details of book are”);
printf(“\npages =%d\n author = %s\n price = %f”, b.pages, b.author, b.price);
getch();
157
PROGRAMMING FOR PROBLEM SOLVING
158
PROGRAMMING FOR PROBLEM SOLVING
program code:
with the help of keyboard:
#include<stdio.h>
#include<conio.h>
struct book
{
int pages;
char author[30];
float price;
}b;
void main ( )
{
clrscr ( );
printf ( “enter no of pages, author, price of book”);
scanf (“%d%s%f”, &b.pages, b.author, &b.price);
printf(“ Details of book are”);
printf(“\npages =%d\n author = %s\n price = %f”, b.pages, b.author, b.price);
getch();
}
Structure within structure (or) Nested structures:
❖ Creating a structure inside another structure is called nested structure.
❖ Consider the following example
struct emp
{
int eno;
char ename[30];
float sal;
float da;
float hra;
float ea;
}e;
❖ This is structure defines eno, ename, sal and 3 kinds of allowances. All the items
related to allowances can be grouped together and declared under a sub – structure
as shown below.
159
PROGRAMMING FOR PROBLEM SOLVING
stuct emp
{
int eno;
char ename[30];
float sal;
struct allowance
{
float da;
float hra;
float ea;
}a;
}e;
❖ The inner most member in a nested structure can be accessed by changing all the
concerned structure variables (from outer most to inner most) with the member using
dot operator
E.g.:
e.eno; e.ename e.sal;
e.a.da; e.a.hra; e.a.ea;
Program:
#include<stdio.h>
#include<conio.h>
struct emp
{
int eno;
char ename[30];
float sal;
struct allowance
{
float da;
float hra;
float ea;
}a;
}e;
160
PROGRAMMING FOR PROBLEM SOLVING
void main ( )
{
clrscr ( );
printf(“enter eno, ename, salary”);
scanf (“%d%s%f”, &e.eno, e.ename, &e.sal);
printf (“enter da, hra, ea, values”);
scanf (“%f%f%f’’, &e.a.da, &e.a.hra, &e.a.ea);
printf(“employee details are”)
printf (“number = %d”, e.eno);
printf (“name = %s”, e.ename);
printf(“salary = %f”, e.sal);
printf(“Dearness Allowance = %f”, e.a.da);
printf (“House Rent Allowance = %f”, e.a.hra);
printf(“City Allowance = %f”, e.a.ea);
getch ( )
}
Array of structures:
❖ The most common use of structure is array of structures
❖ To declare an array of structures, first the structure must be defined and then an
array variable of that type.
E.g.: struct book b[10]; 10 elements in an array of structures of type ‘book’
Program: for accepting and printing details of 10 students
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[30];
float marks;
};
void main ( )
{
struct student s[10];
int i;
161
PROGRAMMING FOR PROBLEM SOLVING
clrscr ( );
for (i=0; i<10; i++)
{
printf(“enter details of students%d”, i+1);
scanf (“%d%s%f”, & s[i]. sno, s[i]. sname, &s[i].marks);
}
for (i=0; i<10; i++)
{
printf (“the details of student %d are”, i+1);
printf (“Number = %d”, s[i]. sno);
printf (“name = %s”, s[i]. sname);
printf (“marks =%f”, s[i]. marks);
}
getch ( );
}
Pointer to structure:
❖ It holds the address of the entire structure.
❖ Mainly these are used to create complex data structures such as linked lists, trees,
graphs and so on.
❖ The members of the structure can be accessed using a special operator called arrow
operator ( ).
Declaration
struct tagname *ptr;
eg; struct student *s;
Accessing;
ptr→ membername;
E.g.: s→sno, s→sname, s→marks;
162
PROGRAMMING FOR PROBLEM SOLVING
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[30];
float marks;
};
void main ( )
{
struct student s;
struct student *st;
clrscr ( );
printf(“enter sno, sname, marks”);
scanf (“%d%s%f”, & s.sno, s.sname, &s. marks);
st = &s;
printf (“details of the student are”);
printf (“Number = %d”, st →sno);
printf (“name = %s”, st→sname);
printf (“marks =%f”, st →marks);
getch ( );
}
Structure and functions:
❖ There are 3 ways by which the values of structure can be transferred from one
function to another.
1) passing individual members as arguments to function
❖ Each member is passed as an argument in the function call.
❖ They are collected independently in ordinary variables in function header.
163
PROGRAMMING FOR PROBLEM SOLVING
E.g.:
#include<stdio.h>
#include<conio.h>
struct date
{
int day;
int mon;
int yr;
};
void main ( )
{
struct date d= {02,01,2010};
clrscr ( );
display (d.day, d.mon, d.yr);
getch( );
}
display (int a, int b, int c)
{
printf(“day = %d”, a);
printf(“month = %d”,b);
printf(“year = %d”,c);
}
164
PROGRAMMING FOR PROBLEM SOLVING
165
PROGRAMMING FOR PROBLEM SOLVING
Program:
#include<stdio.h>
#include<conio.h>
struct date
{
int day;
int mon;
int yr;
};
Void main ( )
{
struct date d= {02,01,2010};
display (&d);
getch ( );
}
display (struct date *dt)
{
printf(“day = %d”, dt→day);
printf(“month = %d”,dt→mon);
printf(“Year = %d”,dt →yr);
}
Union:
Def: A union is a memory location that is shared by several variables of different data
types.
Syntax:
union unionname
{
datatype datamember 1;
datatype datamember 2;
datatype datmember n;
}objectname;
166
PROGRAMMING FOR PROBLEM SOLVING
E.g.:
union sample
{
int a;
float b;
char c;
};
Declaration of union variable:
1) union sample
{
int a;
float b; 4bytes
char c; s
}s;
a
2) union b
{ c
int a;
float b;
char c;
}s;
3) union sample
{
int a;
float b;
char c;
};
union sample s;
167
PROGRAMMING FOR PROBLEM SOLVING
c=A
168
PROGRAMMING FOR PROBLEM SOLVING
Structure Union
1. Definition 1. Definition
Structure is a heterogenous collection of A union is a memory location that is shared
dataitems grouped together under a single by several variables of different datatypes.
name
2. Syntax:
2. Syntax: union tagname
struct tagname {
{ datatype member1;
datatype member1; datatype member2;
datatype member2;
};
}; 3. E.g.:
3. E.g.: union sample
struct sample {
{ int a;
int a; float b;
float b; char c;
char c; };
}; 4. Keyword: union
4. Keyword: struct 5. Memory allocation
5. Memory allocation
a 2 bytes 4 bytes
b 4 bytes a
c 1 byte b
7 bytes c
6. Memory allocated is the maximum size
6. Memory allocated is the sum of sizes of allocated among all the datatypes in union
all the datatypes in structure
(Here, 7bytes) (Here, 4bytes)
169
PROGRAMMING FOR PROBLEM SOLVING
Union of structures:
• A structure can be nested inside a union and it is called union of structures.
• It is also possible to create a union inside a structure.
Program:
#include<stdio.h>
#include<conio.h>
struct x
{
int a;
float b;
};
union z
{
struct x s;
};
Void main ( )
{
union z u;
clrscr ( );
u.s.a = 10;
u.s.b = 30.5;
printf(“a=%d”, u.s.a);
printf(“b=%f”, u.s.b);
getch ( );
}
Output:
a= 10
b = 30.5
170
PROGRAMMING FOR PROBLEM SOLVING
Typedef;
❖ ‘C’ allows to define new datatype names using the ‘typedef’ keyword.
❖ Using ‘typedef’, user will not actually create a new datatype but define a new
name for an existing type.
Syntax:
typedef datatype newname;
E.g.:
typedef int num; int a;
num a;
❖ This statement tells the compiler to recognize ‘num’ as another name for ‘int’.
❖ ‘num’ is used to create another variable ‘a’ .
❖ ‘num a’ declares ‘a’ as a variable of type ‘int’.
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
typedef int hours;
hours h;
clrscr ( );
printf(“enter hours”);
scanf (“%d”, &h);
printf(“Minutes =%d”, h*60);
printf(“Seconds = %d”, h*60*60);
getch ( );
}
Output: Enter hours =1
Minutes = 60
Seconds = 360
171
PROGRAMMING FOR PROBLEM SOLVING
Void main ( )
{
emp e = {10, “ramu”, 5000};
clrscr( );
printf(“number = %d”, e.eno);
printf(“name = %d”, e.ename);
printf(“salary = %d”, e.sal);
getch ( );
}
172
PROGRAMMING FOR PROBLEM SOLVING
Bit Fields
❖ These are used to change the order of allocation of memory from bytes to bits.
❖ A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length.
❖ There are occasions where data items require much less than 16 bits of space. In
such cases memory will be wasted. Bit fields can pack several data items in a word
of memory.
Syntax:
173
PROGRAMMING FOR PROBLEM SOLVING
2) struct pack
{
unsigned a: 2;
int count;
unsigned b: 3;
};
Here, ‘a’ will be in 1 byte, ‘count’ in 2 bytes and ‘b’ in 1 byte.
Note:
1. Bit Fields are packed into words as they appear in the definition
2. All unsigned bit fields must be placed in order for effectively using the memory.
Program:
#include<stdio.h>
#include<conio.h>
struct vehicle
{
unsigned type: 3; Note: Instead of 6 bytes only 1 byte of memory
unsigned fuel: 2; will be allocated
unsigned model: 3;
};
Void main ( )
{
struct vehicle v;
v.type = 4;
v. fuel = 2;
v. model = 5;
printf (“type of vehicle =%d”, v.type);
printf (“fuel =%d”, v.fuel);
printf (“model =%d”, v.model);
}
174
PROGRAMMING FOR PROBLEM SOLVING
E.g.:
enum week
{
mon, tue, wed, thu, fri, sat, sun
};
• Here, with identifier values are constant unsigned integers and start from 0.
• mon refers 0, tue refers 1 and so on.
• enum identifiers can also be assigned initial value.
Program:
#include<stdio.h>
#include<conio.h>
Void main ( )
{
enum week {mon, tue, wed, thu, fri, sat, sun};
clrscr ( );
printf (“Monday = %d”, mon);
printf (“Thursday = %d”, thu);
printf (“Sunday = %d”, sun);
getch();
}
Output: Monday = 0
Thursday =3
Sunday =6
175
PROGRAMMING FOR PROBLEM SOLVING
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
enum week {mon=1, tue, wed, thu, fri, sat, sun};
clrscr ( );
printf (“Monday = %d”, mon);
printf (“Thursday = %d”, thu);
printf (“Sunday = %d”, sun);
getch();
}
Output: Monday = 1
Thursday =4
Sunday =7
176
PROGRAMMING FOR PROBLEM SOLVING
Long answers:
Write a C program to add two complex numbers (with real part and imaginarypart)
using functions, pointers as arguments and print the result.
9. i) Define structure? Give the syntax and declare the structure?
ii)Write a C program to read and display the student detailsusing structure.
10. Write short notes on (a) Nested structure (b)Self-referential structure.
11. (i) Discuss the difference between a structureand union in C with example.
(ii) Develop a C program that reads two complex numbers, calls a function for adding
these two complex numbers and displays the result. Represent the complex number using a
structure in C.
177
PROGRAMMING FOR PROBLEM SOLVING
Short answers:
#include <stdio.h>
void main( )
{
int i=1, *j, k;
j=&i;
Printf(“%d”, i**j*i+*j);
}
178
PROGRAMMING FOR PROBLEM SOLVING
UNIT-V
179
PROGRAMMING FOR PROBLEM SOLVING
FILES
Definition: I t is collection of records (or) It is a place on hard disk where data is
storedpermanently.
Types of Files: (1) Text file
(2) Binary File
1. Text File: It contains alphabets and numbers which are easily understood by human
beings.
2. Binary file: It contains 1’s and 0’s which are easily understood by computers.
❖ Based on the data that is accessed, files are classified into
(1) Sequential files
(2) Random access files
(1) Sequential files: Data is stored and retained in a sequential manner.
(2) Random access Files: Data is stored and retrieved in a random way.
Operations on files: 1. Naming the file
2. Opening the file
3. Reading from the file
4. Writing into the file
5. Closing the file
Syntax for opening and naming file:
1) FILE *File pointer;
Eg : FILE * fp;
2) File pointer = fopen (“File name”, “mode”);
Eg : fp = fopen (“sample.txt”, “w”);
FILE *fp;
fp = fopen (“sample.txt”, “w”);
181
PROGRAMMING FOR PROBLEM SOLVING
I/O STREAMS:
Stream : flow of data
scanf( )
Keyboard Input stream ‘C’
Program
Monitor Output stream
printf ( )
I/0 functions:
1) high level I/o
182
PROGRAMMING FOR PROBLEM SOLVING
2) fscanf ( )
Syntax : fscanf(file pointer, “control string”, & variable list);
Eg: FILE *fp;
fscanf (fp, “%d%c”, &a,&b);
Program for storing the details of an employee in a file and print the same
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
int eno;
char ename [30];
float sal;
clrscr ( );
fp =fopen (“emp.txt”, “w”);
printf (“enter the details of eno, ename, sal”);
scanf (“%d%s%f”, &eno, ename, &sal);
fprintf (fp, “%d%s%f”, eno, ename, sal);
fclose (fp);
fp = fopen (“emp.txt”, “r”);
fscanf (fp, “%d%s%f”, &eno, ename, &sal);
printf (“employee no: = %d”, eno);
printf (“employee name = %s”, ename);
printf (“salary = %f”, sal);
fclose (fp);
getch( );
}
183
PROGRAMMING FOR PROBLEM SOLVING
Program for storing the details of 60 employers in a file and print the same
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
int eno, i;
char ename [80];
float sal;
clrscr ( );
fp = fopen (“emp1. txt”, “w”);
for (i=1; i<60; i++)
{
printf (“enter the eno, ename, sal of emp%d”, i);
scanf (“%d%s%f”, &eno, ename, &sal);
fprintf (fp, “%d %s %f”, eno, ename, sal);
}
fclose (fp);
fp = fopen (“emp1.txt”, “r”);
for (i=1; i<60; i++)
{
fscanf(fp, “%d %s %f”, &eno, ename, &sal);
printf (“details of employee %d are \n”, i);
printf (“eno = %d, ename = %s, sal = %f”, eno, ename, sal);
}
fclose (fp);
getch ( );
}
putc( ) and getc( ) functions:
1) putc ( ): It is used for writing a character into a file.
Syntax:
putc (char ch, FILE *fp);
E.g.: FILE *fp;
char ch;
putc(ch, fp);
2) get c ( ) : It is used to read a character from file.
184
PROGRAMMING FOR PROBLEM SOLVING
Syntax:
char getc (FILE *fp);
E.g.: FILE *fp;
char ch;
ch = getc(fp);
Program code:
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
char ch;
clrscr ( );
fp = fopen (“characters.txt”, “w”);
printf (“enter text. press ctrl+z at the end”);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp);
}
fclose (fp);
fp =open (“characters. txt”, “r”);
printf (“file content is \n”);
while ((ch = getc (fp))! = EOF)
{
putchar (ch);
}
fclose (fp);
getch ();
}
185
PROGRAMMING FOR PROBLEM SOLVING
Input:
Enter text press ctrl+z at the end.
Hello how r u
^z
Output:
File Content is
Hello How r u
putw ( ) and getw ( ) functions:
1. putw( ): It is used for writing a number into file.
Syntax: putw (int num, FILE *fp);
E.g.: FILE *fp;
int num;
putw(num, fp);
2. getw( ): It is used for reading a number from a file
Syntax:
int getw (FILE *fp);
E.g.: FILE *fp;
int num;
num = getw(fp);
File
Keyboard scanf (“%d”) putw ( )
186
PROGRAMMING FOR PROBLEM SOLVING
187
PROGRAMMING FOR PROBLEM SOLVING
Program for copying the contents of one file into another file
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp1, *fp2;
char ch;
clrscr ( );
fp1 = fopen (“file1.txt”, “w”);
printf (“enter text press ctrl+z at the end”);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp1);
}
fclose (fp1);
fp1 =fopen (“file1. txt”, “r”);
fp2 =fopen (“file2. txt”, “w”);
while ((ch = getc (fp1))! = EOF)
{
putc(ch,fp2);
}
fclose (fp1);
fclose (fp2);
fp2 = fopen (“file2.txt”, “r”);
printf (“File2 contents are”);
while ((ch = getc(fp2))! = EOF)
putchar (ch);
fclose (fp2);
getch ();
}
188
PROGRAMMING FOR PROBLEM SOLVING
fclose (fp);
getch ( );
}
189
PROGRAMMING FOR PROBLEM SOLVING
Program to merge two files into a third file. (The contents of file1, file2 are placed in
file3)
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp1, *fp2, *fp3;
char ch;
clrscr ( );
fp1 = fopen (“file1.txt”, “w”);
printf (“enter text into file1”);
while ((ch = getchar ( ))! = EOF)
{
putc(ch, fp1);
}
fclose (fp1);
fp2 = fopen (“file2.txt”, “r”);
printf (“enter text into file2”);
while ((ch = getchar ( ))! = EOF)
putc(ch, fp2);
fclose (fp2);
fp1 =fopen (“file1. txt”, “r”);
fp2 =fopen (“file2. txt”, “r”);
fp3 =fopen (“file3. txt”, “w”);
while ((ch = getc (fp1))! = EOF)
putc(ch,fp3);
while ((ch = getc (fp2))! = EOF)
putc(ch,fp3);
fclose(fp1);
fclose (fp2);
fclose (fp3);
fp3 = fopen (“file3.tx”, “r”);
printf (“File3 contents is”);
while ((ch = getc(fp3))! = EOF)
purchar (ch);
190
PROGRAMMING FOR PROBLEM SOLVING
fclose (fp3);
getch ();
}
fputc ( ) and fgetc ( ) functions:
1. fputc( ) : It is used for writing a character in to a file .
Syntax:
fputc (char ch, FILE *fp);
E.g.: FILE *fp;
char ch;
fputc (ch,fp);
2. fgetc( ): This is used for reading a character from a file.
Syntax:
fputc (char ch, FILE *fp);
E.g.: FILE *fp;
char ch;
ch = fgetc(fp);
puts ( )
Monitor fgets ( )
191
PROGRAMMING FOR PROBLEM SOLVING
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
char str [30];
int i,n;
clrscr ( );
printf (“enter no of strings”);
scanf (“%d”, & n);
fp = fopen (‘strings.txt”, “w”);
for (i=1; i<=n; i++)
{
printf (”enter string %d”,i);
gets (str);
fputs (str, fp);
}
fclose (fp);
fp = fopen (”strings.txt”, ”r”);
for (i=1; i<=n; i++)
{
fgets (str, 30, fp);
printf (”string %d =”, i);
puts (str);
}
fclose (fp);
getch ( );
}
192
PROGRAMMING FOR PROBLEM SOLVING
193
PROGRAMMING FOR PROBLEM SOLVING
194
PROGRAMMING FOR PROBLEM SOLVING
2) perror ( )
3) feof ( )
1. ferror ( )
It is used for detecting an error while performing read / write operations.
Syntax:
int ferror (file pointer);
E.g.: FILE *fp;
if (ferror (fp))
printf (“error has occurred”);
it returns zero if success and a non- zero otherwise.
2. perror ( )
It is used for printing an error.
Syntax:
perror (string variable);
E.g.: FILE *fp;
char str[30] = ”Error is”;
perror (str);
O/P: Error is: error 0
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
char str[30] = “error is”;
int i = 20;
clrscr ( );
fp = fopen (“sample. txt”, “r”);
if (fp = = NULL)
{
printf (“file doesnot exist”);
}
else
{
195
PROGRAMMING FOR PROBLEM SOLVING
196
PROGRAMMING FOR PROBLEM SOLVING
n = ftell (fp);
Note: ftell ( ) is used for counting the no of characters entered into a file.
197
PROGRAMMING FOR PROBLEM SOLVING
2. rewind ( )
It makes the file pointer move to the beginning of the file.
Syntax: rewind (file pointer);
E.g.: FILE *fp;
rewind (fp);
n = ftell (fp);
printf (“%d”, n);
Output: 0 (always).
3. fseek ( )
It is used to make the file pointer point to a particular location in a file.
Syntax: fseek(file pointer,offset,position);
offset:
➢ The no of positions to be moved while reading or writing.
➢ If can be either negative (or) positive.
Positive - forward direction.
Negative – backward direction.
position:
➢ it can have 3 values.
0 – Beginning of the file
1 – Current position
2 – End of the file
E.g.:
1. fseek (fp,0,2) - fp is moved 0 bytes forward from the end of the file.
2. fseek (fp, 0, 0) – fp is moved 0 bytes forward from beginning of the file
3. fseek (fp, m, 0) – fp is moved m bytes forward from the beginning of the file.
4. fseek (fp, -m, 2) – fp is moved m bytes backward from the end of the file.
Errors:
1. fseek (fp, -m, 0);
2. fseek(fp, +m, 2);
198
PROGRAMMING FOR PROBLEM SOLVING
Write a program for printing some content in to the file and print the following?
1. Number of characters entered into the file.
2. Reverse the characters entered into the file.
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
char ch;
int n;
clrscr ( );
fp = fopen (“reverse. txt”, “w”);
printf (“enter text press ctrl+z of the end”);
while ((ch = getchar( ) ) != EOF)
{
putc (ch, fp);
}
n = ftell (fp);
printf ( “No. of characters entered = %d”, n);
rewind (fp);
n = ftell (fp);
printf (“fp value after rewind = %d”,n);
fclose (fp);
fp = fopen (“reverse.txt”, “r”);
fseek (fp, -1, 2);
printf (“reversed content is”);
do
{
ch = getc(fp);
printf (“%c”, ch);
} while (!fseek (fp, -2, 1);
fclose (fp);
getch ( );
}
199
PROGRAMMING FOR PROBLEM SOLVING
200
PROGRAMMING FOR PROBLEM SOLVING
Searching:
• The searching is a process of finding one or more elements from a dataset.
• Searching may be sequential or sometimes non-sequential.
• In such non-sequential, we need to use sequential searching, otherwise, we can use other techniques to
reduce the complexity.
• Types of Searching discussed in this chapter are:
1. Linear Search
2. Binary Search
Linear Search:
Linear searching technique is the simplest technique. In this technique, the items are searched one by
one. This procedure is also applicable for unsorted data set. Linear search is also known as sequential search. It is
named as linear because its time complexity is of the order of n O(n).
201
PROGRAMMING FOR
PROGRAMMING FOR PROBLEM
PROBLEM SOLVING
SOLVING
#include <stdio.h>
int main()
{
int array[100], search, c, n;
return 0;
}
Input:
Enter number of elements in array
6
Enter 6 integer(s) 2 3 1 4 6 9
Enter a number to search 1
Output:
1 is present at location 3
202
PROGRAMMING FOR PROBLEM SOLVING
Binary Search:
• When the list is sorted, we can use the binary search technique to find items on the list.
• In this procedure, the entire list is divided into two sub-lists.
• If the item is found in the middle position, it returns the location, otherwise jumps to either left or right
sub-list and do the same process again until finding the item or exceeds the range.
Time Complexity: O(1) for the best case. O(log2 n) for average or worst case.
Space Complexity: O(1)
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
first = 0;
last = n - 1;
middle = (first+last)/2;
return 0;
}
203
PROGRAMMING FOR PROBLEM SOLVING
Sorting:
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
Bubble Sort:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements
if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 )
Here, algorithm compares the first two elements, and swaps since 5 > 1
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 )
Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 )
Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ),
Now, since these elements are already in order (8 > 5), algorithm does not
swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 )
Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is
completed. The algorithm needs one whole pass without any swap to know it is
sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
204
PROGRAMMING FOR PROBLEM SOLVING
Time Complexity:
O(n*n) in Worst and Average case, where Worst case occurs when array is reverse sorted.
O(n) in Best case, where Best case occurs when array is already sorted.
#include <stdio.h>
Input:
64, 34, 25, 12, 22, 11, 90
(Given array)
Output:
Sorted array: 11 12 22 25 34 64 90
205
PROGRAMMING FOR PROBLEM SOLVING
Selection Sort:
The selection sort technique sorts an array by repeatedly finding the minimum element (considering
ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray.
Example:
arr[] = 64 25 12 22 11
Time Complexity:
O(n*n) in Worst and Average case, where Worst case occurs when array is reverse sorted.
O(n) in Best case, where Best case occurs when array is already sorted.
206
PROGRAMMING FOR PROBLEM SOLVING
Input:
64, 34, 25, 12, 22, 11, 90
(Given array)
Output:
Sorted array: 11 12 22 25 34 64 90
207
PROGRAMMING FOR PROBLEM SOLVING
Insertion Sort:
Insertion sort is a simple sorting technique that works similar to that of playing cards in hands. The
array is virtually split into sorted part and an unsorted part. Values from the unsorted part are picked and
placed at the correct position in the sorted part.
Example:
Arr[] = 4 3 2 10 12 1 5 6
4 3 2 10 12 1 5 6
4 3 2 10 12 1 5 6
3 4 2 10 12 1 5 6
2 3 4 10 12 1 5 6
2 3 4 10 12 1 5 6
2 3 4 10 12 1 5 6
1 2 3 4 10 12 5 6
1 2 3 4 5 10 12 6
1 2 3 4 5 6 10 12
Time Complexity:
O(n^2) in Worst and Average case, where Worst case occurs when array is reverse sorted.
O(n) in Best case, where Best case occurs when array is already sorted.
208
PROGRAMMING FOR PROBLEM SOLVING
#include <math.h>
#include <stdio.h>
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
Input:
{ 12, 11, 13, 5, 6 }
(Given array)
Output:
Sorted array: 5 6 11 12 13
209
PROGRAMMING FOR PROBLEM SOLVING
Long answers:
1. 1. Explain about file status function? Write a Cprogram which copies one
file into another file.
2. 2. What are command line arguments? Write aC program to copy content
from one file to another file?
3. 3. i) Define a file and its modes.
4. Define file? What are file streams? Discussstate of file, opening and
closing file with a sample C Program.
5. What are the file error handling functionsand give their syntax?
6. (a) Write a C program to display the contents of a file.
210
Short answers:
void main()
{
struct employee
{
unsigned id:8;
unsigned sex:1;
unsigned age:7;
};
struct employee emp1={203, 1, 23};
clrscr();
printf(“%d%d%d”, emp1.id, emp1.sex, emp1.age);
}
6. What is file stream?
7. Write syntax to open a file and to perform append operation.
8. What will be the o/p of the following segment?
#include<stdio.h>
#include<conio.h>
void main()
{
char
s1[]="NewDelhi";
char
s2[]="Bangalore";
clrscr();
strncpy(s1,s2,s3);
printf("%s", s1);
getch();
}
ASSIGNMENT QUESTION
PARERS AND WITH
SOLUTIONS
DS&A ASSIGNMENT QUESTIONS
ASSIGNMENT -1
1. Implement queue ADT using
a. Linked list in C
b. Arrays in C
Answer: This C Program implements queue using linked list. Queue is a particular
kind of abstract data type or collection in which the entities in the collection are kept
in order and the principal (or only) operations on the collection are the addition of
entities to the rear terminal position, known as enqueue, and removal of entities
from the front terminal position, known as dequeue. This makes the queue a First-
In-First-Out (FIFO) data structure. Linked list is a data structure consisting of a
group of nodes which together represent a sequence. Here we need to apply the
application of linkedlist to perform basic operations of queue.
Here is source code of the C Program to implement queue using linked list. The C
program is successfully compiled and run on a Linux system. The program output is
also shown below.
rear = temp;
}
count++;
}
void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
Arrays in C:
A queue data structure can be implemented using one dimensional array. The queue
implemented using array stores only fixed number of data values. The
implementation of queue data structure using array is very simple. Just define a one
dimensional array of specific size and insert or delete the values into that array by
using FIFO (First In First Out) principle with the help of variables 'front' and
'rear'. Initially both 'front' and 'rear' are set to -1. Whenever, we want to insert a new
value into the queue, increment 'rear' value by one and then insert at that position.
Whenever we want to delete a value from the queue, then delete the element which is
at 'front' position and increment 'front' value by one.
In a queue data structure, enQueue() is a function used to insert a new element into
the queue. In a queue, the new element is always inserted at rear position. The
enQueue() function takes one integer value as a parameter and inserts that value
into the queue. We can use the following steps to insert an element into the queue...
Answer:
Binary search tree is a data structure that quickly allows us to maintain a sorted list
of numbers.
It is called a binary tree because each tree node has a maximum of two
children.
It is called a search tree because it can be used to search for the presence of a
number in O(log(n)) time.
The properties that separate a binary search tree from a regular binary tree is
1. All nodes of left subtree are less than the root node
2. All nodes of right subtree are more than the root node
3. Both subtrees of each node are also BSTs i.e. they have the above two
properties
The binary tree on the right isn't a binary search tree because the right subtree of
the node "3" contains a value smaller than it.
There are two basic operations that you can perform on a binary search tree:
Search Operation
The algorithm depends on the property of BST that if each left subtree has values
below root and each right subtree has values above the root.
If the value is below the root, we can say for sure that the value is not in the right
subtree; we need to only search in the left subtree and if the value is above the root,
we can say for sure that the value is not in the left subtree; we need to only search
in the right subtree.
Algorithm:
If root == NULL
return NULL;
If number == root->data
return root->data;
If number < root->data
return search(root->left)
If number > root->data
return search(root->right)
Insert Operation
Algorithm:
If node == NULL
return createNode(data)
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;
Answer:
Brute-force pattern matching:
The brute-force pattern matching algorithm compares the pattern P with the text T
for each possible shift of P relative to T, until either
n a match is found, or
n all placements of the pattern have been tried
Brute-force pattern matching runs in time O(nm)
Example of worst case:
T = aaa ... ah
P = aaah
may occur in images and DNA sequences
unlikely in English text
Algorithm BruteForceMatch(T, P)
Input text T of size n and pattern
P of size m
Output starting index of a
substring of T equal to P or -1 if no such substring exists
for i ← 0 to n - m
{ test shift i of the pattern }
j←0
while j < m ∧ T[i + j] = P[j]
j←j+1
if j = m
return i {match at i}
else
break while loop {mismatch}
return -1 {no match anywhere}
Algorithm KMPMatch(T, P)
F ← failureFunction(P)
i←0
j←0
while i < n
if T[i] = P[j]
if j = m - 1
return i - j { match }
else
i←i+1
j←j+1
else
if j > 0
j ← F[j - 1]
else
i←i+1
return -1 { no match }
Answer:
The process of reshaping a binary tree into a Heap data structure is known as
‘heapify’. A binary tree is a tree data structure that has two child nodes at max. If a
node’s children nodes are ‘heapified’, then only ‘heapify’ process can be applied over
that node. A heap should always be a complete binary tree.
heapify(array)
Root = array[0]
Largest = largest( array[0] , array [2 * 0 + 1]. array[2 * 0 + 2])
if(Root != Largest)
Swap(Root, Largest)
Example of “heapify”:
30(0)
/ \
70(1) 50(2)
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into
smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the
specified value, say pivot, based on which the partition is made and another array holds values greater
than the pivot value.
Quicksort partitions an array and then calls itself recursively twice to sort the two resulting subarrays.
This algorithm is quite efficient for large-sized data sets as its average and worst-case complexity are
O(n2), respectively.
Partition in Quick Sort
Following animated representation explains how to find the pivot value in an array.
The pivot value divides the list into two parts. And recursively, we find the pivot for each sub-lists until
all lists contains only one element.
Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for it,
which is as follows.
PART-A
2.
Data structure where data elements are arranged sequentially or linearly where the elements are
attached to its previous and next adjacent in what is called a linear data structure. In linear
data structure, single level is involved. Therefore, we can traverse all the elements in single run
only. Linear data structures are easy to implement because computer memory is arranged in a
linear way. Its examples are array, stack, queue, linked list, etc.
Data structures where data elements are not arranged sequentially or linearly are called non-
linear data structures. In a non-linear data structure, single level is not involved. Therefore,
we can’t traverse all the elements in single run only. Non-linear data structures are not easy to
implement in comparison to linear data structure. It utilizes computer memory efficiently in
comparison to a linear data structure. Its examples are trees and graphs.
3.
Stack: Stack is a linear data structure which follows a particular order in which the operations are performed. The
order may be LIFO(Last In First Out) or FILO(First In Last Out).
Queue: Queue is a linear structure which follows a particular order in which the operations are performed. The order is
First In First Out (FIFO).
Linked list: Linked list is a linear collection of data elements whose order is not given by their
physical placement in memory. Instead, each element points to the next. It is a data structure
consisting of a collection of nodes which together represent a sequence.
Doubly Linked List: Doubly Linked List is a variation of Linked list in which navigation is possible in
both ways, either forward and backward easily as compared to Single Linked List. Following are the
important terms to understand the concept of doubly linked list.
4.
Array Linked list
A linked list is a collection of objects known as a node
An array is a collection of elements of a
where node consists of two parts, i.e., data and
similar data type.
address.
Array elements store in a contiguous Linked list elements can be stored anywhere in the
memory location. memory or randomly stored.
Array works with a static memory. Here The Linked list works with dynamic memory. Here,
static memory means that the memory size dynamic memory means thatII MID AUGUST 2021
is fixed and cannot be changed at the run the memory size can be changed at the run time
time. according to our requirements.
Array elements are independent of each Linked list elements are dependent on each other. As
other. each node contains the address of the next node so to
access the next node, we need to access its previous
node.
Array takes more time while performing Linked list takes less time while performing any
any operation like insertion, deletion, etc. operation like insertion, deletion, etc.
5.
PART-B
6.a)
#include <bits/stdc++.h>
usingnamespacestd;
structQNode {
intdata;
QNode* next;
QNode(intd)
{
data = d;
next = NULL;
}
};
structQueue {
QNode *front, *rear;
Queue()
{
front = rear = NULL;
}
voidenQueue(intx)
{
// Function to remove
// a key from given queue q
voiddeQueue()
{
// If queue is empty, return NULL.
if(front == NULL)
return;
delete(temp);
}
};
// Driven Program
intmain()
{
Queue q;
q.enQueue(10);
q.enQueue(20);
q.deQueue();
q.deQueue();
q.enQueue(30);
q.enQueue(40);
q.enQueue(50);
q.deQueue();
cout <<"Queue Front : "<< (q.front)->data << endl;
cout <<"Queue Rear : "<< (q.rear)->data;
}
// This code is contributed by rathbhupendra
Output:
Queue Front : 40
Queue Rear : 50
OR
b)
7.a) #include<stdio.h>
#include<conio.h>
#define SIZE 10
void push(int);
void pop();
void display();
clrscr();
while(1){
scanf("%d",&choice);
switch(choice){
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
if(top == SIZE-1)
else{
top++;
stack[top] = value;
printf("\nInsertion success!!!");
}
void pop(){
if(top == -1)
else{
top--;
void display(){
if(top == -1)
printf("\nStack is Empty!!!");
else{
int i;
printf("%d\n",stack[i]);
OR
b)
1) Add ) to postfix expression.
2) Read postfix expression Left to Right until ) encountered
3) If operand is encountered, push it onto Stack
[End If]
4) If operator is encountered, Pop two elements
i) A -> Top element
ii) B-> Next to Top element
iii) Evaluate B operator A
push B operator A onto Stack
5) Set result = pop
6) END
b) #include<stdio.h>
#include<stdlib.h>
void insertbeginning(int);
struct node
{
int data;
struct node *next;
struct node *prev;
};
struct node *head;
void main ()
{
int choice,item;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
insertbeginning(item);
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void insertbeginning(int item)
{
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
}
}
Function to reverse a Doubly Linked List using Stacks
*/
void reverse()
{
stack<int> st;
Node* temp = head;
while (temp != NULL)
{
st.push(temp->data);
temp = temp->next;
}
// added all the elements sequence wise in the
// st
temp = head;
while (temp != NULL) {
temp->data = st.top();
st.pop();
temp = temp->next;
}
Output
Original linked list
10 8 4 2
The reversed Linked List is
2 4 8 10
1.
A graph is a collection of nodes also called vertices which are connected between one another.
Each connection between two vertices is called an edge (sometimes called a branch). Use a directed
graph or an undirected graph, ... Use a weighted graph or an unweighted graph.
#
2. Hashing is the process of converting a given key into another value. A hash function is used to generate the new
value according to a mathematical algorithm ...
Collision resolution techniques
There are two types of collision resolution techniques.
1.Separate chaining (open hashing)
2.Open addressing (closed hashing)
Separate chaining
In this technique, a linked list is created from the slot in which collision has occurred, after which the new key is
inserted into the linked list. This linked list of slots looks like a chain, so it is called separate chaining. It is used more
when we do not know how many keys to insert or delete.
Time complexity
1.Its worst-case complexity for searching is o(n).
2.Its worst-case complexity for deletion is o(n).
Advantages of separate chaining
1.It is easy to implement.
2.The hash table never fills full, so we can add more elements to the chain.
3.It is less sensitive to the function of the hashing.
Disadvantages of separate chaining
1.In this, cache performance of chaining is not good.
2.The memory wastage is too much in this method.
3.It requires more space for element links.
Open addressing
Open addressing is collision-resolution method that is used to control the collision in the hashing table. There is no
key stored outside of the hash table. Therefore, the size of the hash table is always greater than or equal to the
number of keys. It is also called closed hashing.
The following techniques are used in open addressing:
1.Linear probing
2.Quadratic probing
3.Double hashing
Linear probing
In this, when the collision occurs, we perform a linear probe for the next slot, and this probing is performed until an
empty slot is found. In linear probing, the worst time to search for an element is O(table size). The linear probing
gives the best performance of the cache but its problem is clustering. The main advantage of this technique is that it
can be easily calculated.
Disadvantages of linear probing
1.The main problem is clustering.
2.It takes too much time to find an empty slot.
Quadratic probing
In this, when the collision occurs, we probe for i2th slot in ith iteration, and this probing is performed until an empty
slot is found. The cache performance in quadratic probing is lower than the linear probing. Quadratic probing also
reduces the problem of clustering.
Double hashing
In this, you use another hash function, and probe for (i * hash 2(x)) in the ith iteration. It takes longer to determine
two hash functions. The double probing gives the very poor the cache performance, but there has no clustering
problem in it.
Q.4 Write a simple code for add queue and delete queue function.
void addq(element item)
{/* add an item to the queue */}
if(rear == MAX_QUEUE_SIZE-1)
queueFull();
queue[++rear] = item;
}
Q.5 What properties a binary search tree satisfies if it is not empty? Property
1: Each node has exactly one key and the keys in the tree are distinct. Property 2:
The keys (if any) in the left subtree are smaller than the key in the root. Property 3:
The keys (if any) in the right subtree are larger than the key in the root. Property 4:
The left and right subtrees are also binary search trees.
Q.6 How to obtain and construct degree – two tree representation of a tree using the
below diagram.
Figure: Graph
Q.10 Compare sorting techniques with worst case and average case.
Table: Comparison of sorting techniques with worst case and average case
Part – B
Q.11 a) Explain Doubly Linked List with the following operations:
i) Insertion and ii) Deletion
A doubly-linked list is a linked data structure that consists of a set of sequentially linked records
called nodes. Each node contains two fields, called links, that are references to the previous
and to the next node in the sequence of nodes.
A node in a doubly linked list has at least 3 fields, say DATA, LLINK (left link) and RLINK (right
link). A doubly linked list may or may not be circular. A sample doubly linked circular list with 3
nodes is given in figure. Besides these three nodes a special node has been added called a
head node.
i) Insertion
ii) Deletion
Q.11 b) i) Write a program to create two node lists.
The linked representation of any binary tree, we notice that there are more null links than actual
pointers. As we saw before, there are n + 1 null links and 2n total links. A clever way to make
use of these null links has been devised. to replace the null links by pointers, called threads, to
other nodes in the tree.
If the RCHILD(P) is normally equal to zero, we will replace it by a pointer to the node
which would be printed after P when traversing the tree in inorder. A null LCHILD link at
node P is replaced by a pointer to the node which immediately precedes node P in inorder.
Figure 5.10 shows the binary tree of figure 5.3(b) with its new threads drawn in as dotted lines.
The tree T has 9 nodes and 10 null links which have been replaced by threads. If we
traverse T in inorder the nodes will be visited in the order H D I B E A F C G. For
example node E has a predecessor thread which points to B and a successor thread which
points to A.
In the memory representation we must be able to distinguish between threads and
normal pointers. This is done by adding two extra one bit fields LBIT and RBIT.
In figure we see that two threads have been left dangling in LCHILD(H) and
RCHILD(G). In order that we leave no loose threads we will assume a head node for all
threaded binary trees. Then the complete memory representation for the tree of figure 5.10 is
shown in figure 5.11. The tree T is the left subtree of the head node. We assume that an
empty binary tree is represented by its head node as
This assumption will permit easy algorithm design. Now that we have made use of the old null
links we will see that the algorithm for inorder traversal is simplified. First, we observe that for
any node X in a binary tree, if RBIT(X) = 0, then the inorder successor of X is RCHILD(X) by
definition of threads. If RBIT(X) = 1, then the inorder successor of X is obtained by following a
path of left child links from the right child of X until a node with LBIT = 0 is reached.
The algorithm INSUC finds the inorder successor of any node X in a threaded binary tree.
Array Representation:
The figure shows the array representation for both trees of figure a and b. For complete binary
trees such as the one in figure b the representation is ideal, as no space is wasted. For this
skewed tree of figure a, however, less than half the array is utilized. In the worst case a skewed
tree of depth k will require 2k-1 spaces. Of these only k will be used.
Linked Representation:
Insertion and Deletion of nodes from the middle of a tree required the movements of potentially
many nodes to reflect the change in level number of these nodes. These problems can
be overcome easily through the use of linked representations as shown in figure c.
Adjacency matrix
Let G = (V,E) be a graph with n vertices, n 1. The adjacency matrix of G is a 2-
dimensional n n array, say A, with the property that A(i,j) = 1 iff the edge (vi,vj) (<vi,vj>
for a directed graph) is in E(G). A(i,j) = 0 if there is no such edge in G. The adjacency
matrices for the graphs G1, G3 and G4 are shown in figure. The adjacency matrix for an
undirected graph is symmetric as the edge (vi,vj) is in E(G) iff the edge (vj,vi) is
also in E(G). The adjacency matrix for a directed graph need not be symmetric (as is the
case for G3). The space needed to represent a graph using its adjacency matrix is n2 bits.
About half this space can be saved in the case of undirected graphs by storing only the
upper or lower triangle of the matrix.
From the adjacency matrix, one may readily determine if there is an edge connecting any
two vertices i and j. For an undirected graph the degree of any vertex i is its row
sum A(i,j). For a directed graph the row sum is the out-degree while the
column
sum is the in-degree. Suppose we want to answer a nontrivial question about graphs such
as: How many edges are there in G or is G connected. Using adjacency matrices all
algorithms will require at least O(n2) time as n2 - n entries of the matrix (diagonal entries
are zero) have to be examined. When graphs are sparse, i.e., most of the terms in
the adjacency matrix are zero, one would expect that the former questions would be
answerable in significantly less time, say O(e + n) where e is the number of edges in G and
e << n2/2. Such a speed up can be made possible through the use of linked lists in which
only the edges that are in G are represented. This leads to the next representation for
graphs.
Figure: Adjacency matrix for i) G1, ii) G3 and iii) G4
Adjacency list
In this representation the n rows of the adjacency matrix are represented as n linked lists.
There is one list for each vertex in G. The nodes in list i represent the vertices that
are adjacent from vertex i. Each node has at least two fields: VERTEX and LINK.
The VERTEX fields contain the indices of the vertices adjacent to vertex i. The adjacency
lists for G1, G3 and G4 are shown in figure. Each list has a headnode. The headnodes
are sequential providing easy random access to the adjacency list for any particular vertex.
In the case of an undirected graph with n vertices and e edges, this
representation requires n head nodes and 2e list nodes. Each list node has 2 fields. In
terms of the number of bits of storage needed, this count should be multiplied by log n
for the head nodes and log n + log e for the list nodes as it takes O(log m) bits to represent
a number of value m. Often one can sequentially pack the nodes on the adjacency lists and
eliminate the link fields.
Q 14 b) Define Hash functions. Describe four hash functions in Detail.
Hash Functions:
A hash function is any function that can be used to map data of arbitrary size onto
data of a fixed size. The values returned by a hash function are called hash
values, hash codes, digests, or simply hashes. Hash functions are often used in
combination with a hash table, a common data structure used in computer software
for rapid data lookup. Hash functions accelerate table or database lookup by
detecting duplicated records in a large file. One such application is finding similar
stretches in DNA sequences.
i) Division
h(k) = k mod m
Mid-Square hashing is a hashing technique in which unique keys are generated. In this
technique, a seed value is taken and it is squared. Then, some digits from the middle are
extracted. These extracted digits form a number which is taken as the new seed. This
technique can generate keys with high randomness if a big enough seed value is taken.
However, it has a limitation. As the seed is squared, if a 6-digit number is taken, then
the square will have 12-digits. This exceeds the range of int data type. So,
overflow must be taken care of. In case of overflow, use long long int data type or
use string as multiplication if overflow still occurs. The chances of a collision in mid-
square hashing are low, not obsolete. So, in the chances, if a collision occurs, it
is handled using some hash map.
iii)
Folding
Two folding methods are used they
are:
Fold shift
Fold boundary
Fold Shift
In fold shift the key value is divided into parts whose size matches the size of
the required address. Then the left and right parts are shifted and added with the middle
part.
Fold Boundary
In fold boundary the left and right numbers are folded on a fixed boundary between
them and the center number. The two outside values are thus reversed. If the need is to
generate a 5 digit address then make units of 4 digits and add them which will make a
4 or 5 digit address. If the records will be less than 999 then use 1764. If records will be
near to 9999 then use 13221. Fold and achieve expected size of address space. The
loading factor will be 999/1764 = 0.57
This method is particularly useful in the case of a static file where all the keys in the table are
known in advance. Each key is interpreted as a number using some radix r. The same radix
is used for all keys in the table. Using this radix, the digits of each keys are examined. Digits
having the most skewed distributions are deleted. Enough digits are deleted so that the
number of remaining digits is small enough to give an address in the range of the hash table.
Example: The input file has 10 records with keys (26, 5, 37, 1, 61, 11, 59, 15, 48, 19). The
table below gives the status of the file at each call of QSORT. Square brackets are used to
demarcate subfiles yet to be sorted.
R1 R 2 R3 R4 R5 R6 R7 R8 R9 Rl0 m n
[26 5 37 1 61 11 59 15 48 19] 1 10
[11 5 19 1 15] 26 [59 61 48 37] 1 5
[ 1 5] 11 [19 15] 26 [59 61 48 37] 1 2
1 5 11 [19 15] 26 [59 61 48 37] 4 5
1 5 11 15 19 26 [59 61 48 37] 7 10
1 5 11 15 19 26 [48 37] 59 [61] 7 8
1 5 11 15 19 26 37 48 59 [61] 10 10
1 5 11 l5 l9 26 37 48 59 6l
Program:
RESULT ANALYSIS
Assignment Question Papers
Key for Assignment Question
Papers
Key for Mid Question Papers