C Programming and Data Structures
C Programming and Data Structures
www.poriyaan.in/
CS3353 C PROGRAMMING AND DATA STRUCTURES eee.poriyaan.in/
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.
To understand the concepts of ADTs and linear data structures.
To know the concepts of non-linear data structure and hashing.
To familiarize the concepts of sorting and searching techniques.
TOTAL 45 PERIODS
COURSE OUTCOMES:
CO1: Develop C programs for any real world/technical application.
CO2: Apply advanced features of C in solving problems.
CO3: Write functions to implement linear and non–linear data structure operations.
CO4: Suggest and use appropriate linear/non–linear data structure operations for
solving a givenproblem.
CO5: Appropriately use sort and search algorithms for a given application.
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:// https://
www.poriyaan.in/ 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.
UNIT-I
C PROGRAMMING FUNDAMENTALS
1.1 Introduction to Programming Paradigms 1.1
1.1.1 Imperative Programming Paradigm 1.1
1.1.1.1 Procedural Programming Paradigm 1.2
1.1.1.2 Object Oriented Programming 1.3
1.1.1.3 Parallel Processing Approach 1.7
1.1.2 Declarative Programming Paradigm 1.7
1.1.2.1 Logic Programming Paradigms 1.7
1.1.2.2 Functional Programming Paradigms 1.7
1.1.2.3 Database/Data Driven Programming Approach 1.8
1.1.3 Characteristics of a Good Programming Language 1.8
1.2 History of C Programming 1.9
1.2.1 Features of C Programming 1.10
1.3 Applications of C Language 1.10
1.4 Structure of C Program 1.11
1.5 Lexical Elements of C 1.14
1.5.1 Character Set 1.15
1.5.2 Delimite 1.17
1.5.3 Keywords 1.17
1.5.4 Identifiers 1.18
1.5.5 Data Types 1.18
1.5.6 Constants 1.25
1.5.7 Variables and Declaration 1.27
1.6 Operators in C 1.29
1.6.1 Types of Operators 1.29
1.6.1.1 Arithmetic Operators 1.30
1.6.1.2 Relational Operators 1.32
1.6.1.3 Logical Operators 1.32
1.6.1.4 Assignment Operator 1.34
1.6.1.5 Increment and Decrement Operators (Unary Operators) 1.35
https:// https://
www.poriyaan.in/
1.6.1.6 Conditional Operator (Or) Ternary Operator eee.poriyaan.in/
1.37
1.6.1.7 Bitwise Operators 1.38
1.6.1.8 The Special Operator 1.39
1.7 Expressions And Statements 1.41
1.7.1 Expressions 1.41
1.7.2 Statements 1.41
1.8 Conditional Statements 1.42
1.8.1 Conditional Branching Statement 1.43
1.8.1.1 Selection Statement 1.43
1.8.1.2 Looping Statements 1.58
1.9 Functions 1.64
1.9.1 Function Prototype 1.65
1.9.1.1 User Defined Function 1.65
1.9.1.2 Elements of User Defined Functions 1.66
1.10 Recursive Functions 1.78
1.11 Arrays 1.81
1.11.1 Declaration of an Array 1.82
1.11.2 Initialization of Arrays 1.83
1.12 One Dimensional Array 1.83
1.12.1 Declaration of Single Dimensional Array 1.83
1.12.2 Initialization of Single Dimensional Array 1.84
1.13 Multi-Dimensional Array 1.87
1.13.1 Two Dimensional Array 1.87
1.13.2 Three-Dimensional Arrays 1.91
Review Questions 1.94
UNIT -II
PROGRAMMING - ADVANCED FEATURES
2.1 Introduction 2.1
2.2 Structure 2.1
2.2.1 Three Main Aspects of Working with Structure 2.1
2.2.1.1 Defining Structure 2.2
2.2.1.2 Initializing Structure Elements 2.3
https:// https://
www.poriyaan.in/
2.2.1.3 Declaring Structure Objects eee.poriyaan.in/
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
2.4 Pointers 2.14
2.4.1 Pointers to Variables 2.14
2.4.2 Pointer Operators 2.18
2.4.3 Arrays and Pointers 2.20
2.4.3.1 Pointers with Multi-Dimensional Array 2.23
2.4.4 Functions Pointers 2.24
2.5 Enumerated Data Types 2.25
2.5.1 Enumerated Type Declaration to Create a Variable 2.26
2.5.2 Implementing enum Using C Program 2.26
2.6 File Handling 2.27
2.6.1 Why We Need File 2.27
2.6.2 File Operations 2.28
2.6.2.1 Types of Files 2.28
2.7 Preprocessor Directives 2.41
Review Questions 2.44
UNIT - III
LINEAR DATA STRUCTURES
3.1 Abstract Data Types (ADTS) 3.1
3.1.1 Abstract Data Type Model 3.1
3.2 List ADT 3.3
3.2.1 Operations on the List Data Structure 3.4
3.3 Array-Based Implementation 3.4
3.3.1 Properties of Array 3.4
3.3.2 Representation of an Array 3.5
3.3.3 Memory Allocation of an Array 3.5
3.3.4 Access an Element from the Array 3.6
3.3.5 Basic Operations of an Array 3.6
https:// https://
www.poriyaan.in/
3.3.6 Complexity of Array Operations eee.poriyaan.in/
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
3.4.1 Representation of a Linked List 3.8
3.4.2 Why Use Linked List Over Array 3.8
3.4.3 Declare a Linked List 3.9
3.4.4 Types of Linked List 3.9
3.4.4.1 Singly-Linked List 3.9
3.4.4.2 Doubly Linked List 3.10
3.4.4.3 Circular Singly Linked List 3.10
3.4.4.4 Circular Doubly Linked List 3.10
3.4.5 Advantages of Linked List 3.10
3.4.6 Disadvantages of Linked List 3.11
3.4.7 Applications of Linked List 3.11
3.4.8 Operations Performed on Linked List 3.11
3.4.9 Complexity of Linked List 3.12
3.5 Doubly Linked List 3.12
3.5.1 Memory Representation of a Doubly Linked List 3.13
3.5.2 Operations on Doubly Linked List 3.14
3.5.2.1 Insertion at Beginning 3.15
3.5.2.2 Insertion at End 3.16
3.5.2.3 Insertion After Specified Node 3.18
3.5.2.4 Deletion at Beginning 3.19
3.5.2.5 Deletion at the End 3.20
3.5.2.6 Deletion of the Node Having Given Data 3.21
3.5.2.7 Searching for a Specific Node 3.22
3.5.2.8 Traversing in Doubly Linked List 3.23
3.5.3 Advantages of Doubly Linked Lists 3.23
3.5.4 Disadvantages of Doubly Linked Lists 3.24
3.6 Circular Linked List 3.24
3.6.1 Memory Representation of Circular Linked List 3.24
https:// https://
www.poriyaan.in/
3.6.2 Operations on Circular Singly Linked List eee.poriyaan.in/
3.25
3.6.2.1 Insertion at the Beginning 3.26
3.6.2.2 Insertion at the End 3.27
3.6.2.3 Deletion at the Beginning 3.28
3.6.2.4 Deletion at the End 3.30
3.6.2.5 Searching 3.31
3.6.2.6 Searching 3.32
3.6.3 Advantages of Circular Linked Lists 3.32
3.6.4 Disadvantages of Circular Linked Lists 3.33
3.7 Stack ADT 3.33
3.7.1 Working of Stack 3.33
3.7.2 Operations on Stack 3.34
3.7.2.1 Push Operation 3.34
3.7.2.2 Pop Operation 3.35
3.7.3 Applications of Stack 3.36
3.8 Implementation of Stack 3.36
3.8.1 Array Implementation of Stack 3.37
3.8.1.1 Adding an Element onto the Stack 3.37
3.8.1.1.1 Implementation of Push Algorithm in C 3.37
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
UNIT - IV
NON-LINEAR DATA STRUCTURES
4.1 Introduction to Tress 4.1
4.1.1 Example of Tree Data Structure 4.1
4.1.2 Basic Terminologies in Tree Data Structure 4.2
4.1.3 Properties of a Tree 4.2
4.1.4 Syntax for Creating a Node 4.3
4.2 Binary Trees 4.3
4.2.1 Binary Tree Representation 4.3
4.2.2 Types of Binary Trees 4.4
4.2.3 Benefits of Binary Trees 4.4
4.3 Tree Traversal 4.6
4.3.1 Types of Tree Traversal 4.6
4.4 Expression Trees 4.10
4.4.1 Properties of an Expression Tree 4.10
4.4.2 Construction of Expression Tree 4.10
4.4.3 Example - Postfix Expression Construction 4.11
4.4.4 Implementation of Expression Tree in C Programming Language 4.12
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
https:// https://
www.poriyaan.in/
4.4.5 Use of Expression Tree eee.poriyaan.in/
4.15
4.5 Binary Search Tree 4.15
4.5.1 Advantages of Binary Search Tree 4.16
4.5.2 Example of Creating a Binary Search Tree 4.16
4.5.3 Operations Performed on a Binary Search Tree 4.20
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
Tree
4.5.3.1.2 Algorithm to Search an Element in Binary 4.22
Search Tree
4.5.3.2 Deletion in Binary Search Tree 4.22
4.5.3.2.1 When the Node to be Deleted is the Leaf Node 4.22
4.5.3.2.2 When the Node to be Deleted has Only One 4.23
Child
4.5.3.3 Insertion in Binary Search Tree 4.24
4.5.3.4 The Complexity of the Binary Search Tree 4.24
4.5.3.5 Implementation of Binary Search Tree 4.25
4.6 Hashing 4.29
4.6.1 Examples 4.29
4.7 Hash Function 4.30
4.7.1 Hash Table 4.30
4.7.2 How Does Hashing in Data Structure Works 4.31
4.8 Separate Chaining 4.32
4.8.1 Separate Chaining Hash Table 4.32
4.8.2 Example for Separate Chaining 4.32
4.8.3 How to Avoid Collision in Separate Chaining Method 4.33
4.8.4 Practice Problem Based on Separate Chaining 4.34
4.8.5 Advantages and Disadvantages of Separate Chaining 4.37
4.9 Open Addressing 4.37
4.10 Linear Probing 4.37
4.10.1 Solution 4.38
4.11 Quadtratic Probing 4.39
4.12 Double Hashing 4.41
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
4.12.1 Double Hashing - Hash Function 1 or First Hash Function – 4.41
Formula
4.12.2 Double Hashing - Hash Function 2 or Second Hash Function – 4.42
Formula
4.12.3 Double Hashing Example - Closed Hash Table 4.42
4.13 Re-Hashing 4.44
4.13.1 Why Rehashing is Done 4.44
4.13.2 What is Load Factor in Hashmap 4.44
4.13.3 How Rehashing is Done 4.44
4.13.4 Rehashing Steps 4.45
Review Questions 4.46
UNIT - V
SORTING AND SEARCHING TECHNIQUES
5.1 Introduction to Sorting 5.1
5.2 Insertion Sort 5.2
5.2.1 Algorithm 5.3
5.2.2 Working of Insertion Sort Algorithm 5.3
5.2.3 Analysis of Insertion Sort 5.4
5.2.4 Applications 5.4
5.3 Quick Sort 5.6
5.3.1 Algorithm for Quick Sort 5.6
5.3.2 Working of Quick Sort Algorithm 5.6
5.3.3 Quicksort Complexity 5.8
5.3.4 Applications of Quick Sort 5.8
5.4 Heap Sort 5.11
5.4.1 What is a Heap 5.11
5.4.2 Working of Heap Sort Algorithm 5.11
5.4.3 Heapsort Complexity 5.16
5.4.4 Heap Sort Applications 5.16
5.5 Merge Sort 5.18
5.5.1 Algorithm 5.19
5.5.2 Working of Merge Sort Algorithm 5.19
https:// https://
www.poriyaan.in/
5.5.3 Merge Sort Complexity eee.poriyaan.in/
5.19
5.5.4 Merge Sort Applications 5.19
5.6 Introduction to Searching 5.23
5.6.1 Searching Methods 5.24
5.7 Linear Search 5.24
5.7.1 Steps Used in the Implementation of Linear Search 5.25
5.7.2 Algorithm 5.25
5.7.3 Working of Linear Search 5.25
5.7.4 Linear Search Complexity 5.27
5.7.5 Applications of Linear Search Algorithm 5.27
5.7.6 Advantages and Disadvantages 5.27
5.8 Binary Search 5.28
5.8.1 Algorithm 5.29
5.8.2 Working of Binary Search 5.29
5.8.3 Binary Search Complexity 5.31
5.8.4 Advantages and Disadvantages 5.31
5.8.5 Linear Search Vs Binary Search 5.33
Review Questions 5.34
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
I
C PROGRAMMING
FUNDAMENTALS
Data Types – Variables – Operations – Expressions and Statements – Conditional
Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional
Arrays.
Program 1.1
/* Program to find the area of a circle */ /* Documentation Section */
# include<stdio.h> /* Preprocessor Section */
# include<conio.h>
# define PI 3.14 /* Definition Section */
void main() /* main( ) function */
{
float area,r; /* Local variable declaration */
clrscr(); // Executable part of the program
printf("\n Enter the radius:\n");
scanf("%f",&r);
area= PI*(r*r);
printf("\n Area of the Circle = %8.2f", area);
https:// https://
www.poriyaan.in/
getch(); eee.poriyaan.in/
}
Output
Enter the radius: 4.5
Area of the Circle = 63.58
Program 1.2
/* Program to find the sum of two numbers using function */
/*Documentation Section */
# include<stdio.h> /* Preprocessor Section */
# include<conio.h>
int a,b; /* Global Variable declaration */
int add(int,int); /* Function declaration */
void main() /* main( ) function */
{
int c; /* Local Variable declaration */
clrscr(); // Executable part of the main() program
printf("\n Enter the values for a and b:\n");
scanf("%d %d",&a,&b);
c = add(a,b);
printf("\n Sum of %d + %d = %d", a,b,c);
getch();
}
int add(int a,int b) /* Subprogram of add() function definition */
{
int c; /* Local Variable declaration */
c=a+b; // Executable part of the function
return(c);
}
https:// https://
www.poriyaan.in/
Output eee.poriyaan.in/
Enter the values for a and b: 5 3
Sum of 5 + 3 = 8
Documentation section
The documentation section is included in the comments, which contains the author
name, the date of development and the program details.
Preprocessor section
The preprocessor section provides preprocessor statements which direct the
compiler to link functions from the system library.
Definition section
The definition section defines all symbolic constants refer to assigning a macro
of a name to a constant. The general syntax of a symbolic constant is
#define constant_name constant_value
Global declaration section
The global declaration section contains variable declarations which can be
accessed anywhere within the program.
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.
Syntax
long a; —> by default which represent long int
short
In general int data type occupies different memory spaces for a different
operating systems; to allocated fixed memory space a short keyword can be
used.
Syntax
short int a; —> occupies 2 bytes of memory space in every operating system
unsigned
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
https:// https://
www.poriyaan.in/
signed int a = -10; // right eee.poriyaan.in/
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
1.5.6 Constants
https:// https://
www.poriyaan.in/ 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
decimal integer constant can consist of any combination of digits taken from the
set 0 through 9.
1. Decimal number – 0 to 9
2. Octal number – 0 to 7
3. Hexadecimal number – 0 to 9, A, B, C, D, E, F
Examples
Decimal number – 10, 145,-89, 067 etc.
Octal number – 037, 0, 057, 0456 etc.
Hexadecimal number – 0x4, 0x9C, 0xAFE etc.
Rules for an integer constant
o It must have at least one digit.
o Decimal point is not allowed.
o It can be either positive or negative.
o If it is negative the sign must be preceded. For positive the sign is not
necessary.
o No commas or blank spaces are allowed.
o The allowable range for integer constant is –32,768 to +32,767
Real Constant
It is made up of a sequence of numeric digits with presence of a decimal point.
It is to represent quantities that vary continuously such as distance, height,
temperature etc.
Example:
Distance=134.9;
Height=88.10;
https:// https://
www.poriyaan.in/
Rules for a real constant eee.poriyaan.in/
o It must have one digit.
o It must have decimal point.
o It can be either positive or negative.
o If it is negative the sign must be preceded. For positive the sign is not
necessary.
o No commas or blank spaces are allowed.
Character constants
Single Character Constant
It contains a single character enclosed within a pair of single quote marks.
Example
‘d’, ‘r’, ‘6’, ‘_’
String Constant
It is a sequence of characters enclosed in double quotes.
The characters may be letters, numbers, special characters and blank spaces
At the end of string ‘\0’ is automatically placed.
Example
“hai”
“4565”
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.
Example:
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
real/real real 5.0/2.0=2.5
https:// https://
www.poriyaan.in/
Arithmetic operators can be classified as eee.poriyaan.in/
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
o Integer arithmetic – it requires both operands to be integer type for
arithmetic operation.
Example:
a=4, b=3
a+b =4+3 =7
a-b =4-3=1
o Floating Point arithmetic – It requires both operands to be float type for
arithmetic operation.
Example:
a=6.5, b=3.5
a+b =6.5+3.5 =10.0
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);
https:// https://
www.poriyaan.in/
sub=b-c; eee.poriyaan.in/
mul=b*c;
div=b/c;
printf(“\n sum=%d,sub=%d,mul=%d,div=%f”,sum,sub,mul,div);
getch();
}
Output:
Enter the value of b,c: 8 4
sum=12,sub=4,mul=32,div=2
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
Logical Operators are used to combine the result of two or more conditions.
https:// https://
www.poriyaan.in/ 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
5<10
|| Logical OR 8>5 || 8<2 1
!= Logical NOT 8!=8 0
&& - This operator is usually used in situation where two or more expressions
must be true.
Syntax:
(exp1) && (exp2)
|| – This is used in situation, where at least one expression is true.
Syntax:
(exp1) || (exp2)
! – This operator reverses the value of the expression it operates on. (i.e.,) it
makes a true expression false and false expression true.
Syntax:
!(exp1)
Program 1.4
/* Program using Logical operators */
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
printf("\n Condition : Return values ");
printf("\n 5<=8 && 4>2: %5d",5<=8 && 4>2);
https:// https://
www.poriyaan.in/
printf("\n !(7==7): %5d",!(7==7)); eee.poriyaan.in/
getch( );
}
Output
Condition : Return values
5<=8 && 4>2 : 1
5>=3 || 6<8 : 1
!(7==7) : 0
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;
https:// https://
www.poriyaan.in/
b- =x; eee.poriyaan.in/
c*=x;
d/=x;
e%=x;
printf("\n Value of a=%d",a);
printf("\n Value of b=%d",b);
printf("\n Value of c=%d",c);
printf("\n Value of d=%d",d);
printf("\n Value of e=%d",e);
getch();
}
Output
Value of a = 20
Value of b = 10
Value of a = 25
Value of b = 5
Value of c = 75
Value of d = 5
Value of e = 4
Pre-increment operator
This operator increment the value of a variable first and then perform other
https:// https://
www.poriyaan.in/
Program 1.6 eee.poriyaan.in/
#include <stdio.h>
void main()
{
int a,b;
a=10;
b=++a;
printf(“a=%d”,a);
printf(“b=%d”,b);
}
output: a=11 b=11
#include <stdio.h>
void main()
{
int a,b;
a=10;
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()
https:// https://
www.poriyaan.in/
int a,b; eee.poriyaan.in/
a=10;
b=a++;
printf(“a=%d”,a);
printf(“b=%d”,b);
}
Output:
a=11 b=10
Program 1.8
#include <stdio.h>
void main()
{
int a,b;
a=10;
b=a--; printf(“a=
%d”,a);
printf(“b=%d”,b);
}
Output:
a=9 b=10
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
https:// https://
www.poriyaan.in/
Example: eee.poriyaan.in/
val=(a=3,b=9,c=77,a+c);
Where,
First assigns the value 3 to a
Second assigns the value 9 to b
Third assigns the value 77 to c
Last assigns the value 80.
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
in memory.
Syntax:
sizeof(var);
Example:
void main()
{
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.
https:// https://
www.poriyaan.in/
1.7 EXPRESSIONS AND STATEMENTS eee.poriyaan.in/
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.
Syntax
Variable = expression;
Example: 1
x=a*b-c;
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
a++;
In example 2, the value of variable a is incremented by 1, i.e, this expression is
equivalent to a = a + 1.
1.7.2 Statements
A statement is an instruction given to the computer to perform an action. There
are three different types of statements in C:
1. Expression Statements
2. Compound Statements
3. Control Statements
Expression Statement
An expression statement or simple statement consists of an expression followed
by a semicolon (;).
Example
a=100;
b=20;
c=a/b;
https:// https://
www.poriyaan.in/
Compound Statement eee.poriyaan.in/
A compound statement also called a block, consists of several individual
statements enclosed within a pair of braces { }.
Example
{
a=3;
b=10;
c=a+b;
}
Control Statement
A single statement or a block of statements can be executed depending upon a
condition using control statements like if, if-else, etc.
Example
a=10;
if (a>5)
{
b= a+10;
}
}
}
Output
Enter the Average Mark : 65
First Class
Program 1.16
Write a program to calculate the gross salary for the conditions given below:
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
statementsn;
break;
}
default:
{
default statements;
}
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
break;
case 0:
exit();
break;
default:
printf(“Invalid choice”);
break;
https:// https://
www.poriyaan.in/
getch(); eee.poriyaan.in/
}
Output
Menu
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 2
Enter two numbers: 40 20
Subtraction: 20
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)
{ if(i
https:// https://
www.poriyaan.in/
%2==0) eee.poriyaan.in/
https:// https://
www.poriyaan.in/
printf(“%d\t”,i); eee.poriyaan.in/
i++;
}
getch( );
}
Output
Enter the limit: 10
2 4 6 8 10
Do While Statement
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
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 itself. It is otherwise called as exit control loop.
printf(“%d is a palindrome”,t);
else
printf (“%d is not a palindrome”, t);
getch( );
}
Output
https:// https://
www.poriyaan.in/
Enter the number 242 eee.poriyaan.in/
https:// https://
www.poriyaan.in/
1.9 FUNCTIONS eee.poriyaan.in/
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
divide complex task into manageable tasks. The function can also help to avoid
duplication of work.
Advantages of Functions
Code reusability
Better readability
Reduction in code redundancy
Easy to debug & test.
How Does Function Work?
Once a function is called, it takes some data from the calling function and
returns back some value to the called function.
Whenever function is called control passes to the called function and working of
the calling function is temporarily stopped, when the execution of the called
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
https:// https://
www.poriyaan.in/
Example: printf( ), scanf( ) eee.poriyaan.in/
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.
When a called function returns some result back to the calling function, it is said
to return that result.
The calling function may or may not pass parameters to the called function. If
the called function accepts arguments, the calling function will pass parameters,
else not.
Function declaration is a declaration statement that identifies a function’s
name, 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,
followed by the body of the function containing the executable code for that
function.
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.
https:// https://
www.poriyaan.in/
Syntax: eee.poriyaan.in/
return_type function_name(arguments_list);
void main()
{
…….
variable_name=function_name(argument_list);
…..
}
return_type function_name(arguments_list)
{
//function body
}
Program 1.24
#include<stdio.h>
#include<conio.h>
int add(int,int); //function declaration with return type and with arguments list
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)
{
https:// https://
www.poriyaan.in/
int z; eee.poriyaan.in/
z=x+y;
return(z); /*returning result to calling function*/
}
Output:
Enter the two numbers: 10 20
sum is. . 30
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.
Syntax:
return_type function_name(void);
void main()
{
…….
variable_name=function_name();
…..
}
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()
https:// https://
www.poriyaan.in/
int c; eee.poriyaan.in/
c=add(); //function call
printf(“sum is . . . %d”,c);
}
int add(void)
{
int a,b,c;
printf(“Enter the two numbers . . . “);
scanf(“ %d %d”,&a,&b);
c=a+b;
return(c);
}
Function Definition
It is the process of specifying and establishing the user defined function by
specifying all of its elements and characteristics.
When a function is defined, space is allocated for that function in the memory.
A function definition comprises of two parts:
Function header
Function Body
Syntax
return_type function_name(argument_list)
{
//function body
}
Example
int add(int x, int y)
{
int z;
https:// https://
www.poriyaan.in/
return(z); eee.poriyaan.in/
}
Program 1.26
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n"); scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{
float p ;
p = x * x ; return ( p ) ;
}
Output
Enter some number for finding square
2
Square of the given number 2.000000 is 4.00000
Function Call
The function can be called by simply specifying the name of the function, return
https:// https://
www.poriyaan.in/
The function call statement invokes the function. When aeee.poriyaan.in/
function is invoked,
the compiler jumps to the called function to execute the statements that are a part
of that function. Once the called function is executed, the program control passes
back to the calling function.
Syntax
function_name();
function_name(parameter);
variable_name=function_name(parameter);
variable_name=function_name();
Example
add();
add(a,b);
c=add(a,b);
c=add;
There are two ways that a C function can be called from a program. They are,
a) Call by value
b) Call by reference
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
https:// https://
www.poriyaan.in/
int sum(int a, int b) eee.poriyaan.in/
{
int c=a+b;
return c;
}
int main(
{
int var1 =10;
int var2 = 20;
int var3 = sum(var1, var2);
printf("%d", var3);
return 0;
}
In the above example variable a and b are the formal parameters (or formal
arguments). Variable var1 and var2 are the actual arguments (or actual parameters). The
actual parameters can also be the values. Like sum(10, 20), here 10 and 20 are actual
parameters.
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;
int num2 = increment(num1);
https:// https://
www.poriyaan.in/
printf("num1 value is: %d", num1); eee.poriyaan.in/
printf("\nnum2 value is: %d", num2);
return 0;
}
Output
Before swapping:
https:// https://
num1 value is 35
www.poriyaan.in/ eee.poriyaan.in/
https:// https://
www.poriyaan.in/
num2 value is 45 eee.poriyaan.in/
After swapping:
num1 value is 45
num2 value is 35
int f;
if(x==1)
return(1);
else
f=x*fact(x-1); //recursive function call
return (f);
https:// https://
}
www.poriyaan.in/ eee.poriyaan.in/
https:// https://
www.poriyaan.in/
Output: eee.poriyaan.in/
Enter the number 5
The factorial of 5=120
1.11 ARRAYS
Introduction to Arrays
An Array is a collection of similar data elements
These data elements have the same data type
The elements of the array are stored in consecutive memory locations and are
referenced by an index
Definition
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.
Example
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
https:// https://
www.poriyaan.in/
etc. The eee.poriyaan.in/
size of the array operates the number of elements that can be stored in an array.
https:// https://
www.poriyaan.in/
1.11.2 Initialization of arrays eee.poriyaan.in/
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:
The values are written with curly brackets and every value is separated by a comma.
It is a compiler error to specify more number of values than the number of elements in
the array.
Example: int marks [5] = {90, 92, 78, 82, 58};
Example
int a[4]; // a is an array of 4 integers
https:// https://
www.poriyaan.in/
1.12.2 Initialization of single dimensional array eee.poriyaan.in/
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
initialization list is a comma separated list of initializers enclosed within braces.
Example
1. int a[3]={1,3,4};
2. int i[5] ={1, 2, 3, 4, 5};
3. float a[5]={1.1, 2.3, 5.5, 6.7, 7.0};
4. int b[ ]={1,1,2,2};
In the fourth example the size has been omitted (it can be) and have been
declared 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:
char array_name[size]=”string”
For example,
char mess[ ]={‘w’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’};
If the number of initializers in the list is less than array size, the leading array
locations gets initialized with the given values. The rest of the array locations
gets initialized to
0 - for int array
0.0 - for float array
\0 - for character array
Example
int a[2]={1}; a
1 0
char b[5]={‘A’.’r’,’r’}; b
}
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>
https:// https://
www.poriyaan.in/
{ eee.poriyaan.in/
int a[10], i;
int n;
printf(“Enter the maximum number of elements\n”);
scanf(“%d”, &n);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
}
printf(“Array in the reverse order\n”);
for(i=n–1; i>=0; i--)
{
printf(“%d\t”, a[i]);
}
getch( );
}
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:”);
https:// https://
www.poriyaan.in/
scanf(“%d”, &n) eee.poriyaan.in/
printf (“\n Enter the %d numbers one by one:”);
for (i=0; i<n; i++)
{
scanf(“%d”, &a[i]);
sum = sum + a[i];
}
printf (“The sum of array content = %d”, sum);
getch( );
}
Output
Declaration
datatype arrayname [row size][column size]
a 1 4 6
2 0 0
}
}
/* 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);
}
https:// https://
www.poriyaan.in/
diasum=0; eee.poriyaan.in/
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);
/ * Program module to sum off diagonal */
diasum=0;
for(i=0;i<n;i++)
{
j= -n1;
diasum +=a[i][j];
}
printf(“Off diagonal sum%d\n”,diasum);
}
Output
Enter order [row][col] of the matrix
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
https:// https://
www.poriyaan.in/
1.13.2 Three-Dimensional Arrays eee.poriyaan.in/
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] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Program 1.36
Write a C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}mnn
// Printing values with the proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
https:// https://
www.poriyaan.in/
for (int j = 0; j < 3; ++j) eee.poriyaan.in/
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Output
Enter 12 values:
1
2
3
4
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
https:// https://
www.poriyaan.in/
test[0][2][0] = 5 eee.poriyaan.in/
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
https:// https://
www.poriyaan.in/ REVIEW QUESTIONS eee.poriyaan.in/
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.
Character – It refers to all ASCII character sets as well as the single alphabets,
such as ‘x’, ‘Y’, etc.
Double – These include all large types of numeric values that do not come
under either floating-point data type or integer data type.
Floating-point – These refer to all the real number values or decimal points,
such as 40.1, 820.673, 5.9, etc.
Void – This term refers to no values at all. We mostly use this data type when
defining the functions in a program.
2. What is Variable?
Variables are containers for storing data values.
Its value can be changed, and it can be reused many times.
Syntax for creating variables
type variableName = value;
Example: int a = 5;
3. What is Operator?
An operator is a special symbol that tells the compiler to perform specific
mathematical or logical operations.
Operators in programming languages are taken from mathematics.
C language supports a rich set of built-in operators.
4. List the types of operators supported in C
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
https:// https://
www.poriyaan.in/
Assignment operators eee.poriyaan.in/
Type Information Operators(Special operators)
5. What is Ternary operators or Conditional operators?
Ternary operators is a conditional operator with symbols? and :
Syntax: variable = exp1 ? exp2 : exp3
If the exp1 is true variable takes value of exp2. If the exp2 is false, variable
takes the value of exp3.
6. What is an Operator and Operand?
An operator is a symbol that specifies an operation to be performed on
operands.
Example: *, +, -, / are called arithmetic operators.
The data items that operators act upon are called operands.
7. What is type casting?
Type casting is the process of converting the value of an expression to a
particular data type.
Example: int x,y.
c = (float) x/y; where a and y are defined as integers. Then the result of x/y is
converted into float.
8. What is the difference between while loop and do while loop?
Whil do while
e
In the while loop the condition is first In the do…while loop first the
executed. statement is executed and then the
condition is checked.
If the condition is true, then it executes The do…while loop will execute at
the body of the loop. When the least one time even though the
condition is false it comes of the loop. condition is false at the very first time.
PART-B
1. Explain the different types of operators with neat examples.
2. Illustrate the different conditional statements available in C with syntax and
examples
3. Explain the looping statements with neat examples.
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:// https://
www.poriyaan.in/ eee.poriyaan.in/
II
PROGRAMMING - ADVANCED FEATURES
Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays
and Functions – File Handling – Preprocessor Directives.
2.1 INTRODUCTION
Structures, unions and enumerations are known as user defined data types.
These data types are used to create a flexible new data type.
Structure can be used for the storage of different data types. The similarity
between structure and array is both contain a finite number of elements.
Union is similar to structures in all aspects except the manner in which their
constituent elements are stored.
In structures, separate memory is allocated to each element, while in unions all
the elements are share the same memory.
Enumeration helps to define a data type whose objects can take a limited set of
values.
2.2 STRUCTURE
Definition
A Structure is a collection of variables of different data types under a single
name and provides a convenient way of grouping several of related information
together.
Unlike arrays, it can be used for the storage of heterogeneous data (data of
different data types).
2.2.1 Three main aspects of working with structure
https:// https://
www.poriyaan.in/
2. Initializing structure elements eee.poriyaan.in/
3. Declaring variables and constants (objects) of the newly created type.
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();
}
https:// https://
www.poriyaan.in/
Output: eee.poriyaan.in/
enter the name
xyz
enter the rno
20
enter the marks
80
90
95
NAME=xyz
RNO=20
AVERAGE MARK=88.33
Example Program 2.3
#include<stdio.h>
struct book //Struct datatype declaration
{
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
https:// https://
www.poriyaan.in/
(ii) Indirect member access operator (arrow operator) eee.poriyaan.in/
Syntax :
struct variable name -> struct element name
(or)
*struct variable name . struct element name
Example Program 2.4
#include<stdio.h>
struct book // structure data type declaration
{
int x,y;
};
struct book *b1; //pointer to structure
void main()
{
printf(“enter the values”);
scanf(“%d”, &b1->x);
scanf(“%d”,&b1->y); //-> operator used
printf(“\nx=%d”, b1->x);
printf(“\ny=%d”, *b1.y);
}
Output:
Enter the values 10 20
x=10
y=20
b) Assigning a structure object to a structure variables
Assignment operator (=) is used to assign the values of one variable to another
variable. When assignment operator (=) is applied on structure variables, it
performs member by member copy.
https:// https://
www.poriyaan.in/
Example Program 2.5 eee.poriyaan.in/
#include<stdio.h>
struct book // struct datatype is declared
{
char title[25], author[20];
int price;
};
void main()
{
struct book b1,b2,b3; //structure variables are declared
b1={“ cutting stone”, “Abraham”,400};
b2.author=b1.author;
b3=b1; // b1 variable values are assigned to b3
printf(“%s by %s is of Rs. %d \n”, b1.title,b1.author,b1.price);
printf(“%s is the author of second book”,b2.author);
printf(“%s by %s is of Rs. %d \n”, b3.title,b3.author,b3.price);
}
Output:
https:// https://
www.poriyaan.in/
cutting stone by Abraham is of Rs.400 eee.poriyaan.in/
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
https:// https://
www.poriyaan.in/
more than one member for your program. The format of theeee.poriyaan.in/
union statement is
as follows:
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
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
of the union's definition, before the final semicolon, you can specify one or more
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.
union Data {
int i;
float f;
char str[20];
} 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.
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
Example Program 2.9 Illustration of Union
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
void main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "Charulatha publication");
printf( "data.str : %s\n", data.str);
}
Output
data.i : 10
data.f : 220.500000
data.str : Charulatha publication
Difference between Structure and Union
Sl.No Structure Union
1 The member of a structure occupies The member of union share same
its own memory space. memory space.
2 The keyword struct is used to define The keyword union is used to define a
a structure structure
https:// https://
www.poriyaan.in/
3 eee.poriyaan.in/
All the members of a structure can Only the first member of a union can
be initialized. be initialized.
4 In structure, each member is stored In union, all members are stored in
in a separate memory location. So the same memory locations. So, need
need more memory space. less memory space.
2.4 POINTERS
2.4.1 Pointers to Variables
A pointer is a variable that stores an address of another variable of same type.
Pointer can have any name that is legal for other variable.
https:// https://
www.poriyaan.in/
Pointer variables are declared with prefix of ‘*’ operator. eee.poriyaan.in/
Using a pointer variable, we can access the value of another variable assigned to
it.
Syntax
data_type *pointer_name;
Example
int *a;
variable *a can store the address of any integer type variable.
A pointer is a variable whose value is also an address.
Each variable has two attributes
Value
Address
We can define pointers in two ways.
i) First a pointer is a variable and assigns different values to a pointer variable.
ii) Second the value contained by a pointer must be an address which indicates the
location of another variable in the memory. So, pointer is called as “address
variable”.
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’.
https:// https://
www.poriyaan.in/
Advantages of Using Pointers eee.poriyaan.in/
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
function arguments.
Pointers also provide an alternate way to access an array element.
A pointer enables us to access the memory directly.
Example Program 2.10
/*C program for printing value and address of a variable using pointer variable*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *ptr;
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*/
#include<stdio.h>
https:// https://
www.poriyaan.in/
#include<conio.h> eee.poriyaan.in/
void main()
{
int i=4;
int *j;
j=&i;
clrscr();
printf(“Address of i=%u\n”,&i);
printf(“Address of i=%u\n”,j);
printf(“Address of j=%u\n”,&j);
printf(“value of j=%u\n”,j);
printf(“value of i=%d\n”,i);
printf(“value of i=%d\n”,*(&i));
printf(“value of i=%d\n”,*j);
getch();
}
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>
https:// https://
www.poriyaan.in/
void main() eee.poriyaan.in/
{
int a,b,*p,*q,sum;
clrscr();
printf(“Enter two integers”);
scanf(“%d %d”,&a,&b);
p=&a;
q=&b;
sum=*p+*q;
printf(“sum=%d”,sum);
getch();
}
Output
Enter two integers 2 3
sum=5
Address of a[0]=4000
https:// https://
www.poriyaan.in/
The value of a[1]=20 eee.poriyaan.in/
Address of a[1]=4002
The value of a[2]=10
Address of a[2]=4004
The value of a[3]=10
Address of a[3]=4006
The value of a[4]=10
Address of a[4]=4008
Example Program 2.15
/*C program to print the value and address of an array elements using pointer*/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5]={10,20,30,40,50};
int i,*p;
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
https:// https://
www.poriyaan.in/
Address 4004 Element=30 eee.poriyaan.in/
Address 4006 Element=40
Address 4008 Element=50
Example Program 2.16
/*C program to add sum of elements of an array using pointer*/
#include<stdio.h>
main()
{
int i,sum; int arr[5]; int *ptr;
for(i=0;i<5;i++)
{
printf (“Enter the number”); scanf(“%d”,&arr[i]);
}
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
https:// https://
www.poriyaan.in/
30 eee.poriyaan.in/
40
50
Total= 150
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.
3. fscanf( file pointer, format string, address of the variable)
Example: fscanf(fptr,”%d”, &num);
4. fprintf(console output, “format string”, file pointer);
Example: fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
5. getw (): This function returns the integer value from a given file and increment the
file pointer position to the next message.
Syntax: getw (fptr);
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()
{
FILE *fp;
https:// https://
www.poriyaan.in/
int n; eee.poriyaan.in/
clrscr();
fp=fopen(“c.dat”, “wb+”);
printf(“Enter the integer data”);
scanf(“%d”,&n);
while(n!=0)
{
putw(n,fp);
scanf(“%d”,&n);
}
rewind(fp);
printf(“Reading data from file”);
while((n=getw(fp))!=EOF)
{
printf(“%d\n”,n);
}
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
https:// https://
www.poriyaan.in/
Program 2.25: program for fwrite(): eee.poriyaan.in/
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>
void main()
{
struct emp
{
int eno;
char ename[20]; float sal;
}e;
FILE *fp; fp=fopen(“emp.dat”, “wb”); clrscr();
printf(“Enter employee number”); scanf(“&d”,&e.eno); printf(“Enter employee name”); ff
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. ftell()
https:// https://
www.poriyaan.in/
3. rewind() eee.poriyaan.in/
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
required data can be achieved using fseek().
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
fseek(file pointer, displacement, pointer position);
The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.
This function is used for seeking the pointer position in the file at the specified
byte.
Syntax: fseek( file pointer, displacement, pointer position);
file pointer - It is the pointer which points to the file.
displacement -It is positive or negative.
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.
https:// https://
www.poriyaan.in/
2. fseek( p,5L,1) eee.poriyaan.in/
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
current position.
else
{
printf(“Enter value of n to read last ‘n’ characters”);
scanf(“%d”,&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf(“%c\t”,ch);
}
}
fclose(fp);
getch();
}
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.
https:// https://
www.poriyaan.in/
#error can be performed to stop compilation. eee.poriyaan.in/
#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
and collapse features.
https:// https://
www.poriyaan.in/ REVIEW QUESTIONS eee.poriyaan.in/
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
which is more meaningful.
In structure, data is stored in form of records.
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.
Syntax
struct [structure_tag]
{
//member variable 1
//member variable 2
//member variable 3
...
}[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;
https:// https://
www.poriyaan.in/ ... eee.poriyaan.in/
member definition;
};
5. Difference between Structure and Union.
Structure Union
The Keyword struct is used to define The Keyword union is used to define
the Structure the Union
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
when compared to Structure
We can access all members of Only one member of union can be
Structure at a time accessed at a time.
Altering the value of a member will Altering the value of a member will
not affect other member of a structure alter other member value in union.
User can only use the function but User can use this type of function.
cannot change (or) modify this function. User can also modify this function.
3
LINEAR DATA STRUCTURES
Abstract Data Types (ADTs) – List ADT – Array-Based Implementation – Linked List
– Doubly-Linked Lists – Circular Linked List – Stack ADT – Implementation of Stack –
Applications – Queue ADT – Priority Queues – Queue Implementation – Applications.
3.3.6 C
3.3.7
3.3.8 omplexity of Array operations
Time and space complexity of various array operations are described below.
Time Complexity
Operation Average Case Worst Case
Access O(1) O(1)
Search O(n) O(n)
Insertion O(n) O(n)
Deletion O(n) O(n)
Space Complexity
In array, space complexity for worst case is O(n).
2. Space Complexity
Operation Space complexity
Insertion O(n)
Deletion O(n)
Search O(n)
A doubly linked list containing three nodes having numbers from 1 to 3 in their
data part, is shown in Fig 3.6
Fig. 3.13: Deletion of a specified node in Doubly Linked List at the end
In the second scenario, the condition head == NULL will become false which
means that the list contains at least one node.
In this case, traverse the list in order to reach the last node of the list.
At the end of the loop, the pointer temp would point to the last node of the list.
The existing last node i.e. temp must point to the new node ptr
Algorithm 3.10
Step 1: IF PTR = NULL
Write OVERFLOW
https:// https://
www.poriyaan.in/Go to Step 1 eee.poriyaan.in/
[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 NEW_NODE -> NEXT = HEAD
Step 6: SET TEMP = HEAD
Step 7: Repeat Step 8 while TEMP -> NEXT != HEAD Step 8: SET TEMP = TEMP -> N
[END OF LOOP]
Step 9: SET TEMP -> NEXT = NEW_NODE Step 10: EXIT
3.6.2.5 Searching
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
list once.
If the match found then the location of that item is returned otherwise -1 is
returned.
Algorithm 3.13
STEP 1: SET PTR = HEAD
STEP 2: Set I = 0
STEP 3: IF PTR = NULL
WRITE "EMPTY LIST"
GOTO STEP 8
END OF IF
STEP 4: IF HEAD → DATA = ITEM
WRITE i+1 RETURN [END OF IF]
STEP 5: REPEAT STEP 5 TO 7 UNTIL PTR->next != head
STEP 6: if ptr → data = item
write i+1
RETURN
https:// https://
www.poriyaan.in/
End of IF eee.poriyaan.in/
STEP 7: I = I + 1
STEP 8: PTR = PTR → NEXT
[END OF LOOP]
STEP 9: EXIT
3.6.2.5 Searching
Traversing in circular singly linked list can be done through a loop.
Initialize the temporary pointer variable temp to head pointer and run the while
loop until the next pointer of temp becomes head.
Algorithm 3.14
STEP 1: SET PTR = HEAD
STEP 2: IF PTR = NULL
WRITE "EMPTY LIST"
GOTO STEP 8
END OF IF
STEP 4: REPEAT STEP 5 AND 6 UNTIL PTR → NEXT != HEAD
STEP 5: PRINT PTR → DATA
STEP 6: PTR = PTR → NEXT
[END OF LOOP]
STEP 7: PRINT PTR→ DATA
STEP 8: EXIT
If the stack is not empty, we first access the element which is pointed by the top
Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
Let's take the example of Converting an infix expression into a postfix expression
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
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
https:// https://
www.poriyaan.in/
When an operator encounters the scanning process, the Stackeee.poriyaan.in/
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
Now let us consider the following infix expression 2 * (4+3) - 5.
Its equivalent postfix expression is 2 4 3 + * 5.
The following step illustrates how this postfix expression is evaluated.
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 ( (
https:// https://
www.poriyaan.in/
( Push ( (( eee.poriyaan.in/
) Pop ( (
Test if ( and A[i] match? YES
[ Push [ ([
( Push ( ([(
) Pop ) )
Test if ( and A[i] match? YES
] Pop [ (
Test if [ and A[i] match? YES
) Pop (
Test if ( and A[i] match? YES
Test if Stack is Empty? YES TRUE
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
https:// https://
www.poriyaan.in/ 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
position of an element in the stack (the row) with the value of that element (the
column) for each queen.
Two examples of this are shown below:
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
queen in the next available row.
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.
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...
https:// https://
www.poriyaan.in/
Create empty stack and set current position to 0 eee.poriyaan.in/
Repeat {
loop from current position to the last position until valid position found
//current row
if there is a valid position {
push the position to stack, set current position to 0 // move to next row
}
if there is no valid position {
if stack is empty, break // stop search
else pop stack, set current position to next position // backtrack to previous
row
}
if stack has size N { // a solution is found
pop stack, set current position to next position // backtrack to find next solution
}
}
3.11.6 Heap
A heap is a tree-based data structure that forms a complete binary tree, and
satisfies the heap property.
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.
It means that the value of the parent node could be more than or equal to the
value 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:
Now, let’s try to insert a new element, 6. Since there are nodes present in the heap, we
insert this node at the end of heap so it looks like this:
Then, heapify operation is implemented. After which, the heap will look like this:
https:// https://
www.poriyaan.in/
3.11.7.2 Removing the minimum element from the priorityeee.poriyaan.in/
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
is restored.
Algorithm 3.19:
START
If node that needs to be deleted is a leaf node:
Remove the node
Else:
Swap node that needs to be deleted with the last leaf node present.
Remove the node
Heapify
END
Let us now see with an example how this works:
Example: 3.11
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:
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
Then, heapify operation is implemented. After which, the heap will look like this:
}
queue[rear]=item;
}
}
if(front == rear)
{
front = rear = -1;
else
front = front + 1;
}
return y;
}
}
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
be arranged in hierarchical fashion. For example- Trees and graphs.
2. List the various operations that can be performed on data structure.
Various operations that can be performed on the data structure are
Create
Insertion of element
Deletion of element
Searching for the desired element
Sorting the elements in the data structure
Reversing the list of elements.
3. What is abstract data type
The abstract datatype is special kind of datatype, whose behavior is defined by
a set of values and set of operations.
4. What is list ADT in data structure?
The list ADT is a collection of elements that have a linear relationship with
each other. A linear relationship means that each element of the list has a
unique successor.
5. What Are Arrays in Data Structures?
An array is a linear data structure that collects elements of the same data type
and stores them in contiguous and adjacent memory locations. Arrays work on
an index system starting from 0 to (n-1), where n is the size of the array.
6. What is a linked list?
A linked list is a set of nodes where each node has two fields ‘data’ and ‘link’.
The data field is used to store actual piece of information and link field is used
to store address of next node.
https:// https://
www.poriyaan.in/
7. What are the pitfall encountered in singly linked list? eee.poriyaan.in/
The singly linked list has only forward pointer and no backward link is
provided. Hence the traversing of the list is possible only in one direction.
Backward traversing is not possible.
Insertion and deletion operations are less efficient because for inserting the
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.
8. What is Singly Linked List?
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).
9. Define doubly linked list.
Doubly linked list is a kind of linked list in which each node has two link
fields. One link field stores the address of previous node and the other link field
stores the address of the next node.
10. Write down the steps to modify a node in linked lists.
o Enter the position of the node which is to be modified.
o Enter the new value for the node to be modified.
o Search the corresponding node in the linked list.
o Replace the original value of that node by a new value.
o Display the messages as “The node is modified”.
11. Difference between arrays and lists.
In arrays any element can be accessed randomly with the help of index of
array, whereas in lists any element can be accessed by sequential access only.
Insertion and deletion of data is difficult in arrays on the other hand insertion
and deletion of data is easy in lists.
12. State the properties of LIST abstract data type with suitable example.
It is linear data structure in which the elements are arranged adjacent to each
other.
It allows to store single variable polynomial.
If the LIST is implemented using dynamic memory, then it is called linked list.
https:// https://
www.poriyaan.in/
13. State the advantages of circular lists over doubly linked list.eee.poriyaan.in/
In circular list the next pointer of last node points to head node, whereas in
doubly linked list each node has two pointers: one previous pointer and another
is next pointer.
The main advantage of circular list over doubly linked list is that with the help
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.
14. What are the advantages of doubly linked list over singly linked list?
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 stores forward pointer.
15. Why is the linked list used for polynomial arithmetic?
We can have separate coefficient and exponent fields for representing each
term of polynomial. Hence there is no limit for exponent. We can have any
number as an exponent.
16. What is the advantage of linked list over arrays?
The linked list makes use of the dynamic memory allocation. Hence the user
can 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.
https:// https://
www.poriyaan.in/
Understandability: ADT specifies what is to be done andeee.poriyaan.in/
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 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 methodology, i.e., the data item stored first will be accessed first.
21. What is priority queue
A priority queue is a special type of queue in which each element is associated
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
priority occur, they are served according to their order in the queue.
22. What is stack?
Stack is an abstract data type that serves as a collection of elements, with two
main operations: Push, which adds an element to the collection, and Pop, which
removes the most recently added element that was not yet removed.
23. How is Stack represented in Data Structure?
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
https:// https://
www.poriyaan.in/ 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
4
NON-LINEAR DATA STRUCTURES
Trees – Binary Trees – Tree Traversals – Expression Trees – Binary Search Tree –
Hashing - Hash Functions – Separate Chaining – Open Addressing – Linear Probing–
Quadratic Probing – Double Hashing – Rehashing.
Here,
Node A is the root node
B is the parent of D and E
https:// https://
www.poriyaan.in/
D and E are the siblings eee.poriyaan.in/
D, E, F and G are the leaf nodes
A and B are the ancestors of E
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
https:// https://
www.poriyaan.in/
Algorithm for Preorder Traversal eee.poriyaan.in/
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.
Pseudo-code for Preorder Traversal
void Preorder(struct node* ptr)
{
if(ptr != NULL)
{
printf("%d", ptr->data);
Preorder(ptr->left);
Preorder(ptr->right);
}
}
Uses of Preorder Traversal
o If we want to create a copy of a tree, we make use of preorder
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:
https:// https://
www.poriyaan.in/
In this case, as we visit the left subtree first, we get theeee.poriyaan.in/
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
o for all nodes of the tree:
Step 1: Traverse left subtree recursively.
Step 2: Visit the root node.
Step 3: Traverse right subtree recursively.
Pseudo-code for Inorder Traversal
void Inorder(struct node* ptr)
{
if(ptr != NULL)
{
Inorder(ptr->left); printf("%d", ptr->data); Inorder(ptr->right);
}
}
Uses of Inorder Traversal
o It helps to delete the tree.
The operator, which is not much at the depth in the tree, is always at the lowest
priority compared to the operators lying at the depth.
The operand will always present at a depth of the tree; hence it is considered the
highest priority among all the operators.
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.
https:// https://
www.poriyaan.in/ 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.
}
void push ( struct node* x )
{
if ( head == NULL )
head = x ;
else
{
( x )->nxt = head ;
https:// https://
www.poriyaan.in/
head = x ; eee.poriyaan.in/
}
// struct node* temp ;
// while ( temp != NULL )
// {
// printf ( " %c " , temp->info ) ;
// temp = temp->nxt ;
// }
}
struct node* pop()
{
// Poping out the top most [pointed with head] element struct node* n = head ;
head = head->nxt ; return n ;
}
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
if ( t[i] == '+' || t[i] == '-' || t[i] == '*' || t[i] == '/' || t[i] == '^' )
https:// https://
www.poriyaan.in/
{ eee.poriyaan.in/
s = newnode ( t [ i ] ) ;
p = pop() ;
q = pop() ;
s->l = q ;
s->r = p;
push(s);
}
else {
s = newnode ( t [ i ] ) ;
push ( s ) ;
}
}
printf ( " The Inorder Traversal of Expression Tree: " ) ;
Inorder ( s ) ;
return 0 ;
}
The output of the above program is
X+Y*Z/W
In the above figure, we can observe that the root node is 40, and all the nodes of
the left subtree are smaller than the root node, and all the nodes of the right
subtree are greater than the root node.
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.
Therefore, we can say that the tree in the above image is a binary search tree.
Step 5 - Insert 10
o 10 is smaller than 45 and 15, so it will be inserted as a left subtree of 15.
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.
https:// https://
www.poriyaan.in/
Step 7 - Insert 12 eee.poriyaan.in/
o 12 is smaller than 45 and 15 but greater than 10, so it will be inserted as the
right subtree of 10.
Step 8 - Insert 20
o 20 is smaller than 45 but greater than 15, so it will be inserted as the right
subtree of 15.
https:// https://
www.poriyaan.in/
Step 9 - Insert 50. eee.poriyaan.in/
o 50 is greater than 45 but smaller than 79 and 55. So, it will be inserted as a
left subtree of 55.
Step2:
Step3:
https:// https://
www.poriyaan.in/ 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)
return Search(root → left, item)
else
return Search(root → right, item)
END if
Step 2 - END
}
}
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*/
https:// https://
www.poriyaan.in/
return; eee.poriyaan.in/
if (cur->left == NULL && cur->right == NULL) /*When node has no
children*/
{
if (cur != root)
{
if (parent->left == cur)
parent->left = NULL;
else
parent->right = NULL;
}
else
root = NULL; free(cur);
}
else if (cur->left && cur->right)
{
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)
https:// https://
www.poriyaan.in/
else eee.poriyaan.in/
parent->right = child;
}
else
root = child;
free(cur);
}
}
int main()
{
Node* root = NULL; root = insertion(root, 45); root = insertion(root, 30); root = insertio
printf("The inorder traversal of the given binary tree is - \n");
inorder(root);
deletion(root, 25);
printf("\nAfter deleting node 25, the inorder traversal of the given binary tree is
- \n");
inorder(root);
insertion(root, 2);
printf("\nAfter inserting node 2, the inorder traversal of the given binary tree is
- \n");
inorder(root);
https:// https://
www.poriyaan.in/
return 0; eee.poriyaan.in/
}
Output
4.6 HASHING
Hashing in the data structure is a technique of mapping a large chunk of data into
small tables using 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.
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 these unique index numbers for each value stored in an array format.
This technique is called the hash technique.
You only need to find the index of the desired item, rather than finding the data.
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
https:// https://
www.poriyaan.in/ 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.
If we insert a new element 52 , that would also go to the fourth index as 52%7 is
3.
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.
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.
https:// https://
www.poriyaan.in/ 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.
Step 4: The next key is 65. It will map to bucket number 5 because 65%6=5. So,
insert it to bucket number 5.
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.
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
Step 6: Now the next key is 42. Its bucket number will be 42%6=0. But bucket 0
is already occupied by key 24. So separate chaining method will again handles
the collision by creating a linked list to bucket 0.
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.
https:// https://
www.poriyaan.in/
In this way the separate chaining method is used as theeee.poriyaan.in/
collision resolution
technique.
4.10.1 Solution
Although, the quadratic probing eliminates the primary clustering, it still has the
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
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
https:// https://
www.poriyaan.in/
4.13 RE-HASHING eee.poriyaan.in/
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.
PART A
1. Define binary
tree?
A binary tree is a tree data structure composed of nodes, each of which has
utmost, two children, referred to as left and right nodes. The tree starts off with
a single node known as the root.
2. What are the two methods of binary tree implementation?
Linear representation.
Linked representation
3. What are the applications of binary tree?
Binary tree is used in data processing.
o File index schemes
o Hierarchical database management system
4. List out few of the Application of tree data-structure?
The manipulation of Arithmetic expression
Used for Searching Operation
Used to implement the file system of several popular operating systems
Symbol Table construction
Syntax analysis
5. Define expression tree?
Expression tree is also a binary tree in which the leaf’s terminal nodes or
operands and non-terminal intermediate nodes are operators used for traversal.
6. Define tree– traversal and mention the type of traversals?
Three types of tree traversal
Inorder traversal
Preoder traversal
Postorder traversal.
https:// https://
www.poriyaan.in/
7. Define in -order traversal? eee.poriyaan.in/
https:// https://
www.poriyaan.in/
Traverse the left subtree eee.poriyaan.in/
Visit the root node
Traverse the right subtree
8. What is pre-order traversal?
In preorder traversal, first, root node is visited, then left sub-tree and after that
right sub-tree is visited. The process of preorder traversal can be represented
as: root → left → right
9. Define threaded binary tree.
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 would normally be null point to the in-order predecessor of the node.
10. What are the types of threaded binary tree?
Right-in threaded binary tree
Left-in threaded binary tree
Fully-in threaded binary tree
11. Define Binary Search Tree.
Binary search tree is a binary tree in which for every node X in the tree, the
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
https:// https://
www.poriyaan.in/
15. Write short notes on Expression Trees. eee.poriyaan.in/
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
both unary and binary operators.
16. What is Hashing?
Hashing is a technique of mapping a large chunk of data into small tables using
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.
17. What is Hash Function?
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.
18. List the advantages of hashing in data structure
Hash provides better synchronization than other data structures. Hash tables are
more efficient than search trees or other data structures. Hash provides constant
time for searching, insertion and deletion operations on average.
19. What is separate chaining?
Separate Chaining is one of the techniques that is used to resolve the collision.
It is implemented using linked lists.
This method combines a linked list with a hash table in order to resolve the
collision. In this method, we put all the elements that hash to the same slot in
the linked list.
20. What is open addressing in hashing?
In open addressing,
Unlike separate chaining, all the keys are stored inside the hash table.
No key is stored outside the hash table.
21. List the techniques used in open addressing.
Linear Probing
Quadratic Probing
https:// https://
www.poriyaan.in/
Double Hashing eee.poriyaan.in/
22. What is Linear Probing?
Linear probing is a scheme in computer programming for resolving collisions
in hash tables, data structures for maintaining a collection of key–value pairs
and looking up the value associated with a given key.
23. Write short notes on Quadratic Probing?
Quadratic probing is an open addressing scheme in computer programming for
resolving hash collisions in hash tables.
Quadratic probing operates by taking the original hash index and adding
successive values of an arbitrary quadratic polynomial until an open slot is
found.
24. Explain about Double Hashing.
Double hashing is a collision resolving technique in Open Addressed Hash
tables. Double hashing uses the idea of applying a second hash function to key
when a collision occurs.
25. What is rehashing in data structure?
Rehashing is a technique in which the table is resized, i.e., the size of table is
doubled by creating a new table.
26. List the advantages of Double hashing
The advantage of Double hashing is that it is one of the best form of probing,
producing a uniform distribution of records throughout a hash table.
This technique does not yield any clusters.
It is one of effective method for resolving collisions.
https:// https://
www.poriyaan.in/ PART-B eee.poriyaan.in/
5
SORTING AND SEARCHING TECHNIQUES
Insertion Sort – Quick Sort – Heap Sort – Merge Sort –Linear Search – Binary Search
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.
https:// https://
www.poriyaan.in/ 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
Best O(n)
Worst O(n2)
Average O(n2)
Space Complexity O(1)
Stability Yes
5.2.4 Applications
The insertion sort is used when:
The array is has a small number of elements
There are only a few elements left to be sorted
Example Program 5.1
#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++)
https:// https://
www.poriyaan.in/
d = c; eee.poriyaan.in/
while ( d > 0 && array[d] < array[d-1])
{
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++)
{
printf("%d\n", array[c]);
}
return 0;
}
Output
Enter the number of elements
5
Enter 5 integers
40
30
20
10
40
Sorted list in ascending order
10
20
https:// https://
www.poriyaan.in/
40 eee.poriyaan.in/
40
array[index2] = temp;
//Recursive call for quick sort, with partiontioning
quicksort(array, firstIndex, index2-1);
quicksort(array, index2+1, lastIndex);
}
}
int main()
https:// https://
www.poriyaan.in/
//Declaring variables eee.poriyaan.in/
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);
//code to ask to enter elements from user equal to n
printf("Enter Elements in the list : ");
for(i = 0; i < n; i++)
{
scanf("%d",&array[i]);
}
//calling quickSort function defined above
quicksort(array,0,n-1);
//print sorted array
printf("Sorted elements: ");
for(i=0;i<n;i++)
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
https:// https://
www.poriyaan.in/
5.4 HEAP SORT eee.poriyaan.in/
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
Min-heap or max-heap represents the ordering of array in which the root element
represents the minimum or maximum element of the array
Heap sort basically recursively performs two main operations
Build a heap H, using the elements of array.
Repeatedly delete the root element of the heap formed in 1st phase.
First, construct a heap from the given array and convert it into max heap
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
After converting the given heap into max heap, the array elements are
Next step is to delete the root element (89) from the max heap. To delete this
node, swap it with the last node, i.e. (11). After deleting the root element, again
heapify it to convert it into max heap.
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,
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
After swapping the array element 81 with 54 and converting the heap into max-
heap, the elements of array are
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 heapify it to convert it into max heap.
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,
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
After swapping the array element 54 with 14 and converting the heap into max-
heap, the elements of array are
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,
again heapify it to convert it into max heap.
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.
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
After swapping the array element 14 with 9 and converting the heap into max-
heap, the elements of array are
In the next step, again delete the root element (11) 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.
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.
heapify(a, n, largest);
}
}
/*Function to implement the heap sort*/ void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--) heapify(a, n, i);
// One by one extract an element from heap for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/
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 sort combines the smaller sorted lists keeping the new list sorted too
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.
Step 3 − merge the smaller lists into new list in sorted order.
First divide the given array into two equal halves. Merge sort keeps dividing the
list into equal parts until it cannot be further divided.
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.
https:// https://
www.poriyaan.in/
Now, combine them in the same manner they were broken. eee.poriyaan.in/
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 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.
Now, there is a final merging of the arrays. After the final merging of above
arrays, the array will look like
5.7.2 Algorithm
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val'
is the value to search
Step 1: set pos = -1
Step 2: set i = 1
Step 3: repeat step 4 while i <= n
Step 4: if a[i] == val
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
The value of K, i.e., 41, is not matched with the first element of the array. So, move to
the next element. And follow the same process until the respective element is found.
https:// https://
www.poriyaan.in/ eee.poriyaan.in/
Now, the element to be searched is found. So algorithm will return the index of
the element matched.
5.8.1 Algorithm
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 array
element, 'val' is the value to search
Step 1: set beg = lower_bound, end = upper_bound, pos = - 1 Step 2: repeat steps 3 and 4 w
Step 3: set mid = (beg + end)/2 Step 4: if a[mid] = val
set pos = mid print pos
go to step 6
else if a[mid] > val set end = mid - 1 else
set beg = mid + 1 [end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit
Now, the element to search is found. So algorithm will return the index of the
element matched.
5.8.3 Binary Search complexity:
Time Complexity
Best O(1)
Worst O(logn)
Average O(logn)
Space Complexity O(1)
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
https:// https://
www.poriyaan.in/
int res = binarySearch(a, 0, n-1, val); // Store result eee.poriyaan.in/
The elements of the array are - 21, 14, 35, 30, 40, 51, 55, 57, 70
Element to be searched is – 40
Element is present at 5 position of array
PART A
1. What is sorting?
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
https:// https://
www.poriyaan.in/
14. What is the advantage of using Quick sort algorithm? eee.poriyaan.in/
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
Binary search
16. Define Searching.
Searching in data structure refers to the process of finding the required
information from a collection of items stored as elements in the computer
memory.
These sets of items are in different forms, such as an array, linked list, graph, or
tree.
17. Compare Quick sort and Merge Sort.
Basis for comparison Quick Sort Merge Sort
Efficiency Inefficient for larger arrays More efficient
Sorting method Internal External
Stability Not Stable Stable
Preferred for for Arrays for Linked Lists
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: b. Hashing : Hashing | Basic Concept | Hash Functions | Properties of Good Hash
Function | Collision Handling | Applications of Hashing | Two Marks Questions with Answers
4th Semester
6th Semester
Protection and
5th Semester Switchgear
Power System
Operation and Control
Open Elective – I
Professional Elective IV
8th Semester Professional Elective V
Professional Elective VI
Mandatory Course-
II& MC
7th Semester
High Voltage
Engineering
Human Values and
Ethics
Elective – Click on Clouds to navigate other department
Management
Open Elective – II
https://www.poriyaan.in/
Open Elective – III
Open Elective – IV
Professional Elective
VII