0% found this document useful (0 votes)
8 views

C Programming and Data Structures

Uploaded by

Dineshkumar. A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

C Programming and Data Structures

Uploaded by

Dineshkumar. A
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 333

https://www.poriyaan.in/ https://eee.poriyaan.

in/
CS3353 C PROGRAMMING AND DATA STRUCTURES L TPC
C Programming and Data Structures 3 0 0 3
COURSE OBJECTIVES:
• To introduce the basics of C programming language.
• To learn the concepts of advanced features of C.

in
• To understand the concepts of ADTs and linear data structures.
• To know the concepts of non-linear data structure and hashing.

n.
• To familiarize the concepts of sorting and searching techniques.

aa
UNIT I C PROGRAMMING FUNDAMENTALS (8+1 SKILL) 9

iy
Data Types – Variables – Operations – Expressions and Statements – Conditional
Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional
or
Arrays.
.p
UNIT II C PROGRAMMING - ADVANCED FEATURES
w

(8+1 SKILL) 9
w

Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays


and Functions – File Handling – Preprocessor Directives.
w

UNIT III LINEAR DATA STRUCTURES (8+1 SKILL) 9


Abstract Data Types (ADTs) – List ADT – Array-Based Implementation – Linked List
– Doubly- Linked Lists – Circular Linked List – Stack ADT – Implementation of Stack
– Applications – Queue ADT – Priority Queues – Queue Implementation –
Applications.

UNIT IV NON-LINEAR DATA STRUCTURES (8+1 SKILL) 9


Trees – Binary Trees – Tree Traversals – Expression Trees – Binary Search Tree –
Hashing - Hash Functions – Separate Chaining – Open Addressing – Linear Probing–
Quadratic Probing – Double Hashing – Rehashing.
https://www.poriyaan.in/ https://eee.poriyaan.in/
UNIT V SORTING AND SEARCHING TECHNIQUES
(8+1 SKILL) 9
Insertion Sort – Quick Sort – Heap Sort – Merge Sort –Linear Search – Binary Search.

TOTAL 45 PERIODS

in
n.
SKILL DEVELOPMENT ACTIVITIES
(Group Seminar/Mini Project/Assignment/Content Preparation / Quiz/ Surprise Test /

aa
Solving GATE questions/ etc) 5

iy
COURSE OUTCOMES:
or
CO1: Develop C programs for any real world/technical application.
CO2: Apply advanced features of C in solving problems.
.p
CO3: Write functions to implement linear and non–linear data structure operations.
w

CO4: Suggest and use appropriate linear/non–linear data structure operations for
solving a givenproblem.
w

CO5: Appropriately use sort and search algorithms for a given application.
w

CO6: Apply appropriate hash functions that result in a collision free scenario for data
storage andretrieval.

TEXT BOOKS:
1. Mark Allen Weiss, “Data Structures and Algorithm Analysis in C”, Second
Edition, PearsonEducation, 1997.
2. ReemaThareja, “Programming in C”, Second Edition, Oxford University Press,
2016.

REFERENCES:
1. Brian W. Kernighan, Rob Pike, “The Practice of Programming”, Pearson
Education, 1999.
2. Paul J. Deitel, Harvey Deitel, “C How to Program”, Seventh Edition,
Pearson Education,2013.
https://www.poriyaan.in/ https://eee.poriyaan.in/
3. Alfred V. Aho, John E. Hopcroft, Jeffrey D. Ullman, “Data Structures
and Algorithms”,Pearson Education,1983.
4. Ellis Horowitz, SartajSahni and Susan Anderson, “Fundamentals of Data
Structures”,Galgotia, 2008.

in
List of Open Source Software/ Learning website:

n.
https://www.coursera.org/specializations/data-structures-algorithms
https://nptel.ac.in/courses/112107243 https://nptel.ac.in/courses/112105598

aa
iy
or
.p
w
w
w
https://www.poriyaan.in/ https://eee.poriyaan.in/
CONTENTS
UNIT-I
C PROGRAMMING FUNDAMENTALS
1.1 Introduction to Programming Paradigms 1.1

in
1.1.1 Imperative Programming Paradigm 1.1
1.1.1.1 Procedural Programming Paradigm 1.2

n.
1.1.1.2 Object Oriented Programming 1.3
1.1.1.3 Parallel Processing Approach 1.7

aa
1.1.2 Declarative Programming Paradigm 1.7
1.1.2.1 Logic Programming Paradigms 1.7

iy
1.1.2.2 Functional Programming Paradigms 1.7
or
1.1.2.3 Database/Data Driven Programming Approach
1.1.3 Characteristics of a Good Programming Language
1.8
1.8
.p
1.2 History of C Programming 1.9
1.2.1 Features of C Programming 1.10
w

1.3 Applications of C Language 1.10


w

1.4 Structure of C Program 1.11


1.5 Lexical Elements of C 1.14
w

1.5.1 Character Set 1.15


1.5.2 Delimite 1.17
1.5.3 Keywords 1.17
1.5.4 Identifiers 1.18
1.5.5 Data Types 1.18
1.5.6 Constants 1.25
1.5.7 Variables and Declaration 1.27
1.6 Operators in C 1.29
1.6.1 Types of Operators 1.29
1.6.1.1 Arithmetic Operators 1.30
1.6.1.2 Relational Operators 1.32
1.6.1.3 Logical Operators 1.32
1.6.1.4 Assignment Operator 1.34
1.6.1.5 Increment and Decrement Operators (Unary Operators) 1.35
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.6.1.6 Conditional Operator (Or) Ternary Operator 1.37
1.6.1.7 Bitwise Operators 1.38
1.6.1.8 The Special Operator 1.39
1.7 Expressions And Statements 1.41
1.7.1 Expressions 1.41

in
1.7.2 Statements 1.41
1.8 Conditional Statements 1.42

n.
1.8.1 Conditional Branching Statement 1.43
1.8.1.1 Selection Statement 1.43

aa
1.8.1.2 Looping Statements 1.58
1.9 Functions 1.64

iy
1.9.1 Function Prototype 1.65
or
1.9.1.1 User Defined Function
1.9.1.2 Elements of User Defined Functions
1.65
1.66
.p
1.10 Recursive Functions 1.78
1.11 Arrays 1.81
w

1.11.1 Declaration of an Array 1.82


w

1.11.2 Initialization of Arrays 1.83


1.12 One Dimensional Array 1.83
w

1.12.1 Declaration of Single Dimensional Array 1.83


1.12.2 Initialization of Single Dimensional Array 1.84
1.13 Multi-Dimensional Array 1.87
1.13.1 Two Dimensional Array 1.87
1.13.2 Three-Dimensional Arrays 1.91
Review Questions 1.94

UNIT -II
PROGRAMMING - ADVANCED FEATURES
2.1 Introduction 2.1
2.2 Structure 2.1
2.2.1 Three Main Aspects of Working with Structure 2.1
2.2.1.1 Defining Structure 2.2
2.2.1.2 Initializing Structure Elements 2.3
https://www.poriyaan.in/ https://eee.poriyaan.in/
2.2.1.3 Declaring Structure Objects 2.3
2.2.2 Operations on Structures 2.4
2.2.2.1 Aggregate Operations 2.4
2.2.2.2 Segregate Operations 2.11
2.3 Union 2.12

in
2.4 Pointers 2.14
2.4.1 Pointers to Variables 2.14

n.
2.4.2 Pointer Operators 2.18
2.4.3 Arrays and Pointers 2.20

aa
2.4.3.1 Pointers with Multi-Dimensional Array 2.23
2.4.4 Functions Pointers 2.24

iy
2.5 Enumerated Data Types 2.25
or
2.5.1 Enumerated Type Declaration to Create a Variable
2.5.2 Implementing enum Using C Program
2.26
2.26
.p
2.6 File Handling 2.27
2.6.1 Why We Need File 2.27
w

2.6.2 File Operations 2.28


w

2.6.2.1 Types of Files 2.28


2.7 Preprocessor Directives 2.41
w

Review Questions 2.44

UNIT - III
LINEAR DATA STRUCTURES
3.1 Abstract Data Types (ADTS) 3.1
3.1.1 Abstract Data Type Model 3.1
3.2 List ADT 3.3
3.2.1 Operations on the List Data Structure 3.4
3.3 Array-Based Implementation 3.4
3.3.1 Properties of Array 3.4
3.3.2 Representation of an Array 3.5
3.3.3 Memory Allocation of an Array 3.5
3.3.4 Access an Element from the Array 3.6
3.3.5 Basic Operations of an Array 3.6
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.3.6 Complexity of Array Operations 3.7
3.3.7 Limitations of Array 3.7
3.3.8 Advantages of Array 3.7
3.3.9 Disadvantages of Array 3.7
3.4 Linked List 3.8

in
3.4.1 Representation of a Linked List 3.8
3.4.2 Why Use Linked List Over Array 3.8

n.
3.4.3 Declare a Linked List 3.9
3.4.4 Types of Linked List 3.9

aa
3.4.4.1 Singly-Linked List 3.9
3.4.4.2 Doubly Linked List 3.10

iy
3.4.4.3 Circular Singly Linked List 3.10
or
3.4.4.4 Circular Doubly Linked List
3.4.5 Advantages of Linked List
3.10
3.10
.p
3.4.6 Disadvantages of Linked List 3.11
3.4.7 Applications of Linked List 3.11
w

3.4.8 Operations Performed on Linked List 3.11


w

3.4.9 Complexity of Linked List 3.12


3.5 Doubly Linked List 3.12
w

3.5.1 Memory Representation of a Doubly Linked List 3.13


3.5.2 Operations on Doubly Linked List 3.14
3.5.2.1 Insertion at Beginning 3.15
3.5.2.2 Insertion at End 3.16
3.5.2.3 Insertion After Specified Node 3.18
3.5.2.4 Deletion at Beginning 3.19
3.5.2.5 Deletion at the End 3.20
3.5.2.6 Deletion of the Node Having Given Data 3.21
3.5.2.7 Searching for a Specific Node 3.22
3.5.2.8 Traversing in Doubly Linked List 3.23
3.5.3 Advantages of Doubly Linked Lists 3.23
3.5.4 Disadvantages of Doubly Linked Lists 3.24
3.6 Circular Linked List 3.24
3.6.1 Memory Representation of Circular Linked List 3.24
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.6.2 Operations on Circular Singly Linked List 3.25
3.6.2.1 Insertion at the Beginning 3.26
3.6.2.2 Insertion at the End 3.27
3.6.2.3 Deletion at the Beginning 3.28
3.6.2.4 Deletion at the End 3.30

in
3.6.2.5 Searching 3.31
3.6.2.6 Searching 3.32

n.
3.6.3 Advantages of Circular Linked Lists 3.32
3.6.4 Disadvantages of Circular Linked Lists 3.33

aa
3.7 Stack ADT 3.33
3.7.1 Working of Stack 3.33

iy
3.7.2 Operations on Stack 3.34
or
3.7.2.1 Push Operation
3.7.2.2 Pop Operation
3.34
3.35
.p
3.7.3 Applications of Stack 3.36
3.8 Implementation of Stack 3.36
w

3.8.1 Array Implementation of Stack 3.37


w

3.8.1.1 Adding an Element onto the Stack 3.37


3.8.1.1.1 Implementation of Push Algorithm in C 3.37
w

Language
3.8.1.2 Deletion of an Element from a Stack 3.38
3.8.1.2.1 Implementation of Pop Algorithm Using C 3.38
Language
3.8.1.3 Visiting Each Element of the Stack 3.39
3.8.2 Linked List Implementation Of Stack 3.40
3.8.2.1 Adding a Node to the Stack 3.40
3.8.2.1.1 Implementation of Push in C Language Program 3.41
3.8.2.2 Deleting a Node from the Stack 3.42
3.8.2.2.1 Implementation of Pop in C Language Program 3.43
3.8.2.3 Display the Nodes (Traversing) 3.43
3.8.2.3.1 Implementation of Display in C Language 3.43
Program
3.9 Applications of Stack 3.44
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.9.1.1 Infix Notation 3.46
3.9.1.2 Prefix Notation 3.46
3.9.1.3 Postfix Notation 3.46
3.9.2 Balancing Symbols 3.48
3.9.3 Processing Function Calls 3.50

in
3.9.4 Backtracking 3.51
3.9.5 Reverse a Data 3.53

n.
3.9.5.1 Reverse a String 3.53
3.9.5.2 Converting Decimal to Binary 3.54

aa
3.10 Queue ADT 3.55
3.10.1 Applications of Queue 3.55

iy
3.10.2 Basic Operations in Queue 3.56
3.10.3 Types of Queue or
3.10.3.1 Simple Queue or Linear Queue
3.56
3.56
.p
3.10.3.2 Circular Queue 3.57
3.10.3.3 Priority Queue 3.57
w

3.10.3.4 Deque 3.58


w

3.11 Priority Queues 3.58


3.11.1 Characteristics of a Priority Queue 3.59
w

3.11.2 Types of Priority Queue 3.60


3.11.3 Representation of Priority Queue 3.60
3.11.4 Implementation of Priority Queue 3.61
3.11.5 Analysis of Complexities Using Different Implementations 3.62
3.11.6 Heap 3.62
3.11.7 Priority Queue Operations 3.63
3.11.7.1 Inserting the Element in a Priority Queue 3.63
3.11.7.2 Removing the Minimum Element From the Priority 3.65
Queue
3.11.7.3 Peeking the Element From a Priority Queue 3.66
3.11.8 Applications of Priority Queue 3.67
3.12 Queue Implementation 3.67
3.12.1 Array Implementation of Queue 3.67
3.12.1.1 Algorithm to Insert Any Element in a Queue 3.68
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.12.1.3 Algorithm to Delete an Element From the Queue 3.70
3.12.1.4 Implementation Using C Function 3.70
3.12.1.5 Drawback of Array Implementation 3.71
3.12.2 Linked List Implementation of Queue 3.71
3.12.2.1 Insertion on Linked Queue 3.72

in
3.12.2.2 Implementation Using C Function 3.73
3.13 Applications of Queue 3.74

n.
3.13.1 Type Declarations for Queue-Array Implementation 3.74
3.13.2 Routine to Test Whether a Queue is Empty-Array 3.74

aa
Implementation
3.13.3 Routine to Make an Empty Queue-Array Implementation 3.75

iy
3.13.4 Routines to Enqueue-Array Implementation 3.75
3.13.5 Other Applications
Review Questions
or 3.76
3.77
.p
UNIT - IV
w

NON-LINEAR DATA STRUCTURES


w

4.1 Introduction to Tress 4.1


w

4.1.1 Example of Tree Data Structure 4.1


4.1.2 Basic Terminologies in Tree Data Structure 4.2
4.1.3 Properties of a Tree 4.2
4.1.4 Syntax for Creating a Node 4.3
4.2 Binary Trees 4.3
4.2.1 Binary Tree Representation 4.3
4.2.2 Types of Binary Trees 4.4
4.2.3 Benefits of Binary Trees 4.4
4.3 Tree Traversal 4.6
4.3.1 Types of Tree Traversal 4.6
4.4 Expression Trees 4.10
4.4.1 Properties of an Expression Tree 4.10
4.4.2 Construction of Expression Tree 4.10
4.4.3 Example - Postfix Expression Construction 4.11
4.4.4 Implementation of Expression Tree in C Programming Language 4.12
https://www.poriyaan.in/ https://eee.poriyaan.in/
4.4.5 Use of Expression Tree 4.15
4.5 Binary Search Tree 4.15
4.5.1 Advantages of Binary Search Tree 4.16
4.5.2 Example of Creating a Binary Search Tree 4.16
4.5.3 Operations Performed on a Binary Search Tree 4.20

in
4.5.3.1 Searching in Binary Search Tree 4.20
4.5.3.1.1 Steps Involved in Searching in a Binary Search 4.20

n.
Tree
4.5.3.1.2 Algorithm to Search an Element in Binary 4.22

aa
Search Tree
4.5.3.2 Deletion in Binary Search Tree 4.22

iy
4.5.3.2.1 When the Node to be Deleted is the Leaf Node 4.22
or
4.5.3.2.2 When the Node to be Deleted has Only One 4.23
Child
.p
4.5.3.3 Insertion in Binary Search Tree 4.24
4.5.3.4 The Complexity of the Binary Search Tree 4.24
w

4.5.3.5 Implementation of Binary Search Tree 4.25


w

4.6 Hashing 4.29


4.6.1 Examples 4.29
w

4.7 Hash Function 4.30


4.7.1 Hash Table 4.30
4.7.2 How Does Hashing in Data Structure Works 4.31
4.8 Separate Chaining 4.32
4.8.1 Separate Chaining Hash Table 4.32
4.8.2 Example for Separate Chaining 4.32
4.8.3 How to Avoid Collision in Separate Chaining Method 4.33
4.8.4 Practice Problem Based on Separate Chaining 4.34
4.8.5 Advantages and Disadvantages of Separate Chaining 4.37
4.9 Open Addressing 4.37
4.10 Linear Probing 4.37
4.10.1 Solution 4.38
4.11 Quadtratic Probing 4.39
4.12 Double Hashing 4.41
https://www.poriyaan.in/ https://eee.poriyaan.in/
4.12.1 Double Hashing - Hash Function 1 or First Hash Function – 4.41
Formula
4.12.2 Double Hashing - Hash Function 2 or Second Hash Function – 4.42
Formula
4.12.3 Double Hashing Example - Closed Hash Table 4.42
4.13 Re-Hashing 4.44

in
4.13.1 Why Rehashing is Done 4.44

n.
4.13.2 What is Load Factor in Hashmap 4.44
4.13.3 How Rehashing is Done 4.44

aa
4.13.4 Rehashing Steps 4.45
Review Questions 4.46

iy
or
UNIT - V
SORTING AND SEARCHING TECHNIQUES
.p
5.1 Introduction to Sorting 5.1
5.2 Insertion Sort 5.2
w

5.2.1 Algorithm 5.3


w

5.2.2 Working of Insertion Sort Algorithm 5.3


5.2.3 Analysis of Insertion Sort 5.4
w

5.2.4 Applications 5.4


5.3 Quick Sort 5.6
5.3.1 Algorithm for Quick Sort 5.6
5.3.2 Working of Quick Sort Algorithm 5.6
5.3.3 Quicksort Complexity 5.8
5.3.4 Applications of Quick Sort 5.8
5.4 Heap Sort 5.11
5.4.1 What is a Heap 5.11
5.4.2 Working of Heap Sort Algorithm 5.11
5.4.3 Heapsort Complexity 5.16
5.4.4 Heap Sort Applications 5.16
5.5 Merge Sort 5.18
5.5.1 Algorithm 5.19
5.5.2 Working of Merge Sort Algorithm 5.19
https://www.poriyaan.in/ https://eee.poriyaan.in/
5.5.3 Merge Sort Complexity 5.19
5.5.4 Merge Sort Applications 5.19
5.6 Introduction to Searching 5.23
5.6.1 Searching Methods 5.24
5.7 Linear Search 5.24

in
5.7.1 Steps Used in the Implementation of Linear Search 5.25
5.7.2 Algorithm 5.25

n.
5.7.3 Working of Linear Search 5.25
5.7.4 Linear Search Complexity 5.27

aa
5.7.5 Applications of Linear Search Algorithm 5.27
5.7.6 Advantages and Disadvantages 5.27

iy
5.8 Binary Search 5.28
5.8.1 Algorithm or
5.8.2 Working of Binary Search
5.29
5.29
.p
5.8.3 Binary Search Complexity 5.31
5.8.4 Advantages and Disadvantages 5.31
w

5.8.5 Linear Search Vs Binary Search 5.33


w

Review Questions 5.34


w
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
C PROGRAMMING

n.
FUNDAMENTALS

aa
Data Types – Variables – Operations – Expressions and Statements – Conditional

iy
Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional
Arrays.
or
.p
1.1 INTRODUCTION TO PROGRAMMING PARADIGMS
w

➢ Paradigm can also be termed as method to solve some problem or do some task.
➢ Programming paradigm is an approach to solve problem using some
w

programming language or also we can say it is a method to solve a problem using


w

tools and techniques that are available to us following some approach.


➢ There are lots for programming language that are known but all of them need to
follow some strategy when they are implemented and this methodology/strategy
is paradigms. Apart from varieties of programming language there are lots of
paradigms to fulfil each and every demand. The programming paradigm is
divided into two broad categories.
• Imperative programming paradigm
• Declarative programming paradigm

1.1.1 Imperative programming paradigm


➢ It is one of the oldest programming paradigm. It features close relation to
machine architecture. It is based on Von Neumann architecture. It works by
changing the program state through assignment statements. It performs step by
step task by changing state. The main focus is on how to achieve the goal. The
1.2 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
paradigm consist of several statements and after execution of all the result is
stored.
Advantage
1. Very simple to implement
2. It contains loops, variables etc.

in
Disadvantage

n.
1. Complex problem cannot be solved
2. Less efficient and less productive

aa
3. Parallel programming is not possible

iy
Examples of Imperative programming paradigm: C, FORTAN, Basic

or
.p
w
w
w

Figure 1.1 Types Programming Paradigms


➢ Imperative programming is divided into three broad categories: Procedural,
OOP and parallel processing. These paradigms are as follows:
1.1.1.1 Procedural programming paradigm
➢ This programming has a single program that is divided into small piece called
procedure (also known as functions, routines, subroutines). These procedures are
C Programming and Data Structures 1.3
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ From the main controlling procedure, a procedure call is used to invoke the
required procedure. After the sequence is processed, the flow of control continues
from where the call was made.
➢ The main program coordinates calls to procedures and hands over appropriate data
as parameters. The data is processed by the procedures and once the program has
finished, the resulting data is displayed.

in
➢ Example: C, C++, JAVA, Pascal.

n.
1.1.1.2 Object Oriented Programming

aa
➢ It is a type of programming in which programmers define not only the data type
of a data structure, but also the types of operations (functions) that can be applied

iy
to the data structure.
➢ In this way, the data structure becomes an object that includes both data and
or
functions. In addition, programmers can create relationships between one object
.p
and another. For example, objects can inherit characteristics from other objects.
➢ One of the principal advantages of object-oriented programming techniques over
w

procedural programming techniques is that they enable programmers to create


modules that do not need to be changed when a new type of object is added. A
w

programmer can simply create a new object that inherits many of its features from
w

existing objects. This makes object-oriented programs easier to modify. The basic
concepts of OOP are as follows:
1. Objects 2. Classes
3. Data abstraction and encapsulation 4. Inheritance
5. Polymorphism 6. Dynamic binding
7. Message passing.
Objects:
Objects are the basic run-time entities in an object oriented system. They may
represent a person, place or a bank a/c or a table of data that the program has to handle.
When a program is executed the objects interact by sending messages to one another.
They can interact without knowing the details of each other’s data or code. Thus an object
is considered to be a partitioned area of computer memory that stores data and set of
functions that can access the data.
1.4 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Classes:
The entire set of data and code of an object can be made a user-defined data type
with the help of a class. Objects are variables of the type class. Each object is associated
with the data of type class with which they are created. A class is thus a collection of
objects of similar type.

in
n.
aa
iy
or
.p
w

Fig. 1.2 Class and Objects


w

Data abstraction and encapsulation


w

Encapsulation:
The wrapping up of data and functions in to a single unit (that unit is called a
class) is known as encapsulation. The data is not accessible to the outside world (other
functions which are not the members of that class) and only those functions which are
wrapped in the class can access it. This insulation of data from the direct access by the
program is called data hiding or information hiding.
Abstraction:
Abstraction refers to the act of representing essential features without including
the background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost and functions to operate
on these attributes. The attributes are sometimes called data members because they hold
information. The functions that operate on these data are called member functions.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
C Programming and Data Structures 1.5
https://www.poriyaan.in/ https://eee.poriyaan.in/
concept of inheritance provides the idea of reusability. This means that we can include
additional features to an existing class without modifying it. It is important because it
supports the concept of classification. C++ supports different types of inheritance such as
single inheritance, multiple inheritance, multilevel inheritance and hierarchical
inheritance.
To understand the concept of inheritance, let us consider an example of vehicles

in
as shown in Fig.1.3. Here the class car is a subclass of automatic vehicle, which is again

n.
a subclass of the class vehicle. This implies that the class car has all the characteristics of
automatic vehicles which in turn has all the properties of vehicles. However, car has some

aa
unique features which differentiate it from other subclasses. For example, it has four
wheels and five gears, while scooter has two wheels and four gears.

iy
or
.p
w
w
w

Fig. 1.3 Inheritance


Polymorphism:
Polymorphism, a Greek term means the ability to take more than one form. An
operation may exhibit different behaviour in different instances. The behaviour depends
up on the types of data used in the operation. The concepts of polymorphism are Operator
overloading and Function overloading. For two numbers, the operator + will give the sum.
If the operands are strings, then the operation would produce a third string by
concatenation. Thus the process of making an operator to exhibit different behaviours in
different instances is known as operator overloading. Similarly, we can use a single
function to perform different tasks which is known as function overloading. A single
function can be used to handle different number and types of arguments.
Binding:
1.6 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Dynamic Binding:
Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at run-time. It is associated with polymorphism
concept.
Message Passing:

in
OOP consists of a set of objects that communicate with each other by sending and
receiving information. A message for an object is a request for execution of a procedure

n.
(function) and therefore will invoke a function in the receiving object that generates the

aa
desired result.
Benefits of OOP

iy
➢ Through inheritance we can eliminate redundant code and extend the use of
existing classes.
or
➢ We can build secure programs by the principle of data hiding.
.p
➢ It is easy to partition the work in a project based on objects.
➢ Object oriented systems can be easily upgraded from small to large systems.
w

➢ Communication with external systems are much simpler by means of message


w

passing techniques.
➢ Software complexity can be easily managed.
w

Applications of OOP
OOP can be applied in the following areas:
➢ Real time systems
➢ Simulation and modeling
➢ Object oriented data bases
➢ Hypertext, hypermedia and expertext
➢ Artificial Intelligence and expert systems.
➢ Neural networks and parallel programming
➢ Office automation systems
➢ CIM / CAM / CAD systems
Example: Simula, JAVA, Python, VB.NET, Ruby.
C Programming and Data Structures 1.7
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.1.1.3 Parallel processing approach
➢ Parallel processing is the processing of program instructions by dividing them
among multiple processors. A parallel processing system possess many numbers
of processor with the objective of running a program in less time by dividing
them. This approach seems to be like divide and conquer.

in
➢ Examples are NESL (one of the oldest one) and C/C++ also supports because of
some library function.

n.
1.1.2 Declarative programming paradigm

aa
➢ It is divided as Logic, Functional, and Database. In computer science
the declarative programming is a style of building programs that expresses logic

iy
of computation without talking about its control flow.
➢ It often considers programs as theories of some logic. It may simplify writing
or
parallel programs. The focus is on what needs to be done rather how it should
.p
be done basically emphasize on what code is actually doing.
➢ It just declare the result we want rather how it has be produced. This is the only
w

difference between imperative (how to do) and declarative (what to do)


w

programming paradigms.
w

1.1.2.1 Logic programming paradigms


➢ It can be termed as abstract model of computation. It would solve logical
problems like puzzles, series etc.
➢ In logic programming we have a knowledge base which we know before and
along with the question and knowledge base which is given to machine, it
produces result. In normal programming languages, such concept of knowledge
base is not available but while using the concept of artificial intelligence,
machine learning.
➢ In logical programming the main emphasize is on knowledge base and the
problem. The execution of the program is very much like proof of mathematical
statement, e.g., Prolog

1.1.2.2 Functional programming paradigms


➢ The functional programming paradigms has its roots in mathematics and it is
language independent. The key principal of this paradigms is the execution of
1.8 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ The central model for the abstraction is the function which are meant for some
specific computation and not the data structure. Data are loosely coupled to
functions.
➢ The function hide their implementation. Function can be replaced with their
values without changing the meaning of the program. Some of the languages
like Perl, java script mostly uses this paradigm.

in
1.1.2.3 Database/Data driven programming approach

n.
➢ This programming methodology is based on data and its movement. Program

aa
statements are defined by data rather than hard-coding a series of steps.
➢ A database program is the heart of a business information system and provides

iy
file creation, data entry, update, query and reporting functions. There are several
programming languages that are developed mostly for database application.
or
➢ For example SQL. It is applied to streams of structured data, for filtering,
.p
transforming, aggregating (such as computing statistics), or calling other
programs. So it has its own wide application.
w

1.1.3 Characteristics of a Good Programming Language


w

➢ A programming language must be simple, easy to learn and use, have good
w

readability and human recognizable.


➢ Abstraction is a must-have Characteristics for a programming language in which
ability to define the complex structure and then its degree of usability comes.
➢ A portable programming language is always preferred.
➢ Programming language’s efficiency must be high so that it can be easily
converted into a machine code and executed consumes little space in memory.
➢ A programming language should be well structured and documented so that it is
suitable for application development.
➢ Necessary tools for development, debugging, testing, and maintenance of a
program must be provided by a programming language.
➢ A programming language should provide single environment known as
Integrated Development Environment (IDE).
➢ A programming language must be consistent in terms of syntax and semantics.
C Programming and Data Structures 1.9
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.2 HISTORY OF C PROGRAMMING
➢ C is a general purpose structured programming language. C was developed by
Dennis Ritchie at AT & T Bell laboratories in 1972. It is an outgrowth of an earlier
language called BCPL & B. It was named as C to present it as the successor of B
language which was developed earlier by Ken Thompson in 1970 at AT & T Bell

in
laboratories. The various stages in evolution of C language is given in Fig 1.4.

n.
CPL (Combined Programming Language)
Developed by Cambridge and University of London in 1963

aa
iy
BCPL (Basic Combined Programming Language)
Developed by Martin Richards in 1967
or
.p
B Language Developed by Ken Thompson at AT and T Bell
Laboratory in 1970
w
w

C Language Developed by Dennis Ritchie at AT and T


w

Bell Laboratory in 1972

Fig. 1.4 Various Stages in Evaluation of C Languages


➢ C is a highly portable, which means that C program written for one computer can
be run on another with little or no modification. C is well suited for structured
programming; thus user has to think of a problem in terms of function modules
and blocks.
➢ The proper collection of these modules would makes a complete program. This
modular structures makes program debugging, testing and maintenance easier.
➢ Another important feature of C is its ability to extend itself. A C program is
basically a collection of functions that are supported by the C library. We can add
our own functions to the C library. With the availability of a large number of
functions, the programming task becomes simple.
➢ Its flexibility allows C to be used for system programming (For example: the
UNIX operating system, the C compiler and all UNIX application software are
1.10 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.2.1 Features of C Programming
➢ C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language

in
4. structured programming language

n.
5. Rich Library

aa
6. Memory Management
7. Fast Speed

iy
8. Pointers
9. Recursion or
10. Extensible
.p
1.3 APPLICATIONS OF C LANGUAGE
w

➢ The applications of C are not only limited to the development of operating


w

systems, like Windows or Linux, but also in the development of GUIs (Graphical
User Interfaces) and, IDEs (Integrated Development Environments).
w

➢ Here are some striking applications offered by the C programming language:


1. Operating Systems
The first operating system to be developed using a high-level programming language
was UNIX, which was designed in the C programming language. Later on, Microsoft
Windows and various Android applications were scripted in C.
2. Embedded Systems
The C programming language is considered an optimum choice when it comes to
scripting applications and drivers of embedded systems, as it is closely related to machine
hardware.
3. GUI
GUI stands for Graphical User Interface. Adobe Photoshop, one of the most
popularly used photo editors since olden times, was created with the help of C. Later on,
Adobe Premiere and Illustrator were also created using C.
C Programming and Data Structures 1.11
https://www.poriyaan.in/ https://eee.poriyaan.in/
4. New Programming Platforms
Not only has C given birth to C++, a programming language including all
the features of C in addition to the concept of object-oriented programming but, various
other programming languages that are extensively used in today’s world like MATLAB
and Mathematica. It facilitates the faster computation of programs.

in
5. Google
Google file system and Google chromium browser were developed using C/C++.

n.
Not only this, the Google Open Source community has a large number of projects being
handled using C/C++.

aa
6. Mozilla Firefox and Thunderbird
Since Mozilla Firefox and Thunderbird were open-source email client projects,

iy
they were written in C/C++.
7. MySQL or
MySQL, again being an open-source project, used in Database Management
.p
Systems was written in C/C++.
w

8. Compiler Design
One of the most popular uses of the C language was the creation of
w

compilers. Compilers for several other programming languages were designed keeping in
w

mind the association of C with low-level languages, making it easier to be comprehensible


by the machine.
Several popular compilers were designed using C such as Bloodshed Dev-C,
Clang C, MINGW, and Apple C.
9. Gaming and Animation
Since the C programming language is relatively faster than Java or Python, as it is
compiler-based, it finds several applications in the gaming sector. Some of the simplest
games are coded in C such as Tic-Tac-Toe, The Dino game, The Snake game and many
more. Increasing advanced versions of graphics and functions, Doom3 a first-person
horror shooter game was designed by id Software for Microsoft Windows using C in
2004.

1.4 STRUCTURE OF C PROGRAM


➢ As C is a programming language, let us go into the concepts of programming in
C and it is a structured programming language. Every C program contains a
1.12 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ These building blocks should be written in the correct order and procedure, for
the C program to execute without any errors. The structure of C is given below.
documentation section
preprocessor section
definition section

in
global declaration section

n.
main( )
{

aa
declaration part;
executable part;

iy
}
or
sub program
{
.p
body of the subprogram;
w

}
w

Program 1.1
w

/* Program to find the area of a circle */ /* Documentation Section */


# include<stdio.h> /* Preprocessor Section */
# include<conio.h>
# define PI 3.14 /* Definition Section */
void main() /* main( ) function */
{
float area,r; /* Local variable declaration */
clrscr(); // Executable part of the program
printf("\n Enter the radius:\n");
scanf("%f",&r);
area= PI*(r*r);
printf("\n Area of the Circle = %8.2f", area);
C Programming and Data Structures 1.13
https://www.poriyaan.in/ https://eee.poriyaan.in/
getch();
}
Output
Enter the radius: 4.5
Area of the Circle = 63.58

in
Program 1.2

n.
/* Program to find the sum of two numbers using function */

aa
/*Documentation Section */
# include<stdio.h> /* Preprocessor Section */

iy
# include<conio.h>
int a,b;
int add(int,int);
or
/* Global Variable declaration */
/* Function declaration */
.p
void main() /* main( ) function */
w

{
w

int c; /* Local Variable declaration */


clrscr(); // Executable part of the main() program
w

printf("\n Enter the values for a and b:\n");


scanf("%d %d",&a,&b);
c = add(a,b);
printf("\n Sum of %d + %d = %d", a,b,c);
getch();
}
int add(int a,int b) /* Subprogram of add() function definition */
{
int c; /* Local Variable declaration */
c=a+b; // Executable part of the function
return(c);
}
1.14 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Output
Enter the values for a and b: 5 3
Sum of 5 + 3 = 8
Documentation section
The documentation section is included in the comments, which contains the author

in
name, the date of development and the program details.

n.
Preprocessor section

aa
The preprocessor section provides preprocessor statements which direct the
compiler to link functions from the system library.

iy
Definition section
The definition section defines all symbolic constants refer to assigning a macro of
or
a name to a constant. The general syntax of a symbolic constant is
.p
#define constant_name constant_value
Global declaration section
w

The global declaration section contains variable declarations which can be


w

accessed anywhere within the program.


w

Main section
Main section is divided into two portions, the declaration part and the executable
part. The declaration part used to declare any variables in the main block of the program.
The executable part contains set of statements within the open and close braces. Execution
of the program begins at the opening braces and ends at the closing braces.
User defined function section
The user defined function section (or) the Sub program section contains user
defined functions which are called by the main function. Each user defined function
contains the function name, the argument and the return value.

1.5 LEXICAL ELEMENTS OF C


➢ Data’s can be of any kind, it may be numbers, characters and strings. These data
should be processed in order to produce the information output. Programming
languages are used for this processing of data into information.
C Programming and Data Structures 1.15
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Every program consists of a sequence of steps or instruction for processing data.
Each instruction must abide to certain syntax rules of grammar of the particular
language. Likewise C has its own grammar. Data may be either a constant or a
variable.
➢ In ‘C’ language each and every individual unit is called as Token or Lexical
element. The various ‘C’ Tokens are

in
i) Character set

n.
ii) Delimiters

aa
iii) Keywords
iv) Identifiers

iy
v) Data types
vi) Constants
vii) Variables
or
.p
1.5.1 Character Set
w

➢ The set of characters used to write the program words, expressions and statements.
w

It is the basic building block to form program elements. The set of characters used
in a language is known as its character set. These characters can be represented
w

in the computer.
➢ The C character set consists of upper and lower case alphabets, digits, special
characters and white spaces. The alphabets and digits are together called the
alphanumeric characters.
i) Alphabets
A, B, C,…..Z
a, b, c,….z
ii) Digits
0123456789
1.16 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
iii) Special Characters
Table 1.1 List of Special Characters

in
n.
aa
iy
or
.p
w

Table 1.1 List of Special Characters


iv) White space characters
w

Blank space, newline, form feed, horizontal tab, vertical tab


w

v) Trigraph characters
The trigraph characters are used to type certain characters that are not
available on some keyboards. It consists of three characters. Two question
marks followed by character.
C Programming and Data Structures 1.17
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.5.2 Delimiters
➢ The language pattern of C uses a special kind of symbols, which are called
delimiters. They are given in Table. 1.3.

in
n.
aa
iy
or
.p
Table 1.3 Delimiters
1.5.3 Keywords
w

➢ These are certain reserved words called keywords, which are standard, predefined
w

meanings in C. They must be written in lower case. There are 32 keywords


w

available in C. The standard keywords are shown in Table 1.4.

Table 1.4 Keywords in C


1.18 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.5.4 Identifiers
➢ Identifiers are the names defined by the programmer for various program elements
such as variables, constant and functions. An identifier consists of a sequence of
letters and digits.
➢ The following rules are to be followed to declare an identifier.

in
i) The first character must be a letter followed by a letter or a digit.

n.
ii) Special characters are not allowed except underscore.
iii) The length of the variable varies from one compiler to another. Generally,

aa
most of the compilers support eight characters excluding extension. However,
the ANSI standard recognizes the maximum length of a variable up to 31

iy
characters.
iv) The variable should not be a C keyword.
or
v) The variable names may be a combination of upper and lower characters. For
.p
example, suM and sum are not the same variable.
vi) The variable name should not start with a digit.
w

Examples
w

➢ The following names are valid identifier


w

1.5.5 Data Types


➢ The C language supports different types of data. Each data may be represented
differently within the computer memory. Typical memory requirements for each
data will determine the possible range of values for that data type.
➢ The varieties of data types available allow the programmer to select the type
appropriate to the needs of the application as well as the machine.
C Programming and Data Structures 1.19
https://www.poriyaan.in/ https://eee.poriyaan.in/
C supports three categories of data types:
1. Primary data type 2. Derived data type 3. User defined data type.

in
n.
aa
iy
or
.p
w
w
w

Fig. 1.5 Classification of ‘C’ Data types


Primary Data Types
➢ C compiler supports the following four Fundamental/ Primary/ Primitive/ Basic/
Built-in data types:
o Character: Character data type is used to store a character. A variable of
character data type allocated only one byte of memory and can store only one
character. Keyword char is used to declare variables of type character. The
range of character (char) data type is -128 to 127. For Example: char ch = ‘A’;
o Integer: Integer data type is used to store a value of numeric type. Keyword
1.20 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
of integer data type is dependent on the operating system. For example the size
of integer data type in a 32 bit computer is 4 bytes whereas size of integer data
type in 16 bit computer is 2 bytes. For Example: int count = 10;
o Float: Floating point data type is used to store a value of decimal values. The
memory size of a variable of floating point data type is dependent on the
Operating System. Keyword float is used to declare variables of floating data

in
type. For example the size of a floating point data type in a 16 bit computer is

n.
4 bytes. For Example: float rate = 5.6;
o Double: Double data type is similar to floating data type except that it

aa
provides up to ten digits of precision and occupies eight bytes of memory. For
Example: double d = 11676.2435676542;

iy
o Void Data Type: Void is an empty data type that has no value. This can be
or
used in functions and pointers.
Type modifiers in C
.p
➢ In c language Data Type Modifiers are keywords used to change the current
w

properties of data type. Data type modifiers are classified into the following types.
o Long
w

o Short
w

o Unsigned
o signed
➢ Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable. For example, storage
space for int data type is 4 bytes for a 32 bit processor. We can increase the range
by using long int which is 8 bytes. We can decrease the range by using short int
which is 2 bytes.
long
➢ This can be used to increase the size of the current data type by 2 more bytes,
which can be applied on int or double data types. For example int occupy 2 bytes
of memory; if we use long with integer variable, then it occupies 4 bytes of
memory.
C Programming and Data Structures 1.21
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
Syntax

iy
long a; —> by default which represent long int
short or
➢ In general int data type occupies different memory spaces for a different operating
.p
systems; to allocated fixed memory space a short keyword can be used.
w

Syntax
short int a; —> occupies 2 bytes of memory space in every operating system
w

unsigned
w

➢ This keyword can be used to make the accepting values of a data type of positive
data type.
Syntax
unsigned int a = 100; // right
unsigned int a = -100; // wrong
Signed
➢ This keyword accepts both negative and positive values and this is the default
property or data type modifier for every data type.
int a = 10; // right
int a = -10; // right
signed int a = 10; // right
signed int a = -10; // right
1.22 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
Table 1.5 Size and range of Integer type on 16-bit machine

iy
or
.p
w
w

Table 1.6 Size and range of Float type on 16-bit machine


w

Table 1.7 Size and range of Character type on 16-bit machine


Derived data types
➢ Derived data types are derived from the collection of primary data types. C
supports the following derived data types.
➢ Arrays
o Array is a collection of variables of same data type that are referenced by a
common name.
Syntax: <datatype> <variable name> [Index];
C Programming and Data Structures 1.23
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Functions
o A function is a self-contained program segment (block of statements) that
carries out some specific, well defined task.
Syntax for function prototype
<return datatype> function name (forma) arg, formal arg2 ... formal arg

in
n);

n.
Syntax for function definition
<return type> function name (parameter list)

aa
parameter declarations
{

iy
body of the function;
or
return (expression);
}
.p
Example
w

void swap (int x, int y)


w

{
w

int z;
z = x;
x = y;
y = z;
}
➢ Pointers
o Pointer is a variable which stores the address of another variable.
Example
int *p; // declaration of pointer
int x; // declaration of variable
p=&x; // pointer variable stores the address of x variable.
x=5 ; // x variable assigned with value 5.
1.24 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
User defined data types
➢ The user defined data types enable a program to invent his own data types and
define what values it can taken on. Thus these data types can help a programmer
to reducing programming errors.
➢ C supports the following user defined data types.

in
o Structures

n.
A structure is a single entity representing a collection of data items of
different data types.

aa
Example
struct student

iy
{
int roll_no;
char fname[25];
or
.p
char branch[15];
w

int marks;
w

}s1;
o Unions
w

A union is a data type in ‘c’ which allows overlay of more than one variable
in the same memory area.
Example
union emp
{
char name[20];
char eno[10];
}
union emp e1;
o Enumerated data type
A enumerated data type is a set of values represented by identifiers called
enumeration constants. It is a user-defined data type and the general format of
C Programming and Data Structures 1.25
https://www.poriyaan.in/ https://eee.poriyaan.in/
enum name {number 1, number 2, ... number n};
In above format enum is a keyword, name is given by the programmer by the
identifier rules. number 1, number 2, ... number n are the member of
enumerated datatype.
o Type definition

in
“type definition” that allows user to define an identifier that would represent
a data type using an existing data type.

n.
Syntax:

aa
typedef type identifier;
typedef <existing_data_type> <new_user_define_data_type>;

iy
Example
typedef int number; or
typedef long big_ number;
.p
typedef float decimal;
w

number visitors = 25;


w

big_number population = 12500000;


decimal radius = 3.5;
w

1.5.6 Constants
1.26 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Constants are fixed values and they remain unchanged during the execution of the
program. The constants are classified as follows:
Integer constants
➢ It consist of a sequence of digits without any decimal point. Integer constant can
be written in three different number systems: decimal, octal and hexadecimal. A

in
decimal integer constant can consist of any combination of digits taken from the
set 0 through 9.

n.
1. Decimal number – 0 to 9

aa
2. Octal number – 0 to 7
3. Hexadecimal number – 0 to 9, A, B, C, D, E, F

iy
➢ Examples
or
Decimal number – 10, 145,-89, 067 etc.
Octal number – 037, 0, 057, 0456 etc.
.p
Hexadecimal number – 0x4, 0x9C, 0xAFE etc.
w

➢ Rules for an integer constant


w

o It must have at least one digit.


o Decimal point is not allowed.
w

o It can be either positive or negative.


o If it is negative the sign must be preceded. For positive the sign is not
necessary.
o No commas or blank spaces are allowed.
o The allowable range for integer constant is –32,768 to +32,767
Real Constant
➢ It is made up of a sequence of numeric digits with presence of a decimal point.
➢ It is to represent quantities that vary continuously such as distance, height,
temperature etc.
➢ Example:
Distance=134.9;
Height=88.10;
C Programming and Data Structures 1.27
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Rules for a real constant
o It must have one digit.
o It must have decimal point.
o It can be either positive or negative.
o If it is negative the sign must be preceded. For positive the sign is not

in
necessary.
o No commas or blank spaces are allowed.

n.
Character constants

aa
Single Character Constant
➢ It contains a single character enclosed within a pair of single quote marks.

iy
Example
‘d’, ‘r’, ‘6’, ‘_’ or
String Constant
.p
➢ It is a sequence of characters enclosed in double quotes.
w

➢ The characters may be letters, numbers, special characters and blank spaces
w

➢ At the end of string ‘\0’ is automatically placed.


➢ Example
w

“hai”
“4565”

1.5.7 Variables and Declaration


➢ Variables are identifiers whose value changes during the execution of the
program. Variables specify the name and type information. The compiler allocates
memory for a particular variable based on the type.
➢ Variables can be modified using the variable name or address of the variable. The
variable name must be chosen in a meaningful way. The declaration of the
variable must be done before it can be used in the program.
➢ The general syntax of the variable declaration is given below.
datatype : var1, var2, ….,varn;
where datatype : may be any data type
1.28 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Examples
1. int sum, count;
2. int rollno;
3. float int_rate;
4. double avg, netsal;

in
5. char char;
Variable declaration with qualifiers

n.
Examples

aa
1. short int number;
2. unsigned int total;

iy
3. long int ser_no;
4. long double volume;
Variable Initialization
or
.p
➢ Assigning a relevant value to a variable for the first time in a program is known
as initialization. Sometimes a variable may be initialized on its declaration itself.
w

Variables can be initialized with a constant value or expression.


w

Syntax:
w

datatype variablename = expression;


(or)
datatype variablename = constant;
Example
1. int c = 10, d = c + 5;
2. float rate = 12.5;
3. char ch = ‘Y’;
4. int count = 0 , sum = 0;
5. float pi = 3.14;
CONSTANT AND VOLATILE VARIABLE
Constant variable
➢ If we want that the value of a certain variable remain the same or remain
unchanged during the execution of a program, then it can be done only by
C Programming and Data Structures 1.29
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ The keyword constant is then added before the declaration. It tells the compiler
that the variable is a constant. Thus, constant declared variables are protected from
modification.
Example
const int a = 20;

in
where, const is a keyword, a is a variable name and 20 is a constant value. The
compiler protects the value of ‘a’ from modification. The user cannot assign any

n.
value to a; by scanf ( ) statement the value can be replaced.

aa
Volatile variable
➢ The volatile variables are those variables that are changed at any time by any other

iy
external program or the same program. The syntax is as follows.
Example
volatile int b;
or
.p
where volatile is a keyword and b is a variable If the value of a variable in the
current program is to be maintained constant and desired not to be changed by any
w

other external operation, then the declaration of the variable will be as follows;
w

volatile const b = 20;


w

1.6 OPERATORS IN C
Operator: An operator is a symbol that specifies an operation to be performed on
operands. Eg: x= a+b; where + is an operator.
Operands: An operand is an entity on which an operation is to be performed. An operand
can be a variable name, a constant, a function call or a macro name.
Eg. x= a+b; where x, a, b are the operands.
Expression: An expression is a sequence of operands and operators that specifies the
computations of a value. An expression is made up of one or more operands. Eg. x= a+b.

1.6.1 Types of Operators


1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
1.30 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
5. Increment and Decrement Operators
6. Conditional Operators (Ternary Operators)
7. Bitwise Operators
8. Special Operators

in
1.6.1.1 Arithmetic Operators
➢ Addition, subtraction, multiplication, division and modulo are the arithmetic

n.
operations.
➢ The arithmetic operators are used for numerical calculations between two

aa
Constants

iy
Operators Explanations Examples
+ Addition 2+2=4
-
or
Subtraction 3-2=1
.p
* Multiplication 5 * 4 =20
/ Division 10 / 2 = 5
w

% Modular Division 11 % 2 = 1
w

Example:
w

void main()
{
int a=5, b=4, c;
c=a-b;
printf(“%d”, c);
}
➢ The following table show the division operator on various data types.
Operation Result Example
int/int int 2/5=0
real/int real 5.0/2=2.5
int/real real 5/2.0=2.5
C Programming and Data Structures 1.31
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Arithmetic operators can be classified as
o Unary arithmetic – it requires only one operand.
Example: +a, -b
o Binary arithmetic – it requires two operands.
Example: a+b, a-b, a/b, a%b

in
o Integer arithmetic – it requires both operands to be integer type for

n.
arithmetic operation.
Example:

aa
a=4, b=3
a+b =4+3 =7

iy
a-b =4-3=1
or
o Floating Point arithmetic – It requires both operands to be float type for
arithmetic operation.
.p
Example:
w

a=6.5, b=3.5
w

a+b =6.5+3.5 =10.0


w

a-b =6.5-3.5=3.0
Program 1.3
#include<stdio.h>
#include<conio.h>
void main()
{
int b,c;
int sum, sub, mul;
float div;
clrscr();
printf(“enter the value of b,c:”);
scanf(“%d%d”, &b, &c);
1.32 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
sub=b-c;
mul=b*c;
div=b/c;
printf(“\n sum=%d,sub=%d,mul=%d,div=%f”,sum,sub,mul,div);
getch();

in
}

n.
Output:

aa
Enter the value of b,c: 8 4
sum=12,sub=4,mul=32,div=2

iy
1.6.1.2 Relational Operators
or
➢ Relational operators are used to compare two or more operands.
➢ Operands may be variable, constant or expression
.p
Operators Descriptions Example Return Value
w

> Greater than 5>4 1


w

< Less than 10<9 0


<= Less than or equal to 10<=10 1
w

>= Greater than or equal to 11>=5 1


== Equal to 2==3 0
!= Not equal to 3!=3 0

Syntax
AE1 operator AE2
where, AE- Arithmetic Expression or Variable or Value.
➢ These operators provide the relationship between two expressions.
➢ If the condition is true it returns a value 1, otherwise it returns 0.
➢ These operators are used in decision making process. They are generally used in
conditional or control statement.
1.6.1.3 Logical Operators
C Programming and Data Structures 1.33
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ The logical relationship between the two expressions is checked with logical
operators.
➢ After checking the condition, it provides logical true (1) or false (0).
Operators Descriptions Example Return Value
&& Logical AND 5>3 && 1

in
5<10

n.
|| Logical OR 8>5 || 8<2 1
!= Logical NOT 8!=8 0

aa
➢ && - This operator is usually used in situation where two or more expressions
must be true.

iy
Syntax:
(exp1) && (exp2)
or
.p
➢ || – This is used in situation, where at least one expression is true.
Syntax:
w

(exp1) || (exp2)
w

➢ ! – This operator reverses the value of the expression it operates on. (i.e.,) it makes
w

a true expression false and false expression true.


Syntax:
!(exp1)

Program 1.4
/* Program using Logical operators */
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
printf("\n Condition : Return values ");
printf("\n 5<=8 && 4>2: %5d",5<=8 && 4>2);
1.34 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
printf("\n !(7==7): %5d",!(7==7));
getch( );
}
Output
Condition : Return values

in
5<=8 && 4>2 : 1

n.
5>=3 || 6<8 : 1

aa
!(7==7) : 0

1.6.1.4 Assignment Operator

iy
➢ Assignment Operator are used to assign constant or a value of a variable or an
expression to another variable.
or
Syntax
.p
variable =expression (or) value;
w

Example
x=10;
w

x=a+b;
w

x=y;

Program 1.5
/* Program using Assignment and Short-hand Assignment operators */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=20,b=10,c=15,d=25,e=34,x=5;
clrscr( );
printf("\n Value of a=%d",a);
printf("\n Value of b=%d",b);
a+=x;
C Programming and Data Structures 1.35
https://www.poriyaan.in/ https://eee.poriyaan.in/
b-=x;
c*=x;
d/=x;
e%=x;
printf("\n Value of a=%d",a);

in
printf("\n Value of b=%d",b);

n.
printf("\n Value of c=%d",c);
printf("\n Value of d=%d",d);

aa
printf("\n Value of e=%d",e);
getch();

iy
}
Output
Value of a = 20
or
.p
Value of b = 10
w

Value of a = 25
w

Value of b = 5
Value of c = 75
w

Value of d = 5
Value of e = 4

1.6.1.5 Increment and Decrement Operators (Unary Operators)


➢ The ‘++’ adds one to the variable and ‘--‘subtracts one from the variable. These
operators are called unary operators.
Operator Meaning
++X Pre increment
--X Pre decrement
X++ Post increment
X-- Post decrement

Pre-increment operator
➢ This operator increment the value of a variable first and then perform other
1.36 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Program 1.6
#include <stdio.h>
void main()
{
int a,b;

in
a=10;

n.
b=++a;
printf(“a=%d”,a);

aa
printf(“b=%d”,b);

iy
}
output: a=11 b=11 or
#include <stdio.h>
.p
void main()
{
w

int a,b;
w

a=10;
w

b=—a;
printf(“a=%d”,a);
printf(“b=%d”,b);
}
Output:
a=9 b=9
Post-increment operator
➢ This operator perform other actions first and then increment the value of a
variable.
Program 1.7
#include <stdio.h>
void main()
C Programming and Data Structures 1.37
https://www.poriyaan.in/ https://eee.poriyaan.in/
int a,b;
a=10;
b=a++;
printf(“a=%d”,a);
printf(“b=%d”,b);

in
}

n.
Output:
a=11 b=10

aa
Program 1.8
#include <stdio.h>

iy
void main()
{
or
.p
int a,b;
a=10;
w

b=a--;
w

printf(“a=%d”,a);
w

printf(“b=%d”,b);
}
Output:
a=9 b=10

1.6.1.6 Conditional Operator (or) Ternary Operator


➢ Conditional operator checks the condition itself and executes the statement
depending on the condition.
Syntax
condition?exp1:exp2;
Example
void main()
{
1.38 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
big=a>b?a:b;
printf(“big is…%d”,big);
}
Output
big is…5

in
1.6.1.7 Bitwise Operators

n.
➢ Bitwise operators are used to manipulate the data at bit level.

aa
➢ It operates on integers only.
➢ It may not be applied to float or real.

iy
Operator Meaning
&
|
or Bitwise AND
Bitwise OR
.p
^ Bitwise XOR
w

<< Shift left


>> Shift right
w

~ One’s complement
w

Bitwise AND (&):


➢ This operator is represented as ‘&’ and operates on two operands of integer type.
If both the operands bit is ‘1’ then the result is ‘1’.
Bitwise OR (|):
➢ Bitwise OR (|) operator gives the value ‘1’ if either of the operands bit is ‘1’
Bitwise Exclusive OR (^)
➢ Bitwise Exclusive OR(^) gives the value ‘1’ if both operands bit are same.
C Programming and Data Structures 1.39
https://www.poriyaan.in/ https://eee.poriyaan.in/
Program 1.9
/* Program using One's complement operator */
#include<stdio.h>
#include<conio.h>
void main( )

in
{

n.
int a;

aa
clrscr( );
printf("\n Enter the value for a : ");

iy
scanf("%d",&a);
printf("\n The One's complement value for a is : %d", ~a);
or
getch( );
.p
}
Output
w

Enter the value for a: 3


w

The One's complement value for a is: -4


w

1.6.1.8 The Special Operator


➢ C language supports some of the special operators given below.
Operator Meaning
, Comma operators
sizeof Size of operators
& and * Pointer operators
. and — > Member selection operators

a) Comma operator(,):
➢ The comma operator is used to separate the statement elements such as variables,
constants or expression etc.,
➢ This operator is used to link the related expression together.
➢ Such expression can be evaluated from left to right and the value of right most
1.40 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example:
val=(a=3,b=9,c=77,a+c);
Where,
First assigns the value 3 to a
Second assigns the value 9 to b

in
Third assigns the value 77 to c

n.
Last assigns the value 80.

aa
b) The sizeof() operator:
➢ The sizeof() is a unary operator that returns the length in bytes of the specified
variable and it is very useful to find the bytes occupied by the specified variable

iy
in memory.
Syntax: or
sizeof(var);
.p
Example:
w

void main()
w

{
w

int a;
printf(“size of variable a is…%d”, sizeof(a));
}
Output:
size of variable a is…….2
c) Pointer operator:
➢ & : This symbol specifies the address of the variable.
➢ * : This symbol specifies the value of the variable.
d) Member selection operator:
➢ . and — >: These symbols are used to access the elements from a structure.
C Programming and Data Structures 1.41
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.7 EXPRESSIONS AND STATEMENTS
1.7.1 Expressions
➢ An expression represents data item such as variables, constants and are
interconnected with operators as per the syntax of the language.
➢ An expression is evaluated using assignment operators.

in
Syntax

n.
Variable = expression;

aa
Example: 1
x=a*b-c;

iy
➢ In example 1, the expression evaluated from left to right. After the evaluation of
the expression the final value is assigned to the variable from right to left.
Example: 2
or
.p
a++;
➢ In example 2, the value of variable a is incremented by 1, i.e, this expression is
w

equivalent to a = a + 1.
w

1.7.2 Statements
w

➢ A statement is an instruction given to the computer to perform an action. There


are three different types of statements in C:
1. Expression Statements
2. Compound Statements
3. Control Statements
Expression Statement
➢ An expression statement or simple statement consists of an expression followed
by a semicolon (;).
Example
a=100;
b=20;
c=a/b;
1.42 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Compound Statement
➢ A compound statement also called a block, consists of several individual
statements enclosed within a pair of braces { }.
Example
{

in
a=3;

n.
b=10;
c=a+b;

aa
}
Control Statement

iy
➢ A single statement or a block of statements can be executed depending upon a
or
condition using control statements like if, if-else, etc.
Example
.p
a=10;
w

if (a>5)
w

{
w

b= a+10;
}

1.8 CONDITIONAL STATEMENTS


➢ The conditional statement requires the programmer to specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
➢ In a conditional statement, the flow of execution may be transferred from one part
to another part based on the output of the conditional test carried out. It has been
further classified into selective and loop constructs. In a selective constructs, the
statements are selected for execution based on the output of the conditional test
given by an expression. It supports the following constructs such as if-else, if-
else-if, nested-if and switch case statement. In loop constructs, the block of
statements will be executed repeatedly until the condition is true else the loop will
C Programming and Data Structures 1.43
https://www.poriyaan.in/ https://eee.poriyaan.in/
be terminated. It supports the following constructs such as For, While and Do-
while loops.

1.8.1 Conditional Branching Statement


1.8.1.1 Selection Statement
❖ Simple If statement

in
➢ The syntax for a simple if statement is

n.
if (expression)

aa
{
block of statements;

iy
}
➢ In this statement, if the expression is true, the block of statements are executed
or
otherwise false and it comes out of the if condition.
.p
w
w
w

Fig. 1.7 Flowchart for an If statement


Program 1.10
/*Program to find the given number is divisible by 2 */
#include<stdio.h>
void main()
1.44 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
{
int n;
printf(“\n Enter the number”);
scanf(“%d”,&n);
if(n%2==0)

in
{

n.
printf(“\n The given number%d is divisible by 2", n);

aa
}
getch();

iy
}
Output or
Enter the number : 10
.p
The given number 10 is divisible by 2
w

Program 1.11
/* Program to check the given numbers are equal or not */
w

#include<stdio.h>
w

#include<conio.h>
void main()
{
int m,n;
clrscr();
printf(“\n Enter two numbers:”);
scanf(“%d %d”, &m,&n);
if (m==n)
printf(“\n Two numbers are equal”);
getch();
}
Output
C Programming and Data Structures 1.45
https://www.poriyaan.in/ https://eee.poriyaan.in/
Two numbers are equal.
❖ If –else statement
➢ The syntax for the if-else statement is
if(expression)
{

in
block of statements1;

n.
}

aa
else
{

iy
block of statements2;
} or
.p
w
w
w

Fig. 1.8 Flowchart for the If-else statement


➢ In this statement, if the expression is true the block of statements1 will be
executed, otherwise the block of statements2 will be executed.
1.46 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Program 1.12
/* Program to find the given number is positive or negative */
#include<stdio.h>
void main()
{

in
int n;

n.
printf(“\n Enter the number:”);
scanf(“%d”,&n);

aa
if(n>0)

iy
{
printf(“\n The given number %d is positive”, n);
or
}
.p
else
{
w

printf(“\n The given number %d is negative”, n);


w

}
w

}
Output
Enter the number : 5
The given number 5 is positive.
Program 1.13
/* Program to find the given number is even or odd */
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
C Programming and Data Structures 1.47
https://www.poriyaan.in/ https://eee.poriyaan.in/
printf(“\n Enter the number:”);
scanf(“%d”,&a);
if (a%2==0)
printf(“\n %d is an even number”,a);
else

in
printf(“%d is an odd number”,a);

n.
getch();

aa
}
Output

iy
Enter the number: 10
10 is an even number. or
❖ Conditional Expression
.p
➢ The ternary operator is used to form a conditional expression. It uses three
operands and hence it is called as a ternary operator. The syntax for a conditional
w

expression is:
w

<expression-1> ? <expression-2> : <expression-3>;


➢ In this method if expression-1 is true then expression-2 is evaluated, otherwise
w

expression-3 is evaluated.
1.48 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Program 1.14
/* Program to find biggest of two given numbers */
#include<stdio.h>
void main()
{

in
int x,y,z;

n.
printf(“\n Enter the value of x and y:”);
scanf(“%d%d”,&x,&y);

aa
z = ((x>y)?x:y);

iy
printf(“The biggest value is %d”,z);
getch(); or
}
.p
Output
Enter the value of x and y: 5 10
w

The biggest value is 10


w

❖ If-else-if statement
w

➢ The syntax for the if-else-if statement is


if(expression1)
{
statements1;
}
else if(expression2)
{
statements2;
}
else if(expression3)
{
statements3;
C Programming and Data Structures 1.49
https://www.poriyaan.in/ https://eee.poriyaan.in/
else
{
statements4;
}
➢ In this statement, if the expression1 is true, statements1 will be executed,

in
otherwise the expression2 is evaluated, if it is true then statements2 is executed,

n.
otherwise the expression3 is evaluated, if it is true then statements3 is executed,
otherwise statements4 is executed.

aa
iy
or
.p
w
w
w

Fig. 1.10 Flowchart for the If-else-if statement


Program 1.15
/* Program to find the student’s class for the given average marks using if-elseif*/
#include<stdio.h>
void main()
{
1.50 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
printf (“Enter the Average mark:”)
scanf(“%d”,&Avg_Mark);
if(Avg_Mark>=75)
{
printf(“Distinction”);

in
}

n.
elseif((Avg_Mark>=60) && (Avg_Mark<75))

aa
{
printf(“First Class”);

iy
}
elseif((Avg_Mark>=50) && (Avg_Mark<60))
or
{
.p
printf(“Second Class”);
}
w

elseif((Avg_Mark>=45) && (Avg_Mark<50))


w

{
w

printf(“Third Class”);
}
else
{
printf(“Fail”);
}
}
Output
Enter the Average Mark : 65
First Class
Program 1.16
Write a program to calculate the gross salary for the conditions given below:
C Programming and Data Structures 1.51
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
/* Program to Calculate the gross salary */
#include<stdio.h>

aa
#include<conio.h>
void main()

iy
{
float bs, hra, da, cv, ts;
or
.p
clrscr();
printf(“\n Enter Basic salary:”);
w

scanf(“%f”,&bs);
w

if(bs>=5000)
w

{
hra = bs*20/100;
da = bs*110/100;
cv = 500;
}
else if(bs>=3000 && bs<5000)
{
hra = bs*15/100;
da = bs*100/100;
cv = 400;
}
else if(bs<3000)
1.52 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
hra = bs*10/100;
da = bs*90/100;
cv = 300;
}
ts = bs+hra+da+cv;

in
printf(“\nBasic salary: %5.2f”,bs);

n.
printf(“\nHRA: %5.2f”,hra);
printf(“\nDA: %5.2f”,da);

aa
printf(“\nConveyance: %5.2f”,cv);

iy
printf(“\nGross Salary: %5.2f”,ts);
getch(); or
}
.p
Output
Enter basic salary: 5400
w

Basic salary: 5400


w

HRA: 1080
w

DA: 5940
Conveyance: 500
Gross salary: 12920
❖ Nested if statement
➢ The syntax for the nested if statement is
if(expression1)
{
statements1;
}
else
{
if(expression2)
C Programming and Data Structures 1.53
https://www.poriyaan.in/ https://eee.poriyaan.in/
statements2;
}
else
{
statements3;

in
}

n.
}

aa
iy
or
.p
w
w
w

Fig. 1.11 Flowchart for Nested if statement


➢ In this statement, if expression1 is true, then statement1 is evaluated, otherwise
the inner if expression2 is true then statements2 will be executed otherwise inner
else statements3 will be executed.
Program 1.17
/* Program to find the biggest of given three numbers */
#include<stdio.h>
void main()
1.54 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
int x,y,z;
printf(“\n Enter the three numbers”);
scanf(“%d%d%d”,&x,&y,&z);
if ((x>y) && (x>z))
{

in
printf(“The Biggest number = %d”,x);

n.
}

aa
else
{

iy
if(y>z)
{ or
printf(“The Biggest number =%d”,y);
.p
}
else
w

{
w

printf(“The Biggest number =%d”,z);


w

}
}
getch();
}
Output
Enter the three numbers: 5 2 8
The Biggest number = 8
❖ Switch () Case Statement
➢ The switch ( ) case statement is like if statement that allows us to make a decision
from a number of choices. The switch statement requires only one argument of
any data type, which is checked with a number of case options.
➢ The switch statement evaluates the expression and then looks for its value among
the case constants.
C Programming and Data Structures 1.55
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ If the value matches with a case constant, this particular case statement is
executed. If not, the default is executed. The general syntax for the switch - case
statement is:
switch<exprn>
{

in
case constant_1:
{

n.
statements1;

aa
break;
}

iy
case constant_2:
{
statements2;
or
.p
break;
w

}
w

case constant_3:
{
w

statements3;
break;
}
case constant_n:
{
statementsn;
break;
}
default:
{
default statements;
}
1.56 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
iy
or
.p
Fig. 1.12 Flowchart for Switch - Case statement
w

Program 1.18
w

/* Program to provide multiple functions such as 1. Addition 2. Subtraction


w

3. Multiplication 4. Division by using switch statements. */


#include<stdio.h>
#include<conio.h>
void main()
{
float c;
int a,b,n;
printf(“\n MENU”);
printf(“\n 1.Addition”);
printf(“\n 2.Subtraction”);
printf(“\n 3.Multiplication”);
printf(“\n 4.Division”);
C Programming and Data Structures 1.57
https://www.poriyaan.in/ https://eee.poriyaan.in/
printf(“\n Enter your choice:”);
scanf(“%d”,&n);
printf(“Enter two numbers:”);
scanf(“%d%d”,&a,&b);
switch(n)

in
{

n.
case 1:

aa
c = a + b;
printf(“\n Addition: %d”,c);

iy
break;
case 2: or
c = a - b;
.p
printf(“\n Subtraction: %d”,c);
break;
w

case 3:
w

c = a * b;
w

printf(“\n Multiplication: %d”,c);


break;
case 4:
c = a / b;
printf(“\n Division: %d”,c);
break;
case 0:
exit();
break;
default:
printf(“Invalid choice”);
break;
1.58 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
getch();
}
Output
Menu
1. Addition

in
2. Subtraction

n.
3. Multiplication

aa
4. Division
5. Exit

iy
Enter your choice: 2
Enter two numbers: 40 20 or
Subtraction: 20
.p
1.8.1.2 Looping Statements
w

➢ A loop is defined as a block of statements which are repeatedly executed for


certain number of times. The `C’ language supports three types of loop statements.
w

1. for statement
w

2. while statement
3. do-while statement
❖ For Loop Statement
➢ The for loop allows to execute a set of instructions until a certain condition is
satisfied. Condition may be predefined or open-ended.
➢ The syntax for loop this is follows:
for<initial value>;<condition>;<incrementation/decrementation>)
{
block of statements;
}
C Programming and Data Structures 1.59
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
iy
or
.p
w

Fig. 1.13 Flowchart of the For loop statement


w

➢ Here the initial value means the starting value assigned to the variable and
condition in the loop counter to determine whether the loop should continue or
w

not. Incremention / decrementation is to increment/decrement the loop counter


value each time the program segment has been executed.
Program 1.19
/* Program to Generate numbers from 1 to 10 */
#include<stdio.h>
void main()
{
int i,n;
printf(“\n Enter the limit”);
scanf(“%d”,&n);
for(i=1;i <=n;i++)
{
1.60 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
printf(“%d\n”,i);
}
getch( );
}
Output

in
Enter the limit: 10

n.
1

aa
2
3

iy
4
5 or
6
.p
7
8
w

9
w

10
w

❖ While Loop Statement


➢ The syntax for the while loop statement is
while(condition)
{
block of statements;
incr/decr;
}
➢ The while loop is often used when the number of times the loop is to be executed
is not known in advance. A sequence of statements are executed until some
condition is satisfied.
➢ When the condition specified inside the parenthesis the while loop is satisfied, the
control is transferred to the statements inside the loop and executes the body of
the loop. The loop continues until the condition is violated. The while tests the
C Programming and Data Structures 1.61
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ If the condition initially fails the loop is skipped entirely even in the first iteration
itself. It is otherwise called as entry controlled loop.

in
n.
aa
iy
or
.p
w

Fig. 1.14 Flowchart of the While loop


w
w

Program 1.20
/* Program to Generate the Even numbers to a given limit*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
printf(“\n Enter the limit:”);
scanf(“%d”,&n);
i=1;
while(i<=n)
{
1.62 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
printf(“%d\t”,i);
i++;
}
getch( );
}

in
Output

n.
Enter the limit: 10

aa
2 4 6 8 10
❖ Do While Statement

iy
➢ The do while loop varies from the while loop in the checking condition. The
condition of the loop is not tested until the body of the loop has been executed
or
once. If the condition is false, after the first loop iteration the loop terminates. The
statements are executed atleast once even if the condition fails for the first time
.p
itself. It is otherwise called as exit control loop.
w
w
w

Fig. 1.15 Flowchart of the Do while loop


➢ The syntax for the do while loop is
do
{
C Programming and Data Structures 1.63
https://www.poriyaan.in/ https://eee.poriyaan.in/
}
while(condition);
Program 1.21
/* Program to check the given number is palindrome or not */
#include<stdio.h>

in
#include<conio.h>

n.
void main()

aa
{
int n,t,s,r;

iy
clrscr();
printf(“\n Enter the number”);
or
scanf(“%d”,&n);
.p
t=n;
s=0;
w

do
w

{
w

r=n%10;
s=(s*10)+r;
n=n/10;
} while(n>0);
if(t==s)
printf(“%d is a palindrome”,t);
else
printf (“%d is not a palindrome”, t);
getch( );
}
Output
Enter the number 242
1.64 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.9 FUNCTIONS
Introduction
➢ A function is a sub program which contains a set of instructions that are used to
perform specified tasks
➢ A function is used to provide modularity to the software. By using function can

in
divide complex task into manageable tasks. The function can also help to avoid
duplication of work.

n.
Advantages of Functions

aa
✓ Code reusability
✓ Better readability

iy
✓ Reduction in code redundancy
✓ Easy to debug & test.
How Does Function Work?
or
.p
➢ Once a function is called, it takes some data from the calling function and returns
w

back some value to the called function.


➢ Whenever function is called control passes to the called function and working of
w

the calling function is temporarily stopped, when the execution of the called
w

function is completed then a control return back to the calling function and
executes the next statement.
➢ The function operates on formal and actual arguments and send back the result to
the calling function using return() statement.
Types of Functions
Functions are classified into two types
a) User defined functions
b) Predefined functions or Library functions or Built-in functions
a) User-defined functions
➢ User-defined functions are defined by the user at the time of writing a program.
Example: sum( ), square( )
b) Library functions [Built-in functions]
➢ Library functions are predefined functions. These functions are already developed
C Programming and Data Structures 1.65
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example: printf( ), scanf( )
Terminologies used in functions
➢ A function f that uses another function g is known as the calling function, and g
is known as the called function.
➢ The inputs that a function takes are known as arguments.

in
➢ When a called function returns some result back to the calling function, it is said

n.
to return that result.
➢ The calling function may or may not pass parameters to the called function. If

aa
the called function accepts arguments, the calling function will pass parameters,
else not.

iy
➢ Function declaration is a declaration statement that identifies a function’s name,
or
a list of arguments that it accepts, and the type of data it returns.
➢ Function definition consists of a function header that identifies the function,
.p
followed by the body of the function containing the executable code for that
function.
w

1.9.1 Function prototype


w

1.9.1.1 User Defined Function


w

➢ The function defined by the users according to their requirements is called user
defined functions. The users can modify the function according to their
requirement.
Need For user Defined Functions
➢ While it is possible to write any complex program under the main () function
and it leads to a number of problems, such as
➢ The program becomes too large and complex
➢ The users cannot go through at a glance.
➢ The task of debugging, testing and maintenance becomes difficult.
Advantages of user Defined Functions
➢ The length of the source program can be reduced by dividing it into the smaller
functions.
➢ By using functions it is very easy to locate and debug an error.
1.66 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ The user defined function can be used in many other source programs whenever
necessary.
➢ Functions avoid coding of repeated programming of the similar instructions.
➢ Functions enable a programmer to build a customized library of repeatedly used
routines.

in
➢ Functions facilitate top-down programming approach.

n.
1.9.1.2 Elements of user Defined Functions
➢ In order to write an efficient user defined function, the programmer must be

aa
familiar with the following three elements.
− Function declaration

iy
− Function definition
− Function call
or
.p
Function Declaration
➢ A function declaration is defined as a prototype of a function which consists of
w

the functions return type, function name and arguments list


w

➢ It is always terminated with semicolon (;)


➢ Function prototypes can be classified into four types
w

a) Function with no arguments and no return values


b) Function with arguments and no return values
c) Function with arguments and with return values
d) Function with no arguments and with return values
Syntax
return_type function_name (parameter_list);
Where,
return_type can be primitive or non-primitive data type
function_name can be any user specified name
parameter_list can consist of any number of parameter of any type
Example
void add(void);
C Programming and Data Structures 1.67
https://www.poriyaan.in/ https://eee.poriyaan.in/
void add(int,int);
int add(int,int);
int add(void);
a) Function with No Arguments and No Return Values
➢ In this prototype, no data transfer takes place between the calling function and

in
the called function. (i.e) the called program does not receive any data from the

n.
calling program and does not send back any value to the calling program.
Syntax:

aa
void function_name(void);
void main()

iy
{
……. or
function_name();
.p
…..
w

}
w

void function_name(void)
w

{
…..
……
}
Program 1.22
/*Implementation of function with no return type and no argument list*/
#include<stdio.h>
#include<conio.h>
void add(void); //function declaration with no return type and no
arguments list
void main()
{
1.68 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
}
void add()
{
int a,b,c;
printf(“Enter the two numbers . . . “);

in
scanf(“ %d %d”,&a,&b);

n.
c=a+b;
printf(“sum is . . . %d”,c);

aa
}

iy
Output:
Enter the two numbers . . . 10 20
or
Sum is . . . 30
.p
b) Function with Arguments and No Return Values
➢ In this prototype, data is transferred from calling function to called function. i.e
w

the called program receives some data from the calling program and does not
w

send back any values to calling program.


w

Syntax:
void function_name(arguments_list);
void main()
{
…….
function_name(argument_list);
…..
}
void function_name(arguments_list)
{
//function body
}
C Programming and Data Structures 1.69
https://www.poriyaan.in/ https://eee.poriyaan.in/
Program 1.23
/*Implementation of function with no return type and with argument list*/
#include<stdio.h>
#include<conio.h>
int add(int,int); ); //function declaration with no return type and with arguments

in
list

n.
void main()
{

aa
int a,b,;
clrscr();

iy
printf(“enter the two values: “);
or
scanf(“ %d %d”,&a,&b);
.p
add(a,b); /*calling a function with arguments */
getch();
w

}
w

void add(int x,int y)


w

{
int z;
z=x+y;
printf(“Sum is . . . . %d”,z);
}
Output:
Enter two values: 10 20
Sum is . . . . 30
c) Function with arguments and With Return Values
➢ In this prototype, data is transferred between calling function and called function.(
i.e) the called program receives some data from the calling program and send back
a return value to the calling program.
➢ Value received from a function can be further used in rest of the program.
1.70 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Syntax:
return_type function_name(arguments_list);
void main()
{
…….

in
variable_name=function_name(argument_list);

n.
…..

aa
}
return_type function_name(arguments_list)

iy
{
//function body or
}
.p
Program 1.24
w

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

int add(int,int); //function declaration with return type and with arguments list
w

void main()
{
int a,b,c;
clrscr();
printf(“enter the two numbers: “);
scanf(“ %d %d”,&a,&b);
c=add(a,b); /*calling function with arguments*/
printf(“sum is . . . %d “, c);
getch();
}
int add(int x,int y)
{
C Programming and Data Structures 1.71
https://www.poriyaan.in/ https://eee.poriyaan.in/
int z;
z=x+y;
return(z); /*returning result to calling function*/
}
Output:

in
Enter the two numbers: 10 20

n.
sum is. . 30

aa
d) Function with No Arguments and with Return Values
➢ In this prototype, the calling program cannot pass any arguments to the called
program. i.e) program may send some return values to the calling program.

iy
Syntax:
or
return_type function_name(void);
.p
void main()
{
w

…….
w

variable_name=function_name();
w

…..
}
return_type function_name(void)
{
//function body
}
Program 1.25
/*Implementation of function with return type and no argument list*/
#include<stdio.h>
#include<conio.h>
int add(void); //function declaration with no return type and no arguments list
void main()
1.72 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
int c;
c=add(); //function call
printf(“sum is . . . %d”,c);
}
int add(void)

in
{

n.
int a,b,c;
printf(“Enter the two numbers . . . “);

aa
scanf(“ %d %d”,&a,&b);

iy
c=a+b;
return(c); or
}
.p
Function Definition
➢ It is the process of specifying and establishing the user defined function by
w

specifying all of its elements and characteristics.


w

➢ When a function is defined, space is allocated for that function in the memory.
w

➢ A function definition comprises of two parts:


✓ Function header
✓ Function Body
Syntax
return_type function_name(argument_list)
{
//function body
}
Example
int add(int x, int y)
{
int z;
C Programming and Data Structures 1.73
https://www.poriyaan.in/ https://eee.poriyaan.in/
return(z);
}
Program 1.26
#include<stdio.h>
// function prototype, also called function declaration

in
float square ( float x );

n.
// main function, program starts from here

aa
int main( )
{

iy
float m, n ;
or
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
.p
// function call
w

n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
w

}
w

float square ( float x ) // function definition


{
float p ;
p=x*x;
return ( p ) ;
}
Output
Enter some number for finding square
2
Square of the given number 2.000000 is 4.00000
Function Call
➢ The function can be called by simply specifying the name of the function, return
1.74 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ The function call statement invokes the function. When a function is invoked, the
compiler jumps to the called function to execute the statements that are a part of
that function. Once the called function is executed, the program control passes
back to the calling function.
Syntax

in
function_name();
function_name(parameter);

n.
variable_name=function_name(parameter);

aa
variable_name=function_name();
Example

iy
add();
add(a,b);
c=add(a,b);
or
.p
c=add;
w

➢ There are two ways that a C function can be called from a program. They are,
w

a) Call by value
b) Call by reference
w

a) Function-Call by value
➢ In the call by value method the actual arguments are copied to the formal
arguments, hence any operation performed by function on arguments doesn’t
affect actual parameters.
b) Function-Call by Reference
➢ Unlike call by value, in this method, address of actual arguments (or parameters)
is passed to the formal parameters, which means any operation performed on
formal parameters affects the value of actual parameters.
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function declarations.
Program 1.27
//Example program for Actual Parameter and Formal Parameters
C Programming and Data Structures 1.75
https://www.poriyaan.in/ https://eee.poriyaan.in/
int sum(int a, int b)
{
int c=a+b;
return c;
}

in
int main(

n.
{

aa
int var1 =10;
int var2 = 20;

iy
int var3 = sum(var1, var2);
printf("%d", var3); or
return 0;
.p
}
In the above example variable a and b are the formal parameters (or formal
w

arguments). Variable var1 and var2 are the actual arguments (or actual parameters). The
w

actual parameters can also be the values. Like sum(10, 20), here 10 and 20 are actual
parameters.
w

Program 1.28
//Example of Function call by Value
#include <stdio.h>
int increment(int var)
{
var = var+1;
return var;
}
int main()
{
int num1=20;
1.76 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d", num2);
return 0;
}
Output

in
num1 value is: 20

n.
num2 value is: 21

aa
Program 1.29
//Example 2: Swapping numbers using Function Call by Value

iy
#include <stdio.h>
or
void swapnum( int var1, int var2 )
{
.p
int tempnum ;
w

/*Copying var1 value into temporary variable */


tempnum = var1;
w

/* Copying var2 value into var1*/


w

var1 = var2;
/*Copying temporary variable value into var2 */
var2 = tempnum;
}
int main( )
{
int num1 = 35, num2 = 45;
printf("Before swapping: %d, %d", num1, num2);
/*calling swap function*/
swapnum(num1, num2);
printf("\nAfter swapping: %d, %d", num1, num2);
}
C Programming and Data Structures 1.77
https://www.poriyaan.in/ https://eee.poriyaan.in/
Output
Before swapping: 35, 45
After swapping: 45, 35
Program 1.30
Example 2: Function Call by Reference – Swapping numbers

in
#include

n.
void swapnum ( int *var1, int *var2 )

aa
{
int tempnum ;

iy
tempnum = *var1;
*var1 = *var2; or
*var2 = tempnum;
.p
}
int main( )
w

{
w

int num1 = 35, num2 = 45;


w

printf("Before swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
/*calling swap function*/
swapnum( &num1, &num2 );
printf("\nAfter swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
}
Output
Before swapping:
1.78 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
num2 value is 45
After swapping:
num1 value is 45
num2 value is 35

in
1.10 RECURSIVE FUNCTIONS
➢ Recursion is the process of calling the same function again and again until some

n.
condition is satisfied.

aa
➢ This process is used for repetitive computation.
Syntax:

iy
function_name()
{
function_name();
or
.p
}
w

Types of Recursion
a) Direct Recursion
w

b) Indirect Recursion
w

a) Direct Recursion
➢ A function is directly recursive if it calls itself.
Functionname1( )
{
….
Functionname1 ( ); // call to itself
….
}
Example
➢ A function is said to be directly recursive if it explicitly calls itself. Here, the
function Func() calls itself for all positive values of n, so it is said to be a directly
recursive function.
C Programming and Data Structures 1.79
https://www.poriyaan.in/ https://eee.poriyaan.in/
{
if (n == 0)
return n;
else
return (Func (n–1));

in
}

n.
b) Indirect Recursion
➢ Function calls another function, which in turn calls the original function.

aa
Functionname1 ( )

iy
{

Functionname2 ( );
or
.p

}
w

Functionname1 ( )
w

{

w

Functionname1 ( );// function (Functionname2) calls (Functionname1)



}
Example
➢ A function is said to be indirectly recursive if it contains a call to another function
which ultimately calls it. These two functions are indirectly recursive as they both
call each other.
int Funcl (int n)
{
if (n == 0)
return n;
else
1.80 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
}
int Func2(int x)
{
return Func1(x–1);
}

in
Program 1.31

n.
/*C program to find factorial of a given number using recursion*/

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

iy
void main()
{
int fact(int);
or
.p
int num,f;
w

clrscr();
printf(“enter the number”);
w

scanf(“%d”,&num);
w

f=fact(num);
printf(“ the factorial of %d= %d”, num, f);
}
int fact(int x)
{
int f;
if(x==1)
return(1);
else
f=x*fact(x-1); //recursive function call
return (f);
}
C Programming and Data Structures 1.81
https://www.poriyaan.in/ https://eee.poriyaan.in/
Output:
Enter the number 5
The factorial of 5=120

1.11 ARRAYS

in
Introduction to Arrays
➢ An Array is a collection of similar data elements

n.
➢ These data elements have the same data type

aa
➢ The elements of the array are stored in consecutive memory locations and are
referenced by an index

iy
Definition
or
➢ An array is a data structure that is used to store data of the same type. The position
of an element is specified with an integer value known as index or subscript.
.p
Example
w
w
w

Fig. 1.16 Array Structure


Characteristics
➢ All the elements of an array share a common name called as array name
➢ The individual elements of an array are referred based on their position
➢ The array index in c starts with 0
Advantages of C array
➢ Code Optimization : Less code to access the data
1.82 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Easy to traverse data : By using the for loop, we can retrieve the elements of can
array easily
➢ Easy to sort data: To sort the elements of array, we need a few lines of code only
➢ Random Access : We can access any element randomly using the array
Disadvantages of array

in
➢ Fixed Size: Whatever size, we define at the time of declaration of array, we can’t
exceed the limit. So it doesn’t grow the size dynamically like Linked List

n.
Classifications

aa
➢ In general arrays are classified as:
➢ One-Dimensional Array

iy
➢ Two-Dimensional Array
➢ Multi-Dimensional Array or
.p
1.11.1 Declaration of an Array
Array has to be declared before using it in C program. Declaring array means
w

specifying three things.


w

Data_type Data Type of Each Element of the array


w

Array_name Valid variable name


Size Dimensions of the Array
Arrays are declared using the following syntax:

type name[size]

Here the type can be either int, float, double, char or any other valid data type. The number
within the brackets indicates the size of the array, i.e., the maximum number of elements
that can be stored in the array.
Example: i) int marks[10]
ii) int a[5]={10,20,5,56,100}
The declaration of an array tells the compiler that, the data type, name of the array,
size of the array and for each element it occupies memory space. Like for int data type
occupies 2 bytes for each element and for float occupies 4 bytes for each element etc. The
C Programming and Data Structures 1.83
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.11.2 Initialization of arrays
Elements of the array can also be initialized at the time of declaration as in the
case of every other variable. When an array is initialized, we need to provide a value for
every element in the array. Arrays are initialized using the following syntax:

type array_name [size] = { list of values};

in
The values are written with curly brackets and every value is separated by a comma.

n.
It is a compiler error to specify more number of values than the number of elements in
the array.

aa
Example: int marks [5] = {90, 92, 78, 82, 58};

iy
1.12 ONE DIMENSIONAL ARRAY
➢ It is also known as single-dimensional arrays or linear array or vectors
or
➢ It consists of fixed number of elements of same type
.p
➢ Elements can be accessed by using a single subscript
w

Example
w
w

1.12.1 Declaration of Single Dimensional Array


➢ An array must be declared before being used. Declaring an array means specifying
three things.
1. Data type
2. Name
3. Size
Syntax

datatype arrayname [array size];

Example
int a[4]; // a is an array of 4 integers
1.84 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.12.2 Initialization of single dimensional array
➢ Elements of an array can also be initialized. After declaration, the array elements
must be initialized otherwise they hold garbage value. An array can be initialized
at compile time or at run time.
➢ Elements of an array can be initialized by using an initialization list. An

in
initialization list is a comma separated list of initializers enclosed within braces.
Example

n.
1. int a[3]={1,3,4};

aa
2. int i[5] ={1, 2, 3, 4, 5};
3. float a[5]={1.1, 2.3, 5.5, 6.7, 7.0};

iy
4. int b[ ]={1,1,2,2};
➢ In the fourth example the size has been omitted (it can be) and have been declared
or
as an array with 4 elements having 1, 1, 2 and 2 as initial values.
➢ Character arrays that hold strings allow a shortcut initialization of the form:
.p
char array_name[size]=”string”
w

For example,
w

char mess[ ]={‘w’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’};


w

➢ If the number of initializers in the list is less than array size, the leading array
locations gets initialized with the given values. The rest of the array locations gets
initialized to
0 - for int array
0.0 - for float array
\0 - for character array
Example
int a[2]={1};

a 1 0

char b[5]={‘A’.’r’,’r’};

b ‘A’ ‘r’ ‘r’ ‘\0’ ‘\0’


C Programming and Data Structures 1.85
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example Programs
Program 1.32
/*Program to find the maximum number in an array * /
#include<stdio.h>
void main( )

in
{

n.
int a[5], i, max;
printf(“Enter 5 numbers one by one \n”);

aa
for(i=0;i<5;i++)

iy
{
scanf(“%d”, & a[i]);
or
}
.p
max=a[0];
for(i=1;i<5;i++)
w

{
w

if (max<a[i])
w

max =a[i];
}
printf(“\n The maximum number in the array is %d”,max);
getch( ) ;
}
Output:
Enter 5 numbers one by one
57364
The maximum number in the array is 7
Program 1.33
/*Program for reversing an array*/
#include<stdio.h>
1.86 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
{
int a[10], i;
int n;
printf(“Enter the maximum number of elements\n”);
scanf(“%d”, &n);

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

n.
{
scanf(“%d”,&a[i]);

aa
}

iy
printf(“Array in the reverse order\n”);
for(i=n–1; i>=0; i--)or
{
.p
printf(“%d\t”, a[i]);
}
w

getch( );
w

}
w

Output
Enter the maximum number of elements
5 11 12 13 14 15
Array in the reverse order
15 14 13 12 11
Program 1.34
/* Program to calculate sum of array content */
# include<stdio.h>
void main( )
{
int a[20], n, i, sum = 0;
print f(“\n Enter the size of the array:”);
C Programming and Data Structures 1.87
https://www.poriyaan.in/ https://eee.poriyaan.in/
scanf(“%d”, &n)
printf (“\n Enter the %d numbers one by one:”);
for (i=0; i<n; i++)
{

in
scanf(“%d”, &a[i]);
sum = sum + a[i];

n.
}

aa
printf (“The sum of array content = %d”, sum);
getch( );

iy
}
Output
or
.p
Enter the size of the array: 5
Enter the 5 number one by one:
w

10 20 30 40 50
w

The sum oif the array content = 150


w

1.13 MULTI-DIMENSIONAL ARRAY


➢ A multi-dimensional array is an array that has more than one dimension. It is an
array of arrays; an array that has multiple levels. The simplest multi-dimensional
array is the 2D array, or two-dimensional array and 3D or three-dimensional array.

1.13.1 Two Dimensional Array


➢ A two dimensional array is an array of one dimensional arrays and can be
visualized as a plane that has rows and columns.
➢ The elements can be accessed by using two subscripts, row subscript (row
number), column subscript (column number).
➢ It is also known as matrix.
➢ A single dimensional array can store a list of values, whereas two dimensional
array can store a table of values.
1.88 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example
1 2 3 6 7
9 10 5 0 4
a[3][5] 3 1 2 1 6

in
Declaration

n.
datatype arrayname [row size][column size]

aa
Example: int a [2][3]; //a is an integer array of 2 rows and 3 columns

iy
Number of elements=2*3=6
Initialization or
1. By using an initialization list, 2D array can be initialized.
.p
e.g. int a[2][3] = {1,4,6,2}
w

a 1 4 6
w

2 0 0
w

2. The initializers in the list can be braced row wise.


e.g int a[2][3] = {{1,4,6} , {2}};
Program 1.35
/ * Example for two dimensional array handling * /
#include <stdio.h>
void main( )
{
int a[10][10],i,j,sum,d,n1,n,rowsum,colsum,diasum;
printf(“Enter order[row][col] of the matrix\n”);
scanf(“%d %d”,&n,&n1);
printf(“Enter %d elements\n”,n1*n);
C Programming and Data Structures 1.89
https://www.poriyaan.in/ https://eee.poriyaan.in/
for(i=0;i<n;i++)
for(j=0;j<n1;j++)
scanf(“%d”,&a[i][j]);
/ * Program module to sum all elements * /
sum=0;

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

n.
for(j=0;j<n1;j++)

aa
sum+=a[i][j];
printf(“Sum of all elements%d\n”,sum);

iy
/ * Program to module to sum row wise */
for(i=0;i<n;i++) or
{
.p
rowsum=0;
for(j=0;j<n1;j++)
w

{
w

rowsum+=a[i][j];
w

printf(“row no = %d sum = %d\n”,i,rowsum);

}
}
/* Program module to sum colwise */
for(i=0;i<n;i++)
{
colsum=0;
for(j=0;j<n1;j++)
colsum+=a[j][i];
printf(“col no=%d sum=%d\n “,i,colsum);
}
1.90 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
diasum=0;
for(i=0;i<n;i++)
for(j=0;j<n1;j++)
if(i==j) diasum+=a[i][j];
printf(“Principle diagonal sum %d\n”,diasum);

in
/ * Program module to sum off diagonal */

n.
diasum=0;

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

iy
j= -n1;
diasum +=a[i][j];
or
}
.p
printf(“Off diagonal sum%d\n”,diasum);
}
w

Output
w

Enter order [row][col] of the matrix


w

33
Enter 9 elements
123456789
Sum of all elements 45
row no = 0 sum = 6
row no = 1 sum = 15
row no = 2 sum = 24
col no = 0 sum = 12
col no = 1 sum = 15
col no = 2 sum = 18
Principle diagonal sum 15
Off diagonal sum 15
C Programming and Data Structures 1.91
https://www.poriyaan.in/ https://eee.poriyaan.in/
1.13.2 Three-Dimensional Arrays
Initialization of a 3d array
Initialize a three-dimensional array in a similar way to a two-dimensional array.
Example
int test[2][3][4] = {

in
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},

n.
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

aa
Program 1.36
Write a C Program to store and print 12 values entered by the user

iy
#include <stdio.h>
int main()
{
or
.p
int test[2][3][2];
w

printf("Enter 12 values: \n");


for (int i = 0; i < 2; ++i)
w

{
w

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


{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}
// Printing values with the proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
1.92 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);

in
}

n.
}

aa
}
return 0;

iy
}
Output or
Enter 12 values:
.p
1
2
w

3
w

4
w

5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
C Programming and Data Structures 1.93
https://www.poriyaan.in/ https://eee.poriyaan.in/
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9

in
test[1][1][1] = 10

n.
test[1][2][0] = 11

aa
test[1][2][1] = 12

iy
or
.p
w
w
w
1.94 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
REVIEW QUESTIONS
PART-A
1. List down the Primary Data Types in C
• Integer – We use these for storing various whole numbers, such as 5, 8, 67,
2390, etc.

in
• Character – It refers to all ASCII character sets as well as the single alphabets,

n.
such as ‘x’, ‘Y’, etc.
• Double – These include all large types of numeric values that do not come under

aa
either floating-point data type or integer data type.
• Floating-point – These refer to all the real number values or decimal points,

iy
such as 40.1, 820.673, 5.9, etc.

or
Void – This term refers to no values at all. We mostly use this data type when
defining the functions in a program.
.p
2. What is Variable?
w

✓ Variables are containers for storing data values.


w

✓ Its value can be changed, and it can be reused many times.


✓ Syntax for creating variables
w

• type variableName = value;


• Example: int a = 5;
3. What is Operator?
✓ An operator is a special symbol that tells the compiler to perform specific
mathematical or logical operations.
✓ Operators in programming languages are taken from mathematics.
✓ C language supports a rich set of built-in operators.
4. List the types of operators supported in C
✓ Arithmetic operators
✓ Relational operators
✓ Logical operators
✓ Bitwise operators
C Programming and Data Structures 1.95
https://www.poriyaan.in/ https://eee.poriyaan.in/
✓ Assignment operators
✓ Type Information Operators(Special operators)
5. What is Ternary operators or Conditional operators?
✓ Ternary operators is a conditional operator with symbols? and :
✓ Syntax: variable = exp1 ? exp2 : exp3

in
✓ If the exp1 is true variable takes value of exp2. If the exp2 is false, variable

n.
takes the value of exp3.
6. What is an Operator and Operand?

aa
✓ An operator is a symbol that specifies an operation to be performed on
operands.

iy
✓ Example: *, +, -, / are called arithmetic operators.
or
✓ The data items that operators act upon are called operands.
7. What is type casting?
.p
✓ Type casting is the process of converting the value of an expression to a
w

particular data type.


w

✓ Example: int x,y.


c = (float) x/y; where a and y are defined as integers. Then the result of x/y is
w

converted into float.


8. What is the difference between while loop and do while loop?
while do while
In the while loop the condition is first In the do…while loop first the statement
executed. is executed and then the condition is
checked.
If the condition is true, then it executes The do…while loop will execute at least
the body of the loop. When the one time even though the condition is
condition is false it comes of the loop. false at the very first time.

9. What is the difference between ++a and a++?


✓ ++a means do the increment before the operation (pre increment) a++ means
1.96 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
10. What is a Function?
✓ A function is a block of code which only runs when it is called.
✓ It performs a specific task.
11. What is meant by Recursive function?
✓ If a function calls itself again and again, then that function is called Recursive

in
function.

n.
✓ The syntax for recursive function is:
function recurse() {

aa
// function code
recurse();

iy
// function code
}
or
.p
recurse();
12. Write short notes about main() function in ’C’ program.
w

Every C program must have main () function.


w

✓ All functions in C, has to end with ‘( )’ parenthesis.


w

✓ It is a starting point of all ‘C’ programs.


✓ The program execution starts from the opening brace ‘{‘ and ends with closing
brace ‘}’, within which executable part of the program exists.
13. Give the syntax for the ‘for’ loop statement
for (Initialize counter; Test condition; Increment / Decrement)
{
statements;
}
14. What is an Array?
✓ An array is defined as finite ordered collection of homogenous data, stored in
contiguous memory locations.
➢ finite means data range must be defined.
➢ ordered means data must be stored in continuous memory addresses.
C Programming and Data Structures 1.97
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ homogenous means data must be of similar data type.
✓ For example: if you want to store marks of 50 students, you can create an array
for it.
• int marks[50];
15. What are the different types of arrays available in C.

in
✓ One-dimensional arrays

n.
✓ Multidimensional arrays
16. Write short notes on One-dimensional arrays.

aa
✓ A One-Dimensional Array in C programming is a special type of variable that
can store multiple values of only a single data type such as int, float, double, char

iy
etc.
or
✓ The syntax of declaring Two-dimensional arrays is:
➢ datatype array name [size]
.p
✓ Example
w

For example, int a[5]


w

17. Write short notes on Two-dimensional arrays.


✓ A multi-dimensional array can be termed as an array of arrays that stores
w

homogeneous data in tabular form.


✓ The general form of declaring Two-dimensional arrays is:
➢ data_type array_name[x][y];
✓ Example
int x[10][20];
18. What are the key features in the C programming language?
✓ Portability: It is a platform-independent language.
✓ Modularity: Possibility to break down large programs into small modules.
✓ Flexibility: The possibility of a programmer to control the language.
✓ Speed: C comes with support for system programming and hence it compiles
and executes with high speed when compared with other high-level languages.
✓ Extensibility: Possibility to add new features by the programmer.
1.98 C Programming Fundamentals
https://www.poriyaan.in/ https://eee.poriyaan.in/
19. What is a nested loop?
✓ A loop that runs within another loop is referred to as a nested loop. The first loop
is called the Outer Loop and the inside loop is called the Inner Loop. The inner
loop executes the number of times defined in an outer loop.
20. What are the modifiers available in C programming language?

in
✓ Short
✓ Long

n.
✓ Signed

aa
✓ Unsigned
✓ long long

iy
21. What is the explanation for prototype function in C?
or
✓ Prototype function is a declaration of a function with the following information
to the compiler.
.p
• Name of the function.
w

• The return type of the function.


w

• Parameters list of the function.


✓ Example
w

• int sum(int,int);
22. What do you mean by the Scope of the variable?
✓ Scope of the variable can be defined as the part of the code area where the
variables declared in the program can be accessed directly. In C, all identifiers
are lexically (or statically) scoped.
23. Can a C program be compiled or executed in the absence of a main()?
✓ The program will be compiled but will not be executed. To execute any C
program, main() is required.
24. What is the main difference between the Compiler and the Interpreter?
Interpreter Compiler
Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.
C Programming and Data Structures 1.99
https://www.poriyaan.in/ https://eee.poriyaan.in/
Interpreters usually take less amount of Compilers usually take a large amount
time to analyze the source code. of time to analyze the source code.
However, the overall execution time is However, the overall execution time is
comparatively slower than compilers. comparatively faster than interpreters.
No Object Code is generated, hence are Generates Object Code which further

in
memory efficient. requires linking, hence requires more
memory.

n.
Programming languages like Programming languages like C, C++,
JavaScript, Python, Ruby use Java use compilers.

aa
interpreters.

iy
or PART-B
.p
1. Explain the different types of operators with neat examples.
2. Illustrate the different conditional statements available in C with syntax and
w

examples
w

3. Explain the looping statements with neat examples.


w

4. What is an Array? Explain Single and Multi-Dimensional arrays with neat examples.
5. Write a C program for Matrix Multiplication with a 3*3 matrix.
6. Create a C program for Matrix Addition.
7. Write a C program to calculate the total, average and grade for 50 Students.
8. Write a C program to calculate the factorial of a given number.
9. Write a C program to check whether a given number is odd or even.
10. Write a C program to check whether a given number is prime or not.
11. Write a C program to check whether a given number is a palindrome or not.
12. Write a C program to check whether a given number is a Armstrong number or not.
https://www.poriyaan.in/ https://eee.poriyaan.in/

II

in
PROGRAMMING - ADVANCED FEATURES

n.
Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays

aa
and Functions – File Handling – Preprocessor Directives.

iy
2.1 INTRODUCTION
or
➢ Structures, unions and enumerations are known as user defined data types.
➢ These data types are used to create a flexible new data type.
.p
➢ Structure can be used for the storage of different data types. The similarity
w

between structure and array is both contain a finite number of elements.


➢ Union is similar to structures in all aspects except the manner in which their
w

constituent elements are stored.


w

➢ In structures, separate memory is allocated to each element, while in unions all


the elements are share the same memory.
➢ Enumeration helps to define a data type whose objects can take a limited set of
values.

2.2 STRUCTURE
Definition
➢ A Structure is a collection of variables of different data types under a single
name and provides a convenient way of grouping several of related information
together.
➢ Unlike arrays, it can be used for the storage of heterogeneous data (data of
different data types).

2.2.1 Three main aspects of working with structure


2.2 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
2. Initializing structure elements
3. Declaring variables and constants (objects) of the newly created type.

2.2.1.1 Defining Structure


Syntax

in
struct structure_name
{

n.
element-1;

aa
element-2;
element-3; //Variable declarations

iy
...
...
element-n;
or
.p
} v1,v2........vn;
Where element1, element2, element3 are variables of any primitive or derived
w

data types and v1,v2,...vn are structure variable.


w

Example
w

struct book
{
char author[40];
float price;
int page;
}b1,b2;
Rules for defining structure
➢ Structure definition consists of the keyword struct followed by a structure tag
name and a structure declaration list enclosed within braces.
➢ The structure declaration list consists of one or more variables declaration,
possibly of different data types. The variable names declared in the structure
declaration list are known as structure members.
➢ Structure members can be variables of the basic types( eg: char, float, int) or
C Programming and Data Structures 2.3
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ A structure declaration list cannot contain a member of void type or incomplete
type or function type.
➢ Self referential structure: a structure may contain a pointer to an instance of
itself is known as self referential structure.

2.2.1.2 Initializing Structure Elements

in
Syntax

n.
Struct book

aa
{
int page;

iy
char author[10];
float price;
}b1;
or
.p
Example
void main()
w

{
w

b1.author=”Kalam”;
w

printf(“Enter price:”);
scanf(“%f”,&b1.price);
b1.page=178;
}

2.2.1.3 Declaring Structure Objects


➢ Variables (or) constants of the created structure type can be created either at the
time of structure definition (or) after the time of structure definition.
Syntax
[type qualifier] structure type identifier name [= initialization list]; (or)
variables;
Example
struct book b1={3,2,1}; // it contains the initialization list
2.4 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
Rules for declaring structure objects:
➢ It is important to note that the structure members cannot be initialized during the
structure definition; however the members of a structure object can be initialized
by providing an initialization list.

2.2.2 Operations on Structures

in
➢ Aggregate operations

n.
➢ Segregate operations

aa
2.2.2.1 Aggregate Operations
➢ An aggregate operation treats an operand as an entity and operates on the entire

iy
operand as whole instead of operating on its constituent members.
Types
or
a) Accessing members of an object of a structure
.p
b) Assigning a structure object to a structure variables
c) Address of a structure object
w

d) Size of a structure.
w

a) Accessing members of an object of a structure :


w

The members of a structure object can be accessed by using:


(i) Direct member access operator (dot operator)
(ii) Indirect member access operator(arrow operator)
(i) Direct member access operator (dot operator):
Syntax:
struct variable-name.struct-element-name
Example Program 2.1
//C program to print student details using structure
#include<stdio.h>
#include<conio.h>
struct student
{
C Programming and Data Structures 2.5
https://www.poriyaan.in/ https://eee.poriyaan.in/
int rno;
float mark;
};
struct student s;
void main()

in
{

n.
printf(“enter the name”);
scanf(“%c”,&s.name);

aa
printf(“enter the rno”);

iy
scanf(“%d”,&s.rno);
printf(“enter the mark”);
or
scanf(“%f”,&s.mark);
.p
printf(“NAME=%c”,s.name);
w

printf(“RNO=%d”,s.rno);
w

printf(“MARK=%f”,s.mark);
w

getch();
}
OUTPUT
enter the name
xyz
enter the rno
20
enter the mark
80
NAME=xyz
RNO=20
MARK=80
2.6 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example Program 2.2
/*C program to calculate the student’s average marks and student details using
structure*/
#include<stdio.h>
#include<conio.h>

in
struct student

n.
{
char name;

aa
int rno;
int m1,m2,m3;

iy
};
struct student s;
or
.p
void main()
{
w

float total,average;
w

printf(“enter the name”);


w

scanf(“%c”,&s.name);
printf(“enter the rno”);
scanf(“%d”,&s.rno);
printf(“enter the marks”);
scanf("%d %d %d",&s.m1,&s.m2,&s.m3);
total=s.m1+s.m2+s.m3;
average=total/3;
printf(“NAME=%c”,s.name);
printf(“RNO=%d”,s.rno);
printf(“AVERAGE MARK=%f”,average);
getch();
}
C Programming and Data Structures 2.7
https://www.poriyaan.in/ https://eee.poriyaan.in/
Output:
enter the name
xyz
enter the rno
20

in
enter the marks

n.
80

aa
90
95

iy
NAME=xyz
RNO=20
AVERAGE MARK=88.33
or
.p
Example Program 2.3
w

#include<stdio.h>
struct book //Struct datatype declaration
w

{
w

int x,y;
};
void main()
{
struct book s1={4,5}; //s1-> variable of structure and values are
initialized
int a=10 , b=20 ;
printf(“\na=%d”,s1.x+a); // elements are accessed using dot operator(.)
printf(“\nb=%d”, s1.y+b);
}
Output:
a=4
2.8 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
(ii)Indirect member access operator (arrow operator)
Syntax :
struct variable name -> struct element name
(or)
*struct variable name . struct element name

in
Example Program 2.4

n.
#include<stdio.h>

aa
struct book // structure data type declaration
{

iy
int x,y;
}; or
struct book *b1; //pointer to structure
.p
void main()
w

{
printf(“enter the values”);
w

scanf(“%d”, &b1->x);
w

scanf(“%d”,&b1->y); //-> operator used


printf(“\nx=%d”, b1->x);
printf(“\ny=%d”, *b1.y);
}
Output:
Enter the values 10 20
x=10
y=20
b) Assigning a structure object to a structure variables
➢ Assignment operator (=) is used to assign the values of one variable to another
variable. When assignment operator (=) is applied on structure variables, it
performs member by member copy.
C Programming and Data Structures 2.9
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example Program 2.5
#include<stdio.h>
struct book // struct datatype is declared
{
char title[25], author[20];

in
int price;

n.
};

aa
void main()
{

iy
struct book b1,b2,b3; //structure variables are declared
b1={“ cutting stone”, “Abraham”,400};
or
b2.author=b1.author;
.p
b3=b1; // b1 variable values are assigned to b3
printf(“%s by %s is of Rs. %d \n”, b1.title,b1.author,b1.price);
w

printf(“%s is the author of second book”,b2.author);


w

printf(“%s by %s is of Rs. %d \n”, b3.title,b3.author,b3.price);


w

}
Output:
cutting stone by Abraham is of Rs.400
Abraham is the author of second book
cutting stone by Abraham is of Rs. 400
c) Address of a structure object
➢ The address of operator (&) when applied to a structure object gives its base
address. It can also be used to find the address of the constituting members of a
structure object.
Example Program 2.6
#include<stdio.h>
struct book // struct datatype is declared
2.10 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
char title[25], author[20];
int price;
};
void main()
{

in
struct book b1,b2,b3; //structure variables are declared

n.
b1={“ cutting stone”, “Abraham”,400};

aa
b2.author=b1.author;
b3=b1; // b1 variable values are assigned to b3

iy
printf(“%s by %s is of Rs. %d \n”, b1.title,b1.author,b1.price);
printf(“\n address of structure’s element title %u “,&b1.title);
or
}
.p
Output
cutting stone by Abraham is of Rs.400
w

address of structure’s element title 1700printf(“\n address of whole variable


w

%u”,&b1);
w

address of structure’s element author 1725


address of whole variable 4000
d) Size of a structure.
➢ When the sizeof operator is applied to an operand of a structure type it will
produce the result as how much memory space is occupied by that particular
object.
Syntax:
sizeof (expression);
sizeof type
Example:
sizeof (struct book); // use structure’s name
sizeof b1 // use variable
C Programming and Data Structures 2.11
https://www.poriyaan.in/ https://eee.poriyaan.in/
Program 2.7
#include<stdio.h>
struct book //structure type declaration
{
char a; // elements are declared

in
int b;

n.
char c;

aa
float d;
}; //structure type declarations are terminated

iy
void main()
{ or
struct book var; //variable declaratio
.p
printf(“obj of struct book will take %d bytes\n”,sizeof(struct book));
printf(“structure variable var takes %d bytes\n”, sizeof var);
w

}
w

Output:
w

obj of struct pad will take 8 bytes


structure variable var takes 8 bytes

2.2.2.2 Segregate Operations


➢ A segregate operation operates on the individual members of a structure object.
Program 2.8
#include<stdio.h>
struct book
{
char title[25], author[20];
int page; float price;
};
void main()
2.12 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
{
struct book b1;
printf(“enter title, author, page, price”);
scanf(“%s, %s, %d, %f”,& b1.title,&b1.author,&b1.page, &b1.price);
printf(“title is %s, author is %s, page no %d, price %d”,b1.title,

in
b1.author, b1.page, b1.price);

n.
// operations on individual element

aa
b1.page+=100;
b1.price+=10;

iy
printf(“title is %s, author is %s, page no %d”,b1.title, b1.author,
b1.page);
or
printf(“price %d”,b1.price);
.p
}
Output
w

Enter title, author, page, price


w

Principles of life, prabhu, 145, 200.00


w

Title is principles of life, author is prabhu, page no 145, price 200.00


Title is principles of life, author is prabhu, page no 245, price 210.00

2.3 UNION
➢ Union can be defined as a user-defined data type which is a collection of
different variables of different data types in the same memory location. The
union can also be defined as many members, but only one member can contain a
value at a particular point in time. Unions provide an efficient way of using the
same memory location for multiple-purpose.
➢ Union is a user-defined data type, but unlike structures, they share the same
memory location.
Defining a Union
➢ To define a union, you must use the union statement in the same way as did
while defining a structure. The union statement defines a new data type with
C Programming and Data Structures 2.13
https://www.poriyaan.in/ https://eee.poriyaan.in/
more than one member for your program. The format of the union statement is
as follows:
union [union tag] {
member definition;
member definition;

in
...

n.
member definition;
} [one or more union variables];

aa
➢ The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the end

iy
of the union's definition, before the final semicolon, you can specify one or more
or
union variables but it is optional. Here is the way you would define a union type
named Data having three members i, f, and str.
.p
union Data {
w

int i;
float f;
w

char str[20];
w

} data;
➢ Now, a variable of Data type can store an integer, a floating-point number, or a
string of characters. It means a single variable, i.e., same memory location, can be
used to store multiple types of data. You can use any built-in or user defined data
types inside a union based on your requirement.
Example Program 2.9 Illustration of Union
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
2.14 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
void main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;

in
printf( "data.f : %f\n", data.f);

n.
strcpy( data.str, "Charulatha publication");

aa
printf( "data.str : %s\n", data.str);
}

iy
Output
data.i : 10 or
data.f : 220.500000
.p
data.str : Charulatha publication
Difference between Structure and Union
w

Sl.No Structure Union


w

1 The member of a structure occupies The member of union share same


w

its own memory space. memory space.


2 The keyword struct is used to define The keyword union is used to define a
a structure structure
3 All the members of a structure can Only the first member of a union can
be initialized. be initialized.
4 In structure, each member is stored In union, all members are stored in
in a separate memory location. So the same memory locations. So, need
need more memory space. less memory space.

2.4 POINTERS
2.4.1 Pointers to Variables
➢ A pointer is a variable that stores an address of another variable of same type.
➢ Pointer can have any name that is legal for other variable.
C Programming and Data Structures 2.15
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Pointer variables are declared with prefix of ‘*’ operator.
➢ Using a pointer variable, we can access the value of another variable assigned to
it.
Syntax
data_type *pointer_name;

in
Example

n.
int *a;
➢ variable *a can store the address of any integer type variable.

aa
➢ A pointer is a variable whose value is also an address.
➢ Each variable has two attributes

iy
✓ Value
✓ Address
or
.p
We can define pointers in two ways.
i) First a pointer is a variable and assigns different values to a pointer variable.
w

ii) Second the value contained by a pointer must be an address which indicates the
w

location of another variable in the memory. So, pointer is called as “address


variable”.
w

Example
int a=50;
int *ptr;
ptr=&a;

➢ Here ‘a’ is a variable holds a value 50 and stored in a memory location 1001.
‘*ptr’ is pointer variable holds a address of a variable ‘a’.
2.16 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
Advantages of Using Pointers
➢ Pointers are more compact and efficient code.
➢ Pointers can be used to achieve clarity and simplicity.
➢ Pointers are used to pass information between function and its reference point.
➢ A pointer provides a way to return multiple data items from a function using its

in
function arguments.

n.
➢ Pointers also provide an alternate way to access an array element.
➢ A pointer enables us to access the memory directly.

aa
Example Program 2.10

iy
/*C program for printing value and address of a variable using pointer variable*/
#include<stdio.h> or
#include<conio.h>
.p
void main()
{
w

int i=3;
w

int *ptr;
w

ptr=&i;
clrscr();
printf(“Address of i=%u\n”,ptr);
printf(“value of i=%d\n”,*ptr);
getch();
}
Output:
Address of i=65524
value of i=3
Example Program 2.11
/*C program for printing value and address of a variable using pointer variable by
various methods*/
C Programming and Data Structures 2.17
https://www.poriyaan.in/ https://eee.poriyaan.in/
#include<conio.h>
void main()
{
int i=4;
int *j;

in
j=&i;

n.
clrscr();

aa
printf(“Address of i=%u\n”,&i);
printf(“Address of i=%u\n”,j);

iy
printf(“Address of j=%u\n”,&j);
printf(“value of j=%u\n”,j);
or
printf(“value of i=%d\n”,i);
.p
printf(“value of i=%d\n”,*(&i));
printf(“value of i=%d\n”,*j);
w

getch();
w

}
w

Output
Address of i=65524
Address of i=65524
Address of j=65522
value of j=65524
value of i=4
value of i=4
value of i=4
Example Program 2.12
/*C program to add two numbers using pointers*/
#include<stdio.h>
#include<conio.h>
2.18 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
void main()
{
int a,b,*p,*q,sum;
clrscr();
printf(“Enter two integers”);

in
scanf(“%d %d”,&a,&b);

n.
p=&a;

aa
q=&b;
sum=*p+*q;

iy
printf(“sum=%d”,sum);
getch(); or
}
.p
Output
Enter two integers 2 3
w

sum=5
w

2.4.2 Pointer operators


w

a) Referencing a pointer
➢ A pointer variable is made to refer to an object.
➢ Reference operator(&) is used for this.
➢ Reference operator is also known as address of (&) operator.
Example
float a=12.5;
float *p;
p=&a;
C Programming and Data Structures 2.19
https://www.poriyaan.in/ https://eee.poriyaan.in/
b) Dereferencing a pointer
• The object referenced by a pointer can be indirectly accessed by
dereferencing the pointer.
• Dereferencing operator (*) is used for this.
• This operator is also known as indirection operator or value- at-operator.

in
Example

n.
int b;
int a=12;

aa
a int *p;
Example program 2.13

iy
#include<stdio.h>
void main()
or
{
.p
int a=12;
w

int *p;
w

int **pptr;
p=&a;
w

pptr=&p;
printf(“Value=%d”,a);
printf(“value by dereferencing p is %d \n”,*p);
printf(“value by dereferencing pptr is %d \n”,**pptr);
printf(“value of p is %u \n”,p);
printf(“value of pptr is %u\n”,pptr);
}
Output
Value=12
value by dereferencing p is 12
value by dereferencing pptr is 12
value of p is 1000
2.20 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
2.4.3 Arrays and pointers
➢ Array elements are always stored in consecutive memory locations according to
the size of the array.
➢ The size of the variable with the pointer variables refers to, depends on the data
type pointed by the pointer.

in
➢ A pointer when incremented, always points to a location after skipping the
number of bytes required for the data type pointed to by it.

n.
Example

aa
int a[5]={10,20,30,40,50};
a[5] means the array ‘a’ has 5 elements and of integer data type

iy
Program 2.14
or
/*C program to print the value and address of an array elements*/
.p
#include<stdio.h>
#include<conio.h>
w

void main()
w

{
w

int a[5]={10,20,30,40,50};
int i;
clrscr();
for(i=0;i<5;i++)
{
printf(“The value of a[%d]=%d\n”,i,a[i]);
printf(“Address of a[%d]=%u\n”,i,&a[i]);
}
getch();
}
Output
The value of a[0]=10
C Programming and Data Structures 2.21
https://www.poriyaan.in/ https://eee.poriyaan.in/
The value of a[1]=20
Address of a[1]=4002
The value of a[2]=10
Address of a[2]=4004
The value of a[3]=10

in
Address of a[3]=4006

n.
The value of a[4]=10

aa
Address of a[4]=4008
Example Program 2.15

iy
/*C program to print the value and address of an array elements using pointer*/
#include<stdio.h>
#include<conio.h>
or
.p
void main()
w

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

int i,*p;
w

p=arr;
clrscr();
for(i=0;i<=5;i++)
{
printf(“\nAddress=%u\t”,(p+i));
printf(“Element=%d”,*(p+i));
}
getch();
}
Output
Address 4000 Element=10
Address 4002 Element=20
2.22 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
Address 4004 Element=30
Address 4006 Element=40
Address 4008 Element=50
Example Program 2.16
/*C program to add sum of elements of an array using pointer*/

in
#include<stdio.h>

n.
main()

aa
{
int i,sum;

iy
int arr[5];
int *ptr;
for(i=0;i<5;i++)
or
.p
{
printf (“Enter the number”);
w

scanf(“%d”,&arr[i]);
w

}
w

ptr=arr;
for(i=0;i<5;i++)
{
sum=sum+*ptr
Functions and Pointers 3.29
ptr=ptr+1;
}
printf(“Total=%d”,sum);
}
Output
Enter the number
10
C Programming and Data Structures 2.23
https://www.poriyaan.in/ https://eee.poriyaan.in/
30
40
50
Total= 150

in
2.4.3.1 Pointers with Multi-Dimensional Array
➢ A multi-dimensional array can also be represented with an equivalent pointer

n.
notation. A two dimensional array can be considered as a collection of one-

aa
dimensional arrays.
Syntax

iy
data_type (*pointer variable) [expression];
data_type array name[expression 1][expression 2];
Example Program 2.17
or
.p
/*C program to print the value and address of the element using array of
pointers*/
w

#include<stdio.h>
w

#include<conio.h>
w

void main()
{
int * int *a[3];
int b=10,c=20,d=30,i;
a[0]=&b;
a[1]=&c;
a[2]=&d;
clrscr();
for(i=0;i<3;i++)
{
printf(“Address=%u\n”,a[i]);
printf(“Value=%d\n”,*(a[i]));
2.24 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
getch();
}
Output
Address=4000
Value=10

in
Address=5000

n.
Value=20

aa
Address=6000
Value=30

iy
2.4.4 Functions Pointers
or
➢ Function pointers in C can be used to create function calls to which they point.
This allows programmers to pass them to functions as arguments. Such
.p
functions passed as an argument to other functions are also called callback
functions.
w

➢ In C programming, it is also possible to pass addresses as arguments to


w

functions. To accept these addresses in the function definition, we can use


pointers. It's because pointers are used to store addresses.
w

Example Program 2.18


Write a C Program for Swapping of two numbers using function pointers.
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
// address of num1 and num2 is passed
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
return 0;
C Programming and Data Structures 2.25
https://www.poriyaan.in/ https://eee.poriyaan.in/
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;

in
*n1 = *n2;

n.
*n2 = temp;
}

aa
Output
num1 = 10

iy
num2 = 5
or
➢ The address of num1 and num2 are passed to the swap() function using
swap(&num1, &num2);
.p
➢ When *n1 and *n2 are changed inside the swap() function, num1 and num2
w

inside the main() function are also changed.


➢ Inside the swap() function, *n1 and *n2 swapped. Hence, num1 and num2 are
w

also swapped.
w

2.5 ENUMERATED DATA TYPES


➢ Enumeration or Enum in C is a special kind of data type defined by the user. It
consists of constant integrals or integers that are given names by a user. The use of
enum in C to name the integer values makes the entire program easy to learn,
understand, and maintain by the same or even different programmer.
Syntax to Define Enum in C
• An enum is defined by using the ‘enum’ keyword in C, and the use of a comma
separates the constants within. The basic syntax of defining an enum is:
enum enum_name{int_const1, int_const2, int_const3, …. int_constN};
• In the above syntax, the default value of int_const1 is 0, int_const2 is 1,
int_const3 is 2, and so on. However, you can also change these default values
while declaring the enum.
2.26 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example
• Below is an example of an enum named cars and how you can change the
default values.
enum cars{BMW, Ferrari, Jeep, Mercedes-Benz};
o Here, the default values for the constants are:

in
BMW=0, Ferrari=1, Jeep=2, and Mercedes-Benz=3. However, to change

n.
the default values, you can define the enum as follows:
enum cars{

aa
BMW=3,
Ferrari=5,

iy
Jeep=0,
Mercedes-Benz=1
or
.p
};

2.5.1 Enumerated Type Declaration to Create a Variable


w

➢ Similar to pre-defined data types like int and char, you can also declare a
w

variable for enum and other user-defined data types. Here’s how to create a
w

variable for enum.


▪ enum condition (true, false); //declaring the enum
▪ enum condition e; //creating a variable of type condition
➢ Suppose we have declared an enum type named condition; we can create a
variable for that data type as mentioned above. We can also converge both the
statements and write them as: enum condition (true, false) e;
➢ For the above statement, the default value for true will be 1, and that for false
will be 0.

2.5.2 Implementing enum using C Program


Example program 2.19: Printing the Values of Weekdays
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
C Programming and Data Structures 2.27
https://www.poriyaan.in/ https://eee.poriyaan.in/
// printing the values of weekdays
for(int i=Sunday;i<=Saturday;i++){
printf("%d, ",i);
}
return 0;

in
}

n.
Output

aa
iy
2.6 FILE HANDLING
or
.p
➢ A file is a collection of bytes stored on a secondary storage device, which is
generally a disk of some kind. The collection of bytes may be interpreted, for
w

example, as characters, words, lines, paragraphs and pages from a textual


w

document; fields and records belonging to a database; or pixels from a graphical


image.
w

➢ The meaning attached to a particular file is determined entirely by the data


structures and operations used by a program to process the file. It is conceivable
(and it sometimes happens) that a graphics file will be read and displayed by a
program designed to process textual data.
➢ The result is that no meaningful output occurs (probably) and this is to be
expected. A file is simply a machine decipherable storage media where
programs and data are stored for machine usage.

2.6.1 Why we need file?


➢ When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
➢ If you have to enter a large number of data, it will take a lot of time to enter
them all. However, if you have a file containing all the data, you can easily
access the contents of the file using few commands in C. It is possible easily
2.28 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
2.6.2 File Operations
➢ In programming, we may require some specific input data to be generated
several numbers of times. Sometimes, it is not enough to only display the data
on the console. The data to be displayed may be very large, and only a limited
amount of data can be displayed on the console, and since the memory is

in
volatile, it is impossible to recover the programmatically generated data again
and again.

n.
➢ However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in

aa
C.
➢ File handling in C enables us to create, update, read, and delete the files stored

iy
on the local file system through our C program. The following operations can be
performed on a file.
• Creation of the new file
or
.p
• Opening an existing file

w

Reading from the file


• Writing to the file
w

• Deleting the file


w

2.6.2.1 Types of Files


➢ There are two kinds of files in which data can be stored in two ways either in
characters coded in their ASCII character set or in binary format. They are
1. Text Files (or) ASCII file
2. Binary Files
Text Files (or) ASCII file
➢ The file that contains ASCII codes of data like digits, alphabets and symbols is
called text file (or) ASCII file.
Binary Files
➢ A binary file is a file that uses all 8 bits of a byte for storing the information .It is
the form which can be interpreted and understood by the computer.
➢ The only difference between the text file and binary file is the data contain in
text file can be recognized by the word processor while binary file data can’t be
C Programming and Data Structures 2.29
https://www.poriyaan.in/ https://eee.poriyaan.in/
1. wb(write)
This opens a binary file in write mode.
SYNTAX: fp=fopen(“data.dat”,”wb”);
2. rb(read)
This opens a binary file in read mode

in
SYNTAX:fp=fopen(“data.dat”,”rb”);

n.
3. ab(append)

aa
This opens a binary file in a Append mode i.e. data can be added at the end
of file.
SYNTAX: fp=fopen(“data.dat”,”ab”);

iy
4. r+b(read+write)
or
This mode opens preexisting File in read and write mode.
.p
SYNTAX: fp=fopen(“data.dat”,”r+b”);
5. w+b(write+read)
w

This mode creates a new file for reading and writing in Binary mode.
w

SYNTAX: fp=fopen(“data.dat”,”w+b”);
w

6. a+b(append+write)
This mode opens a file in append mode i.e. data can be written at the end of
file.
SYNTAX: fp=fopen(“data.dat”,”a+b”);
Opening Modes in Standard I/O
r Open for reading If the file does not exist, fopen() returns
NULL
rb Open for reading in binary If the file does not exist, fopen() returns
mode. NULL.
w Open for writing. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
wb Open for writing in binary If the file exists, its contents are overwritten.
mode. If the file does not exist, it will be created.
2.30 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
a Open for append. i.e, Data is If the file does not exists, it will be created.
added to the end of file.
ab Open for append in binary If the file does not exists, it will be created.
mode. i.e, Data is added to
end of file.

in
r+ Open for both reading and If the file does not exist, fopen() returns
writing. NULL.

n.
rb+ Open for both reading and If the file does not exist, fopen() returns

aa
writing in binary file. NULL
w+ Open for both reading and If the file exists, its contents are overwritten.

iy
writing. If the file does not exist, it will be created.
wb+ Open for both reading and If the file exists, its contents are overwritten.
writing in binary mode.
or
If the file does not exist, it will be created.
.p
a+ Open for both reading and If the file does not exists, it will be created.
appending.
w

ab+ Open for both reading and If the file does not exists, it will be created.
w

appending in binary mode.


w

Closing a File: fclose(fptr);


➢ The file (both text and binary) should be closed after reading/writing. Closing a
file is performed using library function fclose().
Reading and writing to a text file
➢ The functions fprintf() and fscanf() are used to read or write the file They are
just the file versions of printf() and scanf(). The only difference is that, fprint
and fscanf expects a pointer to the structure FILE.
Writing to a text file
Program 2.20: Write to a text file using fprintf()
#include <stdio.h>
int main()
{
C Programming and Data Structures 2.31
https://www.poriyaan.in/ https://eee.poriyaan.in/
FILE *fptr;
fptr = fopen(“C:\\program.txt”,”w”);
if(fptr == NULL)
{
printf(“Error!”);

in
exit(1);

n.
}

aa
printf(“Enter num: “);
scanf(“%d”,&num);

iy
fprintf(fptr,”%d”,num);
fclose(fptr);
return 0;
or
.p
}
➢ This program takes a number from user and stores in the file program.txt. After
w

you compile and run this program, you can see a text file program.txt created in
w

C drive of your computer. When you open the file, you can see the integer you
entered.
w

Reading from a text file


Program 2.21: Read from a text file using fscanf()
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.txt”,”r”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
2.32 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
fscanf(fptr,”%d”, &num);
printf(“Value of n=%d”, num);
fclose(fptr);
return 0;
}

in
Reading and writing to a binary file

n.
➢ Functions fread() and fwrite() are used for reading from and writing to a file on
the disk respectively in case of binary files.

aa
Writing to a binary file
➢ To write into a binary file, you need to use the function fwrite(). The functions

iy
takes four arguments: Address of data to be written in disk, Size of data to be
or
written in disk, number of such type of data and pointer to the file where you
want to write.
.p
fwrite(address_data,size_data,numbers_data,pointer_to_file);
w

Program 2.22: Writing to a binary file using fwrite()


w

#include <stdio.h>
struct threeNum
w

{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.bin”,”wb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
C Programming and Data Structures 2.33
https://www.poriyaan.in/ https://eee.poriyaan.in/
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;

in
num.n3 = 5n + 1;

n.
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}

aa
fclose(fptr);
return 0;

iy
}
or
➢ We declare a structure three Num with three numbers - n1, n2 and n3, and
define it in the main function as num. Now, inside the for loop, we store the
.p
value into the file using fwrite.
w

➢ The first parameter takes the address of num and the second parameter takes the
size of the structure three Num. Since, we’re only inserting one instance of num,
w

the third parameter is 1. And, the last parameter *fptr points to the file we’re
w

storing the data. Finally, we close the file.


Reading from a binary file
➢ Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);
Program 2.23: Reading from a binary file using fread()
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
2.34 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.bin”,”rb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.

in
exit(1);

n.
}

aa
for(n = 1; n < 5; ++n)
{

iy
fread(&num, sizeof(struct threeNum), 1, fptr);
printf(“n1: %d\tn2: %d\tn3: %d”, num.n1, num.n2, num.n3);
or
}
.p
fclose(fptr);
return 0;
w

}
w

➢ This program will start reading the records from the file program.bin in the
w

reverse order (last to first)


Text Files
➢ In C, all components are files, each with a different behavior based on the
attached devices. To enable the I/O functions, several standard built-in functions
were created and stored in libraries.
➢ Some of the high level file I/O functions are given in Table 2.1
Table 2.1 High level file I/O functions
S.No Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
C Programming and Data Structures 2.35
https://www.poriyaan.in/ https://eee.poriyaan.in/
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file

in
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file

n.
aa
1. fopen () : It creates a new file for use or opens an existing file for use.
2. fclose (): It closes a file which has been opened for use.

iy
3. fscanf( file pointer, format string, address of the variable)
Example: fscanf(fptr,”%d”, &num);
or
4. fprintf(console output, “format string”, file pointer);
.p
Example: fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
w

5. getw (): This function returns the integer value from a given file and increment the
file pointer position to the next message.
w

Syntax: getw (fptr);


w

Where fptr is a file pointer which takes the integer value from file.
6. putw (): This function is used for writing an integer value to a given file.
Syntax: putw (value,fptr);
Where fptr is a file pointer Value is an integer value which is written to a given file.
Example Program for getw() and putw()
Program 2.24: Write a program to read integer data from the user and write it
into the file using putw() and read the same integer data from the file using getw()
and display it on the output screen.
#include<stdio.h>
#include<conio.h>
void main()
{
2.36 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
int n;
clrscr();
fp=fopen(“c.dat”, “wb+”);
printf(“Enter the integer data”);
scanf(“%d”,&n);

in
while(n!=0)

n.
{

aa
putw(n,fp);
scanf(“%d”,&n);

iy
}
rewind(fp); or
printf(“Reading data from file”);
.p
while((n=getw(fp))!=EOF)
{
w

printf(“%d\n”,n);
w

}
w

fclose(fp);
getch();
}
7. fwrite()
➢ This function is used for writing an entire block to a given file.
Syntax: fwrite(ptr,size,nst,fptr);
ptr is a pointer ,it points to the array of structure.
Size is the size of the structure
nst is the number of the structure
fptr is a filepointer.
8. fread()
➢ fread(ptr,size,position,fptr);similar to fwrite
C Programming and Data Structures 2.37
https://www.poriyaan.in/ https://eee.poriyaan.in/
Program 2.25: program for fwrite():
Write a program to read an employee details and write them into the file at a time
using fwrite().
#include<stdio.h>
#include<conio.h>

in
void main()

n.
{
struct emp

aa
{
int eno;

iy
char ename[20];
float sal;
}e;
or
.p
FILE *fp;
w

fp=fopen(“emp.dat”, “wb”);
w

clrscr();
printf(“Enter employee number”);
w

scanf(“&d”,&e.eno);
printf(“Enter employee name”);
fflush(stdin);
scanf(“%s”,e.ename);
printf(“Enter employee salary”);
scanf(“%f”,&e.sal);
fwrite(&e,sizeof(e),1,fp);
printf(“One record stored successfully”);
getch();
}
Operations for Search data in a file
1. fseek()
2.38 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
3. rewind()
fseek() : Getting data using fseek()
➢ When many records inside a file and need to access a record at a specific
position, you need to loop through all the records before it to get the record. This
will waste a lot of memory and operation time. An easier way to get to the

in
required data can be achieved using fseek().
Syntax of fseek()

n.
fseek(FILE * stream, long int offset, int whence)

aa
fseek(file pointer, displacement, pointer position);
➢ The first parameter stream is the pointer to the file. The second parameter is the

iy
position of the record to be found, and the third parameter specifies the location
where the offset starts.
or
➢ This function is used for seeking the pointer position in the file at the specified
.p
byte.
Syntax: fseek( file pointer, displacement, pointer position);
w

file pointer - It is the pointer which points to the file.


w

displacement -It is positive or negative.


w

➢ This is the number of bytes which are skipped backward (if negative) or forward
(if positive) from the current position. This is attached with L because this is a
long integer.
Pointer position: This sets the pointer position in the file.
Value Pointer position Value Pointer position
0 Beginning of file.
1 Current position
2 End of file

Example:
1. fseek( p,10L,0)
➢ This 0 means pointer position is on beginning of the file, from this statement
pointer position is skipped 10 bytes from the beginning of the file.
C Programming and Data Structures 2.39
https://www.poriyaan.in/ https://eee.poriyaan.in/
2. fseek( p,5L,1)
➢ This 1 means current position of the pointer position. From this statement
pointer position is skipped 5 bytes forward from the current position.
3. fseek(p,-5L,1):
➢ From this statement pointer position is skipped 5 bytes backward from the

in
current position.

n.
aa
iy
or
.p
Program 2.26: for fseek()
#include <stdio.h>
w

struct threeNum
w

{
w

int n1, n2, n3;


};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen(“C:\\program.bin”,”rb”)) == NULL){
printf(“Error! opening file”);
// Program exits if the file pointer returns NULL.
exit(1);
}
2.40 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
fseek(fptr, sizeof(struct threeNum), SEEK_END);
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf(“n1: %d\tn2: %d\tn3: %d”, num.n1, num.n2, num.n3);

in
}

n.
fclose(fptr);

aa
return 0;
}

iy
ftell()
➢ This function is used to move the file pointer to the beginning of the given file.
or
This function returns the value of the current pointer position in the file. The
value is count from the beginning of the file.
.p
Syntax: ftell(fptr); fptr is a file pointer.
w

rewind()
w

Syntax: rewind( fptr); fptr is a file pointer.


w

Program 2.27: program for fseek():


Write a program to read last ‘n’ characters of the file using appropriate file
functions(Here we need fseek() and fgetc()).
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen(“file1.c”, “r”);
if(fp==NULL)
C Programming and Data Structures 2.41
https://www.poriyaan.in/ https://eee.poriyaan.in/
printf(“file cannot be opened”);
else
{
printf(“Enter value of n to read last ‘n’ characters”);

in
scanf(“%d”,&n);

n.
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)

aa
{
printf(“%c\t”,ch);

iy
} or
}
.p
fclose(fp);
w

getch();
w

}
w

2.7 PREPROCESSOR DIRECTIVES


➢ The C preprocessor is a microprocessor that is used by compiler to transform
your code before compilation. It is called micro preprocessor because it allows
us to add macros.
➢ Note: A macro is a segment of code which is replaced by the value of macro.
Macro is defined by #define directive.
Example
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
2.42 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
iy
or
.p
w
w
w

➢ All preprocessor directives starts with hash # symbol. Let's see a list of
preprocessor directives.
• #define: It substitutes a preprocessor using macro.
• #include: It helps to insert a certain header from another file.
• #undef: It undefines a certain preprocessor macro.
• #ifdef: It returns true if a certain macro is defined.
• #ifndef: It returns true if a certain macro is not defined.
• #if, #elif, #else, and #endif: It tests the program using a certain condition;
these directives can be nested too.
• #line: It handles the line numbers on the errors and warnings. It can be used
to change the line number and source files while generating output during
compile time.
• #error and #warning: It can be used for generating errors and warnings.
C Programming and Data Structures 2.43
https://www.poriyaan.in/ https://eee.poriyaan.in/
• #error can be performed to stop compilation.
• #warning is performed to continue compilation with messages in the console
window.
• #region and #endregion: To define the sections of the code to make them
more understandable and readable, we can use the region using expansion

in
and collapse features.

n.
aa
iy
or
.p
w
w
w
2.44 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
REVIEW QUESTIONS
PART A
1. What is a Structure in C?
➢ Structure is a user-defined datatype in C language which allows us to combine
data of different types together. Structure helps to construct a complex data type

in
which is more meaningful.

n.
➢ In structure, data is stored in form of records.

aa
2. How to define a Structure?
➢ struct keyword is used to define a structure. struct defines a new data type
which is a collection of primary and derived data types.

iy
➢ Syntax
struct [structure_tag]
or
.p
{
//member variable 1
w

//member variable 2
w

//member variable 3
w

...
}[structure_variables];
3. What is Union?
➢ A union is a special data type available in C that allows to store different data
types in the same memory location.
➢ You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same
memory location for multiple purpose.
4. Give the syntax for creating a union.
union [union name]
{
member definition;
member definition;
C Programming and Data Structures 2.45
https://www.poriyaan.in/ https://eee.poriyaan.in/
...
member definition;
};
5. Difference between Structure and Union.
Structure Union

in
The Keyword struct is used to define The Keyword union is used to define

n.
the Structure the Union

aa
Structure allocates storage space for all Union allocates one storage space for
its members seperately. all its members.
Structure occupies high memory space Union occupies low memory space

iy
when compared to Structure

Structure at a time
or
We can access all members of Only one member of union can be
accessed at a time.
.p
Altering the value of a member will Altering the value of a member will
w

not affect other member of a structure alter other member value in union.
w

6. What are Enumerated Datatypes?


➢ Enumeration (or enum) is a user defined data type in C. It is mainly used to
w

assign names to integral constants, the names make a program easy to read and
maintain.
7. What is pointer?
➢ A pointer is a variable that stores the memory address of another variable as its
value. A pointer variable points to a data type (like int) of the same type and is
created with the * operator.
8. How addresses are assigned to Pointers?
➢ Example
int* p, a;
a= 8;
p = &a;
➢ Here, 8 is assigned to the variable a and the address of a is assigned to the
2.46 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
9. What are the uses of Pointers?
➢ Pointers are used to return more than one value to the function
➢ Pointers are more efficient in handling the data in arrays
➢ Pointers reduce the length and complexity of the program
➢ They increase the execution speed

in
➢ The pointers saves data storage space in memory.

n.
10. What is the difference between an array and pointer?

aa
Arrays Pointers
Array allocates space automatically. Pointer is explicitly assigned to point

iy
to an allocated space.
It cannot be resized. It can be resized using realloc ().
It cannot be reassigned.
or Pointers can be reassigned.
.p
Sizeof(array name) gives the number Sizeof(pointer name) returns the
of bytes occupied by the array. number of bytes used to store the
w

pointer variable.
w

11. What is dangling pointer?


w

➢ In C, a pointer may be used to hold the address of dynamically allocated


memory. After this memory is freed with the free() function, the pointer itself
will still contain the address of the released block. This is referred to as a
dangling pointer.
➢ Using the pointer in this state is a serious programming error. Pointer should be
assigned NULL after freeing memory to avoid this bug.
12. What is ‘C’ functions?
➢ A function is a self-contained block (or) a sub-program of one or more
statements that performs a special task when called.
➢ To perform a task repetitively then it is not necessary to re-write the particular
block of the program again and again. The function defined can be used for any
number of times to perform the task.
C Programming and Data Structures 2.47
https://www.poriyaan.in/ https://eee.poriyaan.in/
13. Differentiate library functions and User-defined functions.
Library Functions User-defined Functions
The User-defined functions are the
Library functions are pre-defined set of functions defined by the user according
functions that are defined in C libraries. to his/her requirement.

in
User can only use the function but User can use this type of function.

n.
cannot change (or) modify this function. User can also modify this function.

aa
14. What are the steps in writing a function in a program?
➢ Function Declaration (Prototype declaration): Every user-defined function has to

iy
be declared before the main().
or
➢ Function Calling: The user-defined functions can be called inside any functions
like main(), user-defined function, etc.
.p
➢ Function Definition: The function definition block is used to define the user-
defined functions with statements.
w

15. What is a use of ‘return’ Keyword?


w

➢ The ‘return’ Keyword is used only when a function returns a value.


w

16. What is the purpose of the function main()?


➢ The function main () invokes other functions within it. It is the first function to
be called when the program starts execution.
➢ Features of Main method
o It is the starting function.
o It returns an int value to the environment that called the program.
o Recursive call is allowed for main () also.
o It is a user-defined function.
o Program execution ends when the closing brace of the function main() is
reached.
o It has two arguments (a) argument count and (b)argument vector (represents
strings passed.)
2.48 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
17. Compare between Array and Structure
Arrays Structures
An array is a collection of data items A structure is a collection of data items
of same data type. of different data types.
Arrays can only be declared. There is Structures can be declared and defined.

in
no keyword for arrays. The Keyword for structures is struct.
An array name represents the address A structure name is known as tag. It is a

n.
of the starting element. shorthand notation of the declaration.

aa
An array cannot have bit fields. A structure may contain bit fields.

18. Is it better to use a macro or a function?

iy
➢ Macros are more efficient (and faster) than function because their corresponding
code is inserted directly at the point where the macro is called. There is no
or
overhead involved in using a macro like there is in placing a call to a function.
.p
➢ However, macros are generally small and cannot handle large, complex coding
constructs. In cases where large, complex constructs are to handled, functions
w

are more suited, additionally; macros are expanded inline, which means that the
code is replicated for each occurrence of a macro.
w

19. List the characteristics of Arrays.


w

➢ All elements of an array share the same name, and they are distinguished form
one another with help of an element number.
➢ Any element of an array can be modified separately without disturbing other
elements.
20. What are the types of Arrays?
➢ One-Dimensional Array
➢ Two-Dimensional Array
➢ Multi-Dimensional Array
21. What is File Handling in C?
➢ A file is nothing but a source of storing information permanently in the form of a
sequence of bytes on a disk. The contents of a file are not volatile like the C
compiler memory. The various operations available like creating a file, opening
a file, reading a file, or manipulating data inside a file is referred to as file
C Programming and Data Structures 2.49
https://www.poriyaan.in/ https://eee.poriyaan.in/
22. What is the need for File Handling in C?
➢ Reusability: It helps in preserving the data or information generated after
running the program.
➢ Large storage capacity: Using files, you need not worry about the problem of
storing data in bulk.

in
➢ Saves time: There are certain programs that require a lot of input from the user.
You can easily access any part of the code with the help of certain commands.

n.
➢ Portability: You can easily transfer the contents of a file from one computer

aa
system to another without having to worry about the loss of data.
23. List some of C File Handling Operations.

iy
➢ Creating a new file: fopen()
or
➢ Opening an existing file in your system: fopen()
➢ Closing a file: fclose()
.p
➢ Reading characters from a line: getc()
w

➢ Writing characters in a file: putc()


➢ Reading a set of data from a file: fscanf()
w

➢ Writing a set of data in a file: fprintf()


w

➢ Reading an integral value from a file: getw()


24. Give the syntax for Opening a Text File in C.
Syntax
*fpointer = FILE *fopen(const char *file_name, const char *mode);
• *fpointer is the pointer to the file that establishes a connection between the
file and the program.
• *file_name is the name of the file.
• *mode is the mode in which we want to open our file.
25. How to Read and Write a Text File in C?
➢ The input/output operations in a file help you read and write in a file.
➢ The simplest functions used while performing operations on reading and writing
characters in a file are getc() and putc() respectively.
2.50 Programming – Advanced Features
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ In order to read and write a set of data in a file, we use the fscanf() and fprintf()
operators.
26. Write short notes on Preprocessor Directives.
➢ The C preprocessor is a macro processor that is used automatically by the C
compiler to transform your program before actual compilation (Preprocessor

in
directives are executed before compilation.).
➢ It is called a macro processor because it allows you to define macros, which are

n.
brief abbreviations for longer constructs.

aa
27. What is macro?
➢ A macro is a segment of code which is replaced by the value of macro. Macro is

iy
defined by #define directive.
28. List few preprocessor directives in C.
➢ #include
or
.p
➢ Macro's (#define)
➢ #undef
w

➢ #ifdef
w

➢ #ifndef
w

➢ #if
➢ #else
C Programming and Data Structures 2.51
https://www.poriyaan.in/ https://eee.poriyaan.in/
PART-B

1. Explain Structure in C with neat program.


2. Write short notes on Union with example program.
3. What is a function? Explain with neat program.

in
4. Explain call by value and call by reference with example programs.

n.
5. Explain the file handling mechanism in C with programs.

aa
6. Explain preprocessor directives with its types and examples.
7. Explain the concept of pointers with neat programs.

iy
8. Write shorts notes on Arrays.
9. or
How to write Data into a text file and Read Data from the file? Discuss.
10. How to read and write data to the binary file in a program? Explain.
.p
w
w
w
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
LINEAR DATA STRUCTURES

aa
Abstract Data Types (ADTs) – List ADT – Array-Based Implementation – Linked List –
Doubly-Linked Lists – Circular Linked List – Stack ADT – Implementation of Stack –

iy
Applications – Queue ADT – Priority Queues – Queue Implementation – Applications.
or
.p
3.1 ABSTRACT DATA TYPES (ADTS)
➢ An abstract data type is an abstraction of a data structure that provides only the
w

interface to which the data structure must adhere. The interface does not give any
w

specific details about something should be implemented or in what programming


language.
w

➢ In other words, we can say that abstract data types are the entities that are
definitions of data and operations but do not have implementation details. In this
case, we know the data that we are storing and the operations that can be
performed on the data, but we don't know about the implementation details.
➢ The reason for not having implementation details is that every programming
language has a different implementation strategy for example; a C data structure
is implemented using structures while a C++ data structure is implemented using
objects and classes.

3.1.1 Abstract data type model


Abstraction: It is a technique of hiding the internal details from the user and only
showing the necessary details to the user.
Encapsulation: It is a technique of combining the data and the member function in a
single unit is known as encapsulation.
3.2 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
Figure 3.1 shows the ADT model. There are two types of models in the ADT
model, i.e., the public function and the private function. The ADT model also contains
the data structures that we are using in a program. In this model, first encapsulation is
performed, i.e., all the data is wrapped in a single unit, i.e., ADT. Then, the abstraction is
performed means showing the operations that can be performed on the data structure and
what are the data structures that we are using in a program

in
n.
aa
iy
or
.p
w
w

Fig 3.1 Abstract Data Type Model


w

Example 3.1
Suppose we have an index array of size 4. We have an index location starting from
0, 1, 2, 3. Array is a data structure where the elements are stored in a contiguous location.
The memory address of the first element is 1000, second element is 1004, third element
is 1008, and the fourth element is 1012. Since it is of integer type so it will occupy 4 bytes
and the difference between the addresses of each element is 4 bytes. The values stored in
an array are 10, 20, 30 and 40. These values, index positions and the memory addresses
are the implementations.
The abstract or logical view of the integer array can be stated as:
➢ It stores a set of elements of integer type.
➢ It reads the elements by position, i.e., index.
➢ It modifies the elements by index
➢ It performs sorting
C Programming and Data Structures 3.3
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.2 LIST ADT
➢ The list can be defined as an abstract data type in which the elements are stored
in an ordered manner for easier and efficient retrieval of the elements. List Data
Structure allows repetition that means a single piece of data can occur more than
once in a list.

in
➢ In the case of multiple entries of the same data, each entry of that repeating data
is considered as a distinct item or entry. It is very much similar to the array but

n.
the major difference between the array and the list data structure is that array
stores only homogenous data in them whereas the list (in some programming

aa
languages) can store heterogeneous data items in its object. List Data Structure is
also known as a sequence.

iy
➢ The list can be called Dynamic size arrays, which means their size increased as
or
we go on adding data in them and we need not to pre-define a static size for the
list
.p
For example,
w

numbers = [ 1, 2, 3, 4, 5]
➢ In this example, 'numbers' is the name of the List Data Structure object and it has
w

five items stored in it. In the object named numbers, we have stored all the
w

elements of numeric type. In the list, the indexing starts from zero, which means
if we want to access or retrieve the first element of this list then we need to use
index zero and similarly whenever we want to access any element from this list
named numbers. In other words, we can say that element 1 is on the index 0 and
element 2 is on index 1 and similarly for further all elements.
Mixed_data = [205, ‘Mathu’, 8.56]
➢ In this second example, mixed_data is the name of the list object that stores the
data of different types. In the mixed_data list, we have stored data of three types,
first one is the integer type which is id '205', after the integer data we have stored
a string type data having the value ‘Mathu’ stored at index 1 and at last the index
value 2, we have stored a float type data having the value '8.56'.
➢ To access the elements of the mixed_data list, we need to follow the same
approach as defined in the previous example.
➢ And we can add more data to these defined List objects and that will get appended
3.4 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
it will get appended after the float value object having value '8.56'. And we can
add repeating values to these list-objects.

3.2.1 Operations on the List Data Structure


Add or Insert Operation:
In the Add or Insert operation, a new item (of any data type) is added in the List

in
Data Structure or Sequence object.

n.
Replace or reassign Operation:
In the Replace or reassign operation, the already existing value in the List object

aa
is changed or modified. In other words, a new value is added at that particular index of
the already existing value.

iy
Delete or remove Operation:
or
In the Delete or remove operation, the already present element is deleted or
removed from the Dictionary or associative array object.
.p
Find or Lookup or Search Operation:
w

In the Find or Lookup operation, the element stored in that List Data Structure or
Sequence object is fetched.
w

3.3 ARRAY-BASED IMPLEMENTATION


w

➢ Arrays are defined as the collection of similar types of data items stored at
contiguous memory locations.
➢ It is one of the simplest data structures where each data element can be randomly
accessed by using its index number.
➢ They are the derived data types in C programming that can store the primitive type
of data such as int, char, double, float, etc.
➢ For example, if we want to store the marks of a student in 6 subjects, then we don't
need to define a different variable for the marks in different subjects. Instead, we
can define an array that can store the marks in each subject at the contiguous
memory locations.

3.3.1 Properties of array


➢ Each element in an array is of the same data type and carries the same size that is
4 bytes.
C Programming and Data Structures 3.5
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Elements in the array are stored at contiguous memory locations from which the
first element is stored at the smallest memory location.
➢ Elements of the array can be randomly accessed since we can calculate the address
of each element of the array with the given base address and the size of the data
element.

in
3.3.2 Representation of an array

n.
➢ Array can be represented in various ways in different programming languages. As
an illustration, let's see the declaration of array in C language

aa
iy
or
Fig. 3.2: Illustration of an Array
.p
As per the above illustration of array, there are some of the following important points -
w

➢ Index starts with 0.


➢ The array's length is 10, which means we can store 10 elements.
w

➢ Each element in the array can be accessed via its index.


w

3.3.3 Memory allocation of an array


➢ Data elements of an array are stored at contiguous locations in the main memory.
The name of the array represents the base address or the address of the first
element in the main memory. Each element of the array is represented by proper
indexing.
➢ We can define the indexing of an array in the below ways
• 0 (zero-based indexing): The first element of the array will be arr[0].
• 1 (one-based indexing): The first element of the array will be arr[1].
• n (n - based indexing): The first element of the array can reside at any random
index number
➢ Fig 3.3 shows the memory allocation of an array arr of size 5. The array follows
a 0-based indexing approach. The base address of the array is 100 bytes. It is the
address of arr[0]. Here, the size of the data type used is 4 bytes; therefore, each
3.6 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
Fig. 3.3: Memory allocation of an array

aa
3.3.4 Access an element from the array

iy
The information given below are required to access any random element from the array
➢ Base Address of the array. or
➢ Size of an element in bytes.
.p
➢ Type of indexing, array follows.
The formula to calculate the address to access an array element
w

Byte address of element A[i] = base address + size * ( i - first index)


w

Here, size represents the memory taken by the primitive data types. As an instance, int
w

takes 2 bytes, float takes 4 bytes of memory space in C programming.


Example 3.2
Suppose an array, A[-10 ..... +2 ] having Base address (BA) = 999 and size of an
element = 2 bytes, find the location of A[-1].
L(A[-1]) = 999 + 2 x [(-1) - (-10)]
= 999 + 18
= 1017

3.3.5 Basic operations of an Array


Basic operations supported in the array
➢ Traversal - This operation is used to print the elements of the array.
➢ Insertion - It is used to add an element at a particular index.
➢ Deletion - It is used to delete an element from a particular index.
C Programming and Data Structures 3.7
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Update - It updates an element at a particular index.

3.3.6 Complexity of Array operations


Time and space complexity of various array operations are described below.
Time Complexity

in
Operation Average Case Worst Case
Access O(1) O(1)

n.
Search O(n) O(n)

aa
Insertion O(n) O(n)
Deletion O(n) O(n)

iy
Space Complexity or
In array, space complexity for worst case is O(n).
.p
3.3.7 Limitations of Array
w

➢ The size of the array must be known in advance before using it in the program.
➢ Increasing the size of the array is a time taking process. It is almost impossible to
w

expand the size of the array at run time.


w

➢ All the elements in the array need to be contiguously stored in the memory.
Inserting an element in the array needs shifting of all its predecessors.

3.3.8 Advantages of Array


➢ Arrays are good for storing multiple values in a single variable.
➢ Traversing an array is a very simple process; we just need to increment the base
address of the array in order to visit each element one by one.
➢ Any element in the array can be directly accessed by using the index.
➢ Sorting and searching a value in an array is easier.
➢ Arrays are best to process multiple values quickly and easily.

3.3.9 Disadvantages of Array


➢ Array is homogenous. It means that the elements with similar data type can be
stored in it.
3.8 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ There will be wastage of memory if we store less number of elements than the
declared size.

3.4 LINKED LIST


➢ Linked list is a linear data structure that includes a series of connected nodes.
➢ Linked list can be defined as the nodes that are randomly stored in the memory.

in
➢ A node in the linked list contains two parts, i.e., first is the data part and second is

n.
the address part.
➢ The last node of the list contains a pointer to the null.

aa
➢ After array, linked list is the second most used data structure.

iy
➢ In a linked list, every link contains a connection to another link

or
3.4.1 Representation of a Linked list
➢ Linked list can be represented as the connection of nodes in which each node
.p
points to the next node of the list. The representation of the linked list is shown
below.
w
w
w

Fig. 3.4: Representation of Linked List

3.4.2 Why use linked list over array?


➢ Linked list is a data structure that overcomes the limitations of arrays (Refer 3.3.6)
➢ It allocates the memory dynamically. All the nodes of the linked list are non-
contiguously stored in the memory and linked together with the help of pointers.
➢ In linked list, size is no longer a problem since we do not need to define its size at
the time of declaration.
➢ List grows as per the program's demand and limited to the available memory
space.
C Programming and Data Structures 3.9
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.4.3 Declare a linked list
➢ It is simple to declare an array, as it is of single type, while the declaration of
linked list is a bit more typical than array. Linked list contains two parts, and both
are of different types, i.e.,
• Simple variable,

in
• Pointer variable.

n.
We can declare the linked list by using the user-defined data type structure.
The declaration of linked list is given as follows

aa
struct node
{

iy
int data;
struct node *next;
or
.p
}
In the above declaration, we have defined a structure named as node that contains
w

two variables, one is data that is of integer type, and another one is next that is a pointer
w

which contains the address of next node.


w

3.4.4 Types of Linked list


Linked list is classified into the following types
➢ Singly-Linked List
➢ Doubly Linked List
➢ Circular Singly Linked List
➢ Circular Doubly Linked List

3.4.4.1 Singly-Linked List


➢ Singly linked list can be defined as the collection of an ordered set of elements.
➢ A node in the singly linked list consists of two parts: data part and link part.
➢ Data part of the node stores actual information that is to be represented by the
node
➢ Link part of the node stores the address of its immediate successor.
3.10 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.4.4.2 Doubly Linked List
➢ Doubly linked list is a complex type of linked list
➢ Here, a node contains a pointer to the previous as well as the next node in the
sequence.
➢ Therefore, in a doubly-linked list, a node consists of three parts:

in
• Node data,

n.
• Pointer to the next node in sequence (next pointer), and

aa
• Pointer to the previous node (previous pointer).

3.4.4.3 Circular Singly Linked List

iy
➢ In a circular singly linked list, the last node of the list contains a pointer to the first
node of the list. or
➢ We can have circular singly linked list as well as circular doubly linked list.
.p
3.4.4.4 Circular Doubly Linked List
w

➢ Circular doubly linked list is a more complex type of data structure.


w

➢ Here a node contains pointers to its previous node as well as the next node.
w

➢ Circular doubly linked list doesn't contain NULL in any of the nodes.
➢ The last node of the list contains the address of the first node of the list.
➢ The first node of the list also contains the address of the last node in its previous
pointer.

3.4.5 Advantages of Linked list


➢ Dynamic data structure - The size of the linked list may vary according to the
requirements. Linked list does not have a fixed size.
➢ Insertion and deletion - Unlike arrays, insertion, and deletion in linked list is
easier. Elements in the linked list are stored at a random location.
➢ Memory efficient - The size of a linked list can grow or shrink according to the
requirements, so memory consumption in linked list is efficient.
➢ Implementation - We can implement both stacks and queues using linked list.
C Programming and Data Structures 3.11
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.4.6 Disadvantages of Linked list
➢ Memory usage - In linked list, node occupies more memory than array. Each
node of the linked list occupies two types of variables, i.e., one is a simple
variable, and another one is the pointer variable.
➢ Traversal - Traversal is not easy in the linked list. If we have to access an element

in
in the linked list, we cannot access it randomly.

n.
➢ Reverse traversing - Backtracking or reverse traversing is difficult in a linked
list. In a doubly-linked list, it is easier but requires more memory to store the back

aa
pointer.

3.4.7 Applications of Linked list

iy
➢ Using linked list, the polynomials can be represented as well as we can perform
or
the operations on the polynomial.
➢ A linked list can be used to represent the sparse matrix.
.p
➢ The various operations like student's details, employee's details, or product details
w

can be implemented using the linked list as the linked list uses the structure data
type that can hold different data types.
w

➢ Using linked list, we can implement stack, queue, tree, and other various data
w

structures.
➢ If we want to represent the graph as an adjacency list, then it can be implemented
as a linked list.
➢ A linked list can be used to implement dynamic memory allocation. The dynamic
memory allocation is the memory allocation done at the run-time.

3.4.8 Operations performed on Linked list


➢ Insertion - This operation is performed to add an element into the list.
➢ Deletion - It is performed to delete an operation from the list.
➢ Display - It is performed to display the elements of the list.
➢ Search - It is performed to search an element from the list using the given key.
3.12 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.4.9 Complexity of Linked list
1. Time Complexity
Operation Average Case Worst Case
Insertion O(1) O(1)

in
Deletion O(1) O(1)
Search O(n) O(n)

n.
2. Space Complexity

aa
Operation Space complexity

iy
Insertion O(n)
Deletion
Search
or O(n)
O(n)
.p
w

3.5 DOUBLY LINKED LIST


w

➢ Doubly linked list is a complex type of linked list


➢ Here, a node contains a pointer to the previous as well as the next node in the
w

sequence.
➢ Therefore, in a doubly-linked list, a node consists of three parts:
• Node data,
• Pointer to the next node in sequence (next pointer), and
• Pointer to the previous node (previous pointer).
A sample node in a doubly linked list is shown in Fig. 3.5
C Programming and Data Structures 3.13
https://www.poriyaan.in/ https://eee.poriyaan.in/
A doubly linked list containing three nodes having numbers from 1 to 3 in their
data part, is shown in Fig 3.6

in
n.
Fig. 3.6: Doubly Linked List

aa
In C, structure of a node in doubly linked list can be given as:
struct node

iy
{
struct node *prev;
int data;
or
.p
struct node *next;
w

}
➢ The prev part of the first node and the next part of the last node will always contain
w

null indicating end in each direction.


w

➢ In a singly linked list, we could traverse only in one direction, because each node
contains address of the next node and it doesn't have any record of its previous
nodes. However, doubly linked list overcome this limitation of singly linked list.
➢ Due to the fact that, each node of the list contains the address of its previous node,
we can find all the details about the previous node as well by using the previous
address stored inside the previous part of each node.

3.5.1 Memory Representation of a doubly linked list


➢ Memory Representation of a doubly linked list is shown in Fig. 3.7. Generally,
doubly linked list consumes more space for every node and therefore, causes more
expansive basic operations such as insertion and deletion. However, we can easily
manipulate the elements of the list since the list maintains pointers in both the
directions (forward and backward).
➢ In Fig 3.7, the first element of the list that is i.e. 13 stored at address 1. The head
pointer points to the starting address 1. Since this is the first element being added
3.14 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
to the list therefore the prev of the list contains null. The next node of the list
resides at address 4 therefore the first node contains 4 in its next pointer.
➢ We can traverse the list in this way until we find any node containing null or -1 in
its next part.

in
n.
aa
iy
or
.p
w
w
w

Fig. 3.7: Memory Representation of a doubly linked list

3.5.2 Operations on doubly linked list


Table 3.1 describes all the operations performed on Doubly Linked List
Table 3.1: Operations on Doubly Linked List
Sl. No. Operation Description
1. Insertion at beginning Adding the node into the linked list at beginning.
2. Insertion at end Adding the node into the linked list to the end.
3. Insertion after Adding the node into the linked list after the
specified node specified node.
4. Deletion at beginning Removing the node from beginning of the list
5. Deletion at the end Removing the node from end of the list.
C Programming and Data Structures 3.15
https://www.poriyaan.in/ https://eee.poriyaan.in/
6. Deletion of the node Removing the node which is present just after the
having given data node containing the given data.
7. Searching Comparing each node data with the item to be
searched and return the location of the item in the
list if the item found else return null

in
8. Traversing Visiting each node of the list at least once in order
to perform some specific operation like searching,

n.
sorting, display, etc.

aa
3.5.2.1 Insertion at beginning

iy
➢ There are two scenarios of inserting any element into doubly linked list. Either the
list is empty or it contains at least one element.
or
The following steps to be performed for insert a node in doubly linked list at beginning.
.p
➢ Allocate the space for the new node in the memory.
➢ Check whether the list is empty or not. The list is empty if the condition head ==
w

NULL holds.
w

➢ In that case, the node will be inserted as the only node of the list and therefore the
w

prev and the next pointer of the node will point to NULL and the head pointer will
point to this node.
➢ In the second scenario, the condition head == NULL become false and the node
will be inserted in beginning.
➢ The next pointer of the node will point to the existing head pointer of the node.
➢ The prev pointer of the existing head will point to the new node being inserted.
➢ Since, the node being inserted is the first node of the list and therefore it must
contain NULL in its prev pointer.
➢ Hence assign null to its previous part and make the head point to this node.
Algorithm 3.1
Step 1: IF ptr = NULL
Write OVERFLOW
Go to Step 9
3.16 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
Step 2: SET NEW_NODE = ptr
Step 3: SET ptr = ptr -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> PREV = NULL
Step 6: SET NEW_NODE -> NEXT = START

in
Step 7: SET head -> PREV = NEW_NODE

n.
Step 8: SET head = NEW_NODE

aa
Step 9: EXIT

iy
or
.p
w
w
w

Fig. 3.8: Insertion into Doubly Linked List at the beginning

3.5.2.2 Insertion at end


➢ To insert a node in doubly linked list at the end, make sure whether the list is
empty or it contains any element. Use the following steps in order to insert the
node in doubly linked list at the end.
➢ Allocate the memory for the new node. Make the pointer ptr point to the new node
being inserted.
➢ Check whether the list is empty or not. The list is empty if the condition head ==
NULL holds.
➢ In that case, the node will be inserted as the only node of the list and therefore the
prev and the next pointer of the node will point to NULL and the head pointer will
point to this node.
➢ In the second scenario, the condition head == NULL become false. The new node
C Programming and Data Structures 3.17
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ For this reason, we have to traverse the whole list in order to reach the last node
of the list. Initialize the pointer temp to head and traverse the list by using this
pointer.
➢ Make the next pointer of temp point to the new node being inserted i.e. ptr.
➢ Make the previous pointer of the node ptr point to the existing last node of the list

in
i.e. temp.
➢ Make the next pointer of the node ptr point to the null as it will be the new last

n.
node of the list.

aa
Algorithm 3.2
Step 1: IF PTR = NULL

iy
Write OVERFLOW
Go to Step 11
[END OF IF]
or
.p
Step 2: SET NEW_NODE = PTR
w

Step 3: SET PTR = PTR -> NEXT


Step 4: SET NEW_NODE -> DATA = VAL
w

Step 5: SET NEW_NODE -> NEXT = NULL


w

Step 6: SET TEMP = START


Step 7: Repeat Step 8 while TEMP -> NEXT != NULL
Step 8: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 9: SET TEMP -> NEXT = NEW_NODE
Step 10C: SET NEW_NODE -> PREV = TEMP
Step 11: EXIT
3.18 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.5.2.3 Insertion after specified node
To insert a node after the specified node in the list, we need to skip the required
number of nodes in order to reach the mentioned node and then make the pointer
adjustments as required.
The following steps are used for this purpose.

in
➢ Allocate the memory for the new node.

n.
➢ Traverse the list by using the pointer temp to skip the required number of nodes
in order to reach the specified node.

aa
➢ The temp would point to the specified node at the end of the for loop. The new
node needs to be inserted after this node. Make the next pointer of ptr point to the

iy
next node of temp.
➢ Make the prev of the new node ptr point to temp.
or
➢ Make the next pointer of temp point to the new node ptr.
.p
➢ Make the previous pointer of the next node of temp point to the new node.
w

Algorithm 3.3
Step 1: IF PTR = NULL
w

Write OVERFLOW
w

Go to Step 15
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET TEMP = START
Step 6: SET I = 0
Step 7: REPEAT 8 to 10 until I
Step 8: SET TEMP = TEMP -> NEXT
STEP 9: IF TEMP = NULL
STEP 10: WRITE "LESS THAN DESIRED NO. OF ELEMENTS"
GOTO STEP 15
C Programming and Data Structures 3.19
https://www.poriyaan.in/ https://eee.poriyaan.in/
[END OF IF]
[END OF LOOP]
Step 11: SET NEW_NODE -> NEXT = TEMP -> NEXT
Step 12: SET NEW_NODE -> PREV = TEMP
Step 13 : SET TEMP -> NEXT = NEW_NODE

in
Step 14: SET TEMP -> NEXT -> PREV = NEW_NODE

n.
Step 15: EXIT

aa
iy
or
.p
Fig. 3.10: Insertion of Doubly Linked List after specified node
w

3.5.2.4 Deletion at beginning


w

➢ Deletion in doubly linked list at the beginning is the simplest operation.


w

➢ Just need to copy the head pointer to pointer ptr and shift the head pointer to its
next.
➢ Make the prev of this new head node point to NULL.
➢ Now free the pointer ptr by using the free function.
Algorithm 3.4
STEP 1: IF HEAD = NULL
WRITE UNDERFLOW
GOTO STEP 6
STEP 2: SET PTR = HEAD
STEP 3: SET HEAD = HEAD → NEXT
STEP 4: SET HEAD → PREV = NULL
STEP 5: FREE PTR
3.20 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
Fig. 3.11: Deletion in Doubly Linked List from beginning

iy
3.5.2.5 Deletion at the end
or
Deletion of the last node in a doubly linked list needs traversing the list in order
to reach the last node of the list and then make pointer adjustments at that position. To
.p
delete the last node of the list, following steps are performed.
➢ If the list is already empty then the condition head == NULL will become true
w

and therefore the operation cannot be carried on.


w

➢ If there is only one node in the list then the condition head → next == NULL
become true. In this case, we just need to assign the head of the list to NULL and
w

free head in order to completely delete the list.


➢ Otherwise, just traverse the list to reach the last node of the list.
➢ The ptr would point to the last node of the ist at the end of the for loop. Just make
the next pointer of the previous node of ptr to NULL.
➢ Free the pointer as this the node which is to be deleted.
Algorithm 3.5:
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 7
[END OF IF]
Step 2: SET TEMP = HEAD
Step 3: REPEAT STEP 4 WHILE TEMP->NEXT != NULL
C Programming and Data Structures 3.21
https://www.poriyaan.in/ https://eee.poriyaan.in/
[END OF LOOP]
Step 5: SET TEMP ->PREV-> NEXT = NULL
Step 6: FREE TEMP
Step 7: EXIT

in
n.
aa
iy
or
.p
Fig. 3.12: Deletion in Doubly Linked List at the end

3.5.2.6 Deletion of the node having given data


w

➢ Copy the head pointer into a temporary pointer temp.


w

➢ Traverse the list until we find the desired data value.


w

➢ Check if this is the last node of the list. If it is so then we can't perform deletion.
➢ Check if the node which is to be deleted, is the last node of the list, if it so then
we have to make the next pointer of this node point to null so that it can be the
new last node of the list.
➢ Otherwise, make the pointer ptr point to the node which is to be deleted.
➢ Make the next of temp point to the next of ptr.
➢ Make the previous of next node of ptr point to temp. free the ptr.
Algorithm 3.6
Step 1: IF HEAD = NULL
Write UNDERFLOW
Go to Step 9
[END OF IF]
3.22 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
Step 3: Repeat Step 4 while TEMP -> DATA != ITEM
Step 4: SET TEMP = TEMP -> NEXT
[END OF LOOP]
Step 5: SET PTR = TEMP -> NEXT
Step 6: SET TEMP -> NEXT = PTR -> NEXT

in
Step 7: SET PTR -> NEXT -> PREV = TEMP

n.
Step 8: FREE PTR

aa
Step 9: EXIT

iy
or
.p
w

Fig. 3.13: Deletion of a specified node in Doubly Linked List at the end
w

3.5.2.7 Searching for a specific node


w

To search for a specific element in the list, traverse the list in order. The
following operations to be performed in order to search a specific operation.
➢ Copy head pointer into a temporary pointer variable ptr
➢ Traverse the list until the pointer ptr becomes null. Keep shifting pointer to its
next and increasing i by +1.
➢ Compare each element of the list with the item which is to be searched.
➢ If the item matched with any node value then the location of that value I will be
returned from the function else NULL is returned.
Algorithm 3.7
Step 1: IF HEAD == NULL
WRITE "UNDERFLOW"
GOTO STEP 8
[END OF IF]
C Programming and Data Structures 3.23
https://www.poriyaan.in/ https://eee.poriyaan.in/
Step 2: Set PTR = HEAD
Step 3: Set i = 0
Step 4: Repeat step 5 to 7 while PTR != NULL
Step 5: IF PTR → data = item
return i

in
[END OF IF]

n.
Step 6: i = i + 1
Step 7: PTR = PTR → next

aa
Step 8: Exit

iy
3.5.2.8 Traversing in doubly linked list
or
Traversing is the most common operation in case of each data structure. For this purpose,
➢ Copy the head pointer in any of the temporary pointer ptr.
.p
➢ Traverse through the list by using while loop.
w

➢ Keep shifting value of pointer variable ptr until we find the last node.
➢ The last node contains null in its next part.
w

Algorithm 3.8
w

Step 1: IF HEAD == NULL


WRITE "UNDERFLOW"
GOTO STEP 6
[END OF IF]
Step 2: Set PTR = HEAD
Step 3: Repeat step 4 and 5 while PTR != NULL
Step 4: Write PTR → data
Step 5: PTR = PTR → next
Step 6: Exit

3.5.3 Advantages of Doubly Linked Lists


➢ Reversing the doubly linked list is very easy.
➢ It can allocate or reallocate memory easily during its execution.
3.24 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ As with a singly linked list, it is the easiest data structure to implement.
➢ The traversal of this doubly linked list is bidirectional which is not possible in a
singly linked list.
➢ Deletion of nodes is easy as compared to a Singly Linked List.

3.5.4 Disadvantages of Doubly Linked Lists

in
➢ It uses extra memory when compared to the array and singly linked list.

n.
➢ Since elements in memory are stored randomly, therefore the elements are
accessed sequentially no direct access is allowed.

aa
3.6 CIRCULAR LINKED LIST

iy
➢ In a circular singly linked list, the last node of the list contains a pointer to the first
node of the list. or
➢ We can have circular singly linked list as well as circular doubly linked list.
.p
➢ We traverse a circular singly linked list until we reach the same node where we
started.
w

➢ The circular singly liked list has no beginning and no ending.


w

➢ There is no null value present in the next part of any of the nodes.
w

➢ Circular linked list are mostly used in task maintenance in operating systems. Fig.
3.14 shows a circular singly linked list.

Fig. 3.14: Circular Singly Linked List.


3.6.1 Memory Representation of circular linked list
➢ Fig 3.15 shows the memory representation of a circular linked list containing
marks of a student in 4 subjects. However, the image shows a glimpse of how the
circular list is being stored in the memory. The start or head of the list is pointing
C Programming and Data Structures 3.25
https://www.poriyaan.in/ https://eee.poriyaan.in/
the next part. Which means that it is linked with the node that is being stored at
4th index of the list.
➢ However, due to the fact that we are considering circular linked list in the memory
therefore the last node of the list contains the address of the first node of the list.

in
n.
aa
iy
or
.p
w
w

Fig. 3.15: Memory Representation of Circular Linked List


w

3.6.2 Operations on Circular Singly linked list


Table 3.2 describes all the operations performed on a Doubly Linked List
Table 3.2: Operations on Doubly Linked List
Sl. No. Operation Description
Insertion at beginning Adding a node into circular singly linked list at
1.
the beginning.
Insertion at end Adding a node into circular singly linked list at
2.
the end.
Deletion at beginning Removing the node from circular singly linked
3.
list at the beginning.
Searching Compare each element of the node with the
4. given item and return the location at which the
3.26 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
Traversing Visiting each element of the list at least once in
5.
order to perform some specific operation.

3.6.2.1 Insertion at the beginning


➢ There are two scenario in which a node can be inserted in circular singly linked
list at beginning. Either the node will be inserted in an empty list or the node is to

in
be inserted in an already filled list.

n.
➢ Firstly, allocate the memory space for the new node by using the malloc method
of C language.

aa
➢ In the first scenario, the condition head == NULL will be true. Since, the list in
which, we are inserting the node is a circular singly linked list, therefore the only

iy
node of the list (which is just inserted into the list) will point to itself only.
or
➢ Also need to make the head pointer point to this node.
➢ In the second scenario, the condition head == NULL will become false which
.p
means that the list contains at least one node.
➢ In this case, traverse the list in order to reach the last node of the list.
w

➢ At the end of the loop, the pointer temp would point to the last node of the list.
w

➢ Make the next pointer of the last node point to the head node of the list and the
w

new node which is being inserted into the list will be the new head node of the list
➢ Therefore the next pointer of temp will point to the new node ptr.
Algorithm 3.9
Step 1: IF PTR = NULL
Write OVERFLOW
Go to Step 11
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET TEMP = HEAD
Step 6: Repeat Step 8 while TEMP -> NEXT != HEAD
C Programming and Data Structures 3.27
https://www.poriyaan.in/ https://eee.poriyaan.in/
[END OF LOOP]
Step 8: SET NEW_NODE -> NEXT = HEAD
Step 9: SET TEMP → NEXT = NEW_NODE
Step 10: SET HEAD = NEW_NODE
Step 11: EXIT

in
n.
aa
iy
or
.p
w
w

Fig. 3.16: Insertion into a Circular Linked List at the beginning


w

3.6.2.2 Insertion at the end


➢ Allocate the memory space for the new node by using the malloc method of C
language.
➢ In the first scenario, the condition head == NULL will be true.
➢ Also make the head pointer point to this node.
➢ In the second scenario, the condition head == NULL will become false which
means that the list contains at least one node.
➢ In this case, traverse the list in order to reach the last node of the list.
➢ At the end of the loop, the pointer temp would point to the last node of the list.
➢ The existing last node i.e. temp must point to the new node ptr
Algorithm 3.10
Step 1: IF PTR = NULL
Write OVERFLOW
3.28 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
Go to Step 1
[END OF IF]
Step 2: SET NEW_NODE = PTR
Step 3: SET PTR = PTR -> NEXT

in
Step 4: SET NEW_NODE -> DATA = VAL
Step 5: SET NEW_NODE -> NEXT = HEAD

n.
Step 6: SET TEMP = HEAD

aa
Step 7: Repeat Step 8 while TEMP -> NEXT != HEAD
Step 8: SET TEMP = TEMP -> NEXT

iy
[END OF LOOP]
or
Step 9: SET TEMP -> NEXT = NEW_NODE
.p
Step 10: EXIT
w
w
w

Fig. 3.17: Insertion into a Circular Linked List at the end

3.6.2.3 Deletion at the beginning


In order to delete a node in circular singly linked list, we need to make a few
pointer adjustments. There are three scenarios of deleting a node from circular singly
linked list at beginning.
➢ Scenario 1: (The list is Empty) - If the list is empty then the condition head ==
NULL will become true, in this case, just to print underflow on the screen and
C Programming and Data Structures 3.29
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Scenario 2: (The list contains single node) - If the list contains single node then,
the condition head → next == head will become true. In this case, delete the entire
list and make the head pointer free.
➢ Scenario 3: (The list contains more than one node) - If the list contains more than
one node then, in that case, traverse the list by using the pointer ptr to reach the
last node of the list.

in
➢ At the end of the loop, the pointer ptr point to the last node of the list.

n.
➢ The last node of the list will point to the next of the head node.
➢ Now, free the head pointer by using the free() method.

aa
➢ Make the node pointed by the next of the last node, the new head of the list.

iy
Algorithm 3.11
Step 1: IF HEAD = NULL or
Write UNDERFLOW
.p
Go to Step 8
[END OF IF]
w

Step 2: SET PTR = HEAD


w

Step 3: Repeat Step 4 while PTR → NEXT != HEAD


Step 4: SET PTR = PTR → next
w

[END OF LOOP]
Step 5: SET PTR → NEXT = HEAD → NEXT
Step 6: FREE HEAD
Step 7: SET HEAD = PTR → NEXT
Step 8: EXIT
3.30 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.6.2.4 Deletion at the end
➢ Scenario 1 (the list is empty) - If the list is empty then the condition head ==
NULL will become true, in this case, just to print underflow on the screen and
make exit.
➢ Scenario 2(the list contains single element) - If the list contains single node then,

in
the condition head → next == head will become true. In this case, delete the entire
list and make the head pointer free.

n.
➢ Scenario 3(the list contains more than one element) - If the list contains more than

aa
one element, then in order to delete the last element, reach the last node. Also keep
track of the second last node of the list. For this purpose, the two pointers ptr and

iy
preptr are defined.
➢ Make just one more pointer adjustment. We need to make the next pointer of
or
preptr point to the next of ptr (i.e. head) and then make pointer ptr free.
.p
Algorithm 3.12
Step 1: IF HEAD = NULL
w

Write UNDERFLOW
w

Go to Step 8
w

[END OF IF]
Step 2: SET PTR = HEAD
Step 3: Repeat Steps 4 and 5 while PTR -> NEXT != HEAD
Step 4: SET PREPTR = PTR
Step 5: SET PTR = PTR -> NEXT
[END OF LOOP]
Step 6: SET PREPTR -> NEXT = HEAD
Step 7: FREE PTR
Step 8: EXIT
C Programming and Data Structures 3.31
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
Fig. 3.19: Deletion in a Circular Linked List at the end

iy
3.6.2.5 Searching
or
➢ Searching in circular singly linked list needs traversing across the list.
➢ The item which is to be searched in the list is matched with each node data of the
.p
list once.
w

➢ If the match found then the location of that item is returned otherwise -1 is
returned.
w

Algorithm 3.13
w

STEP 1: SET PTR = HEAD


STEP 2: Set I = 0
STEP 3: IF PTR = NULL
WRITE "EMPTY LIST"
GOTO STEP 8
END OF IF
STEP 4: IF HEAD → DATA = ITEM
WRITE i+1 RETURN [END OF IF]
STEP 5: REPEAT STEP 5 TO 7 UNTIL PTR->next != head
STEP 6: if ptr → data = item
write i+1
RETURN
3.32 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
End of IF
STEP 7: I = I + 1
STEP 8: PTR = PTR → NEXT
[END OF LOOP]
STEP 9: EXIT

in
3.6.2.5 Searching

n.
➢ Traversing in circular singly linked list can be done through a loop.

aa
➢ Initialize the temporary pointer variable temp to head pointer and run the while
loop until the next pointer of temp becomes head.

iy
Algorithm 3.14
STEP 1: SET PTR = HEAD
STEP 2: IF PTR = NULL
or
.p
WRITE "EMPTY LIST"
w

GOTO STEP 8
END OF IF
w

STEP 4: REPEAT STEP 5 AND 6 UNTIL PTR → NEXT != HEAD


w

STEP 5: PRINT PTR → DATA


STEP 6: PTR = PTR → NEXT
[END OF LOOP]
STEP 7: PRINT PTR→ DATA
STEP 8: EXIT

3.6.3 Advantages of Circular Linked Lists


It is possible to traverse from the last node back to the first i.e. the head node.
➢ The starting node does not matter as we can traverse each and every node despite
whatever node we keep as the starting node.
➢ The previous node can be easily identified.
➢ There is no need for a NULL function to code. The circular list never identifies a
NULL identifier unless it is fully assigned.
C Programming and Data Structures 3.33
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.6.4 Disadvantages of Circular Linked Lists
➢ If the circular linked list is not handled properly then it can lead to an infinite loop
as it is circular in nature.
➢ In comparison with singly-linked lists, doubly linked lists are more complex in
nature

in
➢ Direct accessing of elements is not possible.

n.
➢ It is generally a complex task to reverse a circular linked list

aa
3.7 STACK ADT
➢ A Stack is a linear data structure that follows the LIFO (Last-In-First-Out)

iy
principle.
➢ A Stack is an abstract data type with a pre-defined capacity, which means that it
or
can store the elements of a limited size.
➢ Stack has one end, whereas the Queue has two ends (front and rear).
.p
➢ It contains only one pointer top pointer pointing to the topmost element of the
w

stack.
w

➢ Whenever an element is added in the stack, it is added on the top of the stack, and
the element can be deleted only from the stack.
w

➢ In other words, a stack can be defined as a container in which insertion and


deletion can be done from the one end known as the top of the stack.

3.7.1 Working of Stack


➢ Stack works on the LIFO pattern. As we can observe in figure 3.20, there are five
memory blocks in the stack; therefore, the size of the stack is 5.
➢ Suppose we want to store the elements in a stack and let's assume that stack is
empty. We have taken the stack of size 5 as shown below in which we are pushing
the elements one by one until the stack becomes full.
➢ Since our stack is full as the size of the stack is 5. In the above cases, we can
observe that it goes from the top to the bottom when we were entering the new
element in the stack. The stack gets filled up from the bottom to the top.
➢ When we perform the delete operation on the stack, there is only one way for entry
and exit as the other end is closed. It follows the LIFO pattern, which means that
3.34 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
the value entered first will be removed last. In the above case, the value 5 is
entered first, so it will be removed only after the deletion of all the other elements.

in
n.
aa
iy
Fig. 3.20: Working principle of a Stack

3.7.2 Operations on Stack


or
.p
The following are some common operations implemented on the stack:
➢ push(): When we insert an element in a stack then the operation is known as a
w

push. If the stack is full then the overflow condition occurs.


w

➢ pop(): When we delete an element from the stack, the operation is known as a pop.
w

If the stack is empty means that no element exists in the stack, this state is known
as an underflow state.
➢ isEmpty(): It determines whether the stack is empty or not.
➢ isFull(): It determines whether the stack is full or not.'
➢ peek(): It returns the element at the given position.
➢ count(): It returns the total number of elements available in a stack.
➢ change(): It changes the element at the given position.
➢ display(): It prints all the elements available in the stack

3.7.2.1 PUSH operation


➢ Before inserting an element in a stack, we check whether the stack is full.
➢ If we try to insert the element in a stack, and the stack is full, then the overflow
condition occurs.
➢ When we initialize a stack, we set the value of top as -1 to check that the stack is
C Programming and Data Structures 3.35
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ When the new element is pushed in a stack, first, the value of the top gets
incremented, i.e., top=top+1, and the element will be placed at the new position
of the top.
➢ The elements will be inserted until we reach the max size of the stack.

in
n.
aa
iy
or
.p
w
w

Fig. 3.21 PUSH Operation in Stack


w

3.7.2.2 POP operation


➢ Before deleting the element from the stack, we check whether the stack is empty.
➢ If we try to delete the element from the empty stack, then the underflow condition
occurs.
➢ If the stack is not empty, we first access the element which is pointed by the top
➢ Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
3.36 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
Fig. 3.22 POP Operation in Stack

aa
3.7.3 Applications of Stack
➢ Balancing of symbols: Stack is used for balancing a symbol.

iy
➢ String reversal: Stack is also used for reversing a string
or
➢ UNDO/REDO: It can also be used for performing UNDO/REDO operations.
➢ Recursion: The recursion means that the function is calling itself again.
.p
➢ DFS(Depth First Search): This search is implemented on a Graph, and Graph
w

uses the stack data structure.


➢ Backtracking: In order to come at the beginning of the path to create a new path,
w

use the stack data structure


w

➢ Expression conversion: Stack can also be used for expression conversion.


• Infix to prefix
• Infix to postfix
• Prefix to infix
• Prefix to postfix
• Postfix to infix
➢ Memory management: The stack manages the memory. The memory is assigned
in the contiguous memory blocks.

3.8 IMPLEMENTATION OF STACK


➢ Stack can be easily implemented using an Array or a Linked List. Arrays are
quick, but are limited in size and Linked List requires overhead to allocate, link,
unlink, and deallocate, but is not limited in size.
C Programming and Data Structures 3.37
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.8.1 Array implementation of Stack
➢ In array implementation, the stack is formed by using the array. All the operations
regarding the stack are performed using arrays. Let’s see how each operation can
be implemented on the stack using array data structure.

3.8.1.1 Adding an element onto the stack (push operation)

in
➢ Adding an element into the top of the stack is referred to as push operation. Push

n.
operation involves following two steps.
1. Increment the variable Top so that it can now refere to the next memory

aa
location.
2. Add element at the position of incremented top. This is referred to as adding

iy
new element at the top of the stack.
or
➢ Stack is overflown when we try to insert an element into a completely filled stack
therefore, our main function must always avoid stack overflow condition.
.p
Algorithm 3.15
w

begin
if top = n then stack full
w

top = top + 1
w

stack (top) : = item;


end
Time Complexity: O (1)

3.8.1.1.1 Implementation of push algorithm in C language


void push (int val,int n) //n is size of the stack
{
if (top == n )
printf("\n Overflow");
else
{
top = top +1;
stack[top] = val;
3.38 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
}
}

3.8.1.2 Deletion of an element from a stack (Pop operation)


➢ Deletion of an element from the top of the stack is called pop operation.
➢ The value of the variable top will be incremented by 1 whenever an item is deleted

in
from the stack.

n.
➢ The top most element of the stack is stored in another variable and then the top is
decremented by 1.

aa
➢ The operation returns the deleted value that was stored in another variable as the
result.

iy
➢ The underflow condition occurs when we try to delete an element from an already
empty stack. or
Algorithm 3.16
.p
begin
w

if top = 0 then stack empty;


w

item := stack(top);
w

top = top - 1;
end;
Time Complexity: O (1)

3.8.1.2.1 Implementation of POP algorithm using C language


int pop ()
{
if(top == -1)
{
printf("Underflow");
return 0;
}
else
C Programming and Data Structures 3.39
https://www.poriyaan.in/ https://eee.poriyaan.in/
return stack[top - - ];
}
}

3.8.1.3 Visiting each element of the stack (Peek operation)


➢ Peek operation involves returning the element which is present at the top of the

in
stack without deleting it.

n.
➢ Underflow condition can occur if we try to return the top element in an already
empty stack.

aa
Algorithm 3.17

iy
PEEK (STACK, TOP)
Begin
or
if top = -1 then stack empty
.p
item = stack[top]
return item
w

End
w

Time complexity: O(n)


w

Implementation of Peek algorithm in C language


int peek()
{
if (top == -1)
{
printf("Underflow");
return 0;
}
else
{
return stack [top];
}
3.40 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.8.2 Linked list implementation of stack
➢ Linked list allocates the memory dynamically. However, time complexity in both
the scenario is same for all the operations i.e. push, pop and peek.
➢ In linked list implementation of stack, the nodes are maintained non-contiguously
in the memory.

in
➢ Each node contains a pointer to its immediate successor node in the stack.

n.
➢ Stack is said to be overflown if the space left in the memory heap is not enough
to create a node.

aa
➢ The top most node in the stack always contains null in its address field.

iy
or
.p
w
w
w

Fig. 3.23: Linked List implementation of Stack


3.8.2.1 Adding a node to the stack (Push operation)
➢ Adding a node to the stack is referred to as push operation. Pushing an element to
a stack in linked list implementation is different from that of an array
implementation. In order to push an element onto the stack, the following steps
are involved.
• Create a node first and allocate memory to it.
• If the list is empty then the item is to be pushed as the start node of the list.
This includes assigning value to the data part of the node and assign null to
the address part of the node.
C Programming and Data Structures 3.41
https://www.poriyaan.in/ https://eee.poriyaan.in/
• If there are some nodes in the list already, then add the new element in the
beginning of the list (to not violate the property of the stack). For this purpose,
assign the address of the starting element to the address field of the new node
and make the new node, the starting node of the list.
Time Complexity: O (1)

in
n.
aa
iy
or
.p
w
w

Fig 3.24 Adding new Node to Stack


w

3.8.2.1.1 Implementation of PUSH in C Language Program


void push ()
{
int val;
struct node *ptr =(struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
3.42 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;

in
head=ptr;
}

n.
else

aa
{
ptr->val = val;

iy
ptr->next = head;
head=ptr;
or
.p
}
w

printf("Item pushed");
w

}
}
w

3.8.2.2 Deleting a node from the stack (POP operation)


➢ Deleting a node from the top of stack is referred to as pop operation. Deleting a
node from the linked list implementation of stack is different from that in the array
implementation.
➢ In order to pop an element from the stack, do the following steps:
• Check for the underflow condition: The underflow condition occurs when
we try to pop from an already empty stack. The stack will be empty if the head
pointer of the list points to null.
• Adjust the head pointer accordingly: In stack, the elements are popped only
from one end, therefore, the value stored in the head pointer must be deleted
and the node must be freed. The next node of the head node now becomes the
head node.
Time Complexity: O (n)
C Programming and Data Structures 3.43
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.8.2.2.1 Implementation of POP in C Language Program
void pop()
{
int item;
struct node *ptr;

in
if (head == NULL)

n.
{
printf("Underflow");

aa
}

iy
else
{
item = head->val;
or
.p
ptr = head;
head = head->next;
w

free(ptr);
w

printf("Item popped");
w

}
}

3.8.2.3 Display the nodes (Traversing)


Displaying all the nodes of a stack needs traversing all the nodes of the linked list
organized in the form of stack. For this do the following steps.
➢ Copy the head pointer into a temporary pointer.
➢ Move the temporary pointer through all the nodes of the list and print the value
field attached to every node.
Time Complexity: O (n)

3.8.2.3.1 Implementation of Display in C Language Program


void display()
{
3.44 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
struct node *ptr;
ptr=head;
if(ptr == NULL)
{

in
printf("Stack is empty\n");
}

n.
else

aa
{
printf("Printing Stack elements \n");

iy
while(ptr!=NULL)
{
or
.p
printf("%d\n",ptr->val);
w

ptr = ptr->next;
w

}
}
w

3.9 APPLICATIONS OF STACK


➢ A Stack is a widely used linear data structure in modern computers in which
insertions and deletions of an element can occur only at one end, i.e., top of the
Stack. It is used in all those applications in which data must be stored and retrieved
in the last.
➢ Following are the various Applications of Stack in Data Structure:
• Evaluation of Arithmetic Expressions
• Balancing Symbols
• Processing Function Calls
• Backtracking
C Programming and Data Structures 3.45
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.9.1 Evaluation of Arithmetic Expressions
➢ A stack is a very effective data structure for evaluating arithmetic expressions in
programming languages. An arithmetic expression consists of operands and
operators.
➢ In addition to operands and operators, the arithmetic expression may also include

in
parenthesis like "left parenthesis" and "right parenthesis".

n.
Example 3.3: A + (B - C)
To evaluate the expressions, one needs to be aware of the standard precedence

aa
rules for arithmetic expression. The precedence rules for the five basic arithmetic
operators are:

iy
Operators Associativity Precedence
^ exponentiation
or
Right to left Highest followed by
*Multiplication and /division
.p
*Multiplication, Left to right Highest followed by + addition
w

/division and - subtraction


+ addition, - Left to right lowest
w

subtraction
w

Evaluation of Arithmetic Expression requires two steps:


➢ First, convert the given expression into special notation.
➢ Evaluate the expression in this new notation.
Notations for Arithmetic Expression
There are three notations to represent an arithmetic expression:
➢ Infix Notation
➢ Prefix Notation
➢ Postfix Notation

3.9.1.1 Infix Notation


The infix notation is a convenient way of writing an expression in which each
operator is placed between the operands. Infix expressions can be parenthesized or un
3.46 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example 3.4: A + B, (C - D) etc.
All these expressions are in infix notation because the operator comes between
the operands.

3.9.1.2 Prefix Notation


The prefix notation places the operator before the operands. This notation was

in
introduced by the Polish mathematician and hence often referred to as polish notation.

n.
Example 3.5: + A B, -CD etc.
All these expressions are in prefix notation because the operator comes before the

aa
operands.

iy
3.9.1.3 Postfix Notation
The postfix notation places the operator after the operands. This notation is just
or
the reverse of Polish notation and also known as Reverse Polish notation.
.p
Example 3.6: AB +, CD+, etc.
All these expressions are in postfix notation because the operator comes after the
w

operands.
w

Table 3.3 illustrates the conversion of Arithmetic Expression into various Notations
w

Table 3.3: Conversion of Arithmetic Expression into various Notations


Infix Notation Prefix Notation Postfix Notation
A*B *AB AB*
(A+B)/C /+ ABC AB+C/
(A*B) + (D-C) +*AB - DC AB*DC-+

Let's take the example of Converting an infix expression into a postfix expression
C Programming and Data Structures 3.47
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
iy
or
.p
w
w
w

In the above example, the only change from the postfix expression is that the
operator is placed before the operands rather than between the operands.
Evaluating Postfix expression
➢ Stack is the ideal data structure to evaluate the postfix expression because the top
element is always the most recent operand. The next element on the Stack is the
second most recent operand to be operated on.
➢ Before evaluating the postfix expression, the following conditions must be
3.48 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ When an operator encounters the scanning process, the Stack must contain a pair
of operands or intermediate results previously calculated.
➢ When an expression has been completely evaluated, the Stack must contain
exactly one value.
Example 3.7

in
Now let us consider the following infix expression 2 * (4+3) - 5.

n.
Its equivalent postfix expression is 2 4 3 + * 5.
The following step illustrates how this postfix expression is evaluated.

aa
iy
or
.p
w
w
w

3.9.2 Balancing Symbols


➢ Stacks can be used to check if the given expression has balanced symbols or not.
➢ The algorithm is very much useful in compilers.
➢ Each time parser reads one character at a time.
➢ If the character is an opening delimiter like ‘(‘ , ‘{‘ or ‘[‘ then it is PUSHED in to
the stack.
➢ When a closing delimiter is encountered like ‘)’ , ‘}’ or ‘]’ is encountered, the
C Programming and Data Structures 3.49
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ The opening and closing delimiter are then compared.
➢ If they match, the parsing of the string continues.
➢ If they do not match, the parser indicates that there is an error on the line.
A linear time O(n) algorithm based on stack can be given as:-
Create a stack.

in
while ( end of input is not reached ) {

n.
If the character read is not a symbol to be balanced, ignore it.

aa
If the character is an opening delimiter like ( , { or [ , PUSH it into the stack.
If it is a closing symbol like ) , } , ] , then if the stack is empty report an error,
otherwise POP the stack.

iy
If the symbol POP-ed is not the corresponding delimiter, report an error.
or
At the end of the input, if the stack is not empty report an error.
.p
Example 3.8
EXAMPLE Valid? Description
w

(A+B) + (C-D) Yes The expression is having balanced


w

symbol
w

((A+B) + (C-D) No One closing brace is missing.


((A+B) + [C-D]) Yes Opening and closing braces correspond
((A+B) + [C-D]] No The last brace does not correspond with
the first opening brace.
(A+B) + (C-D) Yes The expression is having balanced
symbol

For tracing the algorithm let us assume that the input is () (() [()])
Input Symbol Operation Stack Output
( Push ( (
) Pop (
Test if ( and A[i] match? YES
( Push ( (
3.50 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
( Push ( ((
) Pop ( (
Test if ( and A[i] match? YES
[ Push [ ([
( Push ( ([(

in
) Pop ) )

n.
Test if ( and A[i] match? YES

aa
] Pop [ (
Test if [ and A[i] match? YES

iy
) Pop (
or
Test if ( and A[i] match? YES
Test if Stack is Empty? YES TRUE
.p
w

3.9.3 Processing Function Calls


➢ Stack plays an important role in programs that call several functions in succession.
w

Suppose we have a program containing three functions: A, B, and C. function A


w

invokes function B, which invokes the function C.

Fig. 3.24: Invoking Function Calls


➢ When we invoke function A, which contains a call to function B, then its
processing will not be completed until function B has completed its execution and
returned. Similarly for function B and C. So we observe that function A will only
be completed after function B is completed and function B will only be completed
after function C is completed.
C Programming and Data Structures 3.51
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Therefore, function A is first to be started and last to be completed. To conclude,
the above function activity matches the last in first out behavior and can easily be
handled using Stack.
➢ Consider addrA, addrB, addrC be the addresses of the statements to which control
is returned after completing the function A, B, and C, respectively.

in
n.
aa
iy
or
Fig. 3.25: Different states of stack
.p
➢ Figure 3.26 shows that return addresses appear in the Stack in the reverse order in
which the functions were called. After each function is completed, the pop
w

operation is performed, and execution continues at the address removed from the
Stack.
w

➢ Thus the program that calls several functions in succession can be handled
w

optimally by the stack data structure. Control returns to each function at a correct
place, which is the reverse order of the calling sequence.

3.9.4 Backtracking
➢ Backtracking is used in algorithms in which there are steps along some path (state)
from some starting point to some goal. It uses recursive calling to find the solution
by building a solution step by step increasing values with time. It removes the
solutions that doesn't give rise to the solution of the problem based on the
constraints given to solve the problem.
➢ Let’s see how Stack is used in Backtracking in the N-Queens Problem
➢ For the N-Queens problem, one way we can do this is given by the following:
• For each row, place a queen in the first valid position (column), and then move
to the next row
• If there is no valid position, then one backtracks to the previous row and try
3.52 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
• If one can successfully place a queen in the last row, then a solution is found.
Now backtrack to find the next solution
➢ We can use a stack to indicate the positions of the queens. Importantly, notice that
we only have to put the column positions of the queens on the stack. We can
determine each queen's coordinates given only the stack. We simply combine the

in
position of an element in the stack (the row) with the value of that element (the
column) for each queen.

n.
➢ Two examples of this are shown below:

aa
iy
or
.p
➢ Starting with a queen in the first row, first column (represented by a stack
containing just "0"), we search left to right for a valid position to place another
w

queen in the next available row.


w

➢ If we find a valid position in this row, we push this position (i.e., the column
number) to the stack and start again on the next row.
w

➢ If we don't find a valid position in this row, we backtrack to the previous row --
that is to say, we pop the col position for the previous row from the stack and
search for a valid position further down the row.
➢ Note, when the stack size gets to n, we will have placed n queens on the board,
and therefore have a solution.
➢ Of course, there is nothing that requires there be only one solution. To find the
rest, every time a solution is found, we can pretend it is not a solution, backtrack
to the previous row, and proceed to find the next solution.
➢ Ultimately, every position in the first row will be considered. When there are not
more valid positions in the first row and we need to backtrack, that's our cue that
there are no more solutions to be found. Thus, we may stop searching when we
try to pop from the stack, but can't as it is empty.
➢ Putting all this into pseudo-code form, we have the following algorithm...
C Programming and Data Structures 3.53
https://www.poriyaan.in/ https://eee.poriyaan.in/
Create empty stack and set current position to 0
Repeat {
loop from current position to the last position until valid position found //current
row
if there is a valid position {

in
push the position to stack, set current position to 0 // move to next row

n.
}
if there is no valid position {

aa
if stack is empty, break // stop search
else pop stack, set current position to next position // backtrack to previous

iy
row
} or
if stack has size N { // a solution is found
.p
pop stack, set current position to next position // backtrack to find next solution
w

}
w

}
w

3.9.5 Reverse a Data


➢ To reverse a given set of data, we need to reorder the data so that the first and last
elements are exchanged, the second and second last element are exchanged, and
so on for all other elements. For example, suppose we have a string “welcome”,
then on reversing it would be “emoclew”.
➢ There are different reversing applications:
• Reversing a string
• Converting Decimal to Binary

3.9.5.1 Reverse a String


➢ A Stack can be used to reverse the characters of a string. This can be achieved by
simply pushing one by one each character onto the Stack, which later can be
popped from the Stack one by one. Because of the last in first out property of the
Stack, the first character of the Stack is on the bottom of the Stack and the last
3.54 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
character of the String is on the Top of the Stack and after performing the pop
operation in the Stack, the Stack returns the String in Reverse order.

in
n.
aa
iy
Fig. 3.26: Reverse a String using Stack
or
3.9.5.2 Converting Decimal to Binary
.p
➢ Although decimal numbers are used in most business applications, some scientific
and technical applications require numbers in either binary, octal, or hexadecimal.
w

A stack can be used to convert a number from decimal to


binary/octal/hexadecimal form.
w

➢ For converting any decimal number to a binary number, we repeatedly divide the
w

decimal number by two and push the remainder of each division onto the Stack
until the number is reduced to 0. Then we pop the whole Stack and the result
obtained is the binary equivalent of the given decimal number.
Example: 3.9:
Converting 14 number Decimal to Binary:
C Programming and Data Structures 3.55
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ In the above example, on dividing 14 by 2, we get seven as a quotient and one as
the reminder, which is pushed on the Stack. On again dividing seven by 2, we get
three as quotient and 1 as the reminder, which is again pushed onto the Stack. This
process continues until the given number is not reduced to 0. When we pop off
the Stack completely, we get the equivalent binary number 1110.

in
3.10 QUEUE ADT
➢ A queue can be defined as an ordered list which enables insert operations to be

n.
performed at one end called REAR and delete operations to be performed at

aa
another end called FRONT.
➢ Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a

iy
queue is open at both its ends. One end is always used to insert data (enqueue) and
the other is used to remove data (dequeue)
or
➢ Queue is referred to be as First In First Out list. i.e., the data item stored first will
.p
be accessed first.
➢ For example, people waiting in line for a rail ticket form a queue.
w
w
w

Fig. 3.27: Data Structure of Queue


3.10.1 Applications of Queue
Due to the fact that queue performs actions on first in first out basis which is quite
fair for the ordering of actions. There are various applications of queues discussed as
below.
➢ Queues are widely used as waiting lists for a single shared resource like printer,
disk, CPU.
➢ Queues are used in asynchronous transfer of data (where data is not being
transferred at the same rate between two processes) for eg. pipes, file IO, sockets.
3.56 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Queues are used as buffers in most of the applications like MP3 media player, CD
player, etc.
➢ Queue are used to maintain the play list in media players in order to add and
remove the songs from the play-list.
➢ Queues are used in operating systems for handling interrupts.

in
3.10.2 Basic Operations in Queue

n.
➢ Enqueue operation: The term "enqueue" refers to the act of adding a new element
to a queue.

aa
➢ Dequeue operation: Dequeue is the process of deleting an item from a queue. We
must delete the queue member that was put first since the queue follows the FIFO

iy
principle. Front Operation: This works similarly to the peek operation in stacks
in that it returns the value of the first element without deleting it.
or
➢ isEmpty Operation: The isEmpty() function is used to check if the Queue is empty
.p
or not.
➢ isFull Operation: The isFull() function is used to check if the Queue is full or not.
w

3.10.3 Types of Queue


w

➢ Simple Queue or Linear Queue


w

➢ Circular Queue
➢ Priority Queue
➢ Double Ended Queue (or Deque)

3.10.3.1 Simple Queue or Linear Queue


➢ In Linear Queue, an insertion takes place from one end while the deletion occurs
from another end. The end at which the insertion takes place is known as the rear
end, and the end at which the deletion takes place is known as front end. It strictly
follows the FIFO rule.
➢ The major drawback of using a linear Queue is that insertion is done only from
the rear end. If the first three elements are deleted from the Queue, we cannot
insert more elements even though the space is available in a Linear Queue. In this
case, the linear Queue shows the overflow condition as the rear is pointing to the
last element of the Queue
C Programming and Data Structures 3.57
https://www.poriyaan.in/ https://eee.poriyaan.in/

Fig. 3.28 Representation of Linear Queue

3.10.3.2 Circular Queue

in
➢ In Circular Queue, all the nodes are represented as circular. It is similar to the
linear Queue except that the last element of the queue is connected to the first

n.
element. It is also known as Ring Buffer, as all the ends are connected to another

aa
end.
➢ The drawback that occurs in a linear queue is overcome by using the circular

iy
queue. If the empty space is available in a circular queue, the new element can be
added in an empty space by simply incrementing the value of rear. The main
or
advantage of using the circular queue is better memory utilization.
.p
w
w

Fig. 3.29 Representation of circular Queue


w

3.10.3.3 Priority Queue


➢ It is a special type of queue in which the elements are arranged based on the
priority. It is a special type of queue data structure in which every element has a
priority associated with it. Suppose some elements occur with the same priority,
they will be arranged according to the FIFO principle.
➢ Insertion in priority queue takes place based on the arrival, while deletion in the
priority queue occurs based on the priority. Priority queue is mainly used to
implement the CPU scheduling algorithms.
3.58 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
There are two types of priority queue
1. Ascending priority queue - In ascending priority queue, elements can be inserted
in arbitrary order, but only smallest can be deleted first.
2. Descending priority queue - In descending priority queue, elements can be
inserted in arbitrary order, but only the largest element can be deleted first.

in
3.10.3.4 Deque (or, Double Ended Queue)

n.
➢ In Deque or Double Ended Queue, insertion and deletion can be done from both
ends of the queue either from the front or rear. It means that we can insert and

aa
delete elements from both front and rear ends of the queue. Deque can be used as
a palindrome checker means that if we read the string from both ends, then the

iy
string would be the same.
➢ Deque can be used both as stack and queue as it allows the insertion and deletion
or
operations on both ends.
.p
w
w
w

Fig. 3.31 Representation of Double Ended Queue


There are two types of Deque
➢ Input restricted Deque - As the name implies, in input restricted queue, insertion
operation can be performed at only one end, while deletion can be performed from
both ends.
➢ Output restricted Deque - As the name implies, in output restricted queue,
deletion operation can be performed at only one end, while insertion can be
performed from both ends.

3.11 PRIORITY QUEUES


➢ A priority queue is an abstract data type that behaves similarly to the normal queue
except that each element has some priority, i.e., the element with the highest
priority would come first in a priority queue. The priority of the elements in a
priority queue will determine the order in which elements are removed from the
C Programming and Data Structures 3.59
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ The priority queue supports only comparable elements, which means that the
elements are either arranged in an ascending or descending order.
➢ For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a
priority queue with an ordering imposed on the values is from least to the greatest.
Therefore, the 1 number would be having the highest priority while 22 will be

in
having the lowest priority.

3.11.1 Characteristics of a Priority queue

n.
A priority queue is an extension of a queue that contains the following characteristics:

aa
➢ Every element in a priority queue has some priority associated with it.
➢ An element with the higher priority will be deleted before the deletion of the lesser

iy
priority.
or
➢ If two elements in a priority queue have the same priority, they will be arranged
using the FIFO principle.
.p
Let's understand the priority queue through an example.
w

We have a priority queue that contains the following values:


w

1, 3, 4, 8, 14, 22
w

All the values are arranged in ascending order. Now, we will observe how the
priority queue will look after performing the following operations:
poll(): This function will remove the highest priority element from the priority queue. In
the above priority queue, the '1' element has the highest priority, so it will be removed
from the priority queue.
add(2): This function will insert '2' element in a priority queue. As 2 is the smallest
element among all the numbers so it will obtain the highest priority.
poll(): It will remove '2' element from the priority queue as it has the highest priority
queue.
add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it will
obtain the third highest priority in a priority queue.
3.60 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.11.2 Types of Priority Queue
There are two types of priority queue:
Ascending order priority queue
In ascending order priority queue, a lower priority number is given as a higher
priority in a priority. For example, we take the numbers from 1 to 5 arranged in an

in
ascending order like 1,2,3,4,5; therefore, the smallest number, i.e., 1 is given as the
highest priority in a priority queue.

n.
aa
iy
or
.p
Fig. 3.32 Ascending order priority queue
w

Descending order priority queue:


In descending order priority queue, a higher priority number is given as a higher
w

priority in a priority. For example, we take the numbers from 1 to 5 arranged in


w

descending order like 5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given as the
highest priority in a priority queue.

Fig. 3.33 Descending order priority queue

3.11.3 Representation of priority queue


Now, let’s see how to represent the priority queue through a one-way list.
We will create the priority queue by using the list given below in which INFO list
contains the data elements, PRN list contains the priority numbers of each data element
C Programming and Data Structures 3.61
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
Let's create the priority queue step by step.
In the case of priority queue, lower priority number is considered the higher

iy
priority, i.e., lower priority number = higher priority.
or
Step 1: In the list, lower priority number is 1, whose data value is 333, so it will be inserted
in the list as shown in the below diagram:
.p
Step 2: After inserting 333, priority number 2 is having a higher priority, and data values
w

associated with this priority are 222 and 111. So, this data will be inserted based
on the FIFO principle; therefore 222 will be added first and then 111.
w

Step 3: After inserting the elements of priority 2, the next higher priority number is 4 and
w

data elements associated with 4 priority numbers are 444, 555, 777. In this case,
elements would be inserted based on the FIFO principle; therefore, 444 will be
added first, then 555, and then 777.
Step 4: After inserting the elements of priority 4, the next higher priority number is 5, and
the value associated with priority 5 is 666, so it will be inserted at the end of the
queue.

3.11.4 Implementation of Priority Queue


➢ The priority queue can be implemented in four ways that include arrays, linked
list, heap data structure and binary search tree. The heap data structure is the most
3.62 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
priority queue using a heap data structure in this topic. Now, first we understand
the reason why heap is the most efficient way among all the other data structures.

3.11.5 Analysis of complexities using different implementations


➢ A comparative analysis of different implementations of priority queue is given in
table 3.4

in
Table 3.4 Analysis of priority queue

n.
Operations peek insert delete
Linked List O(1) O(n) O(1)

aa
Binary Heap O(1) O(log n) O(log n)

iy
Binary Search Tree O(1) O(log n) O(log n)

3.11.6 Heap or
➢ A heap is a tree-based data structure that forms a complete binary tree, and
.p
satisfies the heap property.
w

➢ If A is a parent node of B, then A is ordered with respect to the node B for all
nodes A and B in a heap.
w

➢ It means that the value of the parent node could be more than or equal to the value
w

of the child node, or the value of the parent node could be less than or equal to the
value of the child node.
➢ Therefore, we can say that there are two types of heaps:

Fig. 3.34 Max heap Fig. 3.35 Min heap


• Max heap: The max heap is a heap in which the value of the parent node is
C Programming and Data Structures 3.63
https://www.poriyaan.in/ https://eee.poriyaan.in/
• Min heap: The min heap is a heap in which the value of the parent node is
less than the value of the child nodes.

3.11.7 Priority Queue Operations


The common operations that we can perform on a priority queue are
➢ Insertion,

in
➢ Deletion and

n.
➢ Peek

aa
Let's see how we can maintain the heap data structure.

3.11.7.1 Inserting the element in a priority queue (max heap)

iy
If we insert an element in a priority queue, it will move to the empty slot by
or
looking from top to bottom and left to right.
If the element is not in a correct place then it is compared with the parent node; if
.p
it is found out of order, elements are swapped. This process continues until the element
is placed in a correct position.
w

Algorithm 3.18
w

START
w

If(no node):
Create node
Else:
Insert node at end of heap
Heapify
END
Let us now see with an example how this works:
Example 3.10
Let’s say the elements are 1,4,2,7,8,5. The max-heap of these elements would look like:
3.64 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
Now, let’s try to insert a new element, 6. Since there are nodes present in the heap, we

iy
insert this node at the end of heap so it looks like this:
or
.p
w
w
w

Then, heapify operation is implemented. After which, the heap will look like this:
C Programming and Data Structures 3.65
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.11.7.2 Removing the minimum element from the priority queue
In a max heap, the maximum element is the root node. When we remove the root
node, it creates an empty slot. The last inserted element will be added in this empty slot.
Then, this element is compared with the child nodes, i.e., left-child and right child, and
swap with the smaller of the two. It keeps moving down the tree until the heap property

in
is restored.
Algorithm 3.19:

n.
START

aa
If node that needs to be deleted is a leaf node:
Remove the node

iy
Else:
or
Swap node that needs to be deleted with the last leaf node present.
Remove the node
.p
Heapify
w

END
w

Let us now see with an example how this works:


Example: 3.11
w

Let’s say the elements are 1,4,2,7,8,5,6. The max-heap of these elements would look like:

Now, let’s try to delete an element, 6. Since this is not a leaf node, we swap it with the
last leaf node so it looks like this:
3.66 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
Then, we remove the leaf node so it looks like this:

iy
or
.p
w
w
w

Then, heapify operation is implemented. After which, the heap will look like this:

3.11.7.3 Peeking the element from a priority queue


This will return the maximum element if a max-heap is used and the minimum
number if a min-heap is used. To do both of these, we return root node. This is because
in the max-heap or the min-heap the maximum or minimum element will be present at
C Programming and Data Structures 3.67
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.11.8 Applications of Priority Queue
The following are the applications of a Priority Queue:
➢ It is used in Djikstra’s Algorithm – To find the shortest path between nodes in a
graph.
➢ It is used in Prim’s Algorithm – To find the Minimum Spanning Tree in a

in
weighted undirected graph.

n.
➢ It is used in Heap Sort – To sort the Heap Data Structure
➢ It is used in Huffman Coding – A Data Compression Algorithm

aa
➢ It is used in Operating Systems for:
o Priority Scheduling – Where processes must be scheduled according to their

iy
priority.
or
o Load Balancing – Where network or application traffic must be balanced
across multiple servers.
.p
o Interrupt Handling – When a current process is interrupted, a handler is
w

assigned to the same to rectify the situation immediately.


➢ A* Search Algorithm – A graph traversal and a path search algorithm
w

3.12 QUEUE IMPLEMENTATION


w

3.12.1 Array implementation of Queue


➢ Queue can be represented easily by using linear arrays.
➢ There are two variables i.e. front and rear that are implemented in the case of every
queue.
➢ Front and rear variables point to the position from where insertions and deletions
are performed in a queue.
➢ Initially, the value of front and queue is -1 which represents an empty queue.
Array representation of a queue containing 5 elements along with the respective
values of front and rear, is shown in figure 3.36.
The above figure 3.36 shows the queue of characters forming the English word
"HELLO". Since, No deletion is performed in the queue till now, therefore the value of
front remains -1. However, the value of rear increases by one every time an insertion is
performed in the queue. After inserting an element into the queue shown in the above
3.68 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
figure, the queue will look something like following. The value of rear will become 5
while the value of front remains same.

in
n.
aa
Fig. 3.36: Array representation of Queue

iy
or
.p
w
w

Fig. 3.37: Queue after inserting an element


w

After deleting an element, the value of front will increase from -1 to 0. However,
the queue will look something like following.

Fig. 3.38: Queue after deleting an element

3.12.1.1 Algorithm to insert any element in a queue


➢ Check if the queue is already full by comparing rear to max - 1. if so, then return
an overflow error.
C Programming and Data Structures 3.69
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ If the item is to be inserted as the first element in the list, in that case set the value
of front and rear to 0 and insert the element at the rear end.
➢ Otherwise keep increasing the value of rear and insert each element one by one
having rear as the index.
Algorithm 3.20

in
Step 1: IF REAR = MAX - 1

n.
Write OVERFLOW
Go to step

aa
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1

iy
SET FRONT = REAR = 0
ELSE
or
.p
SET REAR = REAR + 1
[END OF IF]
w

Step 3: Set QUEUE[REAR] = NUM


w

Step 4: EXIT
w

3.12.1.2 Implementation using C Function:


void insert (int queue[], int max, int front, int rear, int item)
{
if (rear + 1 == max)
{
printf("overflow");
}
else
{
if(front == -1 && rear == -1)
{
front = 0;
3.70 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
}
else
{
rear = rear + 1;
}

in
queue[rear]=item;

n.
}

aa
}

3.12.1.3 Algorithm to delete an element from the queue

iy
➢ If, the value of front is -1 or value of front is greater than rear, write an underflow
message and exit. or
➢ Otherwise, keep increasing the value of front and return the item stored at the front
.p
end of the queue at each time.
w

Algorithm 3.21
Step 1: IF FRONT = -1 or FRONT > REAR
w

Write UNDERFLOW
w

ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
Step 2: EXIT

3.12.1.4 Implementation using C Function


int delete (int queue[], int max, int front, int rear)
{
int y;
if (front == -1 || front > rear)
{
printf("underflow");
C Programming and Data Structures 3.71
https://www.poriyaan.in/ https://eee.poriyaan.in/
}
else
{
y = queue[front];
if(front == rear)

in
{

n.
front = rear = -1;

aa
else
front = front + 1;

iy
}
return y; or
}
.p
}
w

3.12.1.5 Drawback of array implementation


➢ Memory wastage: The space of the array, which is used to store queue elements,
w

can never be reused to store the elements of that queue because the elements can
w

only be inserted at front end and the value of front might be so high so that, all the
space before that, can never be filled.
➢ Deciding the array size: On of the most common problem with array
implementation is the size of the array which requires to be declared in advance.
Due to the fact that, the queue can be extended at runtime depending upon the
problem, the extension in the array size is a time taking process and almost
impossible to be performed at runtime since a lot of reallocations take place.

3.12.2 Linked List implementation of Queue


➢ One of the alternative of array implementation is linked list implementation of
queue.
➢ The storage requirement of linked representation of a queue with n elements is
O(n) while the time requirement for operations is O(1).
➢ In a linked queue, each node of the queue consists of two parts i.e. data part and
the link part.
3.72 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Each element of the queue points to its immediate next element in the memory.
➢ In the linked queue, there are two pointers maintained in the memory i.e. front
pointer and rear pointer.
➢ The front pointer contains the address of the starting element of the queue while
the rear pointer contains the address of the last element of the queue.

in
➢ Insertion and deletions are performed at rear and front end respectively.
➢ If front and rear both are NULL, it indicates that the queue is empty.

n.
The linked representation of queue is shown in the figure 3.39

aa
iy
or
Fig. 3.39 Linked list representation of queue
.p
3.12.2.1 Insertion on Linked Queue
➢ The insert operation append the queue by adding an element to the end of the
w

queue.
w

➢ The new element will be the last element of the queue.


w

➢ There can be the two scenario of inserting this new node ptr into the linked queue.
➢ In the first scenario, we insert element into an empty queue. In this case, the
condition front = NULL becomes true. Now, the new element will be added as the
only element of the queue and the next pointer of front and rear pointer both, will
point to NULL.
➢ In the second case, the queue contains more than one element. The condition front
= NULL becomes false. In this scenario, we need to update the end pointer rear
so that the next pointer of rear will point to the new node ptr.
➢ Since, this is a linked queue, hence we also need to make the rear pointer point to
the newly added node ptr.
➢ Also make the next pointer of rear point to NULL.
Algorithm 3.22
Step 1: Allocate the space for the new node PTR
C Programming and Data Structures 3.73
https://www.poriyaan.in/ https://eee.poriyaan.in/
Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR

in
SET REAR = PTR

n.
SET REAR -> NEXT = NULL

aa
[END OF IF]
Step 4: END

iy
3.12.2.2 Implementation using C Function
or
void insert(struct node *ptr, int item; )
{
.p
ptr = (struct node *) malloc (sizeof(struct node));
w

if(ptr == NULL)
w

{
printf("\nOVERFLOW\n");
w

return;
}
else
{
ptr -> data = item;
if(front == NULL)
{
front = ptr;
rear = ptr;
front -> next = NULL;
rear -> next = NULL;
}
3.74 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
else
{
rear -> next = ptr;
rear = ptr;
rear->next = NULL;

in
}

n.
}

aa
}

3.13 APPLICATIONS OF QUEUE

iy
There are several algorithms that use queues to give efficient running times. Some
or
simple examples of queue usage are follows.

3.13.1 Type declarations for queue-array implementation


.p
struct queue_record
w

{
w

unsigned int q_max_size; /* Maximum # of elements */


w

/* until Q is full */
unsigned int q_front;
unsigned int q_rear;
unsigned int q_size; /* Current # of elements in Q */
element_type *q_array;
};
typedef struct queue_record * QUEUE

3.13.2 Routine to test whether a queue is empty-array implementation


int
is_empty( QUEUE Q )
{
return( Q->q_size == 0 );
C Programming and Data Structures 3.75
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.13.3 Routine to make an empty queue-array implementation
void
make_null ( QUEUE Q )
{
Q->q_size = 0;

in
Q->q_front = 1;

n.
Q->q_rear = 0;

aa
}

3.13.4 Routines to enqueue-array implementation

iy
unsigned int
or
succ( unsigned int value, QUEUE Q )
{
.p
if( ++value == Q->q_max_size )
w

value = 0;
w

return value;
}
w

void
enqueue( element_type x, QUEUE Q )
{
if( is_full( Q ) )
error("Full queue");
else
{
Q->q_size++;
Q->q_rear = succ( Q->q_rear, Q );
Q->q_array[ Q->q_rear ] = x;
}
}
3.76 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
3.13.5 Other applications
➢ When jobs are submitted to a printer, they are arranged in order of arrival. Thus,
essentially, jobs sent to a line printer are placed on a queue.
➢ Virtually every real-life line is (supposed to be) a queue. For instance, lines at
ticket counters are queues, because service is first-come first-served.

in
➢ Another example concerns computer networks. There are many network setups of
personal computers in which the disk is attached to one machine, known as the

n.
file server. Users on other machines are given access to files on a first-come first-

aa
served basis, so the data structure is a queue.
➢ Calls to large companies are generally placed on a queue when all operators are

iy
busy.
➢ In large universities, where resources are limited, students must sign a waiting list
or
if all terminals are occupied. The student who has been at a terminal the longest
is forced off first, and the student who has been waiting the longest is the next
.p
user to be allowed on.
w
w
w
C Programming and Data Structures 3.77
https://www.poriyaan.in/ https://eee.poriyaan.in/
REVIEW QUESTIONS
PART-A
1. What do you mean by non-linear data structure? Give example.
➢ The non-linear data structure is the kind of data structure in which the data may

in
be arranged in hierarchical fashion. For example- Trees and graphs.
2. List the various operations that can be performed on data structure.

n.
➢ Various operations that can be performed on the data structure are

aa
• Create
• Insertion of element

iy
• Deletion of element
• or
Searching for the desired element
• Sorting the elements in the data structure
.p
• Reversing the list of elements.
w

3. What is abstract data type


w

➢ The abstract datatype is special kind of datatype, whose behavior is defined by


a set of values and set of operations.
w

4. What is list ADT in data structure?


➢ The list ADT is a collection of elements that have a linear relationship with each
other. A linear relationship means that each element of the list has a unique
successor.
5. What Are Arrays in Data Structures?
➢ An array is a linear data structure that collects elements of the same data type
and stores them in contiguous and adjacent memory locations. Arrays work on
an index system starting from 0 to (n-1), where n is the size of the array.
6. What is a linked list?
➢ A linked list is a set of nodes where each node has two fields ‘data’ and ‘link’.
The data field is used to store actual piece of information and link field is used
to store address of next node.
3.78 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
7. What are the pitfall encountered in singly linked list?
➢ The singly linked list has only forward pointer and no backward link is provided.
Hence the traversing of the list is possible only in one direction. Backward
traversing is not possible.
➢ Insertion and deletion operations are less efficient because for inserting the

in
element at desired position the list needs to be traversed. Similarly, traversing of
the list is required for locating the element which needs to be deleted.

n.
8. What is Singly Linked List?

aa
➢ A singly linked list is a type of linked list that is unidirectional, that is, it can be
traversed in only one direction from head to the last node (tail).

iy
9. Define doubly linked list.
➢ Doubly linked list is a kind of linked list in which each node has two link fields.
or
One link field stores the address of previous node and the other link field stores
the address of the next node.
.p
10. Write down the steps to modify a node in linked lists.
w

o Enter the position of the node which is to be modified.


w

o Enter the new value for the node to be modified.


w

o Search the corresponding node in the linked list.


o Replace the original value of that node by a new value.
o Display the messages as “The node is modified”.
11. Difference between arrays and lists.
➢ In arrays any element can be accessed randomly with the help of index of array,
whereas in lists any element can be accessed by sequential access only.
➢ Insertion and deletion of data is difficult in arrays on the other hand insertion
and deletion of data is easy in lists.
12. State the properties of LIST abstract data type with suitable example.
➢ It is linear data structure in which the elements are arranged adjacent to each
other.
➢ It allows to store single variable polynomial.
➢ If the LIST is implemented using dynamic memory, then it is called linked list.
C Programming and Data Structures 3.79
https://www.poriyaan.in/ https://eee.poriyaan.in/
13. State the advantages of circular lists over doubly linked list.
➢ In circular list the next pointer of last node points to head node, whereas in
doubly linked list each node has two pointers: one previous pointer and another
is next pointer.
➢ The main advantage of circular list over doubly linked list is that with the help

in
of single pointer field we can access head node quickly. Hence some amount of
memory get saved because in circular list only one pointer is reserved.

n.
14. What are the advantages of doubly linked list over singly linked list?

aa
➢ The doubly linked list has two pointer fields. One field is previous link field, and
another is next link field. Because of these two pointer fields we can access any
node efficiently whereas in singly linked list only one pointer field is there which

iy
stores forward pointer.
or
15. Why is the linked list used for polynomial arithmetic?
➢ We can have separate coefficient and exponent fields for representing each term
.p
of polynomial. Hence there is no limit for exponent. We can have any number
w

as an exponent.
16. What is the advantage of linked list over arrays?
w

➢ The linked list makes use of the dynamic memory allocation. Hence the user can
w

allocate or de allocate the memory as per his requirements. On the other hand,
the array makes use of the static memory location. Hence there are chances of
wastage of the memory or shortage of memory for allocation.
17. What is the circular linked list?
➢ The circular linked list is a kind of linked list in which the last node is connected
to the first node or head node of the linked list.
18. What is the basic purpose of header of the linked list?
➢ The header node is the very first node of the linked list. Sometimes a dummy
value such - 999 is stored in the data field of header node.
➢ This node is useful for getting the starting address of the linked list.
19. What is the advantage of an ADT?
➢ Change: the implementation of the ADT can be changed without making
changes in the client program that uses the ADT.
3.80 Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Understandability: ADT specifies what is to be done and does not specify the
implementation details. Hence code becomes easy to understand due to ADT.
➢ Reusability: the ADT can be reused by some program in future.
20. What is queue ADT?
➢ Queue is an abstract data structure, somewhat like Stacks. Unlike stacks, a queue

in
is open at both its ends. One end is always used to insert data (enqueue) and the
other is used to remove data (dequeue). Queue follows First-In-First-Out

n.
methodology, i.e., the data item stored first will be accessed first.

aa
21. What is priority queue
➢ A priority queue is a special type of queue in which each element is associated

iy
with a priority value. Elements are served on the basis of their priority. That is,
higher priority elements are served first. However, if elements with the same
or
priority occur, they are served according to their order in the queue.
22. What is stack?
.p
➢ Stack is an abstract data type that serves as a collection of elements, with two
w

main operations: Push, which adds an element to the collection, and Pop, which
removes the most recently added element that was not yet removed.
w

23. How is Stack represented in Data Structure?


w

➢ A stack may be represented in the memory in various ways. There are two main
ways: using a one-dimensional array and a single linked list.
24. List some applications of queue data structure.
➢ Managing requests on a single shared resource such as CPU scheduling and disk
scheduling.
➢ Handling hardware or real-time systems interrupts.
➢ Handling website traffic.
➢ Routers and switches in networking.
➢ Maintaining the playlist in media players.
25. List some applications of stack data structure.
➢ A Stack can be used for evaluating expressions consisting of operands and
operators.
➢ Stacks can be used for Backtracking, i.e., to check parenthesis matching in an
C Programming and Data Structures 3.81
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ It can also be used to convert one form of expression to another form. It can be
used for systematic Memory Management.

PART B

in
1. Explain Singly Link List with algorithm and examples.
2. How insertion and deletion are performed on a singly linked list? Explain with

n.
pseudocode and examples

aa
3. Explain Doubly Linked List with examples and algorithms.
4. Explain Array based implementation of List ADT with examples and pseudocode.

iy
5. Explain Array based implementation of Stack ADT with examples.
6.
or
Demonstrate the implementation of circular linked list with examples.
.p
7. Explain the applications of stack with examples.
8. Write short notes on queue ADT.
w

9. How are insertion and deletion operations performed in a queue? Explain with
w

examples and pseudocode.


w

10. Explain the implementation of priority queue with examples and pseudocode.
11. Explain queue implementation using linked list with pseudocode and examples.
12. Explain queue implementation using stack with pseudocode and examples.
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
NON-LINEAR DATA STRUCTURES

aa
Trees – Binary Trees – Tree Traversals – Expression Trees – Binary Search Tree –
Hashing - Hash Functions – Separate Chaining – Open Addressing – Linear Probing–

iy
Quadratic Probing – Double Hashing – Rehashing.
or
.p
4.1 INTRODUCTION TO TRESS
➢ A tree is non-linear and a hierarchical data structure consisting of a collection of
w

nodes such that each node of the tree stores a value and a list of references to other
w

nodes (the “children”). This data structure is a specialized method to organize and
store data in the computer to be used more effectively.
w

4.1.1 Example of Tree data structure

Here,
➢ Node A is the root node
4.2 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ D and E are the siblings
➢ D, E, F and G are the leaf nodes
➢ A and B are the ancestors of E

4.1.2 Basic Terminologies in Tree Data Structure

in
➢ Parent Node: The node which is a predecessor of a node is called the parent node
of that node.

n.
➢ Child Node: The node which is the immediate successor of a node is called the

aa
child node of that node.
➢ Root Node: The topmost node of a tree or the node which does not have any

iy
parent node is called the root node. A non-empty tree must contain exactly one
root node and exactly one path from the root to all other nodes of the tree.

or
Leaf Node or External Node: The nodes which do not have any child nodes are
called leaf nodes.
.p
➢ Ancestor of a Node: Any predecessor nodes on the path of the root to that node
w

are called Ancestors of that node.


w

➢ Descendant: Any successor node on the path from the leaf node to that node.
w

➢ Sibling: Children of the same parent node are called siblings.


➢ Level of a node: The count of edges on the path from the root node to that node.
The root node has level 0.
➢ Internal node: A node with at least one child is called Internal Node.
➢ Neighbour of a Node: Parent or child nodes of that node are called neighbors of
that node.
➢ Subtree: Any node of the tree along with its descendant.

4.1.3 Properties of a Tree


➢ Number of edges: An edge can be defined as the connection between two nodes.
If a tree has N nodes, then it will have (N-1) edges. There is only one path from
each node to any other node of the tree.
➢ Depth of a node: The depth of a node is defined as the length of the path from
the root to that node. Each edge adds 1 unit of length to the path. So, it can also
C Programming and Data Structures 4.3
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Height of a node: The height of a node can be defined as the length of the longest
path from the node to a leaf node of the tree.
➢ Height of the Tree: The height of a tree is the length of the longest path from the
root of the tree to a leaf node of the tree.
➢ Degree of a Node: The total count of subtrees attached to that node is called the

in
degree of the node. The degree of a leaf node must be 0. The degree of a tree is
the maximum degree of a node among all the nodes in the tree.

n.
4.1.4 Syntax for creating a node

aa
struct Node
{

iy
int data.
struct Node *left_child;
or
.p
struct Node *right_child;
};
w

4.2 BINARY TREES


w

➢ Binary Tree is defined as a Tree data structure with at most 2 children. Since each
w

element in a binary tree can have only 2 children, we typically name them the left
and right child.

4.2.1 Binary Tree Representation


➢ A Binary tree is represented by a pointer to the topmost node of the tree. If the tree
is empty, then the value of the root is NULL.
4.4 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Binary Tree node contains the following parts:
• Data
• Pointer to left child
• Pointer to right child

in
n.
aa
iy
4.2.2 Types of Binary Trees
or
.p
➢ There are various types of binary trees, and each of these binary tree types has
unique characteristics. Here are each of the binary tree types in detail:
w

• Full Binary Tree


w

➢ It is a special kind of a binary tree that has either zero children or two
children. It means that all the nodes in that binary tree should either have
w

two child nodes of its parent node or the parent node is itself the leaf node
or the external node.

• Complete Binary Tree


➢ A complete binary tree is another specific type of binary tree where all
the tree levels are filled entirely with nodes, except the lowest level of
the tree. Also, in the last or the lowest level of this binary tree, every node
should possibly reside on the left side.
C Programming and Data Structures 4.5
https://www.poriyaan.in/ https://eee.poriyaan.in/

• Perfect Binary Tree

in
✓ A binary tree is said to be ‘perfect’ if all the internal nodes have strictly two

n.
children, and every external or leaf node is at the same level or same depth
within a tree. A perfect binary tree having height ‘h’ has 2h – 1 node.

aa
iy
• Balanced Binary Tree
or
.p
✓ A balanced binary tree, also referred to as a height-balanced binary tree, is
defined as a binary tree in which the height of the left and right subtree of any
w

node differs by not more than 1.


w
w

• Degenerate Binary Tree


✓ A binary tree is said to be a degenerate binary tree or pathological binary tree
if every internal node has only a single child.

4.2.3 Benefits of Binary Trees:


❖ The search operation in a binary tree is faster as compared to other trees
4.6 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
❖ It is easy to pick up the maximum and minimum elements
❖ Graph traversal also uses binary trees
❖ Converting different postfix and prefix expressions are possible using binary trees

4.3 TREE TRAVERSAL

in
➢ Tree traversal means visiting each node of the tree. The tree is a non-linear data
structure, and therefore its traversal is different from other linear data structures.

n.
➢ There is only one way to visit each node/element in linear data structures, i.e.

aa
starting from the first value and traversing in a linear order.

4.3.1 Types of Tree Traversal

iy
• Preorder traversal
or
✓ In a preorder traversal, we process/visit the root node first. Then we traverse
the left subtree in a preorder manner. Finally, we visit the right subtree again
.p
in a preorder manner.
✓ For example, consider the following tree:
w
w
w

✓ Here, the root node is A. All the nodes on the left of A are a part of the left
subtree whereas all the nodes on the right of A are a part of the right subtree.
Thus, according to preorder traversal, we will first visit the root node, so A
will print first and then move to the left subtree.
✓ B is the root node for the left subtree. So B will print next, and we will visit
the left and right nodes of B. In this manner, we will traverse the whole left
subtree and then move to the right subtree. Thus, the order of visiting the
C Programming and Data Structures 4.7
https://www.poriyaan.in/ https://eee.poriyaan.in/
❖ Algorithm for Preorder Traversal
o for all nodes of the tree:
▪ Step 1: Visit the root node.
▪ Step 2: Traverse left subtree recursively.
▪ Step 3: Traverse right subtree recursively.

in
❖ Pseudo-code for Preorder Traversal

n.
void Preorder(struct node* ptr)
{

aa
if(ptr != NULL)
{

iy
printf("%d", ptr->data);
or
Preorder(ptr->left);
Preorder(ptr->right);
.p
}
w

}
❖ Uses of Preorder Traversal
w

o If we want to create a copy of a tree, we make use of preorder


w

traversal.
o Preorder traversal helps to give a prefix expression for the expression
tree.
• Inorder Traversal
✓ In an inorder traversal, we first visit the left subtree, then the root node and
then the right subtree in an inorder manner.
✓ Consider the following tree:
4.8 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
✓ In this case, as we visit the left subtree first, we get the node with the value
30 first, then 20 and then 40. After that, we will visit the root node and print
it. Then comes the turn of the right subtree. We will traverse the right subtree
in a similar manner. Thus, after performing the inorder traversal, the order of
nodes will be 30→20→40→10→50→70→60→80.
❖ Algorithm for Inorder Traversal

in
o for all nodes of the tree:

n.
▪ Step 1: Traverse left subtree recursively.

aa
▪ Step 2: Visit the root node.
▪ Step 3: Traverse right subtree recursively.

iy
❖ Pseudo-code for Inorder Traversal
or
void Inorder(struct node* ptr)
{
.p
if(ptr != NULL)
w

{
Inorder(ptr->left);
w

printf("%d", ptr->data);
w

Inorder(ptr->right);
}
}
❖ Uses of Inorder Traversal
o It helps to delete the tree.
o It helps to get the postfix expression in an expression tree.
• Postorder Traversal
✓ Postorder traversal is a kind of traversal in which we first traverse the left
subtree in a postorder manner, then traverse the right subtree in a postorder
manner and at the end visit the root node.
✓ For example, in the following tree:
C Programming and Data Structures 4.9
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
iy
➢ The postorder traversal will be 7→5→4→20→60→30→10.
or
❖ Algorithm for Postorder Traversal
o or all nodes of the tree:
.p
▪ Step 1: Traverse left subtree recursively.
w

▪ Step 2: Traverse right subtree recursively.



w

Step 3: Visit the root node.


❖ Pseudo-code for Postorder Traversal
w

void Postorder(struct node* ptr)


{
if(ptr != NULL)
{
Postorder(ptr->left);
Postorder(ptr->right);
printf(“%d”, ptr->data);
}
}
➢ Uses of Postorder Traversal
o It helps to delete the tree.
o It helps to get the postfix expression in an expression tree.
4.10 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
4.4 EXPRESSION TREES
➢ The expression tree is a tree used to represent the various expressions. The tree
data structure is used to represent the expressional statements. In this tree, the
internal node always denotes the operators. The leaf nodes always denote the
operands.

in
➢ For example, expression tree for 3 + ((5+9)*2) would be:

n.
aa
iy
or
.p
w
w
w

4.4.1 Properties of an Expression tree


➢ In this tree, the internal node always denotes the operators.
➢ The leaf nodes always denote the operands.
➢ The operations are always performed on these operands.
➢ The operator present in the depth of the tree is always at the highest priority.
➢ The operator, which is not much at the depth in the tree, is always at the lowest
priority compared to the operators lying at the depth.
➢ The operand will always present at a depth of the tree; hence it is considered the
highest priority among all the operators.

4.4.2 Construction of Expression Tree


➢ Let us consider a postfix expression is given as an input for constructing an
expression tree. Following are the step to construct an expression tree:
❖ Read one symbol at a time from the postfix expression.
C Programming and Data Structures 4.11
https://www.poriyaan.in/ https://eee.poriyaan.in/
❖ Check if the symbol is an operand or operator.
❖ If the symbol is an operand, create a one node tree and push a pointer onto a
stack
❖ If the symbol is an operator, pop two pointers from the stack namely T1 & T2
and form a new tree with root as the operator, T1 & T2 as a left and right child

in
❖ A pointer to this new tree is pushed onto the stack
➢ Thus, an expression is created or constructed by reading the symbols or numbers

n.
from the left. If operand, create a node. If operator, create a tree with operator as

aa
root and two pointers to left and right subtree

4.4.3 Example - Postfix Expression Construction

iy
➢ The input is: a b + c *
or
o The first two symbols are operands, we create one-node tree and push a
pointer to them onto the stack.
.p
w
w
w

o Next, read a'+' symbol, so two pointers to tree are popped, a new tree is
formed and push a pointer to it onto the stack.

o Next, 'c' is read, we create one node tree and push a pointer to it onto the stack.
4.12 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
o Finally, the last symbol is read ' * ', we pop two tree pointers and form a
new tree with a, ' * ' as root, and a pointer to the final tree remains on the
stack.

in
n.
aa
iy
4.4.4 Implementation of Expression tree in C Programming language
or
// C program for expression tree implementation
#include <stdio.h>
.p
#include <stdlib.h>
w

/* The below structure node is defined as a node of a binary tree consists


of left child and the right child, along with the pointer next which points to the
w

next node */
w

struct node
{
char info ;
struct node* l ;
struct node* r ;
struct node* nxt ;
};
struct node *head=NULL;
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newnode(char data)
{
C Programming and Data Structures 4.13
https://www.poriyaan.in/ https://eee.poriyaan.in/
struct node* node = (struct node*) malloc ( sizeof ( struct node ) ) ;
node->info = data ;
node->l = NULL ;
node->r = NULL ;
node->nxt = NULL ;

in
return ( node ) ;

n.
}

aa
void Inorder(struct node* node)
{

iy
if ( node == NULL)

else
return ; or
.p
{
w

/* first recur on left child */


w

Inorder ( node->l ) ;
/* then print the data of node */
w

printf ( "%c " , node->info ) ;


/* now recur on right child */
Inorder ( node->r ) ;
}
}
void push ( struct node* x )
{
if ( head == NULL )
head = x ;
else
{
4.14 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
head = x ;
}
// struct node* temp ;
// while ( temp != NULL )
// {

in
// printf ( " %c " , temp->info ) ;

n.
// temp = temp->nxt ;

aa
// }
}

iy
struct node* pop()
{ or
// Poping out the top most [pointed with head] element
.p
struct node* n = head ;
w

head = head->nxt ;
w

return n ;
}
w

int main()
{
char t[] = { 'X' , 'Y' , 'Z' , '*' , '+' , 'W' , '/' } ;
int n = sizeof(t) / sizeof(t[0]) ;
int i ;
struct node *p , *q , *s ;
for ( i = 0 ; i < n ; i++ )
{
// if read character is operator then popping two
// other elements from stack and making a binary
// tree
C Programming and Data Structures 4.15
https://www.poriyaan.in/ https://eee.poriyaan.in/
{
s = newnode ( t [ i ] ) ;
p = pop() ;
q = pop() ;
s->l = q ;

in
s->r = p;

n.
push(s);

aa
}
else {

iy
s = newnode ( t [ i ] ) ;

}
push ( s ) ; or
.p
}
w

printf ( " The Inorder Traversal of Expression Tree: " ) ;


w

Inorder ( s ) ;
return 0 ;
w

}
The output of the above program is
X+Y*Z/W

4.4.5 Use of Expression tree


➢ The main objective of using the expression trees is to make complex expressions
and can easily be evaluated using these expression trees.
➢ It is also used to find out the associativity of each operator in the expression.
➢ It is also used to solve the postfix, prefix, and infix expression evaluation.

4.5 BINARY SEARCH TREE


➢ In a Binary search tree, the value of left node must be smaller than the parent node,
and the value of right node must be greater than the parent node. This rule is
applied recursively to the left and right subtrees of the root.
4.16 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Example for Binary Search Tree

in
n.
aa
iy
➢ In the above figure, we can observe that the root node is 40, and all the nodes of
or
the left subtree are smaller than the root node, and all the nodes of the right subtree
are greater than the root node.
.p
➢ Similarly, we can see the left child of root node is greater than its left child and
smaller than its right child. So, it also satisfies the property of binary search tree.
w

Therefore, we can say that the tree in the above image is a binary search tree.
w

4.5.1 Advantages of Binary search tree


w

➢ Searching an element in the Binary search tree is easy as we always have a hint
that which subtree has the desired element.
➢ As compared to array and linked lists, insertion and deletion operations are faster
in BST.

4.5.2 Example of creating a binary search tree


➢ Now, let's see the creation of binary search tree using an example. Suppose the
data elements are : 45, 15, 79, 90, 10, 55, 12, 20, 50
o First, we have to insert 45 into the tree as the root of the tree.
o Then, read the next element; if it is smaller than the root node, insert it as the
root of the left subtree, and move to the next element.
o Otherwise, if the element is larger than the root node, then insert it as the root
of the right subtree.
➢ Now, let's see the process of creating the Binary search tree using the given data
C Programming and Data Structures 4.17
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Step 1 - Insert 45.

in
➢ Step 2 - Insert 15.

n.
o As 15 is smaller than 45, so insert it as the root node of the left subtree.

aa
iy
or
.p
w
w

➢ Step 3 - Insert 79.


o As 79 is greater than 45, so insert it as the root node of the right subtree.
w

➢ Step 4 - Insert 90.


o 90 is greater than 45 and 79, so it will be inserted as the right subtree of 79.
4.18 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
➢ Step 5 - Insert 10

aa
o 10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.

iy
or
.p
w
w
w

➢ Step 6 - Insert 55
o 55 is larger than 45 and smaller than 79, so it will be inserted as the left subtree
of 79.
C Programming and Data Structures 4.19
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Step 7 - Insert 12
o 12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the
right subtree of 10.

in
n.
aa
iy
or
.p
w

➢ Step 8 - Insert 20
w

o 20 is smaller than 45 but greater than 15, so it will be inserted as the right
subtree of 15.
w
4.20 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Step 9 - Insert 50.
o 50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a
left subtree of 55.

in
n.
aa
iy
or
.p
w

➢ Now, the creation of binary search tree is completed.


w

4.5.3 Operations performed on a Binary Search Tree


w

➢ We can perform insert, delete and search operations on the binary search tree.
4.5.3.1 Searching in Binary search tree
➢ Searching means to find or locate a specific element or node in a data structure.
In Binary search tree, searching a node is easy because elements in BST are stored
in a specific order.

4.5.3.1.1 Steps involved in Searching in a Binary Search Tree


❖ First, compare the element to be searched with the root element of the tree.
❖ If root is matched with the target element, then return the node's location.
❖ If it is not matched, then check whether the item is less than the root element, if it
is smaller than the root element, then move to the left subtree.
❖ If it is larger than the root element, then move to the right subtree.
❖ Repeat the above procedure recursively until the match is found.
C Programming and Data Structures 4.21
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Now, let's understand the searching in binary tree using an example. We are
taking the binary search tree formed above. Suppose we have to find node 20
from the below tree.
Step1:

in
n.
aa
iy
or
.p
Step2:
w
w
w

Step3:
4.22 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
4.5.3.1.2 Algorithm to search an element in Binary search tree
Search (root, item)
Step 1 - if (item = root → data) or (root = NULL)
return root
else if (item < root → data)

in
return Search(root → left, item)

n.
else
return Search(root → right, item)

aa
END if

iy
Step 2 - END

or
4.5.3.2 Deletion in Binary Search tree
➢ In a binary search tree, we must delete a node from the tree by keeping in mind
.p
that the property of BST is not violated. To delete a node from BST, there are
three possible situations occur -
w

• The node to be deleted is the leaf node, or,


w

• The node to be deleted has only one child, and,


w

• The node to be deleted has two children

4.5.3.2.1 When the node to be deleted is the leaf node


➢ It is the simplest case to delete a node in BST. Here, we have to replace the leaf
node with NULL and simply free the allocated space.
➢ We can see the process to delete a leaf node from BST in the below image. In
below image, suppose we have to delete node 90, as the node to be deleted is a
leaf node, so it will be replaced with NULL, and the allocated space will free.
C Programming and Data Structures 4.23
https://www.poriyaan.in/ https://eee.poriyaan.in/
4.5.3.2.2 When the node to be deleted has only one child
➢ In this case, we have to replace the target node with its child, and then delete the
child node. It means that after replacing the target node with its child node, the
child node will now contain the value to be deleted. So, we simply have to replace
the child node with NULL and free up the allocated space.

in
➢ We can see the process of deleting a node with one child from BST in the below
image. In the below image, suppose we have to delete the node 79, as the node to

n.
be deleted has only one child, so it will be replaced with its child 55.
➢ So, the replaced node 79 will now be a leaf node that can be easily deleted.

aa
iy
or
.p
w
w

4.5.3.2.3 When the node to be deleted has two children


w

➢ This case of deleting a node in BST is a bit complex among other two cases. In
such a case, the steps to be followed are listed as follows -
o First, find the inorder successor of the node to be deleted.
o After that, replace that node with the inorder successor until the target node
is placed at the leaf of tree.
o And at last, replace the node with NULL and free up the allocated space.
➢ The inorder successor is required when the right child of the node is not empty.
We can obtain the inorder successor by finding the minimum element in the right
child of the node.
➢ We can see the process of deleting a node with two children from BST in the
below image.
➢ In the below image, suppose we have to delete node 45 that is the root node, as
the node to be deleted has two children, so it will be replaced with its inorder
successor. Now, node 45 will be at the leaf of the tree so that it can be deleted
4.24 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
4.5.3.3 Insertion in Binary Search tree

aa
➢ A new key in BST is always inserted at the leaf. To insert an element in BST, we
have to start searching from the root node; if the node to be inserted is less than
the root node, then search for an empty location in the left subtree.

iy
➢ Else, search for the empty location in the right subtree and insert the data. Insert
or
in BST is similar to searching, as we always have to maintain the rule that the left
subtree is smaller than the root, and right subtree is larger than the root.
.p
w
w
w

4.5.3.4 The complexity of the Binary Search tree


➢ Let's see the time and space complexity of the Binary search tree. We will see the
time complexity for insertion, deletion, and searching operations in best case,
C Programming and Data Structures 4.25
https://www.poriyaan.in/ https://eee.poriyaan.in/
4.5.3.5 Implementation of Binary search tree
#include <iostream>
using namespace std;
struct Node {
int data;

in
Node *left;

n.
Node *right;

aa
};
Node* create(int item)

iy
{
Node* node = new Node; or
node->data = item;
.p
node->left = node->right = NULL;
w

return node;
}
w

/*Inorder traversal of the tree formed*/


w

void inorder(Node *root)


{
if (root == NULL)
return;
inorder(root->left); //traverse left subtree
cout<< root->data << " "; //traverse root node
inorder(root->right); //traverse right subtree
}
Node* findMinimum(Node* cur) /*To find the inorder successor*/
{
while(cur->left != NULL) {
cur = cur->left;
4.26 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
return cur;
}
Node* insertion(Node* root, int item) /*Insert a node*/
{
if (root == NULL)

in
return create(item); /*return new node if tree is empty*/

n.
if (item < root->data)

aa
root->left = insertion(root->left, item);
else

iy
root->right = insertion(root->right, item);
return root; or
}
.p
void search(Node* &cur, int item, Node* &parent)
{
w

while (cur != NULL && cur->data != item)


w

{
w

parent = cur;
if (item < cur->data)
cur = cur->left;
else
cur = cur->right;
}
}
void deletion(Node*& root, int item) /*function to delete a node*/
{
Node* parent = NULL;
Node* cur = root;
search(cur, item, parent); /*find the node to be deleted*/
C Programming and Data Structures 4.27
https://www.poriyaan.in/ https://eee.poriyaan.in/
return;
if (cur->left == NULL && cur->right == NULL) /*When node has no
children*/
{
if (cur != root)

in
{

n.
if (parent->left == cur)
parent->left = NULL;

aa
else
parent->right = NULL;

iy
}
else
or
.p
root = NULL;
free(cur);
w

}
w

else if (cur->left && cur->right)


w

{
Node* succ = findMinimum(cur->right);
int val = succ->data;
deletion(root, succ->data);
cur->data = val;
}
else
{
Node* child = (cur->left)? cur->left: cur->right;
if (cur != root)
{
if (cur == parent->left)
4.28 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
else
parent->right = child;
}
else
root = child;

in
free(cur);

n.
}

aa
}
int main()

iy
{
Node* root = NULL; or
root = insertion(root, 45);
.p
root = insertion(root, 30);
root = insertion(root, 50);
w

root = insertion(root, 25);


w

root = insertion(root, 35);


w

root = insertion(root, 45);


root = insertion(root, 60);
root = insertion(root, 4);
printf("The inorder traversal of the given binary tree is - \n");
inorder(root);
deletion(root, 25);
printf("\nAfter deleting node 25, the inorder traversal of the given binary tree is
- \n");
inorder(root);
insertion(root, 2);
printf("\nAfter inserting node 2, the inorder traversal of the given binary tree is
- \n");
C Programming and Data Structures 4.29
https://www.poriyaan.in/ https://eee.poriyaan.in/
return 0;
}
Output

in
n.
aa
4.6 HASHING
➢ Hashing in the data structure is a technique of mapping a large chunk of data into

iy
small tables using a hashing function. It is also known as the message digest
or
function. It is a technique that uniquely identifies a specific item from a collection
of similar items.
.p
➢ It uses hash tables to store the data in an array format. Each value in the array has
been assigned a unique index number. Hash tables use a technique to generate
w

these unique index numbers for each value stored in an array format. This
w

technique is called the hash technique.


➢ You only need to find the index of the desired item, rather than finding the data.
w

With indexing, you can quickly scan the entire list and retrieve the item you wish.
Indexing also helps in inserting operations when you need to insert data at a
specific location. No matter how big or small the table is, you can update and
retrieve data within seconds.
➢ The hash table is basically the array of elements, and the hash techniques of search
are performed on a part of the item i.e. key. Each key has been mapped to a
number, the range remains from 0 to table size 1
➢ Types of hashing in data structure is a two-step process.
o The hash function converts the item into a small integer or hash value. This
integer is used as an index to store the original data.
o It stores the data in a hash table. You can use a hash key to locate data quickly.

4.6.1 Examples
➢ In schools, the teacher assigns a unique roll number to each student. Later, the
4.30 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ A library has an infinite number of books. The librarian assigns a unique number
to each book. This unique number helps in identifying the position of the books
on the bookshelf.

4.7 HASH FUNCTION


➢ The hash function in a data structure maps the arbitrary size of data to fixed-sized

in
data. It returns the following values: a small integer value (also known as hash

n.
value), hash codes, and hash sums. The hashing techniques in the data structure
are very interesting, such as:

aa
o hash = hashfunc(key)
o index = hash % array_size

iy
➢ The hash function must satisfy the following requirements:
or
o A good hash function is easy to compute.
o A good hash function never gets stuck in clustering and distributes keys
.p
evenly across the hash table.
w

o A good hash function avoids collision when two elements or items get
assigned to the same hash value.
w

➢ The three characteristics of the hash function in the data structure are:
w

o Collision free
o Property to be hidden
o Puzzle friendly

4.7.1 Hash Table


➢ Hashing in data structure uses hash tables to store the key-value pairs. The hash
table then uses the hash function to generate an index. Hashing uses this unique
index to perform insert, update, and search operations.
C Programming and Data Structures 4.31
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ It can be defined as a bucket where the data are stored in an array format. These
data have their own index value. If the index values are known then the process
of accessing the data is quicker.

4.7.2 How does Hashing in Data Structure Works?


➢ In hashing, the hashing function maps strings or numbers to a small integer value.

in
Hash tables retrieve the item from the list using a hashing function.

n.
➢ The objective of hashing technique is to distribute the data evenly across an array.
Hashing assigns all the elements a unique key. The hash table uses this key to

aa
access the data in the list.
➢ Hash table stores the data in a key-value pair. The key acts as an input to the

iy
hashing function. Hashing function then generates a unique index number for each
value stored.
or
➢ The index number keeps the value that corresponds to that key. The hash function
.p
returns a small integer value as an output. The output of the hashing function is
called the hash value.
w

➢ Let us understand hashing in a data structure with an example. Imagine you need
to store some items (arranged in a key-value pair) inside a hash table with 30 cells.
w

The values are: (3,21) (1,72) (40,36) (5,30) (11,44) (15,33) (18,12) (16,80) (38,99)
w

➢ The hash table will look like the following:


4.32 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ The process of taking any size of data and then converting that into smaller data
value which can be named as hash value. This hash alue can be used in an index
accessible in hash table. This process define hashing in data structure.

4.8 SEPARATE CHAINING


➢ Separate Chaining is the collision resolution technique that is implemented using

in
linked list. When two or more elements are hash to the same location, these

n.
elements are represented into a singly linked list like a chain. Since this method
uses extra memory to resolve the collision, therefore, it is also known as open

aa
hashing.

4.8.1 Separate Chaining Hash Table

iy
➢ In separate chaining, each slot of the hash table is a linked list. We will insert the
or
element into a specific linked list to store it in the hash table. If there is any
collision i.e. if more than one element after calculating the hashed value mapped
.p
to the same key then we will store those elements in the same linked list. Given
below is the representation of the separate chaining hash table.
w
w
w

4.8.2 Example for Separate Chaining


➢ Let's understand with the help of examples. Given below is the hash function:
h(key) = key % table size
➢ In a hash table with size 7, keys 42 and 38 would get 0 and 3 as hash indices
C Programming and Data Structures 4.33
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
iy
➢ If we insert a new element 52 , that would also go to the fourth index as 52%7 is
3. or
.p
w
w
w

➢ The lookup cost will be scanning all the entries of the selected linked list for the
required key. If the keys are uniformly distributed, then the average lookup cost
will be an average number of keys per linked list.

4.8.3 How to Avoid Collision in Separate Chaining Method


➢ Separate chaining method handles the collison by creating a linked list to the
occupied buckets. So far we only looked at a simple hash function where collision
is imminent.
➢ It is important to choose a good hash function in order to minimize the number of
4.34 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Some characterstics of good hash function are:
✓ Minimize collisions
✓ Be easy and quick to compute
✓ key values inserted evenly in the hash table
✓ Have a high load factor for a given set of keys

in
4.8.4 Practice Problem Based on Separate Chaining

n.
➢ Let's take an example to understand the concept more clearly. Suppose we have

aa
the following hash function, and we have to insert certain elements in the hash
table by using separate chaining as the collision resolution technique.
➢ Hash function = key % 6 Elements = 24, 75, 65, 81, 42, and 63.

iy
➢ Step1: First we will draw the empty hash table which will have possible range of
or
hash values from 0 to 5 according to the hash function provided.
.p
w
w
w

➢ Step 2: Now we will insert all the keys in the hash table one by one. First key to
be inserted is 24. It will map to bucket number 0 which is calculated by using hash
function 24%6=0.
C Programming and Data Structures 4.35
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Step 3: Now the next key that is need to be inserted is 75. It will map to the bucket
number 3 because 75%6=3. So insert it to bucket number 3.

in
n.
aa
iy
or
➢ Step 4: The next key is 65. It will map to bucket number 5 because 65%6=5. So,
.p
insert it to bucket number 5.
w
w
w

➢ Step 5: Now the next key is 81. Its bucket number will be 81%6=3. But bucket 3
is already occupied by key 75. So separate chaining method will handles the
collision by creating a linked list to bucket 3.
4.36 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
➢ Step 6: Now the next key is 42. Its bucket number will be 42%6=0. But bucket 0

iy
is already occupied by key 24. So separate chaining method will again handles the
collision by creating a linked list to bucket 0.
or
.p
w
w
w

➢ Step 7: Now the last key to be inserted is 63. It will map to the bucket number
63%6=3. Since bucket 3 is already occupied, so collision occurs but separate
chaining method will handle the collision by creating a linked list to bucket 3.
C Programming and Data Structures 4.37
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ In this way the separate chaining method is used as the collision resolution
technique.

4.8.5 Advantages and Disadvantages of Separate Chaining


Advantages
➢ Separate Chaining is one of the simplest methods to implement and understand.

in
➢ We can add any number of elements to the chain.

n.
➢ It is frequently used when we don't know about the number of elements and the
number of keys that can be inserted or deleted.

aa
Disadvantages
➢ The keys in the hash table are not evenly distributed.

iy
➢ Some amount of wastage of space occurs.
or
➢ The complexity of searching becomes O(n) in the worst case when the chain
.p
becomes long.

4.9 OPEN ADDRESSING


w

➢ The open addressing is another technique for collision resolution. Unlike chaining,
w

it does not insert elements to some other data-structures. It inserts the data into the
w

hash table itself. The size of the hash table should be larger than the number of
keys.
➢ There are three different popular methods for open addressing techniques. These
methods are −
✓ Linear Probing
✓ Quadratic Probing
✓ Double Hashing

4.10 LINEAR PROBING


➢ This is a simple method, sequentially tries the new location until an empty location
is found in the table.
➢ For example: inserting the keys {79, 28, 39, 68, 89} into closed hash table by
using same function and collision resolution technique as mentioned before and
the table size is 10 ( for easy undestanding we are not using prime number for
4.38 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
slot reached an empty location not found then the search proceeds to the first
location of the array.
➢ The hash function is hi(X)=(Hash(X)+F(i)) % TableSize for i = 0, 1, 2, 3,...etc.

4.10.1 Solution

in
n.
aa
iy
or
.p
A Closed Hash Table using Linear Probing
w

Key Hash Function h(X) Index Collision Alt Index


w

79 h0(79) = (Hash (79) +F(0)) %10 9


= ((79%10) +0) %10 = 9
w

28 h0(28) = (Hash (28) +F(0)) %10 8


= ((28%10) +0) %10 = 8
39 h0(39) = (Hash (39) +F(0)) %10 9 First collision
= ((39%10) +0) %10 = 9 occurs
h1(39) = (Hash (39) +F(0)) %10 0 0
= ((39%10) +1) %10 = 0
68 h0(68) 8 first
= (Hash(68)+F(0))%10 collision
= ((68%10)+0)%10 =8 occurs
h1(68) 9 Again
= (Hash(68)+F(1))%10 collision
= ((68%10)+1)%10 =9 occurs
C Programming and Data Structures 4.39
https://www.poriyaan.in/ https://eee.poriyaan.in/
h2(68) 0 Again
= (Hash(68)+F(2))%10 collision
= ((68%10)+2)%10 =0 occurs

h3(68) 1 1
= (Hash(68)+F(3))%10

in
= ((68%10)+3)%10 =1

n.
89 h0(89) 9 collision

aa
= (Hash(89)+F(0))%10 occurs
= ((89%10)+0)%10 =9

iy
h1(89) 0 Again
collision
= (Hash(89)+F(1))%10
= ((89%10)+1)%10
or
=0 occurs
.p
h2(89) 1 Again
collision
w

= (Hash(89)+F(2))%10
= ((89%10)+2)%10 =1 occurs
w

h3(89) 2 2
w

= (Hash(89)+F(3))%10
= ((89%10)+3)%10 =2

4.11 QUADTRATIC PROBING


➢ Quadratic probing is an open addressing method for resolving collision in the hash
table. This method is used to eliminate the primary clustering problem of linear
probing.
➢ This technique works by considering of original hash index and adding successive
value of an arbitrary quadratic polynomial until the empty location is found. In
linear probing, we would use H+0, H+1, H+2, H+3,.....H+K hash function
sequence.
➢ Instead of using this sequence, the quadratic probing would use another sequence
is that H+12, H+22, H+32,....H+K2. Therefore, the hash function for quadratic
4.40 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/

➢ Let us examine the linear probing with the same example

in
n.
aa
iy
or
.p
Key Hash Function h(X) Index Collision Alt Index
w

79 h0(79) 9
w

= (Hash (79) + F(0)2) % 10


w

= ((79 % 10) + 0) % 10
28 h0(28) 8
= (Hash (28) + F(0)2) % 10
= ((28 % 10) + 0) % 10
39 h0(39) 9 The first
2
= (Hash (39) + F(0) ) % 10 collision
occurs
= ((39 % 10) + 0) % 10
h1(39) 0 0
= (Hash(39) + F(1)2) % 10
= ((39 % 10) + 1) % 10
68 h0(68) 8 The
2
= (Hash (68) + F(0) ) % 10 collision
C Programming and Data Structures 4.41
https://www.poriyaan.in/ https://eee.poriyaan.in/
h1(68) 9 Again
= (Hash (68) + F(1)2) % 10 collision
occurs
= ((68 % 10) + 1) % 10
h2(68) 2 2
= (Hash(68) + F(2)2) % 10

in
= ((68 % 10) + 4) % 10

n.
89 h0(89) 9 The

aa
= (Hash(89) + F(0)2) % 10 collision
= ((89 % 10) + 0) % 10 occurs

iy
h1(89) 0 Again
= (Hash(89) + F(1)2) % 10 collision
or
= ((89 % 10) + 1) % 10
occurs
.p
h2(89) 3 3
w

= ( Hash(89) + F(2)2) % 10
= ((89 % 10) + 4) % 10
w

➢ Although, the quadratic probing eliminates the primary clustering, it still has the
w

problem.
➢ When two keys hash to the same location, they will probe to the same alternative
location. This may cause secondary clustering. In order to avoid this secondary
clustering, double hashing method is created where we use extra multiplications
and divisions

4.12 DOUBLE HASHING


➢ Double Hashing uses 2 hash functions and hence called double hashing. The first
hash function determines the initial location to locate the key and the second hash
function is to determine the size of the jumps in the probe sequence.

4.12.1 Double Hashing - Hash Function 1 or First Hash Function – formula


➢ hi = (Hash(X) + F(i)) % Table Size
were
4.42 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
• X is the Key or the Number for which the hashing is done
• i is the ith time that hashing is done for the same value. Hashing is repeated
only when collision occurs
• Table size is the size of the table in which hashing is done
➢ This F(i) will generate the sequence such as hash2(X), 2 * hash2(X) and so on.

in
4.12.2 Double Hashing - Hash Function 2 or Second Hash Function – formula

n.
➢ Second hash function is used to resolve collision in hashing We use second hash
function as

aa
o hash2(X) = R - (X mod R)
➢ where

iy
• R is the prime number which is slightly smaller than the Table Size.

or
X is the Key or the Number for which the hashing is done
.p
4.12.3 Double Hashing Example - Closed Hash Table
➢ Let us consider the same example in which we choose R = 7.
w
w
w

A Closed Hash Table using Double Hashing


C Programming and Data Structures 4.43
https://www.poriyaan.in/ https://eee.poriyaan.in/
Key Hash Function h(X) Index Collision At Index
79 h0(79)=(Hash(79)+F(0))% 10 9
= ((79 % 10) + 0) % 10 = 9
28 h0(28)=(Hash(28)+F(0))% 10 8
= ((28 % 10) + 0) % 10 = 8

in
39 h0(39)=(Hash(39)+F(0))% 10 9 First collision

n.
= ((39 % 10) + 0) % 10 = 9 occurs

aa
h1(39)=(Hash(39)+F(1))%10 2 2
=((39% 10)+1(7-(39 % 7))) % 10

iy
= (9 + 3) % 10 =12 % 10=2
68 or
h0(68) = (Hash (68) + F(0)) % 10
= ((68 % 10) + 0) % 10 = 8
8 collision
occurs
.p
h1(68) =(Hash(68) +F(1)) % 10 0 0
w

= ((68 % 10) +1(7-(68 % 7))) % 10


= (8 + 2) % 10 =10 % 10=0
w

89 h0(89) =(Hash(89) + F(0)) % 10 9 Collision


w

= ((89 % 10) + 0) % 10 = 9 occurs

h1(89) = (Hash(89) + F(1)) % 10 0 Again


= ((89 % 10) + 1(7-(89 % 7))) % 10 collision
= (9 + 2) % 10 =10 % 10 =0 occurs
h2(89) = (Hash(89) + F(2)) % 10 3 3
= ((89 % 10) + 2(7-(89 % 7))) % 10
= (9 + 4) % 10=13 % 10 =3

➢ The problem with linear probing is primary clustering. This means that even if the
table is empty, any key that hashes to table requires several attempt to resolve the
collision because it has to cross over the blocks of occupied cell.
➢ These blocks of occupied cell form the primary clustering. If any key falls into
clustering, then we cannot predict the number of attempts needed to resolve the
4.44 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
4.13 RE-HASHING
➢ Rehashing is the process of re-calculating the hashcode of already stored entries
(Key-Value pairs), to move them to another bigger size hashmap when the
threshold is reached/crossed.

4.13.1 Why Rehashing is done?

in
➢ Rehashing is done because whenever a new key value pair is inserted into map,
the load factor increases and due to which complexity also increases. And if

n.
complexity increases our HashMap will not have constant O(1) time complexity.

aa
➢ Hence rehashing is done to distribute the items across the hashmap as to reduce
both laod factor and complexity, So that get() and put() have constant time

iy
complexity of O(1).
➢ After rehashing is done existing items may fall in the same bucket or different
bucket.
or
.p
4.13.2 What is Load factor in HashMap?
➢ Load factor in HashMap is basically a measure that decides when exactly to
w

increase the size of the HashMap to maintain the same time complexity of O(1).
w

➢ Load factor is defined as (m/n) where n is the total size of the hash table and m is
w

the preferred number of entries which can be inserted before an increment in the
size of the underlying data structure is required.
➢ If you are going to store really large no of elements in the hashmap then it is
always good to create HashMap with sufficient capacity upfront as rehashing will
not be done frequently, this is more efficient than letting it to perform automatic
rehashing.

4.13.3 How Rehashing is Done?


➢ Let’s try to understand the above with an example: Say we had HashTable with
Initial Capacity of 4. We need to insert 4 Keys: 100, 101, 102, 103
➢ Hash function used was division method: Key % ArraySize
➢ Element1: Hash(100) = 100%6 = 4, so Element1 will be rehashed and will be
stored at 5th Index in this newly resized HashTable, instead of 1st Index as on
previous HashTable.
C Programming and Data Structures 4.45
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Element2: Hash(101) = 101%6 = 5, so Element2 will be rehashed and will be
stored at 6th Index in this newly resized HashTable, instead of 2nd Index as on
previous HashTable.
➢ Element3: Hash(102) = 102%6 = 6, so Element3 will be rehashed and will be
stored at 4th Index in this newly resized HashTable, instead of 3rd Index as on

in
previous HashTable.
➢ Since the Load Balance now is 3/6 = 0.5, we can still insert the 4th element now.

n.
➢ Element4: Hash(103) = 103%6 = 1, so Element4 will be stored at 1st Index in this

aa
newly resized HashTable.

4.13.4 Rehashing Steps

iy
➢ For each addition of a new entry to the map, check the current load factor.
or
➢ If it’s greater than its pre-defined value, then Rehash.
➢ For Rehash, make a new array of double the previous size and make it the new
.p
bucket array.
w

➢ Then traverse to each element in the old bucketArray and insert them back so as
to insert it into the new larger bucket array.
w

➢ If you are going to store a really large number of elements in the HashTable then
w

it is always good to create a HashTable with sufficient capacity upfront as this is


more efficient than letting it perform automatic rehashing.
4.46 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
REVIEW QUESTIONS
PART A
1. Define binary tree?
➢ A binary tree is a tree data structure composed of nodes, each of which has
utmost, two children, referred to as left and right nodes. The tree starts off with

in
a single node known as the root.

n.
2. What are the two methods of binary tree implementation?
➢ Linear representation.

aa
➢ Linked representation

iy
3. What are the applications of binary tree?
➢ Binary tree is used in data processing.
o File index schemes
or
.p
o Hierarchical database management system
4. List out few of the Application of tree data-structure?
w

➢ The manipulation of Arithmetic expression


w

➢ Used for Searching Operation


w

➢ Used to implement the file system of several popular operating systems


➢ Symbol Table construction
➢ Syntax analysis
5. Define expression tree?
➢ Expression tree is also a binary tree in which the leaf’s terminal nodes or
operands and non-terminal intermediate nodes are operators used for traversal.
6. Define tree– traversal and mention the type of traversals?
➢ Three types of tree traversal
• Inorder traversal
• Preoder traversal
• Postorder traversal.
7. Define in -order traversal?
C Programming and Data Structures 4.47
https://www.poriyaan.in/ https://eee.poriyaan.in/
• Traverse the left subtree
• Visit the root node
• Traverse the right subtree
8. What is pre-order traversal?
➢ In preorder traversal, first, root node is visited, then left sub-tree and after that

in
right sub-tree is visited. The process of preorder traversal can be represented as:
root → left → right

n.
9. Define threaded binary tree.

aa
➢ A binary tree is threaded by making all right child pointers that would normally
be null point to the in order successor of the node, and all left child pointers that

iy
would normally be null point to the in-order predecessor of the node.
or
10. What are the types of threaded binary tree?
➢ Right-in threaded binary tree
.p
➢ Left-in threaded binary tree
➢ Fully-in threaded binary tree
w

11. Define Binary Search Tree.


w

➢ Binary search tree is a binary tree in which for every node X in the tree, the
w

values of all the keys in its left subtree are smaller than the key value in X and
the values of all the keys in its right subtree are larger than the key value in X.
12. What is AVL Tree?
➢ AVL stands for Adelson-Velskii and Landis. An AVL tree is a binary search tree
which has the following properties:
• The sub-trees of every node differ in height by at most one.
• Every sub-tree is an AVL tree.
13. List out the steps involved in deleting a node from a binary search tree.
➢ Deleting a node is a leaf node (ie) No children
➢ Deleting a node with one child.
➢ Deleting a node with two Childs.
14. Define complete binary tree.
➢ If all its levels, possible except the last, have maximum number of nodes and if
4.48 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
15. Write short notes on Expression Trees.
➢ A binary expression tree is a specific kind of a binary tree used to represent
expressions.
➢ Two common types of expressions that a binary expression tree can represent
are algebraic and boolean. These trees can represent expressions that contain

in
both unary and binary operators.
16. What is Hashing?

n.
➢ Hashing is a technique of mapping a large chunk of data into small tables using

aa
a hashing function. It is also known as the message digest function. It is a
technique that uniquely identifies a specific item from a collection of similar
items.

iy
17. What is Hash Function?
or
➢ A hash function is a function that takes a set of inputs of any arbitrary size and
fits them into a table or other data structure that contains fixed-size elements.
.p
18. List the advantages of hashing in data structure
w

➢ Hash provides better synchronization than other data structures. Hash tables are
w

more efficient than search trees or other data structures. Hash provides constant
time for searching, insertion and deletion operations on average.
w

19. What is separate chaining?


➢ Separate Chaining is one of the techniques that is used to resolve the collision.
It is implemented using linked lists.
➢ This method combines a linked list with a hash table in order to resolve the
collision. In this method, we put all the elements that hash to the same slot in the
linked list.
20. What is open addressing in hashing?
➢ In open addressing,
• Unlike separate chaining, all the keys are stored inside the hash table.
• No key is stored outside the hash table.
21. List the techniques used in open addressing.
➢ Linear Probing
C Programming and Data Structures 4.49
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Double Hashing
22. What is Linear Probing?
➢ Linear probing is a scheme in computer programming for resolving collisions in
hash tables, data structures for maintaining a collection of key–value pairs and
looking up the value associated with a given key.

in
23. Write short notes on Quadratic Probing?
➢ Quadratic probing is an open addressing scheme in computer programming for

n.
resolving hash collisions in hash tables.

aa
➢ Quadratic probing operates by taking the original hash index and adding
successive values of an arbitrary quadratic polynomial until an open slot is

iy
found.
24. Explain about Double Hashing.
or
➢ Double hashing is a collision resolving technique in Open Addressed Hash
.p
tables. Double hashing uses the idea of applying a second hash function to key
when a collision occurs.
w

25. What is rehashing in data structure?


w

➢ Rehashing is a technique in which the table is resized, i.e., the size of table is
doubled by creating a new table.
w

26. List the advantages of Double hashing


➢ The advantage of Double hashing is that it is one of the best form of probing,
producing a uniform distribution of records throughout a hash table.
➢ This technique does not yield any clusters.
➢ It is one of effective method for resolving collisions.
4.50 Non – Linear Data Structures
https://www.poriyaan.in/ https://eee.poriyaan.in/
PART-B

1. Explain the tree traversal techniques with an example.


2. Construct an expression tree for the expression (a+b*c) + ((d*e+f)*g). Give the
outputs when you apply inorder, preorder and postorder traversals.

in
3. How to insert and delete an element into a binary search tree and write down the code

n.
for the insertion routine with an example.
4. Create a binary search tree for the following numbers start from an empty binary

aa
search tree. 45,26,10,60,70,30,40 Delete keys 10, 60 and 45 one after the other and
show the trees at each stage.

iy
5. Explain Open Addressing techniques in detail.
6. or
Find the In-order, Pre-order, and Post-order for the given tree below
.p
w
w
w
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
SORTING AND SEARCHING TECHNIQUES

aa
Insertion Sort – Quick Sort – Heap Sort – Merge Sort –Linear Search – Binary Search

iy
5.1 INTRODUCTION TO SORTING
or
.p
➢ Sorting is the process of arranging the elements of an array so that they can be
placed either in ascending or descending order. Efficient sorting is important to
w

optimizing the use of other algorithms that require sorted lists to work correctly
w

and for producing human – read able input


For example,
w
5.2 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
There are many techniques by using which, sorting can be performed
Sorting
Sl. No. Description
Algorithms
Insertion sort inserts each element of the array to its
1 Insertion Sort proper place. It is a very simple sort method which is used

in
to arrange the deck of cards while playing bridge
Quick sort follows the divide and conquer approach in

n.
which the algorithm is breaking down into sub problems,
2 Quick Sort

aa
then solving the sub problems, and combining the results
back together to solve the original problem.

iy
In the heap sort, Min heap or max heap is maintained
from the array elements depending upon the choice and
3 Heap Sort or
the elements are sorted by deleting the root element of the
heap.
.p
Merge sort follows divide and conquer approach in
w

which, the list is first divided into the sets of equal


4 Merge Sort elements and then each half of the list is sorted by using
w

merge sort. The sorted list is combined again to form an


w

elementary sorted array

5.2. INSERTION SORT


➢ Insertion sort is a simple sorting algorithm.
➢ This sorting method sorts the array by shifting elements one by one.
➢ It builds the final sorted array one item at a time.
➢ Insertion sort has one of the simplest implementation.
➢ This sort is efficient for smaller data sets but it is insufficient for larger lists.
➢ It has less space complexity like bubble sort.
➢ It requires single additional memory space.
➢ Insertion sort does not change the relative order of elements with equal keys
because it is stable.
C Programming and Data Structures 5.3
https://www.poriyaan.in/ https://eee.poriyaan.in/
5.2.1 Algorithm:
Step 1 − If the element is the first one, it is already sorted.
Step 2 – Move to next element
Step 3 − Compare the current element with all elements in the sorted array
Step 4 – If the element in the sorted array is smaller than the current element, iterate to

in
the next element. Otherwise, shift all the greater element in the array by one

n.
position towards right
Step 5 − Insert the value at the correct position

aa
Step 6 − Repeat until the complete list is sorted
5.2.2 Working of Insertion sort Algorithm

iy
Consider an unsorted array of elements 40, 10, 9, 20, 30, 50
or
.p
w
w
w

➢ The above steps represents how insertion sort works. Insertion sort works like the
way we sort playing cards in our hands. It always starts with the second element
as key. The key is compared with the elements ahead of it and is put it in the right
place.
5.4 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ At the first step, 40 has nothing before it. Element 10 is compared to 40 and is
inserted before 40. Element 9 is smaller than 40 and 10, so it is inserted before 10
and this operation continues until the array is sorted in ascending order.
5.2.3 Analysis of Insertion Sort:
Time Complexity

in
Best O(n)

n.
Worst O(n2)
Average O(n2)

aa
Space Complexity O(1)

iy
Stability Yes

5.2.4 Applications
or
.p
➢ The insertion sort is used when:
• The array is has a small number of elements
w

• There are only a few elements left to be sorted


w

Example Program 5.1


w

#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
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]);
}
for (c = 1 ; c <= n - 1; c++)
C Programming and Data Structures 5.5
https://www.poriyaan.in/ https://eee.poriyaan.in/
d = c;
while ( d > 0 && array[d] < array[d-1])
{
t = array[d];
array[d] = array[d-1];

in
array[d-1] = t;

n.
d--;

aa
}
}

iy
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) or
{
.p
printf("%d\n", array[c]);
}
w

return 0;
w

}
w

Output
Enter the number of elements
5
Enter 5 integers
40
30
20
10
40
Sorted list in ascending order
10
20
5.6 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
40
40

5.3 QUICK SORT


➢ Quick sort is also known as Partition-exchange sort based on the rule of Divide

in
and Conquer.
➢ It is a highly efficient sorting algorithm.

n.
➢ Quick sort is the quickest comparison-based sorting algorithm.

aa
➢ It is very fast and requires less additional space, only O(n log n) space is required.
➢ Quick sort picks an element as pivot and partitions the array around the picked

iy
pivot.

5.3.1 Algorithm for Quick Sort: or


Step 1: Choose the highest index value as pivot.
.p
Step 2: Take two variables to point left and right of the list excluding pivot.
w

Step 3: Left points to the low index.


w

Step 4: Right points to the high index.


Step 5: While value at left < (Less than) pivot move right.
w

Step 6: While value at right > (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 = (Less than or Equal to) right, the point where they met is new pivot.

5.3.2 Working of Quick sort Algorithm


Consider an unsorted array as follows
36, 34, 43, 11, 15, 20, 28, 45, 27, 32
➢ The following steps represents how to find the pivot value in an array. As we see,
pivot value divides the list into two parts (partitions) and then each part is
processed for quick sort. Quick sort is a recursive function. We can call the
partition function again.
C Programming and Data Structures 5.7
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
iy
or
.p
w
w
w
5.8 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
5.3.3 Quicksort Complexity
Time Complexity
Best O(n*log n)
Worst O(n2)

in
Average O(n*log n)
Space Complexity O(log n)

n.
Stability No

aa
5.3.4 Applications of quick sort:

iy
Quicksort algorithm is used when
➢ the programming language is good for recursion
or
➢ time complexity matters
.p
➢ space complexity matters
w

Example Program 5.2: Program for implementing Quick Sort


w

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

//quick Sort function to Sort Integer array list


void quicksort(int array[], int firstIndex, int lastIndex)
{
//declaaring index variables
int pivotIndex, temp, index1, index2;
if(firstIndex < lastIndex)
{
//assigninh first element index as pivot element
pivotIndex = firstIndex;
index1 = firstIndex;
index2 = lastIndex;
//Sorting in Ascending order with quick sort
C Programming and Data Structures 5.9
https://www.poriyaan.in/ https://eee.poriyaan.in/
while(index1 < index2)
{
while(array[index1] <= array[pivotIndex] && index1 < lastIndex)
{
index1++;

in
}

n.
while(array[index2]>array[pivotIndex])

aa
{
index2--;

iy
}
if(index1<index2) or
{
.p
//Swapping opertation
temp = array[index1];
w

array[index1] = array[index2];
w

array[index2] = temp;
w

}
}
//At the end of first iteration, swap pivot element with index2 element
temp = array[pivotIndex];
array[pivotIndex] = array[index2];
array[index2] = temp;
//Recursive call for quick sort, with partiontioning
quicksort(array, firstIndex, index2-1);
quicksort(array, index2+1, lastIndex);
}
}
int main()
5.10 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
//Declaring variables
int array[100],n,i;
//Number of elements in array form user input
printf("Enter the number of element you want to Sort : ");
scanf("%d",&n);

in
//code to ask to enter elements from user equal to n

n.
printf("Enter Elements in the list : ");

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

iy
scanf("%d",&array[i]);
} or
//calling quickSort function defined above
.p
quicksort(array,0,n-1);
//print sorted array
w

printf("Sorted elements: ");


w

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

printf(" %d",array[i]);
getch();
return 0;
}
Output
Enter the number of element you want to sort: 5
Enter the elements in the list:
7
10
3
21
15
C Programming and Data Structures 5.11
https://www.poriyaan.in/ https://eee.poriyaan.in/
5.4 HEAP SORT
➢ Heap sort is a comparison based sorting algorithm.
➢ It is a special tree-based data structure.
➢ Heap sort processes the elements by creating the min-heap or max-heap using the
elements of the given array

in
➢ Min-heap or max-heap represents the ordering of array in which the root element

n.
represents the minimum or maximum element of the array

aa
➢ Heap sort basically recursively performs two main operations
• Build a heap H, using the elements of array.

iy
• Repeatedly delete the root element of the heap formed in 1st phase.

5.4.1 What is a heap? or


➢ A heap is a complete binary tree, and the binary tree is a tree in which the node
.p
can have the utmost two children. A complete binary tree is a binary tree in which
w

all the levels except the last level, i.e., leaf node, should be completely filled, and
all the nodes should be left-justified.
w

5.4.2 Working of Heap sort Algorithm


w

➢ In heap sort, basically, there are two phases involved in the sorting of elements.
By using the heap sort algorithm, they are as follows:
➢ The first step includes the creation of a heap by adjusting the elements of the array.
➢ After the creation of heap, now remove the root element of the heap repeatedly by
shifting it to the end of the array, and then store the heap structure with the
remaining elements.
Consider an unsorted array as follows
81, 89, 9, 11, 14, 76, 54, 22
Given array is

First, construct a heap from the given array and convert it into max heap
5.12 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
After converting the given heap into max heap, the array elements are

iy
or
➢ Next step is to delete the root element (89) from the max heap. To delete this node,
.p
swap it with the last node, i.e. (11). After deleting the root element, again heapify
w

it to convert it into max heap.


w
w

➢ After swapping the array element 89 with 11, and converting the heap into max-
heap, the elements of array are

➢ In the next step, again delete the root element (81) from the max heap. To delete
this node, swap it with the last node, i.e. (54). After deleting the root element,
C Programming and Data Structures 5.13
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
➢ After swapping the array element 81 with 54 and converting the heap into max-
heap, the elements of array are

iy
or
.p
➢ In the next step, delete the root element (76) from the max heap again. To delete
this node, swap it with the last node, i.e. (9). After deleting the root element, again
w

heapify it to convert it into max heap.


w
w

➢ After swapping the array element 76 with 9 and converting the heap into max-
heap, the elements of array are

➢ In the next step, again delete the root element (54) from the max heap. To delete
this node, swap it with the last node, i.e. (14). After deleting the root element,
5.14 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
aa
➢ After swapping the array element 54 with 14 and converting the heap into max-

iy
heap, the elements of array are

or
.p
➢ In the next step, again delete the root element (22) from the max heap. To delete
this node, swap it with the last node, i.e. (11). After deleting the root element,
w

again heapify it to convert it into max heap.


w
w

➢ After swapping the array element 22 with 11 and converting the heap into max-
heap, the elements of array are

➢ In the next step, again delete the root element (14) from the max heap. To delete
this node, swap it with the last node, i.e. (9). After deleting the root element, again
heapify it to convert it into max heap.
C Programming and Data Structures 5.15
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
➢ After swapping the array element 14 with 9 and converting the heap into max-
heap, the elements of array are

aa
iy
➢ In the next step, again delete the root element (11) from the max heap. To delete
or
this node, swap it with the last node, i.e. (9). After deleting the root element, again
heapify it to convert it into max heap.
.p
w
w
w

➢ After swapping the array element 11 with 9, the elements of array are

➢ Now, heap has only one element left. After deleting it, heap will be empty.

➢ After completion of sorting, the array elements are

Now, the array is completely sorted


5.16 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
5.4.3 Heapsort Complexity:
Time Complexity
Best O(n log n)
Worst O(n log n)

in
Average O(n log n)
Space Complexity O(1)

n.
Stability No

aa
5.4.4 Heap Sort Applications:

iy
➢ Systems concerned with security and embedded systems such as Linux Kernel use
Heap Sort. or
➢ Because of the O(n log n) upper bound on Heapsort's running time and constant
.p
O(1) upper bound on its auxiliary storage.
w

➢ Although Heap Sort has O(n log n) time complexity even for the worst case, it
doesn't have more applications ( compared to other sorting algorithms like Quick
w

Sort, Merge Sort ).


w

Example Program 5.3: Program for implementing Heap Sort


#include <stdio.h>
/* function to heapify a subtree. Here 'i' is the
index of root node in array a[], and 'n' is the size of heap. */
void heapify(int a[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
int right = 2 * i + 2; // right child
// If left child is larger than root
if (left < n && a[left] > a[largest])
largest = left;
C Programming and Data Structures 5.17
https://www.poriyaan.in/ https://eee.poriyaan.in/
// If right child is larger than root
if (right < n && a[right] > a[largest])
largest = right;
// If root is not largest
if (largest != i) {

in
// swap a[i] with a[largest]

n.
int temp = a[i];

aa
a[i] = a[largest];
a[largest] = temp;

iy
heapify(a, n, largest); or
}
.p
}
/*Function to implement the heap sort*/
w

void heapSort(int a[], int n)


w

{
w

for (int i = n / 2 - 1; i >= 0; i--)


heapify(a, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/
// swap a[0] with a[i]
int temp = a[0];
a[0] = a[i];
a[i] = temp;
heapify(a, i, 0);
}
}
5.18 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
void printArr(int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d", arr[i]);

in
printf(" ");

n.
}

aa
}
int main()

iy
{
int a[] = {42, 8, 26, 39, 28, 23, 7};
or
int n = sizeof(a) / sizeof(a[0]);
.p
printf("Before sorting array elements are - \n");
printArr(a, n);
w

heapSort(a, n);
w

printf("\nAfter sorting array elements are - \n");


w

printArr(a, n);
return 0;
}
Output
Before sorting array elements are
42, 8, 26, 39, 28, 23, 7
After sorting array elements are
7, 8, 23, 26, 28, 39, 42

5.5 MERGE SORT


➢ Merge sort is a sorting technique based on divide and conquer technique.
➢ With worst-case time complexity being Ο(n log n), it is one of the most respected
algorithms.
C Programming and Data Structures 5.19
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Merge sort first divides the array into equal halves and then combines them in a
sorted manner

5.5.1 Algorithm
➢ Merge sort keeps on dividing the list into equal halves until it can no more be
divided. By definition, if it is only one element in the list, it is sorted. Then, merge

in
sort combines the smaller sorted lists keeping the new list sorted too

n.
Step 1 − if it is only one element in the list it is already sorted, return.
Step 2 − divide the list recursively into two halves until it can no more be divided.

aa
Step 3 − merge the smaller lists into new list in sorted order.

iy
5.5.2 Working of Merge sort Algorithm
Consider an unsorted array elements12, 31, 25, 8, 32, 17, 40 and 42
Let the elements of array are
or
.p
w

First divide the given array into two equal halves. Merge sort keeps dividing the
w

list into equal parts until it cannot be further divided.


w

As there are eight elements in the given array, so it is divided into two arrays of
size 4.

Now, again divide these two arrays into halves. As they are of size 4, so divide
them into new arrays of size 2.

Now, again divide these arrays to get the atomic value that cannot be further
divided.
5.20 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
Now, combine them in the same manner they were broken. First compare the
element of each array and then combine them into another array in sorted order.
So, first compare 12 and 31, both are in sorted positions. Then compare 25 and 8,
and in the list of two values, put 8 first followed by 25. Then compare 32 and 17, sort
them and put 17 first followed by 32. After that, compare 40 and 42, and place them
sequentially.

in
n.
aa
In the next iteration of combining, now compare the arrays with two data values
and merge them into an array of found values in sorted order.

iy
or
.p
Now, there is a final merging of the arrays. After the final merging of above
arrays, the array will look like
w
w
w

5.5.3 Merge sort complexity


Time Complexity
Best O(n*log n)
Worst O(n*logn)
Average O(n*logn)
Space Complexity O(n)
Stability YES

5.5.4 Merge Sort Applications


➢ Inversion count problem
➢ External sorting
C Programming and Data Structures 5.21
https://www.poriyaan.in/ https://eee.poriyaan.in/
Example Program 5.4: Program for implementing Merge Sort
#include <stdio.h>
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end)
{

in
int i, j, k;

n.
int n1 = mid - beg + 1;

aa
int n2 = end - mid;
int LeftArray[n1], RightArray[n2]; //temporary arrays

iy
/* copy data to temp arrays */
for (int i = 0; i < n1; i++)
or
LeftArray[i] = a[beg + i];
.p
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];
w

i = 0; /* initial index of first sub-array */


w

j = 0; /* initial index of second sub-array */


w

k = beg; /* initial index of merged sub-array */


while (i < n1 && j < n2)
{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
5.22 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];

in
i++;

n.
k++;

aa
}
while (j<n2)

iy
{
a[k] = RightArray[j]; or
j++;
.p
k++;
}
w

}
w

void mergeSort(int a[], int beg, int end)


w

{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
/* Function to print the array */
void printArray(int a[], int n)
{
C Programming and Data Structures 5.23
https://www.poriyaan.in/ https://eee.poriyaan.in/
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}

in
int main()
{

n.
int a[] = { 10, 35, 23, 5, 31, 19, 40, 43 };

aa
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");

iy
printArray(a, n);
mergeSort(a, 0, n - 1);
or
.p
printf("After sorting array elements are - \n");
w

printArray(a, n);
w

return 0;
}
w

Output
Before sorting array elements are
10, 35, 23, 5, 31, 19, 40, 43
After sorting array elements are
5, 10, 19, 23, 31, 35, 40, 43

5.6 INTRODUCTION TO SEARCHING


➢ Searching in data structure refers to the process of finding the required
information from a collection of items stored as elements in the computer
memory.
➢ These sets of items are in different forms, such as an array, linked list, graph, or
tree. Another way to define searching in the data structures is by locating the
5.24 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
5.6.1 Searching Methods
➢ Searching in the data structure can be done by applying searching algorithms to
check for or extract an element from any form of stored data structure. These
algorithms are classified according to the type of search operation they perform,
such as:

in
➢ Sequential search - The list or array of elements is traversed sequentially while
checking every component of the set. For example – Linear Search.

n.
➢ Interval Search - The interval search includes algorithms that are explicitly

aa
designed for searching in sorted data structures. In terms of efficiency, these
algorithms are far better than linear search algorithms. Example- Logarithmic

iy
Search, Binary search.
These methods are evaluated based on the time taken by an algorithm to search
or
an element matching the search item in the data collections and are given by,
.p
➢ The best possible time
➢ The average time
w

➢ The worst-case time


w

The primary concerns are with worst-case times, which provide guaranteed
w

predictions of the algorithm’s performance and are also easier to calculate than average
times.

5.7 LINEAR SEARCH


➢ Linear search is also called as sequential search algorithm.
➢ It is the simplest searching algorithm.
➢ In Linear search, we simply traverse the list completely and match each element
of the list with the item whose location is to be found.
➢ If the match is found, then the location of the item is returned; otherwise, the
algorithm returns NULL.
➢ It is widely used to search an element from the unordered list, i.e., the list in which
items are not sorted.
➢ The worst-case time complexity of linear search is O (n).
C Programming and Data Structures 5.25
https://www.poriyaan.in/ https://eee.poriyaan.in/
5.7.1 Steps used in the implementation of Linear Search
➢ First, we have to traverse the array elements using for loop.
➢ In each iteration of for loop, compare the search element with the current array
element, and
• If the element matches, then return the index of the corresponding array

in
element.

n.
• If the element does not match, then move to the next element.
➢ If there is no match or the search element is not present in the given array, return

aa
-1.

5.7.2 Algorithm

iy
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val'
is the value to search
or
.p
Step 1: set pos = -1
Step 2: set i = 1
w

Step 3: repeat step 4 while i <= n


w

Step 4: if a[i] == val


w

set pos = i
print pos
go to step 6
[end of if]
set ii = i + 1
[end of loop]
Step 5: if pos = -1
print "value is not present in the array "
[end of if]
Step 6: exit

5.7.3 Working of Linear search


Consider an array of elements 70, 40, 30, 11, 57, 41, 25, 14, 52
5.26 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/

Let the element to be searched is K = 41


Now, start from the first element and compare K with each element of the array.

in
n.
aa
The value of K, i.e., 41, is not matched with the first element of the array. So, move to

iy
the next element. And follow the same process until the respective element is found.
or
.p
w
w
w
C Programming and Data Structures 5.27
https://www.poriyaan.in/ https://eee.poriyaan.in/
Now, the element to be searched is found. So algorithm will return the index of
the element matched.

5.7.4 Linear Search complexity


Time Complexity
Best O(1)

in
Worst O(n)

n.
Average O(n)

aa
Space Complexity O(1)

5.7.5 Applications of Linear Search Algorithm

iy
➢ Linear search can be applied to both single-dimensional and multi-dimensional
arrays. or
➢ Linear search is easy to implement and effective when the array contains only a
.p
few elements.
w

➢ Linear Search is also efficient when the search is performed to fetch a single
w

search in an unordered-List.
5.7.6 Advantages and Disadvantages
w

Sl. No. Advantages Disadvantages


Will perform fast searches of Time consuming for the enormous
1.
small to medium lists arrays.
2. The list does not need to sorted Slow searching of big lists
Not affected by insertions and A key element doesn't matches any
3. deletions element then Linear search algorithm is
a worst case

Example Program 5.5: Program for Implementation of Linear Search


#include <stdio.h>
int linearSearch(int a[], int n, int val) {
// Going through array sequencially
for (int i = 0; i < n; i++)
5.28 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
{
if (a[i] == val)
return i+1;
}
return -1;

in
}

n.
int main() {

aa
int a[] = {59, 40, 33, 11, 57, 41, 27, 18, 53}; // given array
int val = 41; // value to be searched

iy
int n = sizeof(a) / sizeof(a[0]); // size of array
int res = linearSearch(a, n, val); // Store result
or
printf("The elements of the array are - ");
.p
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
w

printf("\nElement to be searched is - %d", val);


w

if (res == -1)
w

printf("\nElement is not present in the array");


else
printf("\nElement is present at %d position of array", res);
return 0;
}
Output
The elements of the array are - 59, 40, 33, 11, 57, 41, 27, 18, 53
Element to be searched is – 41
Element is present at 6 position of array

5.8 BINARY SEARCH


➢ Binary search is the search technique that works efficiently on sorted lists.
➢ Hence, to search an element into some list using the binary search technique, we
C Programming and Data Structures 5.29
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ Binary search follows the divide and conquer approach in which the list is divided
into two halves, and the item is compared with the middle element of the list.
➢ If the match is found then, the location of the middle element is returned.
➢ Otherwise, we search into either of the halves depending upon the result produced
through the match.

in
5.8.1 Algorithm

n.
Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array,
'lower_bound' is the index of the first array element, 'upper_bound' is the index of the last

aa
array element, 'val' is the value to search
Step 1: set beg = lower_bound, end = upper_bound, pos = - 1

iy
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
or
.p
set pos = mid
w

print pos
w

go to step 6
else if a[mid] > val
w

set end = mid - 1


else
set beg = mid + 1
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit

5.8.2 Working of Binary search


➢ To understand the working of the Binary search algorithm, let's take a sorted array.
It will be easy to understand the working of Binary search with an example.
5.30 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
➢ There are two methods to implement the binary search algorithm -
• Iterative method
• Recursive method
The recursive method of binary search follows the divide and conquer approach
Consider an array of elements 10, 12, 24, 29, 39, 40, 51, 56, 69

in
Let the elements of array are

n.
aa
iy
Let the element to search is, K = 56
or
Use the below formula to calculate the mid of the array
mid = (beg + end)/2
.p
In the given array beg = 0, end = 8. So mid = (0+8)/2 = 4
w
w
w
C Programming and Data Structures 5.31
https://www.poriyaan.in/ https://eee.poriyaan.in/

in
n.
Now, the element to search is found. So algorithm will return the index of the

aa
element matched.
5.8.3 Binary Search complexity:

iy
Time Complexity
Best
or O(1)
.p
Worst O(logn)
w

Average O(logn)
w

Space Complexity O(1)


w

5.8.4 Advantages and Disadvantages


Sl. No. Advantages Disadvantages
1. It is a much faster algorithm It can be used only when data is sorted
It works on the divide and It is more complicated
2.
conquers principle
It is efficient If random access is not supported then
3.
efficiency might be lost
It is a simple algorithm to It can be implemented only for two-way
4.
understand transversal data structures

Example Program 5.6: Program for implementation of Binary Search


#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
5.32 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at middle */
if(a[mid] == val)

in
{

n.
return mid+1;

aa
}
/* if the item to be searched is smaller than middle, then it can only be in
left subarray*/

iy
else if(a[mid] < val)
{
or
.p
return binarySearch(a, mid+1, end, val);
}
w

/* if the item to be searched is greater than middle, then it can only be in


w

right subarray*/
w

else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
int main() {
int a[] = {21, 14, 35, 30, 40, 51, 55, 57, 70}; // given array
int val = 40; // value to be searched
int n = sizeof(a) / sizeof(a[0]); // size of array
int res = binarySearch(a, 0, n-1, val); // Store result
C Programming and Data Structures 5.33
https://www.poriyaan.in/ https://eee.poriyaan.in/
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");

in
else

n.
printf("\nElement is present at %d position of array", res);

aa
return 0;
}

iy
Output
The elements of the array are - 21, 14, 35, 30, 40, 51, 55, 57, 70
or
Element to be searched is – 40
.p
Element is present at 5 position of array
w

5.8.5 Linear Search vs Binary Search


w

Sl.
Linear Search Binary Search
No.
w

In linear search input data need not In binary search input data need to be in
1.
to be in sorted. sorted order.
2. It is also called sequential search. It is also called half-interval search.
It is preferable for the small-sized It is preferable for the large-size data sets.
3.
data sets.
The time complexity of linear The time complexity of binary search
4.
search O(n). O(log n).
Multidimensional array can be Only single dimensional array is used.
5.
used.
Linear search performs equality Binary search performs ordering
6.
comparisons comparisons
7. It is less complex. It is more complex.
8. It is very slow process. It is very fast process
5.34 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
REVIEW QUESTIONS
PART A
1. What is sorting?
➢ Sorting refers to arranging data in a particular format. Sorting algorithm specifies
the way to arrange data in a particular order.

in
2. Define insertion sort?

n.
➢ Successive element in the array to be sorted and inserted into its proper place
with respect to the other already sorted element. We start with second element

aa
and put it in its correct place, so that the first and second elements of the array
are in order.

iy
3. Write short notes on quick sort.
or
➢ Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot'
element from the array and partitioning the other elements into two sub-arrays,
.p
according to whether they are less than or greater than the pivot. For this reason,
it is sometimes called partition-exchange sort.
w

4. What is Time Complexity for Quick Sort?


w
w

5. What is Merge sort?


➢ The Merge Sort function repeatedly divides the array into two halves until we
reach a stage where we try to perform Merge Sort on a subarray of size 1
6. What is Time Complexity for Merge Sort?
➢ Merge Sort is an efficient, stable sorting algorithm with an average, best-case,
and worst-case time complexity of O(n log n).
7. What is Linear Search?
➢ The Linear search algorithm works by sequentially iterating through the whole
array or list from one end until the target element is found.
➢ If the element is found, it returns its index, else -1.
C Programming and Data Structures 5.35
https://www.poriyaan.in/ https://eee.poriyaan.in/
8. What is binary Search?
➢ Binary search follows the divide and conquer approach in which the list is
divided into two halves, and the item is compared with the middle element of
the list. If the match is found then, the location of the middle element is returned.
Otherwise, we search into either of the halves depending upon the result
produced through the match.

in
➢ Binary search can be implemented only on a sorted list of items. If the elements

n.
are not sorted already, we need to sort them first.

aa
9. What is Heap Sort?
➢ Heap sort is a comparison-based sorting technique based on Binary Heap data
structure.

iy
➢ It is like the selection sort where we first find the minimum element and place
or
the minimum element at the beginning. Repeat the same process for the
remaining elements.
.p
10. What is Time Complexity for Heap Sort?
w

➢ The time complexity for Heap sort in average, best-case, and worst-case
time complexity of O(n log n).
w

11. What is Time Complexity for Insertion Sort?


w

Algorithm Best Case Average Case Worst Case


Insertion Sort O(n) O(n2) O(n2)

12. Why quick sort is preferred for arrays and merge sort for linked lists?
➢ Quick sort is an in-place sorting algorithm, i.e. which means it does not require
any additional space, whereas Merge sort does, which can be rather costly. In
merge sort, the allocation and deallocation of the excess space increase the
execution time of the algorithm.
➢ Unlike arrays, in linked lists, we can insert elements in the middle in O(1) extra
space and O(1) time complexities if we are given a reference/pointer to the
previous node. As a result, we can implement the merge operation in the merge
sort without using any additional space.
13. In which case insertion sort is used?
➢ Insertion sort has a fast best-case running time and is a good sorting algorithm
5.36 Sorting and Searching Techniques
https://www.poriyaan.in/ https://eee.poriyaan.in/
14. What is the advantage of using Quick sort algorithm?
➢ Quick sort reduces unnecessary swaps and moves an item to a greater distance,
in one move.
15. Mention the various types of searching techniques in C.
➢ Linear search

in
➢ Binary search

n.
16. Define Searching.
➢ Searching in data structure refers to the process of finding the required

aa
information from a collection of items stored as elements in the computer
memory.

iy
➢ These sets of items are in different forms, such as an array, linked list, graph, or
tree. or
17. Compare Quick sort and Merge Sort.
.p
Basis for comparison Quick Sort Merge Sort
w

Efficiency Inefficient for larger arrays More efficient


Sorting method Internal External
w

Stability Not Stable Stable


w

Preferred for for Arrays for Linked Lists

18. Mention the different ways to select a pivot element.


o Pick the first element as pivot
o Pick the last element as pivot
o Pick the Middle element as pivot
o Median-of-three elements
o Pick three elements, and find the median x of these elements
o Use that median as the pivot.
o Randomly pick an element as pivot.
19. What is divide-and-conquer strategy?
➢ Divide a problem into two or more sub problems
➢ Solve the sub problems recursively
C Programming and Data Structures 5.37
https://www.poriyaan.in/ https://eee.poriyaan.in/
PART B

1. Explain Insertion sort with algorithm and examples.


2. Sort the sequence 13,11,74,37,85,39,22,56,25 using insertion sort.

in
3. Explain the operation and implementation of merge sort.
4. Write quick sort algorithm and explain with an example.

n.
5. Trace the quick sort algorithm for the following list of numbers.

aa
90,77,60,99,55,88,66
6. Explain linear search algorithm with an example.

iy
7. Explain Binary search algorithm with an example.
8. Write down the merge sort algorithm and give its worst case, best case and average
or
case analysis.
.p
9. Explain Heap Sort algorithm with an example
w
w
w
C Programming and Data Structures – Reg 2021 – CS3353
Unit I: C Programming Fundamentals : C Programming Fundamentals | Keywords, Variables and
Constants | Header Files | Data Types | Expressions using Operators | Input and Output Operations |
Decision Making and Conditional Statements | Functions | Recursive Functions | Arrays | Simple
Programs | Two Marks Questions with Answers

Unit II: C Programming – Advanced Features : C Programming – Advanced Features | Structures |


Union | Difference between Data Type, Structures and Unions | Enumerated Data Types | Pointers |
Strings and Pointers | Arrays and Functions | File Handling | Preprocessor Directives | Two Marks
Questions with Answers

Unit III: a. Linear Data Structures – List : Linear Data Structures - List | Introduction to Data Structure
| Abstract Data Types (ADTs) | List ADT | Array Based Implementation | Linked List | Difference between
Array and Linked Listed | Doubly Linked List | Circular Linked List | Applications of Linked Lists | Two
Marks Questions with Answers

Unit III: b. Linear Data Structures Stacks and Queues : Linear Data Structures Stacks and Queues |
Concept of Stack | Stack ADT | Implementation of Stack | Applications of Stack | Expression | Infix to
Postfix Conversion | Evaluation of Postfix Expressions | Concept of Queue | Queue ADT | Queue
Implementation | Priority Queues | Applications of Queue | Two Marks Questions with Answers

Unit IV: a. Non-Linear Data Structures – Trees : Non-Linear Data Structures – Trees | Trees | Binary
Trees | Representation of Binary Tree | Tree Traversal | Expression Trees | Binary Search Tree |
Programming Examples | Two Marks Questions with Answers

Unit IV: b. Hashing : Hashing | Basic Concept | Hash Functions | Properties of Good Hash Function |
Collision Handling | Applications of Hashing | Two Marks Questions with Answers

Unit V: Sorting and Searching Techniques : Sorting and Searching Techniques | Sorting | Insertion
Sort | Quick Sort | Heap Sort | Merge Sort | Searching | Two Marks Questions with Answers

3rd Semester (EEE dept)

HOME | EEE | ECE | MECH | CIVIL | CSE


1st Semester Anna University EEE- Reg 2021
Professional English – I
2nd Semester 3rd Semester
Matrices and Calculus
Probability and Complex
Professional English - II Functions
Engineering Physics
Statistics and Numerical Electromagnetic Fields
Engineering Chemistry Methods
Problem Solving and Physics for Electrical Digital Logic Circuits
Python Programming Engineering
Electron Devices and
Physics and Chemistry Basic Civil and Mechanical Circuits
Laboratory Engineering
Electrical Machines - I
Engineering Graphics
C Programming and Data
4th Semester Electric Circuit Analysis Structures
Environmental Sciences
and Sustainability 6th Semester
Transmission and 5th Semester
Distribution Protection and
Linear Integrated Power System Analysis Switchgear
Circuits
Power Electronics Power System
Measurements and Operation and Control
Instrumentation Control Systems
Open Elective – I
Microprocessor and
Microcontroller Professional Elective I
Professional Elective IV
Electrical Machines - II Professional Elective II
Professional Elective V
Professional Elective III
7th Semester Professional Elective VI
High Voltage Mandatory Course-I& Mandatory Course-
Engineering II& MC
Human Values and 8th Semester
Ethics
Elective –
Management Project Work /
Internship
Open Elective – II
Open Elective – III
Open Elective – IV
Professional Elective
VII Click on Clouds to navigate other department

https://www.poriyaan.in/

You might also like