C Programming and Data Structures
C Programming and Data Structures
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
programming paradigms.
w
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
➢ A programming language must be simple, easy to learn and use, have good
w
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
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
systems, like Windows or Linux, but also in the development of GUIs (Graphical
User Interfaces) and, IDEs (Integrated Development Environments).
w
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
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
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
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
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.
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
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
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
in
n.
aa
iy
or
.p
w
w
w
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
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
{
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
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
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
“hai”
“4565”
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
Syntax:
w
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
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.
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=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
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
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
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
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
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
~ One’s complement
w
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
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
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;
}
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
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
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
}
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-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
❖ If-else-if statement
w
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
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
{
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
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
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
}
}
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
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
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
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
➢ 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
in
Enter the limit: 10
n.
1
aa
2
3
iy
4
5 or
6
.p
7
8
w
9
w
10
w
in
n.
aa
iy
or
.p
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
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
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
➢ 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
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
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
{
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
➢ When a function is defined, space is allocated for that function in the memory.
w
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
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
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
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
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
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
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:
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
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
➢ 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’};
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
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
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
}
}
/* 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
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
{
w
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
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
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
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
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
• 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
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
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).
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
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.
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;
}
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
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
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
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
}
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
%u”,&b1);
w
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
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
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
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
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
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
*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
also swapped.
w
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
};
➢ 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
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
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
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
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
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
#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
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
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
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
➢ 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
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
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
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
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
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
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.
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
➢ 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
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
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
➢ 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.
in
n.
aa
iy
or
.p
w
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.
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
➢ 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.
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
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
Here, size represents the memory taken by the primitive data types. As an instance, int
w
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
➢ 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.
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
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
in
• Node data,
n.
• Pointer to the next node in sequence (next pointer), and
aa
• Pointer to the previous node (previous pointer).
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
➢ 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.
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.
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.
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
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
➢ 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.
in
n.
aa
iy
or
.p
w
w
w
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
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
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
➢ 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
➢ 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
in
n.
aa
iy
or
.p
Fig. 3.12: Deletion in Doubly Linked List at the end
➢ 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
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
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
➢ 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.
in
n.
aa
iy
or
.p
w
w
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
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
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
[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
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
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
n.
aa
iy
Fig. 3.20: Working principle of a Stack
➢ 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
in
n.
aa
iy
or
.p
w
w
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
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
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
item := stack(top);
w
top = top - 1;
end;
Time Complexity: O (1)
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
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
in
n.
aa
iy
or
.p
w
w
in
head=ptr;
}
n.
else
aa
{
ptr->val = val;
iy
ptr->next = head;
head=ptr;
or
.p
}
w
printf("Item pushed");
w
}
}
w
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
}
}
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
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
subtraction
w
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
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
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
symbol
w
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
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
➢ 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
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
➢ 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
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
➢ Circular Queue
➢ Priority Queue
➢ Double Ended Queue (or Deque)
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
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
in
having the lowest priority.
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
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 like 5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given as the
highest priority in a priority queue.
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.
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:
in
➢ Deletion and
n.
➢ Peek
aa
Let's see how we can maintain the heap data structure.
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’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:
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
in
n.
aa
Fig. 3.36: Array representation of Queue
iy
or
.p
w
w
After deleting an element, the value of front will increase from -1 to 0. However,
the queue will look something like following.
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 4: EXIT
w
in
queue[rear]=item;
n.
}
aa
}
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
in
{
n.
front = rear = -1;
aa
else
front = front + 1;
iy
}
return y; or
}
.p
}
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.
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
➢ 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
}
iy
There are several algorithms that use queues to give efficient running times. Some
or
simple examples of queue usage are follows.
{
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
in
Q->q_front = 1;
n.
Q->q_rear = 0;
aa
}
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
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
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
➢ 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
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
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
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
➢ Descendant: Any successor node on the path from the leaf node to that node.
w
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
➢ 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.
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
➢ 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.
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
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.
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
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
in
➢ For example, expression tree for 3 + ((5+9)*2) would be:
n.
aa
iy
or
.p
w
w
w
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
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
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
Inorder ( node->l ) ;
/* then print the data of node */
w
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
Inorder ( s ) ;
return 0 ;
w
}
The output of the above program is
X+Y*Z/W
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
➢ 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.
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
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
➢ 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.
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
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
➢ 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
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
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
{
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
{
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
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
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.
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
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
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.
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
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.
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.
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.
➢ 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.1 Solution
in
n.
aa
iy
or
.p
A Closed Hash Table using Linear Probing
w
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
in
n.
aa
iy
or
.p
Key Hash Function h(X) Index Collision Alt Index
w
79 h0(79) 9
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
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
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
➢ 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.
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.
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.
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
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
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
➢ 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
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
➢ Rehashing is a technique in which the table is resized, i.e., the size of table is
doubled by creating a new table.
w
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
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
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
#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
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.
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.
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
#include<stdio.h>
#include<conio.h>
w
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
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.
all the levels except the last level, i.e., leaf node, should be completely filled, and
all the nodes should be left-justified.
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
➢ 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
➢ 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
➢ 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.
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
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
{
w
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
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.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
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
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
in
i++;
n.
k++;
aa
}
while (j<n2)
iy
{
a[k] = RightArray[j]; or
j++;
.p
k++;
}
w
}
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
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 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.
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
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
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.
in
Worst O(n)
n.
Average O(n)
aa
Space Complexity O(1)
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
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
if (res == -1)
w
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
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
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
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
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
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
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
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 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
https://www.poriyaan.in/