0% found this document useful (0 votes)
120 views291 pages

PPS Course Fie R18

The document is a course file for the Data Structures & Algorithms subject taught by Ms. Anuradha Boya during the academic year 2020-2021 for I B.Tech II Sem students in CSE/ECE/EEE branches. It includes course objectives, syllabus, course outcomes, mapping of course outcomes with program outcomes, a list of textbooks and reference books, session planner, class timetable, personal timetable, and a student list. The syllabus covers various data structures, algorithms, and their applications.

Uploaded by

lavanya.d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views291 pages

PPS Course Fie R18

The document is a course file for the Data Structures & Algorithms subject taught by Ms. Anuradha Boya during the academic year 2020-2021 for I B.Tech II Sem students in CSE/ECE/EEE branches. It includes course objectives, syllabus, course outcomes, mapping of course outcomes with program outcomes, a list of textbooks and reference books, session planner, class timetable, personal timetable, and a student list. The syllabus covers various data structures, algorithms, and their applications.

Uploaded by

lavanya.d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 291

COURSE FILE

Dept. of Computer Science & Engineering

Subject DATA STRUCTURES & ALGORITHMS

Academic Year 2020-2021


Name of the Faculty Ms ANURADHA BOYA
Department CSE
Year & Branch I B.TECH II SEM CSE/ECE/EEE
INDEX
COURSE FILE
S.No. Topic
1 Course Description
2 Course Objectives
3 Syllabus
4 Course Outcomes
5 CO & PO Mapping
6 List of Books 1. Text books 2. Reference Books
7 Session Planner
8 Class time table
9 Personal time table
10 Students List
11 Course Outcomes Attainment Table
12 Course Material
13 Assignment Question papers
14 Key Scripts of Assignments
15 Mid Question papers
16 Key Scripts of Mid QP
17 Previous End Exam Question papers with Scheme
18 End Semester Results
Course Description
COURSE DESCRIPTION

1. Course Description

Course Title Data Structures & Algorithms


Course code A30503
Regulation R18
Course structure Lectures Tutorials Practical’s Credits
3 1 0 3
Course Coordinatror Ms Anuradha Boya
Team of instructors Ms Anuradha Boya
Course Objectives
COURSE OBJECTIVES

Name of the Faculty : Ms Anuradha Boya


Academic Year: 2020-21
Subject: Data Structures & Algorithms Semester: II
Subject Code: (A30503)

Class & Branch / Specialization: I B.TECH II SEM CSE/ECE/EEE

S.No. Course Objectives


1 Use data structure concepts for realistic problems

2 Identify appropriate data structure for solving computing problems in


respective language
3 Develop algorithms, operations on queues, stacks and Linked Lists
Demonstrate the representation and traversal techniques of graphs and their
4
applications

5
Implement basic operations on binary trees

Signature of Faculty Signature of HOD


Date: Date:
Syllabus
(A30503) DATA STRUCTURES & ALGORITHMS
(Common to ECE, CSE, EEE, IT)

B. Tech (CSE) II Semester L T P C


3 0 0 3

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

Sorting: Quick Sort, Merge Sort, Heap Sort, comparison of techniques.


Pattern Matching Algorithms: Brute-Force Algorithm and Knuth-Morris-Pratt Algorithm.

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

Subject : Data Structures & Algorithms


Subject Code : (A30503)

Class & Branch / Specialization: I B.TECH II SEM CSE/ECE/EEE

S.No. Course Outcomes

Use data structure concepts for realistic problems


CO1
Identify appropriate data structure for solving computing problems in
CO2 respective language
Develop algorithms, operations on queues, stacks and Linked Lists
CO3

Demonstrate the representation and traversal techniques of graphs and their


CO4 applications

CO5 Implement basic operations on binary trees

Signature of Faculty Signature of HOD


Date: Date:
Course outcomes mapping
with PO’s
Description
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P010 PO11 PO12 PS01 PSO2
Use data
structure
CO1 concepts for 3 2 3 - 1 - - - - - - 1
realistic
problems.
3 -
Identify
appropriate
data structure
for solving
computing
CO2 problems in 3 2 3 - 1 - - - - - - 1
respective
language.

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:

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
SESSION PLANNER

Academic Year: 2020-2021


Semester : II R-18
Subject : DATA STRUCTURES & ALGORITHMS SUB CODE: A30503
Faculty Name: Ms ANURADHA BOYA

S.No Subject Books No. of Cumulative No. Delivery Method


Topic Name/ Sub Topic Name Periods of Periods (Black Board/,
PPT/Video ...etc)
UNIT-I

1 Data Structures: Introduction, classification of


T1 1 1 PPT,WB
Data structures
2 ADT and applications T1 1 2 PPT,WB
3 Over view of List and its operations T1 1 3 PPT,WB
4 Linked Lists: Representation in memory,
Operations of Singly Linked List: Traversing, T1 2 5 PPT,WB, VIDEO
Searching
5 Insertion, Deletion and Reverse, T1 2 7 PPT,WB
6 Doubly Linked List and its Operations T1 2 9 PPT,WB, VIDEO
7 Circular Linked Lists and its Operations T1 2 11 PPT,WB, VIDEO
UNIT-II

8 Stacks: Stack ADT and its implementations T1 1 12 PPT,WB,VIDEO


9 Applications of Stacks: Infix to Postfix
T1 1 13 PPT,WB
Conversion
10 Postfix evaluation – Corresponding algorithms. T1 1 14 PPT,WB
11 Queues: Queue ADT and its implementations,
T1 1 15 PPT,WB,VIDEO
Types of Queue: Simple Queue & Operations
12 Circular Queue & Operations T1 1 16 PPT,WB
13 Priority Queue & Operations T1 1 17 PPT,WB
UNIT-III

Trees: Basic Tree Terminologies,


14 T1 1 18 PPT,WB
Representations
types of Binary Trees: Threaded Binary Tree
15 T1 2 20 PPT,WB,VIDEO
and operations: Insertion Deletion, Traversal
Binary Search Tree and operations: Insertion
16 T1 2 22 PPT,WB,VIDEO
Deletion, Traversal
AVL Tree and operations: Insertion Deletion,
17 T1 2 24
Traversal PPT,WB,VIDEO
UNIT-IV

18 Graphs: Basic Terminologies, Representations


T1 & T2 1 25
PPT,WB,VIDEO
19 Graph traversal algorithms: BFS T1 & T2 1 26 PPT,WB,VIDEO
20 DFS T1 & T2 1 27 PPT,WB,VIDEO
21 Dictionaries: Dictionary as a linear list and its
T1 & T2 2 29 PPT,WB,VIDEO
operations-Insertion, Deletion, Searching
22 Hash tables, Hash Functions T1 & T2 1 30 PPT,WB,VIDEO
23 Collision Resolution Techniques-Linear Probing T1 & T2 1 31 PPT,WB,VIDEO
24 Quadratic Probing T1 & T2 1 32 PPT,WB,VIDEO
25 Double Hashing T1 & T2 1 33 PPT,WB,VIDEO
UNIT-V

26 Sorting: Quick Sort T1 & T2 2 35 PPT,WB,VIDEO


27 Merge Sort T1 & T2 1 36 PPT,WB,VIDEO
28 Heap Sort, comparison of techniques T1 & T2 1 37 PPT,WB,VIDEO
29 Pattern Matching Algorithms: Brute-Force
T1 & T2 2 39 PPT,WB,VIDEO
Algorithm
30 Knuth-Morris-Pratt Algorithm T1 & T2 2 41 PPT,WB,VIDEO
Class Time Table
CMR COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
KANDLAKOYA, MEDCHAL ROAD, HYDERABAD

DEPARTMENT OF HUMANITIES & SCIENCES

TIME TABLE

CLASS: I B.TECH (II SEM) A.Y: 2020-21

BRANCH: CSE A Room No: 201

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

SUBJECT FACULTY NAME

Ordinary Differential Equations and Multivariable Calculus Mr.Naresh


AppliedPhysics(EP) Dr.Soma Mukhopadhyay

Data Structures & Alogorithms Ms Anuradha Boya


Engineering Drawing Mr Santosh Kulkarni
Data Structures & Algorithms(DS&A) Ms Anuradha Boya
Engineering Drawing Practice Mr Santosh Kulkarni IOT
Ms B Archana / Mr Karthik
Applied Physics Lab (AP) Dr Soma Mukhopadyay

COORDINATOR: Mr.Naresh

I/C TT HOD PRINCIPAL


CMR COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
KANDLAKOYA, MEDCHAL ROAD, HYDERABAD

DEPARTMENT OF HUMANITIES & SCIENCES

TIME TABLE

CLASS : I B.TECH (II SEM) A.Y : 2020-21

BRANCH : CSE B Room N : 203


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 ED DS&A EEP SPORTS
L
TUE EEP ED AP AP LAB
U
WED DS&A ED LIB EDP
N
THU ED DS&A ODE IOT LAB
C
FRI ODE AP DS&A DS&A LAB
H
SAT ED DS&A AP ODE EDP AP

SUBJECT FACULTY NAME

Ordinary Differential Equations and Multivariable Calculus Mr.Naresh


AppliedPhysics(AP) Dr.Soma Mukhopadhyay

Data Structures & Alogorithms Ms Anuradha Boya


Engineering Drawing Mr Santosh Kulkarni
Data Structures & Algorithms(DS&A) Mrs.R.Suhasini
Engineering Drawing Practice Mr Santosh Kulkarni IOT
Ms B Archana / Mr Karthik
Applied Physics Lab (AP) Dr Soma Mukhopadyay

COORDINATOR: Dr Soma Mukhopadhyay

I/C TT HOD PRINCIPAL


Personal Time Table
CMR COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
KANDLAKOYA, MEDCHAL ROAD, HYDERABAD

DEPARTMENT OF HUMANITIES & SCIENCES

TIME TABLE

Course I B.TECH SEM-II A.Y : 2020-21

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

111 19H51A05B1 SINGARAM RAKESH KUMAR CSE S07

112 19H51A05B2 JATHOTH CHANDRA SHEKHAR NAYAK CSE S07

113 19H51A05B3 JAVVAJI NIKHIL CSE S07


114 19H51A05B4 KANNEMONI BHARATH YADAV CSE S07
KOLKAR MAHAMMED MUSADDIQ
115 19H51A05B5 PATEL CSE S07
MEKALA CSE S07
116 19H51A05B6 PRABHATHVISHNUVARDHAN
117 19H51A05B7 PATHA ARPITHA CSE S07

118 19H51A05B8 PEECHARA VAMSHIDHAR GOUD CSE S07

119 19H51A05B9 RAYINI ABHINAV CSE S07

120 19H51A05C0 SEEPATHI RAVEENA CSE S07

121 19H51A05C1 SINGHIWAR RAHUL KUMAVATH CSE S07

122 19H51A05C2 THAMMARASI SAI KRISHNA CSE S07

123 19H51A05C3 VOJJALA RASAGNYA CSE S07

124 19H51A05C4 ASMAT MANAL CSE S07

125 19H51A05C5 BANDIKALLA PRATHAP RAJU CSE S07

126 19H51A05C7 BATTU SRINATH CSE S07

127 19H51A05C8 BONTHA HEMANTH CSE S07

128 19H51A05C9 GATTU SAI SHASHANK GOUD CSE S07

129 19H51A05D0 NATHANI HARIKA RATNA CSE S07

130 19H51A05D1 PATHAKOTHI SATHVIKA CSE S07

131 19H51A05D2 POTHULA UDAY SRI CSE S07

132 19H51A05D3 POTURAJU SAHI SATHVIK CSE S07

133 19H51A05D4 CHEKURI NITIN PRAVEEN CSE S07

134 19H51A05D5 CHINNAM MUKUND CSE S07

135 19H51A05D6 VANCHA LAXMI SHIVANI CSE S07

136 19H51A05D7 BHEEMANATHUNI MANIKANTH CSE S07


CSE S08
137 19H51A05D8 CHETTI THANMAY RAM
CSE S08
138 19H51A05D9 JANAMPALLY MAMATHA
CSE S08
139 19H51A05E0 KOMIRE RAJASHEKAR
CSE S08
140 19H51A05E1 NANDIGAMA BHAVANI
CSE S08
141 19H51A05E2 Sai Supriya CH
CSE S08
142 19H51A05E3 TANISHA GARG
CSE S08
143 19H51A05E4 B SWATHI
CSE S08
144 19H51A05E5 BADAVATH THIRUPATHI
CSE S08
145 19H51A05E6 BANDA AKHIL
CSE S08
146 19H51A05E7 BOTLA PAVAN KUMAR
CSE S08
147 19H51A05E8 DHATRIKA GOUTAM
CSE S08
148 19H51A05E9 DIANA GANDHAM
CSE S08
149 19H51A05F0 JAKKA SAMPATH KUMAR REDDY
CSE S08
150 19H51A05F1 JANGILI VINAY
CSE S08
151 19H51A05F2 KANDULA RACHANA
CSE S08
152 19H51A05F3 KUNTA KARTHIK REDDY
CSE S08
153 19H51A05F4 MARRI SRIKAR REDDY
CSE S08
154 19H51A05F5 ORA ALEKHYA
CSE S08
155 19H51A05F6 PUSULURU SRAVANTHI
CSE S08
156 19H51A05F7 TUMMA PRANAY
CSE S08
157 19H51A05F8 AKSHARA PC
CSE S08
158 19H51A05F9 GATTU SUHASINI
CSE S08
159 19H51A05G0 GUNDU RITHINDATTA
CSE S08
160 19H51A05G1 KANDUKALA VAMSHI KRISHNA
CSE S08
161 19H51A05G2 KOTHAKOTA ROHITH REDDY
CSE S08
162 19H51A05G3 MANTHENA PRASOONA
CSE S08
163 19H51A05G4 PATLOLLA RAGHUVEERA REDDY
CSE S09
164 19H51A05G5 RAMAVATH MUKUND SAI
CSE S09
165 19H51A05G6 YELAGANDULA PAVAN KUMAR
CSE S09
166 19H51A05G7 AITHA AKSHITH
CSE S09
167 19H51A05G8 ALETI AKSHAYA REDDY
CSE S09
168 19H51A05G9 JALA AJAY KUMAR YADAV
CSE S09
169 19H51A05H0 KARUMANCHI RAVITEJA
CSE S09
170 19H51A05H1 KUNA BHARATH RAJ
CSE S09
171 19H51A05H2 LIMBAYYAGARI UPENDRA REDDY
CSE S09
172 19H51A05H3 LODIGA SANDHYA LAVANYA
CSE S09
173 19H51A05H4 MOGUSARI HARSHITHA
CSE S09
NALLANDHIGHAL SRINIVAS
174 19H51A05H5 BHARADWAJ
CSE S09
175 19H51A05H6 PREM KUMAWAT
CSE S09
176 19H51A05H7 SUNKARA DATHU NAGA SAI
CSE S09
177 19H51A05H8 VADLAMUDI VAISHNAVI
CSE S09
178 19H51A05H9 C JOSHNA
CSE S09
179 19H51A05J0 GONUGOPPULA ARCHITH KUMAR
CSE S09
180 19H51A05J1 MOHD IFTEQUARUDDIN
CSE S09
181 19H51A05J2 POLUMURI DEEPTHI
CSE S09
182 19H51A05J3 VIDUSHEE GOURYSHETTY
CSE S09
183 19H51A05J4 AKINAPALLI ANIRUDH
CSE S09
184 19H51A05J5 BURRI VENKATA PRANAY
CSE S09
185 19H51A05J6 GOURANI BHARATHWAJ
CSE S09
186 19H51A05J7 GUDURI SURYA TEJA
CSE S09
187 19H51A05J8 K.KRISHNA PRASAD
CSE S09
188 19H51A05J9 KOBAGAPU VARAHALA SAI
CSE S09
189 19H51A05K0 KOMIRINENI SREEJA
CSE S09
190 19H51A05K1 MIRYALA SATHVIKA
CSE S10
191 19H51A05K2 PANNALA UJWAL REDDY
CSE S10
192 19H51A05K3 AMAN HIRANI
CSE S10
193 19H51A05K4 ANUGAM YUVA RAJU
CSE S10
194 19H51A05K5 ANUSHKA RATHORE
CSE S10
195 19H51A05K6 BOKKA SAI CHAITANYA
CSE S10
196 19H51A05K7 KURMACHALAM ADITHYA
CSE S10
197 19H51A05K8 LALAPNUR BHAGYA SRI
CSE S10
198 19H51A05K9 SAI SUJITH MAVRAM
CSE S10
199 19H51A05L0 BAJINKI MUKESH SRI DURGA
CSE S10
200 19H51A05L1 JADHAV HARSHAVARDHAN
CSE S10
201 19H51A05L2 MONDI KARTHIK YADAV
CSE S10
202 19H51A05L3 NAGIDI PRANAY KUMAR REDDY
CSE S10
203 19H51A05L4 RACHAKONDA ABHIRAM
CSE S10
204 19H51A05L5 YADHA AKHILA
CSE S10
205 19H51A05L6 K AKSHITHA
CSE S10
206 19H51A05L7 UDURUKOTA AKHILA
CSE S10
207 19H51A05L8 YERRAVALLI SAI DEEPAK REDDY
CSE S10
208 19H51A05L9 DUPPALA KEERTHI
CSE S10
209 19H51A05M0 ETTIREDDY SANJUPRIYA
CSE S10
210 19H51A05M1 LAKAVATH ROJA BAI
CSE S10
211 19H51A05M2 SNIGDHA BANDARI
CSE S10
212 19H51A05M3 AMOGH PEECHU
CSE S10
213 19H51A05M4 ALETI ROHAN REDDY
CSE S10
214 19H51A05M5 BYAGARI PRAVEEN KUMAR
CSE S10
215 19H51A05M6 GANGINENI CHINMAY CHIDWI
CSE S10
216 19H51A05M7 KODIGOOTI ARJUN
CSE S10
217 19H51A05M8 LAVANGA VENKATA SAI HRITHIK
CSE S11
MEDISETTI BHAVESH BHAVANI
218 19H51A05M9 SAINATH
CSE S11
219 19H51A05N0 NIKHILA THUMMA
CSE S11
220 19H51A05N1 S JOSPHINE
CSE S11
221 19H51A05N2 DISHA SAINI
CSE S11
222 19H51A05N3 KURAGAYALA SUDHEER
CSE S11
223 19H51A05N4 MOHD ALTAF
CSE S11
224 19H51A05N5 SUNKISHALA MOULIKA
CSE S11
225 19H51A05N6 ALAMURI KAVYA
CSE S11
226 19H51A05N7 ANASARAM AJAY
CSE S11
227 19H51A05N8 BETHI DEEPAK
CSE S11
228 19H51A05N9 LALITH SREEKHAR REDDY C
CSE S11
229 19H51A05P0 RUDRAIAH GARI ROHITH REDDY
CSE S11
230 19H51A05P1 SHAGUFTA SIMRAN
CSE S11
231 19H51A05P2 AKULA HARITH SAI
CSE S11
232 19H51A05P3 ANUDEEP MAREPALLY
CSE S11
233 19H51A05P4 GUNTI SRAVANI
CSE S11
234 19H51A05P5 MANDA LAKSHMI GANESH REDDY
CSE S11
235 19H51A05P6 PRATHAMESH PATASKAR
CSE S11
236 19H51A05P7 BELIGERI BHAVANI
CSE S11
237 19H51A05P8 INTURI SUMANTH
CSE S11
238 19H51A05P9 DUBBAKA VISHESH
CSE S11
239 19H51A05Q1 KATTA JAI SANTHOSH BABU
CSE S11
240 19H51A05Q2 KUTHATI LOHITHA
Course Outcomes
Attainment
CMR COLLEGE OF ENGINEERING & TECHNOLOGY
(UGC AUTONOMOUS)
KANDLAKOYA, MEDCHAL ROAD, HYDERABAD-501 401
ASSESSMENT OF PROGRAMME OUTCOMES & PROGRAMME SPECIFIC OUTCOMES

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 External marks + 30% of Internal marks)

Description CO1 C02 C03 CO4 CO5

External Examinations Attainment 3.00 3.00 2.00 3.00 3.00

Internal Examinations Attainment 3.00 3.00 3.00 3.00 3.00

70% of External Examinations Attainment 2.10 2.10 1.40 2.10 2.10

30% of Internal Examinations 0.90 0.90 0.90 0.90 0.90

Final Attainment (70% of Ext + 30% of Int) 3.00 3.00 3.00 3.00 3.00

ATTAINMENT OF POs & PSOs THROUGH THE COURSE OUTCOMES

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 -

Attainment 3.00 3.00 3.00 - 3.00 - - - - - - 3.00 3.00 -

(Course Coordinator) (Programme Coordinator)


COURSE MATERIAL
Lecture Notes

A.Y:2020-21
SEM: II

Unit No. DATA STRUCTURES & ALGORITHMS Notes Links


Unit -1 https://drive.google.com/open?id=1v9sRp-3ltmBpF9lsl_VD7p-Q0_TKQlj_
Unit-2 https://drive.google.com/open?id=1Sb_MupDr9Qv_nQKDEsb6hARAjQeM4
Cwj
Unit- 3 https://drive.google.com/open?id=1Di1FxyRUVxeAVEP0v9HEDzbC5iwnzrd
3
Unit- 4 https://drive.google.com/open?id=1hGPvFCc7St80T0aBICTfe7Cx9StfLAZU
Unit- 5 https://drive.google.com/open?id=1I_JkPI2HO7KNhM5ipxysEaUSvU406hN
d
YouTube https://nptel.ac.in/courses/106102064/
link
Topics covered beyond
syllabus / Additional Topics
ADDITIONAL TOPICS BEYOND THE SYLLABUS

1. Implement the Priority Queue using Heap.


2. Implementation of Merge sort
3. Implementation of Reversing a node of a Linked List.
4. Implement B Tree operations.
5. Implement B+ Tree operations.
PROGRAMMING FOR PROBLEM SOLVING

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

Computer Programming is dedicated to writing, testing, and maintaining programs


that computers follow to perform their functions. To create programs that control the
behavior of a machine, we need programming languages. This book enables students
to master the necessary skills for computer programming with the C language.

C PROGRAMMING LANGUAGE

C is a general-purpose structured programming language that is powerful, efficient,


and compact. C combines the features of high-level language with the elements of
the assembler and is thus close to both man and machine. The growth of C during the
last few years has been phenomenal. It has emerged as the language of choice for
most applications due to the speed, portability, and compactness of code. It has now
been implemented on virtually every sort of computer, from micro to mainframe.

HOW IS THE BOOK ORGANIZED?

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

(A30501) PROGRAMMING FOR PROBLEM SOLVING


(Common to all branches)
B. Tech (CSE) I Semester L T P C
3 0 0 3
UNIT –I
Introductory Concepts: Introduction to Computers, Computer Characteristics, Modes of Operation, Types of Programming Languages.
Idea of Algorithm: Steps to solve logical and numerical problems.
Representation of Algorithm: Flowchart/ Pseudo code with examples.
Algorithms to programs: Source code, variables (with data types), variables and memory locations, Syntax and Logical Errors in compilation, object
and executable code
Introduction to C: Some Simple C Programs, Desirable Program Characteristics
C Fundamentals: The C Character Set, Identifiers and Keywords, Data Types, Constants Variables and Arrays Declarations, Expressions, Statements,
Symbolic Constants.
Preparing and Running a Complete C Program: Planning a C Program, writing a C Program, Entering the Program into the Computer, Compiling and
Executing the Program, Error Diagnostics, Debugging Techniques.
Operators and Expressions: Unary Operators, Arithmetic Operators, Relational and Logical Operators, Bitwise Operators, Conditional Operator,
Assignment Operators, Special Operators, Precedence & Associativity of Operators, Evaluation of Expressions.
Data Input and Output: Preliminaries, Single Character Input- The getchar Function, Single Character Output- The putchar Function, Entering Input
Data- The scanf Function, More About the scanf Function, Writing Output Data- The printf Function, More About the printf Function, the gets and
puts Functions.
UNIT –II
Control Statements: Preliminaries, branching: The if-else Statements, looping: The while Statement, the do while Statement, the for Statement,
Nested Control Structures, the switch Statement, the break Statement, the continue Statement, the goto Statement.
Arrays: Defining an Array, Processing an Array, Multidimensional Arrays.
UNIT –III
Functions: A Brief Overview, defining a Function, accessing a Function, Function Prototypes, Passing Arguments to a Function, Recursion, Passing
Arrays to Functions.
Program Structure: Storage Classes- Automatic Variables, External Variables, Static Variables and Register Variables, Multi files Programs, More
about Library Functions.
Strings: String Handling Functions, Sample C Programs without using library functions.
UNIT –IV
Pointers: Fundamentals Pointer Declarations, Passing Pointers to Functions, Pointers and One-Dimensional Arrays, Dynamic Memory Allocation,
Operations on Pointers, Pointers and Multidimensional Arrays, Arrays of Pointers, Passing Functions to other Functions, More about Pointer
Declarations.
Structures and Unions: Defining a Structure, processing a Structure, User Defined Data Types- typedef & Enumerations, Structures and Pointers,
Passing Structures to Functions, Bit fields, Self-Referential Structures and Unions.
UNIT –V
Data Files: Opening and Closing a Data File, creating a Data File, Processing a Data File, Unformatted Data Files and Command Line Parameters.
Searching and Sorting: Linear and Binary Search, Bubble Sort, Selection Sort and Insertion Sort.
Text Books
1. Byron Gottfried, Schaum’s Outline series, “Programming with C”, McGrawHill
2. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage Learning, (3rd Edition)
Reference Books:
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of India.
2. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression).
3. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
4. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition.
Course Outcomes
The student shall be able
1. Write algorithms and to draw flowcharts for solving problems.
2. Convert the algorithms/flowcharts to C programs.
3. Code and test a given logic in C programming language.
4. Decompose a problem into functions and to develop modular reusable code.
5. Write C programs using arrays, pointers, strings and structures and perform searching and sorting the data.

2
PROGRAMMING FOR PROBLEM SOLVING

COURSE CONTENTS

UNIT No. & Topic Page No.


UNIT -I
Introductory Concepts 5 – 18
Representation of Algorithm 19 – 20
Flowchart 20 - 22
Introduction to C 23 – 50
LAQ 51
SAQ 52

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

ELEMENTS OF COMPUTER PROCESSING


Computer:
It is a high- s p e e d electronic device that accepts and stores input data and
instructions,processes the data and produces the desired output.

Input Output
(raw data / Instructions) (Information i.e. processed)
data)

* It is made up of 2 major components

* They are: 1) Hardware


2) Software

1. Computer Hardware:

❖ These are the physical components of a computer


❖ It consists of 5 Parts
1) Input Devices 4) Primary Storage
2) Output Devices 5) Secondary Storage
3) CPU
Block diagram of a computer

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

➢ Computer software is divided into 2 categories


1) System Software
2) Application Software

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

General purpose software


➢ These are purchased from software developers
➢ They can be used for more than one application
➢ E.g.: word processors, DBMS etc.,
Application Specific Software
➢ It can be used only for intended purpose i.e., for which they were designed
➢ E.g.: Accounting system, hospital management system, banking system. Etc.

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

Fig: personal computing environment


➢ Disadvantage

Much of the CPU time is wasted


2) Time- Sharing environment
➢ For effective usage of CPU time, many users are connected to one (or) more
computer to form a time- sharing environment.
➢ There will be a central computer which performs the following:
- controls the shared resources
- manages shared data & printing
- does the computing

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

Fig: Client-server environment


4) Distributed computing environment
➢ It provides integration of computing functions between different servers and
clients
➢ “Internet” provides connectivity to different servers throughout the world.
➢ It provides
-- reliable
-- scalable
-- highly available network

Fig: Distributed computing environment

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

Assembly language program Assembler Machine Language code

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

➢ Compiler converts entire statements in the program at a time.


➢ Interpreter converts one statement at a time.

SOFTWARE DEVELOPMENT LIFE CYCLE(SDLC)


➢ Software is a collection of programs
➢ Programming is a problem-solving task/activity
➢ Programmers use the software development method for solving problems
➢ It consists of the following 6 phases
1) Requirements
2) Analysis
3) Design
4) Coding
5) Testing
6) Maintenance

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

➢ This is called the ‘waterfall’ model Maintenance

➢ It is necessary to go back to the previous phase to rework it


Applying The Software Development Method
1) Problem requirement
➢ Finding the roots of a quadratic equation, ax2+bx+c
➢ There will be 2 roots for such a quadratic equation
2) Analysis
Input : a,b,c values
Output: r1, r2 values

−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

Print r1, r2 values

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

printf (“enter a,b,c values”);


scanf (“ %f %f %f”, &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 (“\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’

➢ Pseudocode is an informal high-level description of the operating principle ofa


computer program or other algorithm.
➢ It is intended for human reading rather than machine reading.
➢ Pseudocode typically omits details that are not essential for human understanding of
the algorithm, such as variable declarations, system-specific code and some
subroutines.
➢ The purpose of using pseudocode is that it is easier for people to understand than
conventional programming language code.

19
PROGRAMMING FOR PROBLEM SOLVING

➢ It is an efficient and environment-independent description of the key principles of


an algorithm.
➢ It is commonly used in textbooks and scientific publications that are documenting
various algorithms.
➢ No standard syntax for pseudocode.
➢ Pseudocode is not an executable program.

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.

➢ It is the best way of representing the sequence of steps in an algorithm.

➢ It gives a clear idea about the problem.

➢ Various symbols are used for representing different operations.

➢ Arrows are used for connecting the symbols and show the flow of execution.

20
PROGRAMMING FOR PROBLEM SOLVING

Symbols used in flowchart:

Name Symbol Purpose


Terminal Start /stop/begin/end

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

Double sided rectangle


Page connector Used to connect flowchart
in 2 different pages

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

Compute sum a+b+c

Compute avg sum/3

Print sum & avg values

Stop

22
PROGRAMMING FOR PROBLEM SOLVING

INTRODUCTION TO ‘C’ LANGUAGE


❖ ‘C’ is a high–level programming language developed in 1972 by Dennis Ritchie
at AT & T Bell Laboratories.
❖ It was primarily developed for system programming i.e. for designing operating
systems, compilers, etc.
Importance of ’C’ Language
1. It is a robust language, whose rich set of built-in functions and operations can be used
to write any complex program.
2. It is a middle-level language because the ‘C’ compiler combines the capabilities of an
assembly language with the features of a high-level language and therefore it is well suited
for writing both system software and business packages.
3. ‘C’ Programs are efficient and fast.
4. C is highly portable, that is ‘C’ programs written on one computer can be run on another
with little (or) no modification.
5. ‘C’ Language is well suited for structured programming, thus requiring the user to
think of a problem in terms of function modules (or) blocks.
6. ‘C’ program has the ability to extend itself.
➢ It was named ‘C’ because it is an offspring of BCPL (Basic Combined Programming
Language) which was popularly called ‘B’ language.
Structure (or General form) of a ‘C’ program
/* documentation section */
preprocessor directives
global declaration
main ( )
{
local declaration
executable statements
}
returntype function name (argument list)
{
local declaration
executable statements
}

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.

Identifiers,Constants,Variables & Data types


‘C’ Character set
Character set are the set of alphabets, letters and some special characters that are valid
in the C language.
Alphabets:
Uppercase: A B C ....................................... X Y Z
Lowercase: a b c..........................................x y z
Digits:
0123456 89

Special Characters:
Some of the special characters in ‘C’ are:

25
PROGRAMMING FOR PROBLEM SOLVING

, ; $ “ : /
? < > # ~ `

White space Characters:


blank space, new line, horizontal tab, carriage return and form feed
Keywords:
Keywords are the reserved words used in programming. Each keyword has a
fixed meaning and cannot be changed by the user. For example:
C programming is case sensitive, all keywords must be written in lowercase. Here is the
list of all keywords predefined by ANSI ‘C’.

Keywords in C Language

Auto double Int struct

Break else Long switch

Case enum Register typedef

Char extern Return union

Const for Signed unsigned

Continue float Static void

Do goto Sizeof volatile

Default if Short While

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.

5) White space is not allowed.


Note: In C programming , you have to declare the variable before using it in the
program.
Constants
Constants are the terms that can't be changed during the execution of a program.
For example : 1, 2.5, "Programming is easy." etc. In C,
Constants can be classified as:
➢ Integer constants
Integer constants are the numeric constants (constant associated with a number) without
anyfractional part or exponential part. There are three types of integer constants in C
language: decimal constant (base 10), octal constant (base 8) and hexadecimal constant
(base 16).
Decimal digits: 0 1 2 3 4 5 6 7 8 9
Octal digits: 0 1 2 3 4 5 6 7
27
PROGRAMMING FOR PROBLEM SOLVING

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

\' Single quotation mark

\" Double quotation mark

\? 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

Signed Unsigned signed char

int unsigned int unsigned char


short int unsigned short int
long int unsigned long int

Floating point type


float Double long double

30
PROGRAMMING FOR PROBLEM SOLVING

1. Integral data type


❖ Integral data types are used to store whole numbers and characters
❖ It is further classified into
a) integer data type
b) character data type

a) Integer data type


▪ This data type is used to store whole numbers
▪ It has 3 classes of integer storage namely, short int, int and long int in both
signedand unsigned forms

Integer Data type


Type size (in bytes) Range Control string
Short int (or) 1 -128 to 127 %h
signed short int
Unsigned short int 1 0 to 255 % uh
int (or) signed int 2 -32768 to 32767 % d or %i
unsigned int 2 0 to 65535 %u
Long int (or) 4 -2147483648 to %ld
signed long int 2147483647
Unsigned long int 4 0 to 4294967295 %lu
b) Character data type
• This data type is used to store characters
• These characters are internally stored as integers
• Each character has an equivalent ASCII
value
e.g.: ‘A’ has ASCII value 65

Character data type


Type Size (in bytes) Range Control string
Char (or) signed 1 - 128 to +127 %c
Char
Unsigned char 1 0 to 255 %c

2. Floating-point Data types


• It is used to store real numbers (i.e., decimal point numbers).
• For 6 digits of accuracy, ‘float’ is used.
• For 12 digits of accuracy, ‘double' is used.
• For more than 12 digits of accuracy, ‘long double’ is used.

31
PROGRAMMING FOR PROBLEM SOLVING

Floating point data type


Type Size (in bytes) Range Control string
Float 4 3.4 E – 38 to 3.4 E + 38 %f
Double 8 1.7 E – 308 to 1.7 E +308 %lf
long double 10 3.4 E – 4932 to 1.1 E +4932 %lf
1. Derived data types:
Derived data types are defined by using the primitive data types. It is also called
as user-defined data type. They are arrays, structures,
CONSOLE INPUT/OUTPUT
❖ Storing a value into memory is called ‘input operation’.
❖ After executing the computations, the results are stored in memory and the results
can be displayed to the user by ‘output operation’.
❖ All input/output operations in ‘C’ are performed using input/output functions.
❖ The most common I/O functions are supplied as part of the ‘C’ standard I/O library
through the preprocessor directive # include<stdio.h>.
❖ Most commonly used I/O functions are
a) printf ( )
b) scanf ( )
a) printf ( ) function:
Syntax:
printf(“format string”, print list);
e.g.: printf (“average of 3 numbers = %f”,avg);
*The printf ( ) function displays the value of its format string after substitutingthe
values of the expressions in the print list.
* It also replaces the escape sequences such as ‘\n’ by their meanings.
b) scanf ( ) function:
Syntax:
scanf (“format string”, input list);
e.g.: scanf (“%d %f”, &a, &b);
➢ The scanf ( ) function copies into memory data typed at the keyboard by the
program user during program execution.
➢ The input list must be preceded by ampersand (&)

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.

Operator Description Example a =20, b=10 output


+ Addition a+b 20+10 30
- Subtraction a-b 20-10 10
* Multiplication a*b 20*10 200
/ Division a/b 20/10 2 (quotient)
% Modular division a%b 20%10 0 (remainder)
❖ Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter the values of a&b=”);
scanf(“%d%d”,&a,&b);
Input: enter the values of a&b= 10 20
printf (“ \n(a+b)=%d”, a+b);
printf (“\n(a-b)= %d”, a-b); Output:
(a+b)=30
printf (“\n(a*b)=%d”, a*b); (a-b)=-10
printf (“\n(a/b)=%d”, a/b); (a*b)=20
(a/b)=0
printf (“\n(a%b)=%d”, a%b); (a%b)=10
getch(); }

33
PROGRAMMING FOR PROBLEM SOLVING

2). Relational operators:


❖ These are used for comparing two expressions.

Operator Description Example a =10, b=20 output


< less than a<b 10<20 1
<= less than (or) a<=b 10< = 20 1
equal to
> greater than a>b 10>20 0
>= greater than (or) a>=b 10> =20 0
equal to
== equal to a= =b 10 = = 20 0
!= not equal to a! = b 10! =20 1
❖ The output of a relational expression is either true (1) (or) false (0)
❖ Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter the values of a&b=”);
scanf(“%d%d”,&a,&b);
Input: enter the values of a&b= 10 20
printf (“ \n(a<b)=%d”, a<b);
printf (“\n(a<=b)= %d”, a<=b); Output:
(a<b)=1
printf (“\n(a>b)=%d”, a>b); (a<=b)=1
printf (“\n(a>=b)=%d”, a>=b); (a>b)=0
(a>=b)=0
printf (“\n(a==b)=%d”, a==b); (a==b)=0
printf (“\n(a!=b)=%d”, a!=b); (a!=b)=1
getch();
}

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

Logical NOT (!)


exp ! (exp)
T F
F T

Operator Description Example a =10, b=20, c=30 output


&& logical AND (a>b) && (a<c) (10>20) & & (10<30) 0
|| logical OR (a>b) | | (a<c) (10>20) ||(10<30) 1
! logical NOT ! (a>b) ! (10>20) 1

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

Operator Description Example


= Simple a=10
assignment
+= Compound a+=10 ⭢ a=a+10
-= assignment a-=10 ⭢ a=a-10
*= a*=10 ⭢ a=a*10
/= a/=10 ⭢ a=a/10
%= a%=10 ⭢ a=a%10

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

5. Increment and decrement operator:


a) Increment operator (++):
❖ It is used to increment the value of a variable by 1.
❖ 2 types: i) pre increment
ii) post increment
❖ increment operator is placed before the operand in pre-increment and the value
is first incremented and then operation is performed on it.
eg: z = ++a; a= a+1
z=a

❖ 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

& Bitwise AND


| Bitwise OR
^ Bitwise XOR
<< Left shift
>> Right shift
~ One’s complement

Bitwise AND Bitwise OR Bitwise XOR

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

eg: let a= 12, b=10

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 1 0 1 0 0 Fill it with zero

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

Primary Postfix prefix unary binary ternary

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

Operator Precedence Chart

Operator Type Operator Associativity

Primary Expression
() [] . -> expr++ expr-- left-to-right
Operators

* & + - ! ~ ++expr --expr (typecast)


Unary Operators right-to-left
sizeof

* / %

+ -

>> <<

< > <= >=

== !=

Binary Operators left-to-right


&

&&

||

Ternary Operator ?: right-to-left

Assignment Operators = += -= *= /= %= >>= <<= &= ^= |= right-to-left

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

Here, the above expression finally evaluates to a ‘double’ value

48
PROGRAMMING FOR PROBLEM SOLVING

Explicit type conversion is done by the user by using (type) operator


E.g.: int a, c;
float b;
c = (int) a + b

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:

1. What is an algorithm? What is a flowchart? Write an algorithm and flowchart to


checkwhether the given number is prime or not.
2. Explain the basic structure of C Program? Explain the different data types with
range?
3. What is an operator? Explain Arithmetical operators and Bitwise operators
withexample?
4. (a) Write an algorithm to check whether the given no is Amstrong or not.
(b) Write an algorithm to check whether given no is palindrome or not.
5. What is algorithm and flowchart? Write an algorithm and flowchart to find
whether a given number is palindrome or not. (The reverse of number is same as
the given no. then it is called palindrome ex:141)
6. What is an operator? Explain the relational operators and the logical operators with
anexample.
7. Explain the basic structure of C program? Explain the different data types with
range.
8. What is operator? Explain arithmetic operators and special operators with example.
9. A) i. Explain the characteristics of an algorithm? Draw the flowchart to check
whether given number is prime or not.
ii. Define expression? Evaluate w=x++ * (y-z) / ++ x where x=3, y=4, z=1

what is the final value of w and x?


B) i. Explain ternary operator available in C, with example.
ii. Explain Precedence and associativity of operators in the evaluation of expression.
10. State and explain various data types in C? And also discuss about associativity and
expression evaluation with suitable example?
11. Explain logical operators and bitwise operators? Explain with suitable example.
12. Explain about computing environments.
13. Explain different types of operators in C with examples?

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 block-1 Statement block-2

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

True Condi False True Cond False


tion2 ition3

Stmt1 Stmt2 Stmt3 Stmt4

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

printf (“%d is largest”, b);


else
printf (“%d is largest”, c);
}
Printf(“the values of a,b,c are a=%d b=%d c=%d”,a,b,c);
getch();
}
input
enter the values of a,b,c = 10 20 30
output:
30 is largest
a=10 b=20 c=30
4. Else – if ladder
➢ This is the most general way of writing a multi-way decision.
Syntax
if (condition1)
stmt1;
else if (condition2)
stmt2;
-----
else if (condition n)
stmt n;
else
stmt x;

59
PROGRAMMING FOR PROBLEM SOLVING

flow chart

True Condi False


tion1?

True Condi False


tion2?
Stmt1
------
Stmt2

True Condit False


ion n?

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

printf (“\nroot1 = %f, root2 == %f”, r1, r2);


}
else
if (d= = 0)
{
r1 = -b / (2*a);
r2 = -b/ (2*a);
printf(“roots are equal”);
printf (“\nroot1 = %f, root2 = %f”, r1, r2);
}
else
if(d<0)
{
printf ("roots are imaginary”);
}
getch();
}
1) Input:
enter a, b, c values: 1 4 3
Output:
roots are real
Root 1 = -1
Root 2 = -3
2)Input:
enter a, b, c values: 1 2 1
Output:
roots are equal
Root 1 = -1
Root 2 = -1
3) Input:
enter a, b, c values: 1 2 3
Output: roots are imaginary

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 =value1 Stmt1

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

Loop control statements


❖ These are used to repeat a set of statements
❖ They are
1) for loop
2) while loop
3) do-while loop
1) for loop
Syntax
for (initialization; condition; increment / decrement)
{
body of the loop;
(or)
group of statements;
}
Statement-x;

Flow chart

False
Initialization Increment/
condition decrement

True

Body of the loop

Statement-X

64
PROGRAMMING FOR PROBLEM SOLVING

❖ for statement contains 3 parts


i) initialization is usually an assignment statement that is used to set the loop control
variable.
ii) The condition is a relational expression that determines when the loop will exit.
iii) The increment/decrement part defines how the loop control variable will change
each time loop is repeated.
iv) loop continues to execute as long as the condition is true.
v) Once the condition is false, program continues with the next statement after for
loop.

Program
#include<stdio.h>
#include<conio.h>
void main()
{ Input:
enter the value of n=5
int n,i; Output
clrscr(); i=1

printf(”enter the value of n=”); i=2

scanf(”%d”,&n); i=3

for (i=1; i<=n; i++) i=4

{ 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

Body of the loop

Incr/ dec

Statement-X

❖ Initialization is done before the loop.


❖ Loop continues as long as the condition is true.
❖ Incrementation and defragmentation part is done within the loop.

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

Body of the loop

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

Nested for loops


➢ In nested for loops one (or) more for statements are included in the body of the
loop.
➢ The number of iterations in this type of structure will be equal to number of
iterations in the outer loop multiplied by the number of iterations in the inner loop.
Program
#include<stdio.h>
#include<conio.h>
void main() Input:
{ enter the value of n=5
int i,j,n,m; Output
clrscr(); 1
printf(”enter the value of n=”);
scanf(”%d”,&n); 2 2
for (i=1; i<=n; i++)
{ 3 3 3
4 4 4 4
for (j=i;j<=i; j++)
{ 5 5 5 5 5
printf (”%d\t”, i);
}
printf(“\n”);
}
getch();
}

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

Syntax: goto label;


group of statements;

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.

Syntax Forward jump backward jump


group of statements; group of statements;
goto label; label :stmt

label : stmt goto label;


group of statements; group of statements;

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:

datatype array_name [size];

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]

An array can also be initialized at the time of declaration as follows


int a[5] = { 10,20,30,40,50};
Types of arrays
Arrays are broadly classified into 3 types. They are
1) one – dimensional arrays
2) two – dimensional arrays
3) Multi – dimensional arrays

1. one – dimensional arrays


Syntax: datatype array name [size];
E.g.: int a[5];
Initialization;
An array can be initialized in 2 ways.
a) compile time initialization
b) Runtime initialization

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

int a[5] = {10,20,30,40,50};


a[0] 10
int i;
a[1] 20
clrscr ( );
printf (“\nelements of the array are\n”); a[2] 30

for ( i=0; i<5; i++) a[3] 40

printf (“%d\t”, a[i]); a[4] 50

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 given elements of the array are : 10 20 30 40 50


Note:

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

the given elements of the array are=


10 20 30
40 50 60
70 80 90

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

3. Multi –dimensional arrays


❖ ‘C’ allows arrays of 3 (or) more dimensions
❖ The exact limit is determined by compiler
Syntax:
❖ datatype arrayname [size1] [size2]------ [sizen];
❖ E.g.: for 3 – dimensional array:
int a[3] [3] [3];
❖ No of elements = 3*3*3 = 27 elements
Program
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[2][2] [2] = {1,2,3,4,5,6,7,8};
int i,j,k;
clrscr ( );
printf (“elements of the array are”);
for ( i=0; i<2; i++)
{
for (j=0;j<2; j++)
{
for (k=0;k<2; k++)
{
printf(“%d ”, a[i] [j] [k]);
}
}
}
getch( );
}
Output: Elements of the array are:
1 2 3 4 5 6 7 8

81
PROGRAMMING FOR PROBLEM SOLVING

Array applications:

A. Stores Elements of Same Data Type


B. Array Used for Maintaining multiple variable names using single name
C. Array Can be Used for Sorting Elements
D. Array Can Perform Matrix Operation
E. Array Can be Used in CPU Scheduling
F. Array Can be Used in Recursive Function

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

15. Write a C program to find multiplication of Two Matrices.


16. Write a C program to find both the largest and smallest number in the given list of
integers.

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

How many times CMR gets printed?


13. Change the following for loop to while loop.
for(m=1;m<10;m++)
printf(“%d”,m);
14. What will be the output of the following program fragment when executed?
int x=10,y=20;
if((x<y)||(x+5)>10)
printf(“%d”,x);
else
printf(“%d”,y);
15. (a) In an exit-controlled loop if the body is executed “n” times, the test condition
isevaluated ---------- times.
(b) Draw the flowchart of while loop.

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

17. Define array?


18. What will be the o/p of the following program?
#include<stdio.h>
#include<conio.h>
void main()

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

2) User defined functions


These functions must be defined by the programmer (or) user.
Programmer has to write the coding for such functions and test them properly before using
them
The syntax of the function is also given by the user and therefore need not include any
header files.
E.g.: main ( ), swap ( ), sum ( ) etc
Program
#include<stdio.h>
#include<conio.h>
int sum (int, int);
void main ( )
{
int a, b, c;
Input:
clrscr ( );
Enter the values of a & b=5 7
printf (“enter the values of a&b=”);
Output:
scanf (“ %d %d”, &a ,&b);
Sum = 12
c = sum (a,b);
printf(“sum = %d”, c);
getch();
}
int sum (int a, int b)
{
int c;
c=a+b;
return c;
}

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:

returntype fnname(argument datatype);

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

void sum (int, int);


int sub(int e, float f);
float mul(float x, int y);

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)

Function definition can be classified into 2 types.


➢ Function header
➢ Function body
E.g.:
void sum(int c, int d)
int sub(int e, float f)
float mul (float x, int y)
E.g.:
void sum(int a, int b) function header
{

------------- function body

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

Function return value:


In c function may or may not have return values. If a function does not return any
value, then the return type in the function declaration and function definition is void.
Otherwise, the return type is specified which returns the type of value.
Syntax:
return (var name);

Ex: return(c);

Write a C program to find the sum of two numbers using functions:


Program code:

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

Parameter passing mechanism:


The process of passing the arguments from calling function to called function is known as
parameters passing mechanism.
It can be classified into 2 types
1) Actual parameters.
2) Formal (or) dummy parameters.

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.

1) functions without arguments and without return values

Calling function Analysis Called function


main ( ) No arguments are passed fun ( )
{ {

--- No values are sent back ----


fun ( ); }
}

93
PROGRAMMING FOR PROBLEM SOLVING

Write a C program to find the sum of two numbers


#include<stdio.h>
#include<conio.h>
void sum();
void main()
{
clrscr ( );
sum ( );
getch ( );
input
}
Enter the values of a & b=5 7
void sum ( )
Output
{
Sum = 12
int a,b,c;
printf(“enter the values of a&b=”);
scanf (“%d%d”, &a, &b);
c = a+b;
printf(“sum = %d”,c);
}

2) Functions without arguments and with return values

Calling function Analysis Called function


main ( ) No arguments are passed fun ( )
{ {
int c; ----

c= fun ( ); return c;
values are sent back
----- }
}

94
PROGRAMMING FOR PROBLEM SOLVING

Write a C program to find the sum of two numbers


#include<stdio.h>
#include<conio.h>
int sum();
void main()
{
int c;
clrscr ( ); input

c= sum ( ); Enter the values of a&b=5 7

printf(“sum = %d”,c); Output

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

Calling function Analysis Called function


main ( ) Arguments are passed fun ( int a, int b)
{ {

--- No values are sent back ----


fun ( a,b ); }
---
---
}

95
PROGRAMMING FOR PROBLEM SOLVING

Write a C program to find the sum of two numbers


#include<stdio.h>
#include<conio.h>
void sum (int, int );
void main() input
{ Enter the values of a&b=5 7
int a,b; Output
clrscr ( ); Sum = 12
printf(“enter the values of a&b=”);
scanf(“%d%d”, &a,&b);
sum (a,b);
getch ( );
}
void sum ( int a, int b)
{
int c;
c= a+b;
printf (“sum=%d”, c);
}
4) Functions with arguments and with return values.

Calling function Analysis Called function


main ( ) Arguments are passed fun ( int a, int b)
{ {
int c; ----

---
value are sent back
c= fun ( a,b ); return c;
--- }
---
}

96
PROGRAMMING FOR PROBLEM SOLVING

Write a C program to find the sum of two numbers


#include<stdio.h>
#include<conio.h>
int sum (int, int );
void main() Input:
{ Enter the values of a & b=5 7
int a,b,c; Output:
clrscr ( ); Sum = 12
printf(“Enter the values of a&b=”);
scanf(“%d%d”, &a,&b);
c= sum (a,b);
printf (“sum=%d”, c);
getch ( );
}
int sum ( int a, int b )
{
int c;
c= a+b;
return c;
}

97
PROGRAMMING FOR PROBLEM SOLVING

Arrays and functions


There are 2 ways of passing arrays as arguments to functions. They are
1) sending entire array as argument to function.
2) sending individual elements as argument to function.
1. Sending entire array as argument to function
❖ To send entire array as argument, just send the array name in the function
call.
❖ To receive the entire array, an array must be declared in the function
header.
E.g.:
#include<stdio.h>
#include<conio.h>
void main ( )
{
void display (int a[5]);
int a[5], i;
clrscr( );
printf (“enter 5 elements”);
for (i=0; i<5; i++)
scanf(“%d”, &a[i]);
display (a); Sending entire array ‘a’ using array
name
getch( );
}
void display (int a[5]) Receiving entire array
{
int i;
printf (“elements of the array are”);
for (i=0; i<5; i++)
printf(‘%d ”, a[i]);
}
Input:

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

printf(“\ni=%d”,i); block only

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

Scope rules related to functions:


There are two ways for passing parameters or arguments from calling function to called
function. They are:
Call by value
Call by reference
Call by value:
The process of passing the variables from calling function to called function is
called as call by value.
According to call by value mechanism the modification is done in the function
definition (called function) doesn’t 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 in main function a=%d, b=%d”, a,b);
getch();
}
void swap (int a, int b)
{
a=(a+b)-(b=a);
printf (“after swapping a=%d, b=%d”, a,b);
}
Input:
enter the valuesof a&b=10 20
Output:
Before swapping a=10, b=20
After swapping a = 20, b=10
after swapping in main function a=10 b=20

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

printf (“memory constant = %f”,cpi);


getch();
}

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;

Can be replaced with


*ptr+=9
*ptr+=5;

❖ 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

❖ When fact ( ) is called with an argument of 1 (or) 0, the function returns 1.


otherwise, it returns the product of n*fact (n-1), this happens until ‘n’ equals 1.
Fact (5) =5* fact (4)
=5*4*3* fact (3)
=5*4*3*2* fact (2)
=5*4*3*2*1 fact (1)
=5*4*3*2*1
= 120.
Program code:
#include<stdio.h>
#include<conio.h>
int fact (int);
void main ( )
{
int n,f;
clrscr ( );
printf (“enter the value of n=”);
scanf (“%d”, &n);
f= fact (n);
printf (factorial value = %d”,f);
getch();
}
int fact (int n)
{
int f;
if ( ( n==1) || (n==0))
return 1;
else
f= n*fact (n-1);
return f;
}
Input: enter the value of n=5
output: Factorial value = 120

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.

Difference between Recursion and Iteration


RECURSION ITERATIONS

Recursive function – is a function that is Iterative Instructions –are loop based

partially defined by itself repetitions of a process

Recursion Uses selection structure Iteration uses repetition structure

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

converges on some condition. (Base case) false

Recursion terminates when a base case is Iteration terminates when the loop-

Recognized condition fails

Recursion is usually slower than iteration due Iteration does not use stack so it's faster

to overhead of maintaining stack than recursion

Recursion uses more memory than iteration Iteration consumes less memory

Infinite recursion can crash the system infinite looping uses CPU

cycles repeatedly

Recursion makes code smaller Iteration makes code longer

113
PROGRAMMING FOR PROBLEM SOLVING

HEADER FILES IN C

Some of header files in C Programming are:


• ctype.h: All character type functions are defined in ctype.h header file.
E.g.: isalnum(), isalpha(), isdigit(), etc.
• Math.h: All mathematical related functions are defined in math.h header file.
E.g.: sqrt() ,abs(),
• Stdio.h: This is standard input output header file. All input and output functions
are defined in this header file.
E.g.: printf(), scanf().
• Stdlib.h: Some general functions which are used in program are defined in this
header file.
E.g.: atof(), atoi(),exit(),etc.
• String.h: String functions are defined in string.h header file.
E.g.: strlen(), strcpy, strcmp, etc.
Preprocessor directives
❖ It consists of a) link section
b) Definition Section
❖ The link section provides instructions to the compiler to link functions from the
system library.
E.g.: #include < stdio.h>
❖ The definition section defines all symbolic constants.
E.g.: #define PI 3.1415
❖ Preprocessor directive must start with ‘#’ (hash) symbol.
Preprocessor commands
❖ ‘preprocessor’ is a program that processes the source code before it passes through
the compiler.
❖ It operates under the control of preprocessor directives which begin with the
symbol #
3 types 1) Macro substitution directives
2) File inclusion directives
3) compiler control directives
1) Macro substitution directives
❖ It replaces every occurrence of the identifier by a predefined string.
Syntax: for defining a macro
#define identifier string
E.g.: #define PI 3.1415
#define f(x) x *x
#undef PI

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

3. Compiler control directives


❖ C preprocessor offers a feature known as conditional compilation, which can be
used to switch ON (or) OFF a particular line (or) group of lines in a program.
E.g.: #if, #else, #endif etc.
#define LINE 1
void main ( )
{ Output:
#ifdef LINE This is line number one
printf (”this is line number one”);

#else
printf(‘This is line number two”);
#endif
}

116
PROGRAMMING FOR PROBLEM SOLVING

STRINGS
Definition of Strings:

A group of characters can be stored in a character array. This character


arrayis called as string.
In ‘C’ the strings end with “NULL character” “\0”
Declaration:
Syntax: datatype stringname[size];
E.g.:
Char a[6];

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

Formatted input/output function unformatted input/output function

formatted input formatted output unformatted input unformatted output

scanf () printf () gets() puts()

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

where the character variable refers to the name of the variable.


Putchar():
It is used to display single character on the output screen.

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:

Enter a string= kumar


Output:
The given string = kumar

gets() & puts():


gets():
It is used to read a line of text even the white space is occurred in between the
string.
Syntax:
gets(stringname);
puts():
It is used to display a line of text even the white space is occurred in between the
string.
Syntax:
puts(stringname);

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

String handling functions:


Strlwr()
Strupr()
strlen ( )
strcpy ( )
strncpy ( )
strcat ( )
strncat ( )
strcmp ( )
strncmp ( )
strrev ( )

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

1234 1238 1242

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

toupper ( ) Converts a lower case alphabet to upper 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

String to number and number to string conversion


There are 2 functions available for conversion. They are:
1) sscanf( ) - used for converting string to number
2) sprintf ( ) - used for converting number to string
1) string to number conversion
sscanf ( ) – takes a string as an input and converts it into numbers
Syntax:
sscanf (string name, “control string”, variable list);
for e.g.: a 02 01 2010 - i/p
%s

day month year


- o/p
%d %d %d

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

2. Number to string conversion


sprintf( ) takes different numeric values as input and converts it into a single string
Syntax:
sprintf ( string name, “control string”, variable list);

for e.g.: 02 01 2010 - - i/p


%d %d %d

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.

11. Write a program to check whether string is a palindrome or not.

12. Develop a C program to determine if the given string is a


palindrome or not.

A palindrome is a message that reads same both forwards and


backwards.Ex: The string “madam” is palindrome.

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:

int qty = 179;


The representation of the variable in memory is as follows
qty Variable

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

Accessing a variable through its pointer


❖ To access the value of the variable, indirection operator (*) is used.
E.g.:
int qty = 175, *p,n;

p = &qty;

n = *p;

‘*’ can be treated as value at address.


If we are assigning the address of another variable to the pointer variable at that time
bothvariables must declare the same datatype.
❖ The 2 statements are equivalent to the following statement
p = &qty;
n = *p; n =qty
Program:

#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

Pointers and arrays:

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

Address of a[3] = base address + (3* scale factor of int)


= 1000 + (3*2)
= 1000 +6
= 1006

❖ 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

Pointers and two-dimensional arrays:


❖ Memory allocation for a 2-dimensional array is as follows:
int a[3] [3] = {1,2,3,4,5,6,7,8,9};
a[0] [0] a[0] [1] a[0] [2] a[1] [0] a[1] [1] a[1] [2] a[2] [0] a[2] [1] a[2] [2]
1 2 3 4 5 6 7 8 9
1234 1236 1238 1240 1242 1244 1246 1248
1250
1st row 2nd row 3rd row
base address = 1234 = &a[0] [0]

int *p; Assigning base address to


p = &a[0] [0]; a pointer
(or) p =a

❖ Pointer is used to access the elements of 2 – dimensional array as follows

a[i] [j] = *(p+i*columnsize+j)

a[1] [2] = *(1234 + 1*3+2)


= *(1234 + 3+2)
= *(1234 + 5*2) Scale factor
= * (1234+10)
= *(1244)
a[1] [2] = 6
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[3] [3], i,j;
int *p;
clrscr ( );
printf (“Enter elements of 2D array”);
for (i=0; i<3; i++)
{

140
PROGRAMMING FOR PROBLEM SOLVING

for (j=0; j<3; j++)


{
scanf (“%d”, &a[i] [j]);
}
}
p = &a[0] [0];
printf (“elements of 2d array are”);
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
printf (”%d \t”, *(p+i*3+j));
}
printf (“\n”);
}
getch ( );
}
Input:
enter elements of 2D array
1 2 3 4 5 6 7 8 9
Output:
Elements of 2D array are
1 2 3
4 5 6
7 8 9
Array of pointers
❖ It is collection of addresses (or) collection of pointers .
Declaration
datatype *pointername [size];
eg: int *p[5]; It represents an array of pointers that can hold 5 integer element
addresses
p[0] p[1] p[2] p[3] p[4]

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

Arithmetic operations using pointers


Like any other variables, pointer variables can be used in expressions. For e.g. If p1 and
p2 areproperly declared and initialized then the following statements are valid
a) *p1 + *p2
b) *p1 - *p2
c) *p1 * *p2
d) *p1 / *p2
Note: There must be a blank space between / and * otherwise it is
treated as beginning of comment line
e) p1 + 4
f) p2 - 2
g) p1 - p2

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

Note: Comparisons can be used meaningfully in handling arraysand strings

The following statements are invalid


a) p1 + p2
b) p1 * p2
c) p1 / p2
d) p1 / 3

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

Pointers and functions:

pass by value: Here values are sent as arguments

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

pass by reference: Here addresses are sent as arguments

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

void swap(int *a,int *b)


{
int t;t=*a;
*a=*b; *a = (*a + *b) – (*b = * a);
*b=t;

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

Memory allocation functions:


Memory can be allocated in 2 ways:

❖ If memory is allocated at compile time, it cannot be changed during execution.


There will be a problem of either insufficiency or else wastage of memory.
❖ The solution is to create memory dynamically i.e. as per the requirement of the
user during execution of program.
❖ The standard library functions used for dynamic memory management are:
1) malloc ( )
2) calloc ( )
3) realloc ( )
4) free ( )
1) malloc ( );
❖ This function is used for allocating a block of memory in bytes at runtime.
❖ It returns a void pointer, which points to the base address of allocated
memory.
Syntax:
void *malloc (size in bytes)
E.g.:
1) int *ptr;
ptr = (int * ) malloc (1000);
2) int *ptr;
ptr = (int * ) malloc (n * sizeof (int));
Note: if the memory is not free, it returns NULL.
2) Calloc ( ):
❖ This function is used for allocating continuous blocks of memory at run time.
❖ This is especially designed for arrays.
❖ It returns a void pointer which points to the base address of the allocated memory.
Syntax: void *calloc (numbers of elements, size in bytes)
E.g.: 1) int *ptr;

150
PROGRAMMING FOR PROBLEM SOLVING

ptr = (int * ) calloc (500,2);


Here, 500 blocks of memory each of size 2 bytes will be allocated continuously. Total
memory allocated = 1000 bytes.
2) int *ptr;
500 x 2
ptr = (int * ) calloc (n, sizeof (int));
= 1000
bytes
ptr

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:

void *realloc (pointer, newsize);


E.g.:
int *ptr;
ptr = (int * ) malloc (1000);
---
---
---
ptr = (int * ) realloc (ptr, 500);
---
---
ptr = (int * ) realloc (ptr, 1500);
4. free ( ):
❖ This function frees ( or) deallocates previously allocated memory space..
❖ With dynamic runtime allocation, it is our responsibility to release the space when
it is not required for effective usage of memory.
Syntax:
free (pointer);
E.g.: int *ptr;
ptr = (int *) malloc (1000);
---
---
---
free (ptr);

151
PROGRAMMING FOR PROBLEM SOLVING

Command line arguments:


❖ An executable program that performs a specific task for operating system is called
as command.
❖ These commands are issued from the prompt of operating system.
❖ Some arguments are to be associated with the commands and hence these are
called “command” line arguments. They are
1) argc ----- argument count
2) argv ----- argument vector
argc: it contains the total number of arguments passed from command prompt
argv: it is a pointer to an array of character strings which contains names of arguments.
Each word is an argument
for e.g.:
c: |> sample. Exe hello how are you

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

STRUCTURES AND UNIONS


Introduction:
❖ Structure:
Structure is a derived data type which contains a collection of different data items
that are stored in different memory allocation, but all elements are referred by
common name i.e., name of the structure (or) structure name.
(or)
It is a collection of different datatype variables, grouped together under a single
name.
(or)
It is heterogenous collection of data items that share a common name.
Features of structure
1. It is possible to copy the contents of all structure elements of different datatypes to
another structure variable of its type using assignment operator.
2. To handle complex datatypes, it is possible to create structure within another
structure, which is called nested structures.
3. It is possible to pass entire structure, individual elements of structure and address
of structure to a function.
4. It is possible to create structure pointers.
Declaration and initialization of structures.
General form of structure declaration
struct structurename
{
datatype datamember1;
datatype datamember2;

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

Initialization and accessing of structures


❖ The link between a member and a structure variable is established using member
operator (or) dot operator.
❖ Initialization can be done in the following ways
During declaration:
End of structure declaration:
1. struct book
{
int pages;
char author[30];
float price;
} b = {100, “balu”, 325.75};
In the main program:
2. struct book
{
int pages;
char author[30];
float price;
};
struct book b = {100, “balu”, 325.75};
with the help of keyboard:
syntax:
objname.datamember;

156
PROGRAMMING FOR PROBLEM SOLVING

program code for declare the values in the end of structure


#include<stdio.h>
#include<conio.h>
struct book
{
int pages;
char author[30];
float price;
} b = {100, “balu”, 325.75};
void main ( )
{

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

2. Passing entire structure as an argument to function


❖ Name of the structure variable is given as argument in function call.
❖ It is collected in another structure variable in function header.
Disadvantage: A copy of the entire structure is created again wasting memory.
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);
}
3. Passing the address of structure as an argument to function
❖ The Address of the structure is passed as an argument to the function.
❖ It is collected in a pointer to structure in function header.
Advantages:
1. No wastage of memory as there is no need of creating a copy again
2. No need of returning the values back as the function can access indirectly the
entire structure and work on it.

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;

❖ when a union is declared, the compiler automatically creates a variable large


enough to hold the largest variable type in the union.
❖ At any time only one variable can be referred.

167
PROGRAMMING FOR PROBLEM SOLVING

Initialization and accessing:


❖ To access a union member, the same syntax as that of the structure is used.
❖ The dot operator is used for accessing members normally.
❖ The arrow operator ( ) is used for accessing the members using pointer.
Program:
#include<stdio.h>
#include<conio.h>
union sample
{
int a;
float b;
char c;
}s;
void main ( )
{
union sample s = {10, 20.5, ‘A’};
clrscr( );
printf(“a=%d”,s.a);
printf(“b=%f”,s.b);
printf(“c=%c”,s.c);
getch ( );
}
Output:
a = garbage value Only the variable that is stored at last will
b = garbage value retain its value

c=A

168
PROGRAMMING FOR PROBLEM SOLVING

Differences between structures and Unions:

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)

7. Only one member will be residing in the


7. Memory is allocated for all the members memory at any particular instance
of the structure differently

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

Example for typedefining a structure


:#include<stdio.h>
#include<conio.h>
typedef employee
{
int eno;
char ename[30];
float sal;
} emp;

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:

datatype name : bit – length;


❖ The datatype can be either int (or) unsigned int (or) signed int.
❖ Bit length specifies the number of bits.
❖ The largest value that can be stored is 2n – 1, where ‘n’ is bit length.
NOTE:
1) Bit fields cannot be arrayed.
2) scanf ( ) cannot be used to read values into bit fields.
3) cannot use pointer to access the bit fields.
4) Bit fields should be assigned values within the range of their size.
Bit Length Range of values
1 0 to 1
2 0 to 3 (22-1)
3 0 to 7 (23-1)
N 0 to 2n-1
E.g.:
1) struct pack
{
int count;
unsigned a : 2;
unsigned b : 3;
};
Here, count will be in 2 bytes. ‘a’ and ‘b’ will be packed into next 1 byte

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

Enumerated Data type


❖ These are used by the programmers to create their own data types and define what
values the variables of these data types can hold.
Keyword: enum
Syntax:
enum tagname
{
identifier1, identifier2,…….,identifier n
};

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:

1. i) Explain Dynamic memory allocation functions.


ii) Define
a) Pointers to pointers
b) void pointer
2. Explain array of pointers and pointer to array with an example.
3. Write short notes on
(a) pointers to void

(b) pointers to functions.


4. Define string? Explain how strings are declared and initialized in C? Write a C
program for finding the length of a given string.
5. Explain the difference between call-by-value and call-by-reference with suitable
example.
6. a) Discuss about declaration, initialization,and accessing of structures? And also
discuss about self-Referential structures.
7. Explain about Bitfield, enum, typedef withsuitable examples.
8. i) Difference between structure and union.

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.

12.Write short notes on


a) Union (b) Enumerated data type (c) Type def (d) Bit fields

177
PROGRAMMING FOR PROBLEM SOLVING

Short answers:

a) What operations can be performed on pointers?


b) List the valid and invalid operations on pointers?
c) List the dynamic memory allocation functions?
d) Define pointer to pointer?
e) What will be the output of the program?

#include <stdio.h>
void main( )
{
int i=1, *j, k;
j=&i;
Printf(“%d”, i**j*i+*j);
}

f) Explain how to access the members of a structure.

g) Explain Enumerated data type and typedef.

h) Which operator is used for accessing a structure element using a pointer?

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

Syntax for closing a file:


fclose(filepointer);
E.g.:
fclose(fp);
Modes of the opening the file :
r - File is opened for reading
w - File is opened for writing
180
PROGRAMMING FOR PROBLEM SOLVING

a - File is opened for appending (adding)


r+ - File is opened for both reading & writing
w+ - File is opened for both writing & reading
a+ - File is opened for appending & reading
rt - text file is opened for reading
wt - text file is opened for writing
at - text file is opened for appending
r+t - text file is opened for reading & writing
w+t - text file is opened for both writing & reading
a+t - text file is opened for both appending & reading
rb - binary file is opened for reading
wb - binary file is opened for writing
ab - binary file is opened for appending
r+b - binary file is opened for both reading & writing
w+b - binary file is opened for both writing & reading
a+b - binary file is opened for both appending & reading.
1) Write mode of opening the file
FILE *fp;
fp =fopen (“sample.txt”, “w”);
a) If the file does not exist then a new file will be created.
b) If the file exists then old content gets erased & current content will be stored.
2. Read mode of opening the file:
FILE *fp
fp =fopen (“sample.txt”, “r”);
a) If the file does not exists, then fopen function returns NULL value.
b) If the file exists then data is read from the file successfully.
3. Append mode of opening a file
FILE *fp;
fp =fopen (“sample.txt”, “a”);
a) If the file doesn’t exist, then a new file will be created.
b) If the file exists, the current content will be appended to the old content.

181
PROGRAMMING FOR PROBLEM SOLVING

Mode Exist Not exist


r Read fp = “NULL”
Current New file will be created
w
content

New file will be created


a Old content
Current content

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

❖ These are easily understood by human beings


❖ Advantage: portability.
2) Low level I/o
❖ These are easily understood by computer
❖ Advantages: Execution time is less
❖ Disadvantage: Non portability
High level I/o Functions
1) fprintf ( ) - to write data into a file
2) fscanf ( ) - To read data from a file
3) putc ( )/ fputc() -To write a character into a file
4) getc ( ) /fgetc() -To read a character from a file
5) putw ( ) - To write a number into a file
6) getw ( ) - To read number from a file
7) fputs ( ) - To write a string into a file
8) fgets ( ) - To read a string from a file
9)fread() - To read an entire record from a file
10)fwrite() - To write an entire record into a file

182
PROGRAMMING FOR PROBLEM SOLVING

fprint ( ) & fscanf ( ) functions


1) fprint ( )
Syntax : fprintf (file pointer, “ control string”, variable list);
Eg: FILE *fp;
fprintf (fp, “%d%c”, a,b);

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

Keyboard getchar ( ) putc ( )


file
putchar ( )
Monitor getc ( )

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

Monitor printf (“%d”) getw ( )

186
PROGRAMMING FOR PROBLEM SOLVING

Program for storing no’s from 1 to 10 and print the same


#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
int i;
clrscr ( );
fp = fopen (“number. txt”, “w”);
for (i =1; i< =10; i++)
{
putw (i, fp);
}
fclose (fp);
fp =fopen (“number. txt”, “r”);
printf (“file content is ”);
for (i =1; i< = 10; i++)
{
i= getw(fp);
printf (“%d”,i);
}
fclose (fp);
getch ( );
}

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

Program for displaying the contents of a file


#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
char ch ;
clrscr ( );
fp = fopen (“file1.txt”,”r”);
if (fp = = NULL)
{
printf (“File does not exist”);
}
else
{
printf (“file content is”);
while ((ch = getc(fp))! = EOF)
putchar (ch);
}

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

fgets ( ) and fputs ( ) functions :


1) fgets ( ) : It is used for reading a string from a file.
Syntax:
fgets (string variable, No. of characters, File pointer);
E.g.: FILE *fp;
char str [30];
fgets (str,30,fp);
2) fputs ( ) : It is used for writing a string into a file
Syntax:
fputs (string variable, file pointer);
E.g.: FILE *fp;
char str[30];
fputs (str,fp);
File
Keyboard gets ( ) fputs ( )

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

fread ( ) and fwrite ( ) functions:


1. fread( ) : It is used for reading entire record at a time.
Syntax: fread(& structure variable, size of (structure variable), no of records, filepointer);
E.g.: struct emp
{
int eno;
char ename [30];
float sal;
} e;
FILE *fp;
fread (&e, sizeof (e), 1, fp);
2. fwrite ( ) : It is used for writing an entire record at a time.
Syntax: fwrite( & structure variable , size of structure variable, no of records, file
pointer);
E.g.: struct emp
{
int eno:
char ename [30];
float sal;
} e;
FILE *fp;
fwrite (&e, sizeof(e), 1, fp);
program for storing the details of 60 students into a file and print the same using
fread ( ) and fwrite ( )
struct student
{
int sno;
char sname [30];
float marks;
};
#include<stdio.h>
#include<conio.h>
void main ( )
{

193
PROGRAMMING FOR PROBLEM SOLVING

struct student s[60];


int i;
FILE *fp;
clrscr ( );
fp = fopen (“student1. txt”, “w”);
for (i=0; i<60; i++)
{
printf (“enter details of student %d”, i+1);
scanf (“%d%s%f”. &s[i].sno,s[i].sname, &s[i].marks);
fwrite (&s[i], sizeof (s[i]), 1, fp);
}
fclose (fp);
fp = fopen (“student1. txt”, “r”);
for (i=0; i<60; i++)
{
printf (“details of student %d are”, i+1);
fread (&s[i], sizeof (s[i]) ,1,fp);
printf(“student number = %d”, s[i]. sno.);
printf(“student name = %s”, s[i]. sname.);
printf(“marks = %f”, s[i]. marks);
}
fclose (fp);
getch( );
}
ERROR HANDLING IN FILES:
❖ Some of the errors in files are
1. Trying to read beyond end of the file.
2. Device overflow.
3. Trying to open an invalid file.
4. Performing an invalid operation by opening a file in a different mode.

Functions for error handling.


1) ferror ( )

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

fprintf (fp, “%d”, i);


if (ferror (fp))
{
perror (str);
printf (“error since file is opened for reading only”);
}
fclose (fp);
getch ( );
}
O/P: Error is : Error1 🡒 compiler generated.
Error since file is opened for reading 🡒 by us.
3. feof ( )
It is used for checking whether end of the file has been reached (or) not.
Syntax:
int feof ( file pointer);
E.g.: FILE *fp;
if (feof (fp))
printf (“reached end of the file”);
If returns a non zero if success and zero otherwise.
Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
FILE *fp;
int i,n;
clrscr ( );
fp = fopen (“number. txt”, “w”);
for (i=0; i<=100;i= i+10)
{
putw (i, fp);
}
fclose (fp);
fp = fopen (“number. txt”, “r”);
printf (“file content is”);

196
PROGRAMMING FOR PROBLEM SOLVING

for (i=0; i<=100; i=i+10)


{
n = getw (fp);
if (feof (fp))
{
printf (“reached end of file”);
break;
}
else
{
printf (“%d”, n);
}
}
fclose (fp);
getch ( );
}
Output : File content is
10 20 30 40 50
60 70 80 90 100
Reached end of the file.

Other file functions (Random accessing)


Random accessing of files
1. ftell ( )
2. rewind ( )
3. fseek ( )
1. ftell ( ) : It returns the current postion of the file pointer.
Syntax: int n = ftell (file pointer);
E.g.: FILE *fp;
int n;

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

Output: Enter text press ctrl z at the end.


How are you ^z
No. of characters entered = 11
fp value after rewind =0
Reversed content is uoy era woh.
Command line arguments:
➢ Arguments given at command prompt.
➢ main ( ) takes 2 arguments.
1) int argc – argument count.
2) char *argv [ ] – argument vector.
Program:
#include<stdio.h>
#include<conio.h>
void main (int arg c, char * argv [])
{
int i;
clrscr ( );
printf (“no. of arguments = %d”, argc);
printf (“arguments given at cmd prompt are”);
for (i=0; i<argc; i++)
{
printf (“%s \t”, argv [i]);
}
getch ( );
}
Program: for reversing characters in a file given at command prompt
#include<stdio.h>
#include<conio.h>
void main ( int argc, char *argv [ ] )
{
FILE *fp;
char ch;
clrscr ( );
fp = fopen (argv[1], “w”);
printf (“enter text press ctrl+z at the end”);
while ((ch = getchar ( ))!=EOF)

200
PROGRAMMING FOR PROBLEM SOLVING

putc (ch, fp);


fclose (fp);
fp = fopen (argv[1], “r”);
fseek ( fp,
argv[2], 0);do
{
ch =
getc
(fp);
putcha
r (ch);
} while (! fseek (fp,
-2, 1));fclose (fp);
getch ( );
}

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

The complexity of Linear Search Technique:


Time Complexity: O(n)
Space Complexity: O(1)

201
PROGRAMMING FOR
PROGRAMMING FOR PROBLEM
PROBLEM SOLVING
SOLVING

E.g.: Linear search program in C:

#include <stdio.h>
int main()
{
int array[100], search, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

for (c = 0; c < n; c++)


{
if (array[c] == search) /* If required element is found */
{

printf("%d is present at location %d.\n", search, c+1);


break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

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.

The complexity of Binary Search Technique:

Time Complexity: O(1) for the best case. O(log2 n) for average or worst case.
Space Complexity: O(1)

E.g.: Binary search program in C:

#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}

203
PROGRAMMING FOR PROBLEM SOLVING

Sorting:

▪ Sorting technique is used to rearrange a given array or list of elements according to a


comparison operator on the elements.
▪ The comparison operator is used to decide the new order of element in the respective data
structure.
▪ Types of Searching discussed in this chapter are:

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

The complexity of Bubble Sort Technique:

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.

Space Complexity: O(1)

Bubble Sort program in C:

#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

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

// Find the minimum element in arr[0...4]


// and place it at beginning
11 25 12 22 64

// Find the minimum element in arr[1...4]


// and place it at beginning of arr[1...4]
11 12 25 22 64

// Find the minimum element in arr[2...4]


// and place it at beginning of arr[2...4]
11 12 22 25 64

// Find the minimum element in arr[3...4]


// and place it at beginning of arr[3...4]
11 12 22 25 64

The complexity of Selection Sort Technique:

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.

Space Complexity: O(1)

206
PROGRAMMING FOR PROBLEM SOLVING

Selection Sort program in C:

void #include <stdio.h>

swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

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

The complexity of Insertion Sort Technique:

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.

Space Complexity: O(1)

208
PROGRAMMING FOR PROBLEM SOLVING

Insertion Sort program in C:

#include <math.h>
#include <stdio.h>

/* Function to sort an array using insertion sort*/


void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// A utility function to print an array of size n


void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

/* Driver program to test insertion sort */


int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);

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.

ii)Write a C program to read information about the student record containg


studentnumber, name, age and total marks and write the marks of each
student in an output file.

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:

1. Write the syntax of fwrite ( ), fread( ) functions.


2.
3. What is the importance of self-referentialstructure.
4. What will be the output of the program?
#include <stdio.h>

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.

Enqueing the queue

void enq(int data)


{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;

rear = temp;
}
count++;
}

Dequeing the queue

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.

enQueue(value) - Inserting value into the queue

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

 Step 1 - Check whether queue is FULL. (rear == SIZE-1)


 Step 2 - If it is FULL, then display "Queue is FULL!!! Insertion is not
possible!!!" and terminate the function.
 Step 3 - If it is NOT FULL, then increment rear value by one (rear++) and set
queue[rear] = value.

deQueue() - Deleting a value from the Queue

In a queue data structure, deQueue() is a function used to delete an element from


the queue. In a queue, the element is always deleted from front position. The
deQueue() function does not take any value as parameter. We can use the following
steps to delete an element from the queue...
 Step 1 - Check whether queue is EMPTY. (front == rear)
 Step 2 - If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not
possible!!!" and terminate the function.
 Step 3 - If it is NOT EMPTY, then increment the front value by one (front ++).
Then display queue[front] as deleted element. Then check whether both front
and rear are equal (front == rear), if it TRUE, then set both front and rear to
'-1' (front = rear = -1).

display() - Displays the elements of a Queue

We can use the following steps to display the elements of a queue...

 Step 1 - Check whether queue is EMPTY. (front == rear)


 Step 2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the
function.
 Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i =
front+1'.
 Step 4 - Display 'queue[i]' value and increment 'i' value by one (i++). Repeat
the same until 'i' value reaches to rear (i <= rear)

2. Write an algorithm to delete a node from given doubly linked list

Answer:

Algorithm to delete node from beginning of a doubly linked list


Algorithm to delete node from beginning
%% Input: head {Pointer to first node of the linked list}
Begin:
If (head == NULL) then
write ('Can't delete from an empty list')
End if
Else then
toDelete ← head;
head ← head.next;
head.prev ← NULL;
unalloc (toDelete)
write ('Successfully deleted first node from the list')
End if
End

Algorithm to delete node from end of a doubly linked list


Algorithm to delete node from end
%% Input: last {Pointer to last node of the linked list}
Begin:
If (last == NULL) then
write ('Can't delete from an empty list')
End if
Else then
toDelete ← last;
last ← last.prev;
last.next ← NULL;
unalloc (toDelete)
write ('Successfully deleted last node from the list')
End if
End

3. Write an algorithm to implement Binary Search Tree(BST)

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

Inserting a value in the correct position is similar to searching because we try to


maintain the rule that the left subtree is lesser than root and the right subtree is
larger than root.
We keep going to either right subtree or left subtree depending on the value and
when we reach a point left or right subtree is null, we put the new node there.

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;

DS&A ASSIGNMENT QUESTIONS


ASSIGNMENT -2
1. Compare Brute Force and KMP pattern matching algorithm

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}

The KMP Algorithm:

Knuth-Morris-Pratt’s algorithm compares the pattern to the text in left-to-right, but


shifts the pattern more intelligently than the brute-force algorithm.
When a mismatch occurs, what is the most we can shift the pattern so as to avoid
redundant comparisons?
Answer: The largest prefix of P[0..j] that is a suffix of P[1..j]

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 }

2. Write Heapify procedure of heap sort?

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.

Starting from a complete binary tree, we can modify it to become a Max-Heap by


running a function called ‘heapify’ on all the non-leaf elements of the heap. i.e.
‘heapify’ uses recursion.

Algorithm for “heapify”:

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)

Child (70(1)) is greater than the parent (30(0))

Swap Child (70(1)) with the parent (30(0))


70(0)
/ \
30(1) 50(2)

Heap Sort Algorithm for sorting in increasing order:


1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the
last item of the heap followed by reducing the size of heap by 1. Finally, heapify the
root of the tree.
3. Repeat step 2 while the size of the heap is greater than 1.

How to build the heap?


Heapify procedure can be applied to a node only if its children nodes are heapified.
So the heapification must be performed in the bottom-up order.
Lets understand with the help of an example:

Input data: 4, 10, 3, 5, 1


4(0)
/ \
10(1) 3(2)
/ \
5(3) 1(4)

The numbers in bracket represent the indices in the array


representation of data.

Applying heapify procedure to index 1:


4(0)
/ \
10(1) 3(2)
/ \
5(3) 1(4)

Applying heapify procedure to index 0:


10(0)
/ \
5(1) 3(2)
/ \
4(3) 1(4)
The heapify procedure calls itself recursively to build heap
in top down manner.

3. Write partition procedure of Quick Sort Algorithm

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.

Quick Sort Pivot Algorithm

Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for it,
which is as follows.

Step 1 − Choose the highest index value has pivot


Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot
MID QUESTION PAPERS WITH
SOLUTIONS
MID SOLUTIONS
II MID AUGUST 2021

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

// Create a new LL node


QNode* temp = newQNode(x);

// If queue is empty, then


// new node is front and rear both
if(rear == NULL) {
front = rear = temp;
return;
}

// Add the new node at


// the end of queue and change rear
rear->next = temp;
rear = temp;
}

// Function to remove
// a key from given queue q
voiddeQueue()
{
// If queue is empty, return NULL.
if(front == NULL)
return;

// Store previous front and


// move front one node ahead
QNode* temp = front;
front = front->next;

// If front becomes NULL, then


// change rear also as NULL
if(front == NULL)
rear = NULL;

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

int stack[SIZE], top = -1;


void main()

int value, choice;

clrscr();

while(1){

printf("\n\n***** MENU *****\n");

printf("1. Push\n2. Pop\n3. Display\n4. Exit");

printf("\nEnter your choice: ");

scanf("%d",&choice);

switch(choice){

case 1: printf("Enter the value to be insert: ");

scanf("%d",&value);

push(value);

break;

case 2: pop();

break;

case 3: display();

break;

case 4: exit(0);

default: printf("\nWrong selection!!! Try again!!!");

void push(int value){

if(top == SIZE-1)

printf("\nStack is Full!!! Insertion is not possible!!!");

else{

top++;

stack[top] = value;

printf("\nInsertion success!!!");

}
void pop(){

if(top == -1)

printf("\nStack is Empty!!! Deletion is not possible!!!");

else{

printf("\nDeleted : %d", stack[top]);

top--;

void display(){

if(top == -1)

printf("\nStack is Empty!!!");

else{

int i;

printf("\nStack elements are:\n");

for(i=top; i>=0; 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

8.a) Insert (x, p, L) Insert x at position p in list L. ...


Locate (x, L) returns position of x on L. ...
Retrieve (p, L) returns element at position p on L. ...
Delete (p, L) delete element at position p in L. ...
Next (p, L) ...
Prev (p, L) ...
Makenull (L) ...
First (L)
OR

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

struct node *ptr = (struct node *)malloc(sizeof(struct node));


if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{

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

// popped all the elements and the added in the


// linked list,
// which are in the reversed order->
}

Output
Original linked list
10 8 4 2
The reversed Linked List is
2 4 8 10

II MID AUGUST 2021

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

int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1;


voidbfs(int v) {
for(i = 1; i <= n; i++)
if(a[v][i] && !visited[i])
q[++r] = i;
if(f <= r) {
visited[q[f]] = 1;
bfs(q[f++]);
}
}
voidmain() {
int v;
printf("\n Enter the number of vertices:");
scanf("%d", &n);
for(i=1; i <= n; i++) {
q[i] = 0;
visited[i] = 0;
}
printf("\n Enter graph data in matrix form:\n");
for(i=1; i<=n; i++) {
for(j=1;j<=n;j++) {
scanf("%d", &a[i][j]);
}
}
printf("\n Enter the starting vertex:");
scanf("%d", &v);
bfs(v);
printf("\n The node which are reachable are:\n");
for(i=1; i <= n; i++) {
if(visited[i])
printf("%d\t", i);
else {
printf("\n Bfs is not possible. Not all nodes are reachable");
break;
}
}
}

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.

3. Algorithms based on character comparison:


Naive Algorithm: It slides the pattern over text one by one and check for a match. If a
match is found, then slides by 1 again to check for subsequent matches.
KMP (Knuth Morris Pratt) Algorithm: The idea is whenever a mismatch is detected, we already
know some of the characters in the text of the next window. So, we take advantage of
this information to avoid matching the characters that we know will anyway match.
Boyer Moore Algorithm: This algorithm uses best heurestics of Naive and KMP algorithm
and starts matching from the last character of the pattern.
Using the Trie data structure: It is used as an efficient information retrieval data structure. It
stores the keys in form of a balanced BST.
2.Deterministic Finite Automaton (DFA) method:
Automaton Matcher Algorithm: It starts from the first state of the automata and the first
character of the text. At every step, it considers next character of text, and look for the
next state in the built finite automata and move to a new state.
3.Algorithms based on Bit (parallelism method):
Aho-Corasick Algorithm: It finds all words in O(n + m + z) time where n is the length of text
and m be the total number characters in all words and z is total number of occurrences of
words in text. This algorithm forms the basis of the original Unix command fgrep.
4.Hashing-string matching algorithms:
Rabin Karp Algorithm: It matches the hash value of the pattern with the hash value of current
substring of text, and if the hash values match then only it starts matching individual
character.
PREVIOUS END EXAM
QUESTION PAPERS WITH
SCHEME
CMR COLLEGE OF ENGINEERING & TECHNOLOGY
(AUTONOMOUS)
Kandlakoya, Medchal Road, Hyderabad – 501 401

_I Year and II Semester Examinations (R18)


Data Structures & Algorithms (A3503)
Answer Key (Set 1)
Part - A
Q.1 Define ADT.
An Abstract data type (ADT) is a data type that is organized in such a way that this specification
of the objects and the specification of the operations on the objects are separated from
the
representation of the objects and the implementation of the operations.

Q.2 Draw circular Representation of 3x14+2x8+1

Figure: Circular Representation of 3x14+2x8+1

Q.3 Define Stack.


The stack is an ordered list in which insertions (also called pushes and adds) and
given deletions (also called pops and removes) are made at one end called the top. Given a
stack S = (a0,….,an-1), we say that a0 is the bottom element, an-1 is the top element, and ai is on
the top element ai-1, 0<i<n.

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: Left child – right sibling representation of tree


Solution:

Figure: Left child – right child tree representation of tree


Q.7 Define Graph.
A graph, G, consists of two sets, V and E. V is finite, nonempty set of vertices. E is a set of pairs
Of vertices; these pairs are called edges. V(G) and E(G) will represent the set of vertices and
edges, respectively, of graph G.

Figure: Graph

Q.8 Write a simple program to convert a string into non-negative integer.


Program:
unsigned int stringToInt(char *key)
{
/* simple additive approach to create a natural number that is within the integer range */
int number = 0;
while (*key)
number += *key++;
return number;
}

Q.9 Define analysis of merge sort.


A merge sort consists of several passes over the input. The first pass merges segments of size
th
1, the second merges segments of size 2 and the i pass merges segments of size 2i-1. Thus
the total number of passes is [ log 2 n]. As merge showed, we can merge two sorted segments
in linear time, which means that each pass takes O(n) time. Since there are [log 2 n] passes,
the total computing time is O(n log n).

Q.10 Compare sorting techniques with worst case and average case.

Sorting Techniques Worst Case Average Case


Quick Sort n2 n log n
Merge Sort n log n n log n
Heap Sort n log n n log n

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.

b) ii) Write a program for simple insert into front of list.


void insert(listPointer *first, listPointer x)
{ /* insert a new node with data = 50 into the chain first after node x */
listPointer temp;
MALLOC(temp, sizeof(*temp));
temp->data = 50;
if (*ptr) { // nonempty list
temp->link =node ->link;
node->link = temp;
}
else { // empty list
temp->link = NULL;
*ptr =temp;
} }
Q.12 a) Implement ADT queue with operations.
ADT Queue is
Q.12 b) Write a code to convert from Infix to Postfix using Postfix Function.

Q.13 a) Briefly explain about threaded binary trees.

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.

LBIT(P) =1 if LCHILD(P) is a normal pointer


LBIT(P) = 0 if LCHILD(P) is a thread
RBIT(P) = 1 if RCHILD(P) is a normal pointer
RBIT(P) = 0 if RCHILD(P) is a thread

Figure: Threaded tree

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.

Q.13 b) Explain binary tree representation in detail.

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.

Figure a & b Array Representation

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.

Figure c Linked Representation


Q.14 a) Explain Adjacency matrix and Adjacency list in Graph Representations.

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

A key is mapped into one of m slots using the function

h(k) = k mod m

Requires only a single division, hence fast


m should not be :
o a power of 2, since if m = 2p, then h(k) is just the p lowest order bits of k
o a power of 10, since then the hash function does not depend on all the
decimal digits of k
o 2p - 1. If k is a character string interpreted in radix 2p, two strings that are
identical except for a transposition of two adjacent characters will hash to
the same value.
Good values for m

primes not too close to exact powers of 2.

ii) Mid – Square

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

iv) Digit Analysis

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.

Q.15 a) Write a program to implement quick sort function with an example.

Program to implement quick sort function with an example

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

Q.15 b) Write a program to implement Knuth – Morris – Pratt Pattern Matching


Algorithm.

Knuth – Morris – Pratt Pattern Matching Algorithm:

Program:
RESULT ANALYSIS
Assignment Question Papers
Key for Assignment Question
Papers
Key for Mid Question Papers

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy