CS3353 - Notes 2 Marks and 16 Marks
CS3353 - Notes 2 Marks and 16 Marks
Data Types – Variables – Operations – Expressions and Statements – Conditional Statements – Functions –
Recursive Functions – Arrays – Single and Multi-Dimensional Arrays.
Introduction to C
“C is a structured programming language developed by Dennis Ritchie in 1972”.
C is also called as high level programming language.
The language has small instruction set and people attracted to this language this language is very
powerful.
C language has good programming efficiency hence C can be used for developing database systems,
engineering applications and graphics programming.
What is the Difference between Python and C Language?
Python C Language
Python is a multi-paradigm. It mainly supports
Object-oriented programming, Procedural C is a Structured programming language.
programming, and Functional programming.
Python is an interpreter based language. The C is a compiled language. The complete source code is
interpreter reads the code line by line. converted into machine language.
Python use automatic garbage collector for memory In C, Programmer has to do memory management on
management. his own.
Python is a General-Purpose programming language. C is mainly used for hardware related applications.
Python is slow. C is fast.
In Python, no need to declare variable type. In C, it is compulsory to declare variable type.
Python programs are easier to learn, write and read. C program syntax is complex than Python.
Testing and debugging is easier in Python. Testing and debugging is harder in C.
STRUCTURE OF C PROGRAM
Discuss about the structure of C program in detail.
Documentation Section
It consists of set of comment lines used to specify the name of the program, the author and other
details, etc.
Comments
Comments are very helpful in identifying the program features and underlying logic of the program.
The lines begins with ‘/*’ and ending with ‘*/’ are known as comments lines.
These lines are not executable. There are two types of comment lines,
1
Single Comment Line E.g., //ABCD….
Nested Comment Line (or) Multiple Comment Line E.g, /*…….. ……..*/
Preprocessor Section
It is used to link system library files for defining the macros and for defining the conditional inclusion.
C program depends upon some header file for function definition that is used in program.
Header file is extended with ‘.h’. This file should be included using #.
Eg., #include<stdio.h>, #define A 10, #if def, #endif…
Global Declaration Section
This section declares some variables that are used in more than one function throughout the program.
These variables must be declared outside of the main function. So these variables are known as global
variables.
Main Function
Every C program must contain main function.
Without main function that is not a C program.
After main function empty parenthesis are necessary.
Main () is the starting point of every ‘C’ program.
The execution always begin with the main function
The execution starts with opening brace ‘{’ & closing brace ‘}’
In between these braces the programmer should write executable and declaration part.
Executable part - It contains a set of statements or a single statement. These statements are enclosed
between the braces.
Declaration part - It declares the entire variables that are used in executable part. Variable
initialization is done in declaration section.
Sub Program Section (Or) User Defined Function
These section defined by user are called user defined functions.
These functions are defined after the main function (Or) before the main function.
Programming Rules
While writing a program, a programmer should follow the following rules.
All statements should be written in lowercase letters.
Uppercase letters are only used for symbolic constants.
Blank space may be inserted between the words. But blank space is not used while declaring a variable,
keyword, constant and function.
The programmers can write the statement anywhere between the two braces.
We can write one or more statements in a same line by separating each statement in a same line with
semicolon (:).
The opening and closing braces should be balanced.
CONSTANTS, VARIABLES AND DATA TYPES
C Character Set
Character set are the set of alphabets, letters and some special characters that are valid in C language.
It is used to represent information.
2
Two types of Character Set
Source Character Set
Executable Character Set
Source Character Set
It is used to construct the statements in the source program.
Source character set is classified into,
Alphabets - A to Z and a to z
Digits - 0 to 9
Special Characters - +, -, ?, /, (, ), *, &, ^, $, #, @, !, <, >, :, ;, ’, ”, _, =
White Spaces - Blank Space, Horizontal Tabs, Vertical Tab, New Line, Form Feed.
Executable Character Set
It is used at the time of execution.
Execution character set is also called as non-graphic character (or) Escape sequence.
Escape sequence are invisible and cannot be printed (or) displayed on the output screen.
Escape sequence are always represented by a back slash (\) followed by a character.
Character Escape Sequence Result
Bell (Alert) \a Beep Sound
Back Space \b Moves Previous Position
Horizontal Tab \t Moves next horizontal tab
Vertical Tab \v Moves next vertical tab
Newline (line feed) \n Moves next line
Form feed \f Moves initial position next page
Carriage return \r Moves beginning of the next line
Question mark \? Present Question mark
Backslash \\ \\ Present Back slash mark
NULL \0 NULL
C Tokens
Token is defined as the collection of entities such as identifiers, keywords, constants, strings, operators
and special symbols.
A token is source-program text that the compiler does not break down into component elements.
3
Identifiers
Identifier is a combination of alphanumeric characters.
An identifier is used for any variable, function, data definition, etc.
Eg., STDNAME, _SUB, TOT_MARKS – Valid Identifiers
Eg., Return, STD NAME - Invalid Identifiers
Rules for Naming an Identifier
It consists of letters (uppercase & lowercase), digits and underscore ( _ ) only.
The first letter of an identifier should be either a letter or an underscore.
No space and special symbols are allowed between the identifier.
The identifier cannot be a keyword.
Keywords
Keywords are the reserved words used by the compiler that have standard and fixed (or) predefined
meaning in ‘C’ Language.
Those words cannot be changed by the user and they are the basic building blocks for program
statements.
There are 32 keywords in C language. Some of the keywords are,
Keywords in C Language
auto double int struct do
break else Long switch default
case enum register typedef const
char extern return union if
Signed,
continue for void goto
unsigned
float static sizeof short while
All the keywords must be written in lower case.
Constants
What are Constants? Explain the various types of constants in C. (April/May 2015)
Constants are the entity whose values can't be changed during the execution of a program.
Eg: x=3, Here 3 is a constant.
Constants are classified into two types. They are,
Numerical Constant
Character Constant
4
Numerical Constant
It is divided into two types,
1. Integer Constant
2. Real Constant
Integer Constant
Integer constants are the numeric constants formed with the sequence of digits without any fractional
part or exponential part.
There are three types of integer constants in C language: decimal constant (base 10), octal constant
(base 8) and hexadecimal constant (base 16).
Decimal Digits: 0 1 2 3 4 5 6 7 8 9
Octal Digits: 0 1 2 3 4 5 6 7
Hexadecimal Digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
Example
Decimal Constants: 0, ‐9, 22, etc.
Octal Constants: 021, 077, 033, etc.
Hexadecimal Constants: 0x7f, 0x2a, 0x521, etc.
Floating Point Constant
Floating point constants are the numeric constant that has either fractional part or exponent part.
Example
‐2.0
0.0000234
‐0.22E‐5
Character Constant
Character constants are the constant which use single quotation around characters.
1. Single Character Constant
It contains a single character enclosed within a pair of single inverted commas both pointing to the left.
Eg: ‘s’, ‘M’, ‘3’, etc.
2. String Constant
A string constant is a sequence of characters enclosed in double quotes, the characters may be letters,
numbers, special characters and blank spaces, etc.
Eg: “Hello”, ”23”, “a”, etc.
Rules for Defining Constants
It must have at least one digit.
It can be either positive or negative.
No commas or blank spaces are allowed.
Decimal points are not allowed in integer constants, but allowed in real constants.
VARIABLES
Variables are memory location in computer's memory to store data.
7
To indicate the memory location, each variable should be given a unique name called identifier.
A variable is an identifier that is used to represent some specified type of information within a
designated portion of the program.
Rules for naming the variables
Variable name can be composed of letters (both uppercase and lowercase letters), digits and underscore
'_' only.
The first letter of a variable should be either a letter or an underscore.
No commas or blank spaces are allowed within a variable name.
There is no rule for the length of length of a variable. However, the first 31 characters of a variable are
discriminated by the compiler.
Variable Declaration
Declaration of variable can be done in the declaration part of the program.
The variables must be declared before they are used in the program.
Syntax
Data_type variable name;
Example
int a; char m;
float s;
Initializing Variables
Value can be initialized in the valuable name using an assignment operator = .
Syntax
Data_type variable name = value; (or) variable name=value;
Example
Eg: int x=2; x=2;
Scope of the Variable
Scope of the variable implies the availability of variables within the program.
Variables have 2 types of scope.
Local variables
Global variables
Local Variables
Local variables are defined inside a main function block (Or) inside a compound statement of a
function subprogram are called local variables.
Example
function()
{
int i, j;
}
Global / External Variables
The variables that are declared before the function main() are called the global / external variables.
Eg:
int a, b; // here a,ball is a global variables.
main()
{
……
function()
}
8
function()
{
…….
}
Differences between global variables and Local variables.
Comparisons
Global Variable Local Variable
Basis
Global variables are declared outside Local variables are declared within
Definition
the functions the functions
Global variables are lost when the Local variables are lost when the
Lifetime
program is ended function ends
Local Variables doesn't offers Data
Data Sharing Global Variables Offers Data Sharing
Sharing
Scope Accessible throughout the code Accessible inside the function
Global variables are kept in a fixed
Storage Local variables are kept on the stack
location selected by the compiler
For global variables, parameter For local variables, parameter passing
Parameter Passing
passing is not necessary is necessary
Changes in a Changes in a global variable is Changes in a local variable doesn't
variable value reflected throughout the code affect other functions of the program
9
+ Addition or unary plus c = a + b
d = - a
- Subtraction or unary minus
c= a — b
Arithmetic
* Multiplication c = a * b
/ Division c = a/b
% Mod a%b
< Less than a < 4
> Greater than a > 4
<= Less than equal to a < = 4
Relational
>= Greater than equal to a > = 4
== Equal to a == 4
I- Not equal to a !=4
&& And 0 &&1
Logical
|| Or 0 || 1
Assignment = Is assigned to a = 5
Increment ++ Increment by one ++i or i++
10
clrscr( );
printf(“ \n The sum of the two values:”);
c = a+b;
printf(“%d”,c);
getch( );
}
Output:
The sum of the two values: 15
Relational Operator
Relational operators are used to compare two or more operands. Operands may be variables, constants
or expression.
If the relation is true, it returns value 1 and if the relation is false, it returns value 0.
Relational operators are,
<, >, <=, >=, ==, !=
Example Program
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=5, b=10, c;
clrscr( );
c = a<b;
printf(“%d”,c);
getch( );
}
Output:
1
Logical Operators
Logical operators are used to combine the results of two or more conditions.
Operator Meaning
|| Logical OR
! Logical NOT
Logical AND – This operator is used where a set of statements are to be executed, if two or more
expressions are true.
Logical OR – This is used, if either of them is true from two or more condition, then set of statements
are executed.
Logical NOT – This operator reverses the value of the expression it operates on.
Sample Program
#include<stdio.h>
#include<conio.h>
void main()
{
int c1.c2,c3;
11
clrscr();
printf(“Enter the values c1, c2, c3:”);
scanf(“%d%d%d”, &c1,&c2&c3);
if((c1<c2)&&(c1<c3))
printf(“c1 is less than c2 and c3”);
getch();
}
Output
Enter the values c1, c2, c3: 3 6 9
c1 is less than c2 and c3
Assignment Operator
Assignment operators are used to assign a value or an expression or a value of a variable to another
variable.
Syntax: variable=expression (or) value ;
Example : x=10; x=a+b; x=y;
Two types of assignment operator are,
Compound Assignment
Nested Assignment (or) Multiple Assignment
Compound Assignment or Shorthand assignment
Assign a value to a variable in order to assign a new value to a variable after performing a specified
operation.
Operator Example Same As
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Multiple Assignments
It is used to assign a single value or an expression to multiple variables.
Syntax: var1=var2=…………..varn=single variable or expression;
Sample Program
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=3, b=5;
clrscr( );
a+=b; // a= a+b
printf(" \n The sum of the two values:%d",a);
getch( );}
Output:
The sum of the two values: 8
Increment and Decrement Operators
These are the increment (++) and decrement (--) operators.
12
Both of these are unary operators.
The ++ adds 1 to the operand and – subtracts 1 from the operand.
++x - Pre Increment (First increment and then return the value)
--x - Pre Decrement (First decrement and then return the value)
x++ - Post Increment (First return the value and then increment)
x-- - Post Decrement (First return the value and then decrement)
Example
Let a=5 and b=10
a++; //a becomes 6
a‐‐; //a becomes 5
++a; //a becomes 6
‐‐a; //a becomes 5
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5;
clrscr();
printf(“Post Increment Value a++=%d\n”,a++);
printf(“Pre Increment Value ++a=%d\n”,++a);
printf(“Pre Decrement Value -- a=%d\n”,--a);
printf(“Post Decrement Value a--=%d\n”,a--);
getch();
}
Output:
Post Increment Value a++=5
Pre Increment Value ++a=7
Pre Decrement Value --a=6
Post Decrement Value a--=6
Conditional Operator (Or) Ternary Operator
Conditional operator itself checks the condition and executes the statement depending on the
condition.
Syntax: condition?exp1:exp2
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=5, b=2, big;
clrscr();
big=(a>b)?a:b;
printf(“Largest number is %d”,big);
getch();
}
13
Output:
Largest number is 5
Bitwise Operators
It is used to manipulate the data at bit level. It operates on integers only.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift Left
>> Shift Right
~ One’s Complement
Operations of above operators are,
a b a|b a&b a^b ~a
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
1 1 1 1 0 0
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c;
clrscr();
a=12;
b=25;
c=a&b;
printf(“Bitwise AND=%d”,c);
c=a/b;
getch();
}
Output:
Bitwise AND=8
Special Operators
Operators Meaning
, Comma Operator
sizeof() Size of Operator
& and * Address Operator / Indirection Operator
. and Member Selection Operator
Comma Operator
It is used to separate the statement elements such as variables, constants or expression, etc.
sizeof() Operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.
Address Operator / Indirection Operator
Address Operator (&) - This symbol is used to specify the address of the variable.
14
Indirection Operator (*) - It is used to specify the value of the variable.
Member Selection Operator
These symbols are used to access the elements from a structure.
Sample Program
#include<stdio.h>
#include<conio.h>
void main( )
{
int c;
clrscr( );
printf(" \n Size of Int is:%d",sizeof(c));
getch( );
}
Output:
Size of Int is: 2
OPERATOR PRECENDENCE AND ASSOCIATIVITY
The concept of operator precedence and Associativity in C helps in determining which operators will
be given priority when there are multiple operators in the expression.
It is very common to have multiple operators in C language and the compiler first evaluates the
operator with higher precedence.
It helps to maintain the ambiguity of the expression and helps us in avoiding unnecessary use of
parenthesis.
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the Associativity for each of the
operators:
15
Precedence Operator Description Associativity
* Dereference Operator
12 || Logical OR Left-to-Right
= Assignment
16
Precedence Operator Description Associativity
Operator precedence determines which operation is performed first in an expression with more than
one operator with different precedence.
Example of Operator Precedence
Let’s try to evaluate the following expression,
10 + 20 * 30
The expression contains two operators, + (plus), and * (multiply). According to the given table,
the * has higher precedence than + so, the first evaluation will be
10 + (20 * 30)
After evaluating the higher precedence operator, the expression is
10 + 600
Now, the + operator will be evaluated.
610
EXPRESSIONS
An expression represents data item such as variables, constants and are interconnected with operators
as per the syntax of the language.
Expression consists of operands, operators and symbols
Syntax: variable=expression;
Eg: y=(a/b)+c; z=(a*b)-d;
Type Conversion
It is a process of converting the type of an expression from one type to another type.
Eg: x = (int)10.45
Example Program
#include<stdio.h>
#include<conio.h>
void main( )
{
int c;
clrscr( );
c=(int)10.45;
printf("\n Output is:%d",c);
getch( );
}
17
Output:
Output is: 10
STATEMENTS: INPUT AND OUTPUT STATEMENTS(I/O STATEMENTS)
MANAGING INPUT / OUTPUT FUNCTIONS IN C
Explain briefly about formatted and unformatted input/output functions in C.
Describe the various input and output statements in C with suitable examples. (May/June, Nov Dec 2016)
Explain various input and output functions of C language in detail. (April / May 2017)
Two types of Input/output statements are available and
Unformatted Input / Output Statements
Formatted Input / Output Statements
19
Answer = MECH
Example Program for formatted I/O functions
#include<stdio.h>
#include<conio.h>
void main( )
{
int a;
clrscr( );
printf("\n Enter the Number:");
scanf("%d",&a);
if(a>10)
{
printf("\n a is greater than 10");
}
getch( );
}
CONDITIONAL STATEMENTS (or) DECISION MAKING STATEMENTS
With an example program explain the various decision making statements available in C. (Nov / Dec 2017)
Explain the various decision making statements with example in detail.
Explain in detail about various decision making structures available in C with illustrative examples.
(Nov/Dec 2015) [Nov/Dec 2019] [Nov/Dec 2020][Apr/May 2021]
Definition:
Conditions are placed in the program using decision making statements.
Decision making statements check the condition and then executes its sub blocks.
Types of decision making statements:
‘C’ language provides the following conditional statements or selection structures (decision making).
if statement
if-else statement
nested if-else statement
if-else if ladder
if statement
The if statement is a decision making statement.
It is used to control the flow of execution by executing statements and also test logically whether the
condition is true (or) false.
Syntax
if (condition is true)
{
statement 1;
statement 2;
}
Example
#include<stdio.h>
#include<conio.h>
void main( )
{
20
int a;
clrscr( );
printf("\n Enter the Number:");
scanf("%d",&a);
if(a>10)
{
printf("\n a is greater than 10");
}
getch( );
}
Output:
Enter the Number: 12
a is greater than 10
if…else statement
It is a two way decision making statement used to control the flow of execution and to carry out the
logical test.
It has two blocks if & else.
if block is executed when the condition is true.
else block is executed when the condition is false.
Syntax
if(condition)
{
true statements;
}
else
{
false statements;
}
Example – Greatest of two numbers
#include<stdio.h>
#include<conio.h>
void main( )
{
int a;
clrscr( );
printf("\n Enter the Number:");
scanf("%d",&a);
if(a>10)
{
printf("\n a is greater than 10");
}
else
{
printf("\n a is less than 10");
}
21
getch( );
}
Output:
Enter the number: 2
A is less than 10
nested if…else statement
Writing an entire if…else statement in another if…else statement is called nesting, and the statement is
called nested if…else.
Syntax
if(condition 1)
{
if(condition 2)
{
true statement 2;
}
else
{
false statement 2;
}
}
else
{
false statement 1;
}
Example – largest of three numbers
#include<stdio.h>
void main()
{
int a=45,b=20,c=15;
clrscr();
if(a>b)
{
if(a>c)
{
printf("a is greater");
}
else
{
printf("c is greater");
}
}
else
{
if(b>c)
{
22
printf("b is greater");
}
else
{
printf("c is greater");
}
}
getch();
}
The if…else if Ladder
Number of logical conditions is checked for executing various statements.
If three are more than three alternatives and indentation is not consistent, it may be different for you to
determine the logical structure of the if statement.
Syntax
if(condition 1)
{
statement 1;
}
else if(condition 2)
{
statement 2;
}
else if(condition 3)
{
statement 3;
}
else
{
default statements;
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int m1,m2,m3;
float avg;
printf("\n Enter the Marks:");
scanf("%d%d%d",&m1,&m2,&m3);
avg=(m1+m2+m3)/3;
printf("\n The average is:%f",avg);
printf("\n The Grade is:");
if(avg>=60)
{
printf("First class");
23
}
else if(avg>=50)
{
printf("Second class");
}
else if(avg>=35)
{
printf("Thrid class");
}
else
{
printf("Fail");
}
getch();
}
Output:
Enter the Marks: 65
75
70
The average is: 70.000000
The Grade is: First class
Write a program using control structure if…else that examines the value of an integer variable called rating
and print one of the following messages,
“Not recommended”-if the value of rating is less than 2
“Recommended” – if the value of rating lies between 2 and 4
“Highly recommended” – if the value of rating is above 4. [NOV/DEC 2022]
Program:
#include<stdio.h>
void main()
{
int rating;
printf(“enter the rating value”);
scanf(“%d”,&rating);
if(rating<2)
printf(“not recommended”);
else if(rating<2||rating<4)
printf(“recommended”);
else if(rating>=4)
printf(“highly recommended”);
else
printf(“invalid rating”);
}
Output:
Enter the rating value 10
Highly recommended
24
BRANCHING AND LOOPING [Nov/Dec 2019] [NOV/DEC 2022]
Various Looping Concepts
Write about the need and types of looping statements in C language and discuss with examples. (Dec/Jan
2014)
Explain in detail about various looping structures available in C with illustrative programs. (Nov/Dec 2014,
2016)
Describe the various looping statements used in C with suitable examples. (April/May 2015)
What is the use of looping? Explain about the entry – controlled and exit controlled loops available in C
with appropriate sample C programs. [Apr/May 2023]
The loop is defined as the block of statements which are repeatedly executed for certain number of
times.
The loop in a program consists of two parts,
Body of the loop
Control Statement – Used to test the condition
They are three types of loop control statements
while loop
do-while loop
for loop
The while Loop
The while loop is an entry controlled loop or top tested loop statement, means the condition is
evaluated first if it is true, and then the body of the loop is executed.
It is a repetitive control structure, used to execute the statements within the body until the condition
becomes false.
Syntax
while(condition)
{
……………..
body of the loop;
……………..
}
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int x=0;
while(x<10)
{
printf(“%d\n”,x);
x++;
}
getch();
}
Output
0123456789
The do…while Loop
25
The do…while loop is an exit controlled loop or bottom tested loop statement, means the condition is
evaluated last if it is true, and then the body of the loop is executed.
Loop will be executed at least once even though the condition is false.
It is also a repetitive control structure, used to execute the statements within the body until the
condition becomes false.
Syntax
do
{
…………..
body of the loop;
…………..
}while(condition);
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int x=0;
do
{
printf(“%d\n”,x);
x++;
}while(x<4);
getch();
}
Output
0123
The for Loop
The for loop is another repetitive control structure, and is used to execute set of instructions repeatedly
until the condition becomes false.
for loop has 3 parts,
Initialize Counter – used to initialize counter variable.
Test Condition – used to test the condition
Increment / Decrement Counter – used to increment / decrement the counter variable
Syntax
for(initialize counter;test condition;increment / decrement counter)
{
……………
body of the loop;
……………..
}
Example Program
#include<stdio.h>
#include<conio.h>
void main()
26
{
int x;
for(x=0;x<10,x++)
{
printf(“%d\n”,x);
}
getch();
}
Output
0123456789
Difference between while and do….while loop
Differentiate entry and exit checked conditional constructs with an example.
while do….while
It is an entry controlled loop or top tested It is an exit controlled loop or bottom tested
loop. loop.
First the condition is tested, if it is true then It executes the body once, after it checks the
the block is executed until the condition condition, if it is true the body is executed
becomes false. until the condition becomes false.
Loop will not be executed if the condition is Loop will be executed at least once even
false. though the condition is false.
BRANCHING STATEMENTS
Write about the need and types of branching statements in C language and discuss with examples. (Dec/Jan
2014)
THE SWITCH CASE STATEMENT [NOV/DEC 2022]
The switch statement is used to execute a particular group of statements from several available groups
of statements.
It is a multi-way decision statement, it tests the value of given variable or expression against a list of
case values and when a match is found, a block of statements associated with that case is executed.
Switch statement required only one argument of any data type which is checked with number of case
options.
If the value matches with case constant, that particular case statement is executed if not default is
executed.
Every case statements terminate with break statement is used to exit from the current case structure.
Syntax
switch(expression)
{
case constant 1 :
block 1;
break;
case constant 2 :
block 2;
break;
……………………
default :
27
default block;
break;
}
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c, option;
printf(“\n 1.Addition”);
printf(“\n 2.subtraction”);
printf(“\n 3.multiplication”);
printf(“\n 4.Division”);
printf(“\n 5.Exit”);
printf(“\n Enter Two Numbers:”);
scanf(“%d %d”, &a, &b);
printf(“\n Enter Your Option:”)
scanf(“%d”, &option);
switch(option)
{
case 1:
c=a+b;
printf(“\n Addition=%d” ,c);
break;
case 2:
c=a-b;
printf(“\n subtraction=%d”,c);
break;
case 3:
c=a*b;
printf(“\n multiplication=%d”,c);
break;
case 4:
c=a/b;
printf(“\n division=%d”,c);
break;
case 5:
exit(0);
break;
default:
printf(“Invalid Choice”);
}
getch();
}
Output
28
Enter Two Numbers: 2 4
Enter Your Option: 1
6
The break statement
It is used to terminate the loop.
When a break statement is used inside any C loop, then the loop is terminated.
Syntax: break;
Break statement takes the control to the outside of Continue statement takes the control to the
the loop. beginning of the loop.
It is also used in switch statement. This can be used only in looping statements.
29
Always associated with if condition in loops. This is also associated with if condition.
FUNCTION
Explain different types of functions with suitable example.
It is a set of instructions that are used to perform specified tasks which repeatedly occurs in the main
program.
Functions are a sub-program that contains one or more statements and it performs some task when
called.
Functions are classified into two types,
Pre-defined Functions
User-defined Functions
Pre-defined Functions
The pre-defined functions or library functions are built-in functions.
The user can use the functions, but cannot modify the function.
Example: sqrt()
User-defined Functions
The functions defined by the user for their requirement are called user-defined functions.
Whenever it is needed, the user can modify the function.
Example: sum(a,b)
Advantages
The length of the source program can be reduced by dividing into it into smaller functions.
It is easy to locate and debug an error.
It avoids coding of repeated instructions.
Parameters
It provides the data communication between the calling function and called function.
There are two types of parameters. They are,
Actual Parameters
Formal Parameters
Actual Parameters
These are the parameters transferred from the calling function (main program) to the called function.
Formal Parameters
These are the parameters which are used in the called function.
31
Types of Variable
Local and Global Variables
There are two kinds of variables.
1. Local variable
2. Global variable
Local Variable
The local variable is defined within the body of the function.
These variables are defined local to that function only or block only, other function cannot access these
variables.
Example
value(int a, int b)
{
int c, d;
}
c and d are local variables.
Global Variable
Global variables are defined outside the main() function.
Multiple functions can use these variables.
Example
int m=5,n=10;
main()
{
int a,b;
}
m and n are global variables.
Program to demonstrate local and global variables
#include<stdio.h>
#include<conio.h>
int A, B; //Global Variables
int Add()
{
return A + B;
}
int main()
32
{
int answer; // Local Variable
A=5;
B=7;
clrscr();
answer=Add();
printf(“%d\n”, answer);
getch();
return 0;
}
Output:
12
The return statement
The return statement may or may not send back some values to the calling function.
Syntax: return; (Or) return (expression);
FUNCTION PROTOTYPES
Explain different function prototypes. (Or) Explain function with and without arguments with examples
for each. (Nov/Dec 2014)
Explain about the different parameter passing methods in functions with examples. Nov / Dec 2017.
The functions are classified into the following types depending on whether the arguments are present
or not and whether the value is returned or not.
A function prototype declaration consists of the function’s return type, name and argument list.
It is always terminated with semicolon.
If the programmer makes mistake, the compiler generates an error message.
The 4 types of function prototypes are,
Function with no arguments and no return values.
Function with arguments and no return values.
Function with arguments and with return values.
Function with no arguments and with return values.
Function with no arguments and no return values
In this prototype, no data transfer take place between the calling function and the called function.
The function is only executed and nothing is obtained.
ie., the called program does not receive any data from the calling program and does not send back any
value to the calling program.
These functions act independently, i.e. they get input and display output in the same block.
Syntax
The dotted lines indicate that, there is only transfer of control but no data transfer.
Example Program
33
#include<stdio.h>
#include<conio.h>
void add(); //Function with No Argument
void main()
{
clrscr();
add(); // Calling Function
getch();
}
void add() //Called Function
{
int a = 35, b = 10;
printf("Sum is: %d",a+b);
}
Output
Sum is: 45
Function with arguments and no return values
In this prototype, data transfer take place between the calling function and the called function.
It is a one way data communication, i.e. the called program receives data from calling program but it
does not return any value to the calling program.
Syntax
The continuous line indicates data transfer and the dotted line indicates transfer of control.
Example Program
#include <stdio.h>
#include<conio.h>
void add(int, int); // Function with Argument
void main()
{
int a = 55, b = 10;
clrscr();
add(a,b); // Calling Function
getch();
}
void add(int a, int b) // Called Function
{
printf("Sum is: %d",a+b);
}
Output:
34
Sum is: 65
Function with arguments and with return values
In this prototype, data transfer take place between the calling function and the called function as well
as between called function and calling function.
It is a two way data communication, i.e. the called program receives data from calling program and it
return some value to the calling program.
Syntax
Example Program
#include<stdio.h>
#include<conio.h>
int add(int, int); //Function with Argument
void main()
{
int a = 5, b = 10;
clrscr();
printf("Sum is: %d", add(a,b)); //Calling Function
getch();
}
int add(int a, int b) // Called Function
{
return a+b;
}
Output:
Sum is: 15
Function with no arguments and with return value
In this prototype, data transfer take place between the called function and the calling function.
It is a one way data communication, i.e. the called program does not receives data from calling
program but it return some value to the calling program.
Syntax
Example Program
35
#include<stdio.h>
#include<conio.h>
int add(); //Function with No Argument
void main()
{
clrscr();
printf("Sum is: %d",add()); //Calling Function
getch();
}
int add() //Called Function
{
int a=8,b=2;
return a+b;
}
Output:
Sum is: 10
Call by Reference
It is another way of passing parameters to the function.
While passing parameter using call by address method, we are passing the actual address of the
variable to the called function.
Any changes to the formal parameter will affect the actual parameter.
Example Program
#include<stdio.h>
#include<conio.h>
void swap(int *a, int *b); //Function Definition
37
int main()
{
int a=50, b=70;
clrscr();
printf(“Before swapping”);
printf(“a=%d”,a);
printf(“b=%d”,b);
swap(a, b);
swap(&a, &b); //Calling Function
printf(“After swapping”);
printf("\n Number 1: %d",a);
printf("\n Number 2: %d",b);
getch();
return(0);
}
void swap(int *a, int *b) //Called Function
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
Before swapping
A=50 b=70
After swapping
A=70 b=50
In the above example, a and b are the original values and address of these values is passed to the
function and is copied into formal parameter a and b variable of same function respectively.
38
Difference between Call by Value and Call by Reference
Call by Value Call by Reference
• Values are passed in function call. • Address or pointers are passed in function
• This method copies the values of actual call.
parameters into the formal parameters of the • This method copies the addresses of actual
function. parameters into the formal parameters of the
• Here, the changes to the formal parameter do function.
not affect the actual parameter. • Any changes to the formal parameter will
• Changes to the formal parameter is temporary affect the actual parameter.
• Eg: swap(a,b); • Changes to the formal parameter is permanent
• Eg: swap(&a,&b);
40
4. Extremely useful when applying the same solution.
5. Recursion reduces the length of code.
6. It is very useful in solving the data structure problem.
7. Stacks evolutions and infix, prefix, postfix evaluations etc.
Disadvantages of recursion
1. Recursive functions are generally slower than non-recursive function.
2. It may require a lot of memory space to hold intermediate results on the system stacks.
3. Hard to analyze or understand the code.
4. It is not more efficient in terms of space and time complexity.
5. The computer may run out of memory if the recursive calls are not properly checked.
Applications of recursion
Artificial Intelligence
The NP problems
‘Tree’ data structure
Sorting algorithms (Quick sort, Merge sort, etc) uses recursion.
All the puzzle games(Chess, Candy crush, etc)
Recursion Iteration
Recursion uses the selection structure. Iteration uses the repetition structure.
The system crashes when infinite recursion is Iteration uses the CPU cycles again and again
encountered. when an infinite loop occurs.
Recursion terminates when the base case is Iteration terminates when the condition in the
met. loop fails.
Recursion is slower than iteration since it has Iteration is quick in comparison to recursion. It
the overhead of maintaining and updating doesn't utilize the stack.
the stack.
Recursion uses more memory in comparison Iteration uses less memory in comparison to
to iteration. recursion.
Recursion reduces the size of the code. Iteration increases the size of the code.
41
ARRAY
Explain in detail about array with an example. Nov / Dec 2016
What is an array? Write a C program to arrange the given 10 numbers in ascending order using one
dimensional array. (Nov / Dec 2017)
What is an array? List the various types of arrays. Elaborate on t-D array with an example. [Apr/May 2023]
An array is a collection of similar data items that are stored under a common name.
ie., an array is a group of related data items that share a common name.
A value in an array is identified by index or subscript enclosed in square brackets with array name.
The individual data items can be integers, floating point numbers and characters and so on.
Features of Arrays
An array is a derived data type.
The elements can be accessed with base address and the subscript defined for the position of the
element.
The elements in an array are stored in continuous memory location.
It is easier to refer the array elements by simply incrementing the value of the subscript.
Types of Array
Arrays can be classified into three types. They are,
One Dimensional Array
Two Dimensional Array
Multi Dimensional Array or n – Dimensional array
One Dimensional Array
The collection of data items stored under a one variable name using only one subscript; such a variable
is called as one dimensional array.
An array with a single subscript is known as one dimensional array.
Array Declaration
Arrays are declared in the same manner as ordinary variables except that each array name must have
the size of the array.
Here data-type is the type specifier that indicates what type of data
Array-Name is the name of the declared array and rules of declaring the variable applies to array
name.
Array-Size defines how many elements the array contains. This is always an integer.
Syntax
data_type array_name[size or subscript of the array];
Example
int x[3];
Array Initialization
The values can be initialized to an array, when they are declared like ordinary variables, otherwise they
hold garbage values.
The arrays can be initialized in two ways,
At Compile time
42
At Run time
At Compile time
This initialization is done while writing the program itself.
Syntax:
data_type array_name[size]={list of values};
Eg:
int x[3]={5,3,7};
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char x[5]={'a','b','c','d','e'};
clrscr();
for(i=0;i<5;i++)
printf("\n The value in x[%d] is %c",i,x[i]);
getch();
}
Output
The value in x[0] is a
The value in x[1] is b
The value in x[2] is c
The value in x[3] is d
The value in x[4] is e
At Run time
An array can initialized at run time by the program or by taking the input from the keyboard.
Generally, the large arrays are declared at run time in the program itself. Such as,
int sum[20];
for (i = 0;i<20;i++)
sum[i] = 1;
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int x[2], i;
printf("\n Enter the Inputs:");
for(i=0;i<2;i++)
scanf("%d",&x[i]);
for(i=0;i<2;i++)
43
printf("\n The value in x[%d] is %d",i,x[i]);
getch();
}
Output:
Enter the Inputs: 3 6
The value in x[0] is 3
The value in x[1] is 6
Two Dimensional Arrays (Apr/May 2019)
It is used to store values in the table
It is similar to one dimensional array except a separate pair of square brackets is required for each
subscript.
Two dimensional arrays are stored in a row-column matrix, where the left index indicates the row and
the right indicates the column.
Syntax:
data_type array_name[row size][column size];
Eg:
int x[3][2];
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
int x[3][3][3]= {
{
{11, 12, 13},
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
45
};
clrscr();
printf("3D Array Elements\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",x[i][j][k]);
}
printf("\n");
}
printf("\n");
}
getch();
}
Output:
11 12 13
14 15 16
17 18 19
21 22 23
24 25 26
27 28 29
31 32 33
34 35 36
37 38 39
Passing Arrays to Functions
Array can be transferred to a function as a parameter.
To transfer an array, the array name is enough without subscripts as actual parameters within the
function call.
Example
#include<stdio.h>
#include<conio.h>
void add(int,int b[]);
void main()
{
46
int a[5],i,n;
clrscr();
printf("\n Enter the Number: ");
scanf("%d",&n);
printf("\n Enter the Values: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
add(n,a);
}
void add(int x,int b[])
{
int sum=0,i;
for(i=0;i<x;i++)
sum=sum+b[i];
printf("\n The sum is: %d",sum);
getch();
}
Output:
Enter the Number: 5
Enter the Values: 1
2
3
4
5
The sum is: 15
MATRIX OPERATIONS USING ARRAY
Matrix Addition
Write a C program to print the sum of two matrices. (Dec/Jan 2014) [Nov/Dec 2021] [NOV/DEC 2022]
Write a C program to add two matrices. (April/May 2015, 2018, Nov / Dec 2016)
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("\n Enter the First matrix:");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the Second matrix:");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
47
c[i][j]=a[i][j]+b[i][j];
printf("\n The Addition of two matrix is\n");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
getch();
}
Output
Enter the element of First Matrix:
2
2
2
2
2
2
2
2
2
Enter the element of Second Matrix:
3
3
3
3
3
3
3
3
3
The Addition of Two Matrix is
5 5 5
5 5 5
5 5 5
Matrix Multiplication
48
Write a C program to multiply two matrices. (Nov/Dec 2014) (Nov/Dec 2015) (May/June 2016) (Nov / Dec
2016) [Nov/Dec 2021]
Write a C program to multiply two B x B matrices. (Nov / Dec 2017)
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10], b[10][10], c[10][10], i, j, k;
int sum = 0;
clrscr();
printf("\n Enter First Matrix:");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\n Enter Second Matrix:");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &b[i][j]);
}
}
for (i = 0; i <= 2; i++)
{
for (j = 0; j <= 2; j++)
{
sum = 0;
for (k = 0; k <= 2; k++)
{
sum = sum + a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
printf("\n The Multiplication of Two Matrix is:");
for (i = 0; i < 3; i++)
{
printf("\n");
for (j = 0; j < 3; j++)
printf(" %d\t", c[i][j]);
}
getch();
}
49
Output:
Enter the element of First Matrix:
2
2
2
2
2
2
2
2
2
Enter the element of Second Matrix:
3
3
3
3
3
3
3
3
3
The Multiplication of Two Matrix is
18 18 18
18 18 18
18 18 18
Matrix Subtraction
Write a C program to subtract two matrices and display the resultant matrix. (May/June 2014)
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("\n Enter the element of First Matrix:");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the element of Second Matrix:");
50
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]-b[i][j];
printf("\n The Subtraction of Two Matrix is:");
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
getch();
}
Output:
Enter the element of First Matrix:
3
5
7
9
11
13
7
5
3
Enter the element of Second Matrix:
2
4
6
8
10
12
6
4
2
The Subtraction of Two Matrix is
1 1 1
1 1 1
1 1 1
Write a C program to find the following, where A,B and C are the matrices whose orders are M*N, N*N
respectively. A-A+B*C. Nov 2018
#include<stdio.h>
void main()
{
51
int A[3][3],B[3][3],C[3][3],D[3][3],I,J,K;
clrscr();
printf(“ENTER 3X3 MATRIX A VALUES\n”);
for(I=0;I<3;I++)
{
for(J=0;J<3;J++)
{
scanf(“%d”,&A[I][J]);
}
}
printf(“ENTER 3X3 MATRIX B VALUES\n”);
for(I=0;I<3;I++)
{
for(J=0;J<3;J++)
{
scanf(“%d”,&B[I][J]);
}
}
printf(“ENTER 3X3 MATRIX C VALUES\n”);
for(I=0;I<3;I++)
{
for(J=0;J<3;J++)
{
scanf(“%d”,&C[I][J]);
}
}
for(I=0;I<3;I++)
{
for(J=0;J<3;J++)
{
D[I][J]=0;
for(K=0;K<3;K++)
{
D[I][J]=D[I][J]+A[I][K]*B[K][J];
}
D[I][J]=D[I][J]+C[I][K];
}
}
printf(“RESULT 3X3 MATRIX D VALUES ARE :\n”);
for(I=0;I<3;I++)
{
for(J=0;J<3;J++)
{
printf(“%d\t”,D[I][J]);
}
52
printf(“\n”);
}
getch();
}
Output:
Predict the output of the following program and state the reason (4)
intmain()
{inti=0;
while(i<=4)
{
printf(“%d”,i);
if(i>3)
gotoinside_foo;
i++;
}
getchar();
return0;
}
voidfoo()
{
inside_foo:
printf(“pp”);}
Output: Syntax error at line 1, 8, 12,14
(Or)
If the above program has printing mistakes then, the output will be 0 1 2 3 PP
53
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i=0;
char a[]="abcd";
clrscr();
while(a[i]!='\0')
{
printf("\t%c",a[i]);
i++;
}
}
Output:
a b c d
STRINGS
Handling of Character Strings
Explain in detail about the string with an example.
Explain the concept of strings in detail. (April / May 2017, 2018)
In ‘C’ language the group of characters, digits and symbols enclosed within quotation marks are called
as string, otherwise strings are array of characters.
Null character ‘\0’ is used to mark the end of the string. Header file used is string.h.
Eg: char name[]={‘d’,’a’,’k’,’ ‘s’,’h’,’i’ ‘t’,’h’,’a’,,\0’};
Each character is stored in one byte of memory and successive characters of the string are stored in
successive byte.
Declaration & Initialization of String
String variable is always declared as an array.
Syntax:
data_type string_name[size]=”values”; (or) data_type string_name[size];
The string can be initialized as follows,
char name[]=”BOB”; (or) char name[5];
The characters of the string are enclosed within a pair of double quotes.
The initialization of NULL character is not essential because the ‘C’ compiler itself inserts the NULL
(\0) character automatically at the end of the string.
Reading and Writing String
The ‘%s’ control string can be used in scanf() statement to read a string.
Eg:
scanf(“%s”,name);
And the same may be used to write the string in printf() statement.
Eg:
printf(“%s”,name);
54
STRING HANDLING FUNCTIONS
The ‘C’ compiler provides the following string handling functions.
Function Purpose Syntax
strlen() It is used to find the length of the string. var=strlen(string);
strcpy() It is used to copy one string to another. strcpy(string1,string2);
strcat() It is used to combine two strings. strcat(string1,string2);
strcmp() It is used to compare two strings. strcmp(string1,string2);
strrev() It used to reverse a string. strrev(string);
strlwr(), strlwr(string);
It used to change the case of a string.
strupr() strupr(string);
strncpy() It used to copy ‘n’ characters of one string to another.
strstr() It is used to determine the first occurrence of a given string in another string.
strncat() It appends source string to destination string upto specified length.
strspn() It is used to find upto what length two strings are identical.
strncmp() It is used to compare ‘n’ character of two strings.
strcmpi() It is used to compare two strings without regarding the case.
strnicmp() It is used to compare first ‘n’ characters of two strings without regarding the case.
strchr() It is used to determine the first occurrence of a given character in a string.
strrchr() It is used to determine the last occurrence of a given character in a string.
55
UNIT I TWO MARKS - C PROGRAMMING FUNDAMENTALS
Data Types – Variables – Operations – Expressions and Statements – Conditional Statements – Functions –
Recursive Functions – Arrays – Single and Multi-Dimensional Arrays.
1) Write down the steps involved to solve a problem. (Or) What are the main steps of problem solving?
(April / May 2017)
Define the problem.
Analyze the problem and formulate a method to solve it (see also “validation”).
Describe the solution in the form of an algorithm.
Draw a flowchart for the algorithm.
Write the computer program.
Compile and run the program (debugging).
Test the program (debugging) (see also “verification”) and Interpretation of results.
4) What are Constants? (Or) What are the different types of constants available in C? (April / May 2017)
Constants are the entity whose values can't be changed during the execution of a program.
Eg: x=3, Here 3 is a constant.
Constants are classified into two types. They are,
Numerical Constant
Character Constant
5) What is data type in C?
Data types are the keywords, which are used for assigning a type to a variable.
Allows the programmers to select the appropriate data type as per the need of the application.
56
Data types are used to specify the types of data that are going to process within the program.
6) What are the different data types available in C? [Nov/Dec 2016][May/June 2014][Nov/Dec 2018]
C supports 4 different types of data type. They are,
1. Primary Data Type – int, float, char, double
2. User Defined Data Type - typedef
3. Derived Data Type – array, pointer, struct, union
4. Empty Data Type - void
7) How many bytes are occupied by int, char, float, long int and double? [Nov/Dec 2019]
int - 2 Bytes
char - 1 Byte
float - 4 Bytes
long int - 4 Bytes
double - 8 Bytes
8) What is User Defined Data Type?
The keyword used to define user defined data type is “typedef”.
It allows users to define the identifier which would represent an existing data type.
The main advantage is it increases the program’s readability.
9) What is a Variable? (Or) What is a Variable? Illustrate with an example. (Nov/Dec 2014)
What are Variables? Give Examples. (May/June 2016)
Variables are memory location in computer's memory to store data.
To indicate the memory location, each variable should be given a unique name called identifier.
A variable is an identifier that is used to represent some specified type of information within a
designated portion of the program.
Syntax: Data_type variable name;
Example: int a; char m; float s;
10) Write down the rules for naming a variable. [Nov/Dec 2021]
Variable name can be composed of letters (both uppercase and lowercase letters), digits and
underscore '_' only.
The first letter of a variable should be either a letter or an underscore.
No commas or blank spaces are allowed within a variable name.
There is no rule for the length of length of a variable. However, the first 31 characters of a variable
are discriminated by the compiler.
11) Differentiate local variable and global variable.
Comparisons
Global Variable Local Variable
Basis
Global variables are declared outside Local variables are declared within
Definition
the functions the functions
Global variables are lost when the Local variables are lost when the
Lifetime
program is ended function ends
Local Variables doesn't offers Data
Data Sharing Global Variables Offers Data Sharing
Sharing
Scope Accessible throughout the code Accessible inside the function
Global variables are kept in a fixed
Storage Local variables are kept on the stack
location selected by the compiler
For global variables, parameter For local variables, parameter passing
Parameter Passing
passing is not necessary is necessary
Changes in a Changes in a global variable is Changes in a local variable doesn't
57
variable value reflected throughout the code affect other functions of the program
12) What are the various operators available in C? (Or) What are various types of C operators? (Jan 2014)
The various types of operators in C are,
1. Arithmetic Operators - +,-,*,/,%
2. Relational Operators - <,>,<=,>=,!=
3. Logical Operators - &&,||,!
4. Assignment Operators - =
5. Increment and Decrement Operators - ++,--
6. Conditional Operators - ?,:
7. Bitwise Operators - <<,>>,^,~,&,|
8. Special Operators - , &, sizeof, * ->
13) Define Special Operators. Nov / Dec 2017
Comma Operator
It is used to separate the statement elements such as variables, constants or expression, etc.
sizeof() Operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.
Address Operator / Indirection Operator
Address Operator (&) - This symbol is used to specify the address of the variable.
Indirection Operator (*) - It is used to specify the value of the variable.
Member Selection Operator
These symbols are used to access the elements from a structure.
14) What is Indirection Operator?
Asterisk (*) is the indirection operator used along with pointer variable while dereferencing the pointer
variable.
It is used to specify the value of the variable.
It is also called as value at operator.
15) What is the difference between ‘=’ and ‘==’ operator?
= is an assignment operator. Used to assign values to the variables.
== is a relational operator. Used to find the relation between the value and variable.
Example
i=5 is an infinite loop because it is a non zero value.
i==5 is true only when i=5.
16) What is the difference between ++a and a++? (or) Differentiate prefix and postfix increment operator.
[NOV/DEC 2022]
++a means do the increment before the operation (pre increment)
a++ means do the increment after the operation (post increment)
Example:
a=5;
x=a++; /* assign x=5*/
y=a; /*now y assigns y=6*/
x=++a; /*assigns x=7*/
17) What is the role of Associativity in prioritizing the operators? [Apr/May 2023]
The concept of operator precedence and Associativity in C helps in determining which operators
will be given priority when there are multiple operators in the expression.
It is very common to have multiple operators in C language and the compiler first evaluates the
operator with higher precedence.
58
It helps to maintain the ambiguity of the expression and helps us in avoiding unnecessary use of
parenthesis.
18) What is Type Conversion? (Or) Define Implicit Type Conversion. (May/June 2016)
It is a process of converting the type of an expression from one type to another type.
Eg: x = (int)10.45
19) What is the difference between if and while statement?
If While
It is a conditional statement It is a loop control statement
It the condition is true, it executes some Executes the statement within the while block if
statements the condition is true.
If the condition is false then it stops the execution If the condition is false the control is transferred to
the statements. the next statement of the loop.
20) Differentiate between while and do while statement. (Jan 2013, Nov / Dec 2016, 2017) [Nov/Dec
2020][Apr/May 2021] [Nov/Dec 2021]
while do….while
It is an entry controlled loop or top tested It is an exit controlled loop or bottom tested
loop. loop.
First the condition is tested, if it is true then It executes the body once, after it checks the
the block is executed until the condition condition, if it is true the body is executed
becomes false. until the condition becomes false.
Loop will not be executed if the condition is Loop will be executed at least once even
false. though the condition is false.
21) What is break statement?
It is used to terminate the loop.
When a break statement is used inside any C loop, then the loop is terminated.
Syntax: break;
22) Differentiate between break and continue statement.
Break Continue
Break statement takes the control to the outside Continue statement takes the control to the
of the loop. beginning of the loop.
It is also used in switch statement. This can be used only in looping statements.
Always associated with if condition in loops. This is also associated with if condition.
23) Write a for loop statement to print number from 10 to 1. (Jan 2014)
#include<stdio.h>
#include<conio.h>
void main() {
int i;
clrscr();
for(i=10; i>=1; i--) {
printf(“number is %d”, i);
}
getch();}
24) Write a code segment using while statement to print number from 10 to 1.
#include<stdio.h>
#include<conio.h>
59
void main() {
int x=10;
while(x<=1)
{
printf(“%d\n”,x);
x--;
}
getch();
}
25) Define Array. (Jan 2014) (Or) What is an Array? (May/June & Nov / Dec 2016)
What is an Array? How will you create a 2D array? (April / May 2017)
An array is a collection of similar data items that are stored under a common name.
ie., an array is a group of related data items that share a common name.
A value in an array is identified by index or subscript enclosed in square brackets with array
name.
26) How will you declare an array?
Arrays are declared in the same manner as ordinary variables except that each array name must
have the size of the array.
Here data-type is the type specifier that indicates what type of data the declared array is such as
int, float, double or char.
Array-Name is the name of the declared array and rules of declaring the variable applies to array
name.
Array-Size defines how many elements the array contains. This is always an integer.
Syntax
data_type array_name[size or subscript of the array];
Example
int x[3];
27) What are the features of an array? Nov / Dec 2017
An array is a derived data type.
The elements can be accessed with base address and the subscript defined for the position of the
element.
The elements in an array are stored in continuous memory location.
It is easier to refer the array elements by simply incrementing the value of the subscript.
28) Differentiate between array and structure.
Array Structure
An array is a collection of similar data Structure is a collection of different data
items of same type. items of different type.
An array is a derived data type. It is a user defined data type.
An array behaves like a built-in data type. It must be declared and defined.
29) Write example code to declare two dimensional arrays. (May/June 2014)
#include<stdio.h>
#include<conio.h>
void main() {
int i, j;
60
int x[2][2]={ {1,50},
{2,75}
};
clrscr();
for(i=0;i<2;i++)
for(j=0;j<2;j++)
printf("\n The value in x[%d][%d] is %d",i,j,x[i][j]);
getch();
}
Output:
The value in x[0][0] is 1
The value in x[0][1] is 50
The value in x[1][0] is 2
The value in x[1][1] is 75
30) What is array of characters? (Or) Define String. Give Examples. (May/June 2016)
How to declare strings in C? Nov / Dec 2016
A string is a collection of characters, digit, and symbols within quotes is called as string or
character array.
A string constant is a one dimensional array of characters terminated by a null (‘\0’) character.
‘\0’ is a null character used to specify the end of the string.
Eg: char a[]={‘a’,’b’,’c’,’\0’};
31) Give an example for initialization of string array. (Nov/Dec 2014)
String variable is always declared as an array.
The string can be initialized as follows,
char name[]=”BOB”; (or) char name[5];
The characters of the string are enclosed within a pair of double quotes.
32) Declare a character array of size 5 and assign vowels to it. (Nov/Dec 2015)
Character array can be declared as,
char vowels[SIZE]={'a','e','i','o','u'};
33) What is a static variable? Give example. (Apr/May 2019)
Static variables are initialized only once. The compiler persists with the variable till the end of the
program. Static variables can be defined inside or outside the function. They are local to the block. The
default value of static variables is zero. The static variables are alive till the execution of the program.
Here is the syntax of static variables in C language,
static datatype variable_name = value;
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
value − Any value to initialize the variable. By default, it is zero.
34) What is a Function? (Nov / Dec 2014) (Or) What is the need for function? (Jan 2014), (Nov / Dec
2016)
It is a set of instructions that are used to perform specified tasks which repeatedly occurs in the
main program.
Functions are a sub-program that contains one or more statements and it performs some task
when called.
35) What are the types of function? (Nov / Dec 2016)
Functions are classified into two types,
61
Pre-defined Functions
User-defined Functions
36) Tabulate pre defined or library function and user defined function.
User-defined Functions Library Functions
These functions are not predefined in the These functions are predefined in the compiler
Compiler. of C language.
These function are created by user as per These functions are not created by user as
their own requirement. their own.
User-defined functions are not stored in Library Functions are stored in special library
library file. file.
Execution of the program begins from the Execution of the program does not begin from
user-define function. the library function.
37) Give the advantages of user-defined functions. (Or) Specify the advantages of function. (May/June
2016)
The length of the source program can be reduced by dividing into it into smaller functions.
It is easy to locate and debug an error.
It avoids coding of repeated instructions.
38) What are the elements of user defined functions? (Or) What are the components of a function?
(April / May 2017)
The elements of user defined functions are,
Function Definition
Function Declaration
Function Call
39) Define Function Definition. (Or) What is Function Definition? (Nov/Dec 2015)
A function definition specifies the name of the function, the types and number of parameters it
expects to receive, and its return type.
Syntax: return-type function-name(parameters)
{
Body of the Function;
}
40) What is Parameter?
It provides the data communication between the calling function and called function.
62
There are two types of parameters. They are,
Actual Parameters
Formal Parameters
41) What is Actual Parameter?
These are the parameters transferred from the calling function (main program) to the called
function.
42) What is Formal Parameter?
These are the parameters which are used in the called function.
Recursion Iteration
Recursion uses the selection structure. Iteration uses the repetition structure.
64
The system crashes when infinite recursion is Iteration uses the CPU cycles again and again
encountered. when an infinite loop occurs.
Recursion terminates when the base case is Iteration terminates when the condition in the
met. loop fails.
Recursion is slower than iteration since it has Iteration is quick in comparison to recursion. It
the overhead of maintaining and updating doesn't utilize the stack.
the stack.
Recursion uses more memory in comparison Iteration uses less memory in comparison to
to iteration. recursion.
Recursion reduces the size of the code. Iteration increases the size of the code.
66
UNIT II - CPROGRAMMING - ADVANCED FEATURES
Structures - Union - Enumerated Data Types - Pointers: Pointers to Variables, Arrays and Functions - File
Handling - Preprocessor Directives.
STRUCTURE
Explain in detail about the structure with an example. Apr / May 2018 [Nov/Dec 2019] [Nov/Dec
2020][Apr/May 2021] [NOV/DEC 2022] [Apr/May 2023]
What is structure? Create a structure with data members of various types and declare two structure
variables. (Nov/Dec 2014) (Nov/Dec 2015)
Explain in detail the concept and importance of structures with example. (April / May 2017)
Structure Definition
A Structure is a collection of different data items that are stored under a common name.
Structure is a collection of data items of different data types which are grouped together and each
element in a C structure is called member.
Need for structure data type
Justify the need for structured data type. (Nov/Dec 2014)
Structure is a group name in which dissimilar data are grouped together.
Some problem have own memory space, so structure is needed.
Some problem also has many members that can be accessed at any time without the loss of the data.
Declaring a Structure
The structure can be declared with the keyword struct following the name and opening braces with
data elements of different type, then closing brace with semicolon.
Syntax
struct structure_name
{
structure element 1;
structure element 2;
…………………….
…………………….
structure element n;
};
struct structure_name v1,v2……..vn;
Where v1,v2…vn are called as structure variables.
Example
struct book
{
char title[20];
char author[15];
int pages;
float price;
};
struct book b1,b2,b3;
Rules for Declaring a Structure
A structure must end with a semicolon.
Usually a structure appears at the top of the source program.
1
Each structure element must be terminated.
The members of the structure can be accessed using the structure variables along with dot (.) operator.
Accessing Structure Elements
After declaring the structure type, variables and members, the member of the structure can be accessed
by using the structure variable along with the dot (.) operator.
Example
struct std
{
int no;
char name[15];
int marks;
};
struct std s;
For accessing the structure members from the above example.
s.no; s.name; s.marks;
Where ‘s’ is the structure variable.
Initialization of a Structure
Like normal variables, the structure variables can also be initialized, but this initialization can be made
at the compile time.
Example 1
struct std
{
int sno;
float avg;
}
main()
{
struct std person1 = {39, 39.11};
struct std person2 = {17, 17.25};
}
C language does not permit the initialization of individual structure member within the template. The
initialization must be done only in the declaration of the actual variables.
Rules for Initializing Structure
The individual data members of structure cannot be initialized.
The structure variables can be initialized at compile time only.
The order of data members in a structure must match the order of values in enclosed brackets.
The uninitialized data members can be initialized by default with zero (0) for int and float, ‘\0’ for
character and strings.
Structure within Structure (Structure Assignment / Nested Structure) Apr / May 2018 [Nov/Dec 2021]
It is possible to assign one structure information to another structure of same type using simple
assignment statement.
User Defined Data types
C provides a capability that enables the programmer to assign an alternate same to a data type. This is
done with a statement known as typedef.
Syntax
2
typedef type dataname;
Difference between Array and Structure
Array Structure
An array is a collection of similar data items of Structure is a collection of different data items
same type. of different type.
An array is a derived data type. It is a user defined data type.
An array behaves like a built-in data type. It must be declared and defined.
Example Program (Accessing Structure Elements)
#include<stdio.h>
#include<conio.h>
struct stud
{
int regno;
char name[10];
int m1;
int m2;
int m3;
};
struct stud s;
void main()
{
float total,avg;
printf("\n Enter the student regno,name,m1,m2,m3:");
scanf("%d%s%d%d%d",&s.regno,&s.name,&s.m1,&s.m2,&s.m3);
total=s.m1+s.m2+s.m3;
avg=total/3;
printf("\n The student Details are:");
printf("\n %d\t%s\t%f\t%f",s.regno,s.name,total,avg);
}
Output:
Enter the student regno, name, m1, m2, m3:
100
Mani
87
98
78
The student Details are:
100 Mani 263.000000 87.666664
Example Program (Student Mark Details using Structure)
Write a C program to create a mark sheet for students using structure. (Dec Jan 2014) (May/June 2016, Nov /
Dec 2016) [NOV/DEC 2022]
Write a C program and algorithm to create mark sheet for students using structure. Nov / Dec 2017
Write a C program to get 10 student details using structure from the user and display the details on the
screen. Nov 2018 [Nov/Dec 2019]
#include<stdio.h>
3
#include<conio.h>
struct stud
{
int regno;
char name[10],grade;
int m1,m2,m3;
float avg,tot;
} s[10];
void main()
{
int i,n;
printf("\n Enter the no.of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the student regno,name,m1,m2,m3:");
scanf("%d%s%d%d%d",&s[i].regno,&s[i].name,&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
if(s[i].m1<35||s[i].m2<35||s[i].m3<35)
s[i].grade='F';
else
{
if(s[i].avg>=75)
s[i].grade='D';
else if(s[i].avg>=60)
s[i].grade='A';
else if(s[i].avg>=50)
s[i].grade='B';
else if(s[i].avg>=35)
s[i].grade='C';
}
}
printf("\n STUDENT MARK LIST\n");
printf("\n REGNO\tNAME\tTOTAL\tAvg\tGRADE");
for(i=0;i<n;i++)
printf("\n%d\t%s\t%f\t%f\t%c",s[i].regno,s[i].name,s[i].tot,s[i].avg,s[i].grade);
getch();
}
Output
Enter the no. of students: 02 / 10
Enter the student regno, name, m1, m2, m3: 101
Babu
89
98
4
78
Enter the student regno, name, m1, m2, m3: 102
Mani
59
68
76
STUDENT MARK LIST
REGNO NAME TOTAL Avg GRADE
101 Babu 265.000000 88.333336 D
102 Mani 203.000000 67.666664 A
5
printf("\n HRA:%f",hra);
printf("\n DA:%f",da);
printf("\n Tax:%f",tax);
printf("\n Net Salary:%f",emp.nsal);
printf("\n Gross Salary:%f",emp.gross);
getch();
}
Output:
Employee Details:
Enter the Employee Name: Robin
Enter the Employee ID : 100
Enter the Basic Salary : 30000
Employee Name : Robin
Employee ID : 100
Employee Basic Salary: 30000.000000
HRA : 3000.000000
DA : 10,500.000000
Tax : 4500.000000
Gross Salary : 39000.000000
UNION
Write short notes on union. (Nov/Dec 2014) (Or) What is Union? Discuss with an example. (April/May 2015)
(Nov/Dec 2015, 2016) [Nov/Dec 2020][Apr/May 2021]
A Union is a collection of different data items that are stored under a common name. Here same
memory is shared by its members.
It is a derived data type and it is declared like structure.
In structure each member has its own storage location, whereas all the members of union use the same
location.
Syntax
union union_name
{
union member 1;
union member 2;
…………………..
union member n;
};
union union_variable;
Example
union result
{
int mark;
float avg;
char grade;
};
union result s;
6
Example Program using Union
#include<stdio.h>
#include<conio.h>
union stud {
int a;
char b[2];
};
void main()
{
union stud c;
c.a=256;
printf("\nc.a value is %d",c.a);
printf("\nc.b[0] value is %d",c.b[0]);
printf("\nc.b[1] value is%d",c.b[1]);
}
Output:
c.a value is 256
c.b[0] value is 0
c.b[1] value is 1
7
Example Program
/*Student Marks using Union*/
#include<stdio.h>
main()
{
union student
{
char name[20];
char regno[12];
int avg;
char grade;
}
stud[25],*ptr;
int i,no;
printf(“Enter the Number of the Students:”);
scanf(“%d”,&no);
for(i=0;i<no;i++)
{
printf(“\n Student [%d] Information:\n”,i+1);
printf(“Enter the Name:”);
scanf(“%s”,stud[i].name);
printf(“\n Enter the Roll No of the Student:”);
scanf(“%s”,stud[i].regno);
printf(“\n Enter the Average Value of the Student:”);
scanf(“%d”,&stud[i].avg);
}
pt=stud;
for(pt=stud;pt<stud+no;ptr++)
{
if(ptr->avg<30)
ptr->grade=’D’;
else if(ptr->avg<50)
ptr->grade=’C’;
else if(ptr->avg<70)
ptr->grade=’B’;
else
ptr->grade=’A’;
}
printf(“\n”);
printf(“NAME REGISTER-NO AVERAGE GRADE\n”);
for(ptr=stud;ptr<stud+no;pt++)
{
printf(“%-20s%-10s”,ptr->name,ptr->regno); printf(“%10d \t %c\n”,ptr->avg,ptr->grade);
}
}Output:
8
Enter the Number of the Students… 3
Student [1] Information:
Enter the Name: Jack
Enter the Roll No of the Student: 31705205001
Enter the Average Value of the Student: 90
Student [2] Information:
Enter the Name: Raj
Enter the Roll No of the Student: 31705205002
Enter the Average Value of the Student: 88
Student [3] Information:
Enter the Name: Kiran
Enter the Roll No of the Student: 31705205003
Enter the Average Value of the Student: 75
NAME REGISTER-NO AVERAGE GRADE
Jack 31705205001 90 S
Raj 31705205002 88 A
Kiran 31705205003 75 B
Difference between Data types, Structure and Union [Nov/Dec 2020][Apr/May 2021] [Apr/May 2023]
Data types Structure Union
Data type is used to declare Structure is a collection of Structure is a collection of
a type to a variable. different data items of different different data items of different
It is a predefined data type type stored under a common type.
Syntax : datatype variable name. It is a derived data type.
name; It is a user defined data type. In union, all the members have
Data type cannot be In structure, each member has its a common storage location.
modified by user. Data type own storage location. Members cannot be accessed at
has fixed meaning. Members can be accessed at the the same time.
same time.
POINTERS
Discuss in detail about pointer with an example. (Or) Explain in detail the concept of pointer in C
language. (April / May 2017)
Pointer is a variable which contains the memory address of another variable. (Or) A pointer is a
variable whose value is the address of another variable.
The memory address is the location where program instructions and data are stored; pointers can be
used to access and manipulate data stored in the memory.
Example
a=10
a Variable
10 Value
80F Address
9
The variable that holds memory address is called pointer variables.
A pointer variable is therefore nothing but a variable that contains an address, which is a location of
another variable.
Value of pointer variable will be stored in another memory location.
Features of Pointers
It is more efficient in handling array and structure.
It is used for saving memory space.
It reduces the length and complexity of the program.
It provides dynamic memory allocation.
Advantages of Pointers
It is more compact and efficient code.
It is used to achieve clarity and simplicity.
It enables us to access the memory directly.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int x=5;
printf("\n The Address of x = %u",&x);
printf("\n The Value of x = %d",x);
}
Output
The Address of x = 8714
The Value of x = 5
Declaring a Pointer Variable
Pointer is a variable that contains the address of another variable.
Syntax: data_type *pointer-name;
Eg: int *a;
Initialization of Pointer Variable (Accessing the Pointer Variable)
10
Pointer Initialization is the process of assigning address of a variable to pointer variable.
Pointer variable contains address of variable of same data type.
In C language address operator (&) is used to determine the address of a variable.
The ampersand (&) returns the address of the variable associated with it.
int a = 10 ;
int *ptr ; // Pointer Declaration
ptr = &a ; // Pointer Initialization
(Or)
int *ptr = &a ; // Initialization and Declaration Together
The ampersand (&) is an operator, which is used to access the address of a variable and assign it to a
pointer to initialize it.
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator (*).
Example Program 1
#include<stdio.h>
#include<conio.h>
void main()
{
int x=5;
int *a;
a=&x;
printf("\n The Value of x = %d",x);
printf("\n The Address of x = %u",&x);
printf("\n The Value of a = %d",a);
printf("\n The Value of x = %d",*a);
}
Output
The Value of x = 5
The Address of x = 8758
The Value of a = 8758
The Value of x = 5
Example Program 2
#include<stdio.h>
#include<conio.h>
void main()
{
int y=10;
int *a;
a=&y;
printf("\n The Value of y = %d",y);
printf("\n The Address of y = %u",&y);
printf("\n The Value of a = %d",a);
printf("\n The Address of a = %u",&a);
}
11
Output
The Value of y = 10
The Address of y = 5001
The Value of a = 5001
The Address of a = 8000
Null Pointer
A pointer is said to be null pointer if zero is assigned to the pointer.
Example
int *a,*b;
a=b=0;
Pointer to Pointer
Here one pointer stores the address of another pointer variable.
Example:
int x=10,*a,**b;
a=&x;
b=&a;
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *b,**c;
b=&a;
c=&b;
printf("\n The Value of a = %d",a);
printf("\n The Address of a = %u",&a);
printf("\n The Value of b = %d",b);
printf("\n The Address of b = %u",&b);
printf("\n The Value of c = %d",c);
printf("\n The Address of c = %u",&c);
}
Output
The Value of a = 10
The Address of a = 5001
The Value of b = 5001
The Address of b = 8000
The Value of c = 8000
The Address of c = 9000
12
POINTERS ARITHMETIC
Explain in detail about pointers arithmetic with suitable example.
A pointer in C is an address, which is a numeric value. Therefore we can perform arithmetic operations
on a pointer as we do on a numeric value.
The arithmetic operations on pointer variable affect the memory address pointed by pointer.
The different types of arithmetic operations performed on pointers are,
Incrementing Pointer
Decrementing Pointer
Pointer Addition
Pointer Subtraction
Pointer Comparison
Incrementing Pointer
Incrementing a pointer to an integer data will cause its value to be incremented by 2.
This differs from compiler to compiler as memory required to store integer vary compiler to compiler
Incrementing Pointer Variable Depends Upon data type of the Pointer variable.
Syntax:
new_value = current_address + i * sizeof(pointer_data type)
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3] = {10,20,30};
int i, *ptr;
clrscr();
ptr = a;
for(i=0; i<3; i++)
{
printf("\n Address=%x",ptr);
printf("\t Value=%d",*ptr);
ptr++;
13
}
getch();
}
Output:
Address = fff0 Value=10
Address = fff2 Value=20
Address = fff4 Value=30
Decrementing Pointer
Decrementing a pointer to an integer data will cause its value to be decremented by 2.
This differs from compiler to compiler as memory required to store integer vary compiler to compiler.
Decrementing of pointer variable depends upon data type of the pointer variable.
Syntax:
new_address = current_address - i * sizeof(pointer_data type)
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3] = {10,20,30};
int i, *ptr;
clrscr();
ptr = &a[2];
for(i=3; i>0; i--)
{
printf("\n Address=%x",ptr);
printf("\t Value=%d",*ptr);
ptr--;
}
getch();
}
14
Output:
Address = fff4 Value=30
Address = fff2 Value=20
Address = fff0 Value=10
Pointer Addition
In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable.
Syntax:
final_value = (address) + (number * sizeof(pointer_data type))
Consider the following example,
int *ptr , n;
ptr = &n ;
ptr = ptr + 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
printf(“%d”, (*x + *y));
getch();
}
Output:
15
Pointer Subtraction
In C Programming we can subtract any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable.
Syntax:
ptr = initial_address - n * (sizeof(pointer_data_type))
For Example,
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
15
printf(“%d”, (*x - *y));
getch();
}
Output: -5
Pointer Comparison [NOV/DEC 2022]
Pointer comparison is valid only if the two pointers are pointing to same array.
All Relational Operators can be used for comparing pointers of same type.
All Equality and Inequality Operators can be used with all Pointer types.
Pointers cannot be Divided or Multiplied.
Example
#include<stdio.h>
int main()
{
int *ptr1;
float *ptr2;
ptr1 = (int *) 1000;
ptr2 = (float *) 2000;
if(ptr2 > ptr1)
printf("ptr2 is far from ptr1");
return(0);
}
Output:
ptr2 is far from ptr1
16
printf("Address of c[%d]=%x\n",i,&c[i]);
}
return 0;
}
Output:
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47
Relation between Arrays and Pointers
int num[5];
In arrays, name of the array always points to the first element of an array.
Here, address of first element of an array is &num[0].
Also, num represents the address of the pointer where it is pointing. Hence, &num[0] is equivalent to
arr.
Also, value inside the address &num[0] and address num are equal. Value in address &num[0] is
num[0] and value in address num is *num.
Hence, num[0] is equivalent to *arr.
Similarly,
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).
Example
// Program to find the sum of six numbers with arrays and pointers.
#include<stdio.h>
int main()
{
int i,class[6],sum=0;
printf("Enter 6 Numbers:\n");
for(i=0;i<6;++i)
{
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}
17
Output:
Enter 6 Numbers:
2
3
4
5
3
4
Sum=21
Example of Pointer and Functions
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main()
{
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */
printf("Number 1 = %d\n",num1);
printf("Number 2 = %d",num2);
return 0;
}
void swap(int *a,int *b) /* pointer a and b points to address of num1 and num2 respectively */
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
Number 1 = 10
Number 2 = 5
Explanation
The address of memory location num1 and num2 are passed to function and the pointers *a and *b
accept those values.
So, the pointer a and b points to address of num1 and num2 respectively.
When, the values of pointer are changed, the value in memory location also changed correspondingly.
Hence, change made to *a and *b was reflected in num1 and num2 in main function.
Pointers with Multi-Dimensional Array
A multidimensional array can also be represented with an equivalent pointer notation.
Syntax
data-type (*pointer variable) [Expression2];
Example
int (*a)[20]; //Pointer
18
int a[10][20]; //Array
Example Program
#include<stdio.h>
main()
{
int arr[3][2] = {
{5, 100},
{10, 101},
{15, 102},
};
int a, b;
for(a=0;a<3;a++)
{
printf(“address of %d array=%u”,a,&arr[a]);
for(b=0;b<2;b++)
printf(“value =%d”,arr[a][b]);
}
}
Output
Address of 0 Array=4000
Value=5
Value=100
Address of 1 Array=4002
Value=10
Value=101
Address of 2 Array=4000
Value=15
Value=102
Pointers and Strings
Character and Pointer
A character pointer is a pointer to the character.
It can be declared as,
char *pointer_character;
String and Pointer
char *pointers message;
19
Compiler breaks either approach to a pointer to the base address of the array, i.e. int* array so
passing int array[3] or int array[] or int* array breaks down to the same thing and to access any
element of array compiler can find its value stored in location calculated using the formula
stated above.
Passing the array to function in C is called as pass by reference.
21
return 0;
}
float findAverage(int arr[], int size)
{
int
i;
float
sum = 0,
avg = 0;
for (i = 0; i < size; i++)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
Output:
Average: 80.000000
FILES:[APR/MAY 2022]
INTRODUCTION TO FILES:
A file is a collection of related data that a computers treats as a single unit.
A File is a collection of data stored in the secondary memory.
C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
Files are not only used for storing the data, programs are also stored in files.
How is a file stored?
– Stored as sequence of bytes, logically contiguous.
(may not be physically contiguous on disk).
Why files are needed?
When a program is terminated, the entire data is lost.
Storing in a file will preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the file using
few commands in C.
You can easily move your data from one computer to another without any changes.
Types of Files
There are two types of files.
Text :contains ASCII codes only
Binary :can contain non-ASCII characters
Image, audio, video, executable, etc.
FILE HANDLING (or) BASIC FILE OPERATIONS [APR/MAY 2022]
Explain in detail various operations that can be done on file giving suitable examples. [APR/MAY
2019][Apr/May2021][Nov/Dec2020]
Discuss about the modes of file handling. [NOV/DEC 2019]
1. Declare a file pointer variable.
2. fopen - open a file- specify how its opened (read/write) and type (binary/text).
3. fclose - close an opened file
4. fread - read from a file
5. fwrite - write to a file
6. fseek/fsetpos - move a file pointer to somewhere in a file.
22
7. ftell/fgetpos - tell you where the file pointer is located.
1. Declaration of file pointer
A pointer variable is used to points a structure FILE.
The members of the FILE structure are used by the program in various file access operation, but
programmers do not need to concerned about them.
FILE *file_pointer_name;
Eg : FILE *fp
Example programs
Program to check whether the file exist or not */
void main()
{
FILE *fp;
char *x;
clrscr();
printf("\n enter the file name : ");
gets(x);
23
fp=fopen(x,"r");
if(fp==NULL)
{
printf("The file ---%s--- is not found in the present directory",x);
}
else
{
printf("The file ---%s--- is found in the present directory",x);
}
fclose(fp);
getch();
}
Reading and Writing Files
Exapmle :
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f \n ", a, b, c) ;
printf (“ %f %d %f \n ", e, f, g) ;
fread ()
syntax:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
Example:
#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.txt", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
return 0;
24
}
fwrite()
Syntax: size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
fwrite appends a specified number of equal-sized data items to an output file.
ptr = Pointer to any object; the data written begins at ptr
size = Length of each item of data
n =Number of data items to be appended
stream = file pointer
Example:
#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
Character input / output:
Two functions are used to read the character from the file and write it into
another file.
These functions are getc() & putc() functions. Its prototype is,
int getc(FILE *file_pointer);
putc( char const_char, FILE *file_pointer);
Eg: while((c=getc(fp)!=EOF).
Examples:
/* Read a string into a text file */
void main()
{
FILE *fp;
char text[80];
int i;
clrscr();
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
for(i=0;i<strlen(text);i++) // Read a stream of charcters
putc(text[i],fp);
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
getch();
}
Working with Text files :
C provides various functions to working with text files.
25
Four functions can be used to read text files and four functions that can be used to write text files into a
disk. These are,
fscanf() & fprintf()
fgets() & fputs()
fgetc() & fputc()
fread() & fwrite()
The prototypes of the above functions are,
1. int fscanf(FILE *stream, const char *format,list);
2. int getc(FILE *stream);
3. char *fgets(char *str,int n,FILE *fp);
4. int fread(void *str,size_t size,size_t num, FILE *stream);
5. int fprintf(FILE *stream, const char *format,list);
6. int fputc(int c, FILE *stream);
7. int fputs(const char *str,FILE *stream);
8. int fwrite(const void *str,size_t size, size_t count,FILE *stream);
fprintf()
Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
getc()
Syntax:
identifier = getc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
putc()
write a single character to the output file, pointed to by fp.
Example:
FILE *fp;
char ch;
putc (ch,fp);
26
End of file
There are a number of ways to test for the end-of-file condition.
Another way is to use the value returned by the fscanf function:
Example:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}
fseek()
This function sets the file position indicator for the stream pointed to by stream or you can say it seeks
a specified place within a file and modify it.
SEEK_SET Seeks from beginning of file
SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file
Example:
#include <stdio.h>
int main()
{
FILE * f;
f = fopen("myfile.txt", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);
fclose(f);
return 0;
}
ftell()
syntax:
offset = ftell( file pointer );
"ftell" returns the current position for input or output on the file
Example:
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}
Example programs on text files:
/* Read a string into a text file using fputs() function */
void main()
{
FILE *fp;
char text[80];
27
int i;
clrscr();
fp=fopen("Sample.txt","w");
printf("\n Enter the text : ");
gets(text);
fputs(text,fp); //write a string into a file
if(fp!=NULL)
printf("\n The string copied into a text file ");
fclose(fp);
getch();
}
/* Program to copy from one file to another file */ [Nov/Dec2021]
void main()
{
FILE *fp,*fp1;
int ch;
clrscr();
fp=fopen("ex_file4.c","r");
fp1=fopen("ex_file2.c","w");
if(fp==NULL)
printf(“File is not available”);
ch=getc(fp);
while(ch!=EOF)
{
putc(ch,fp1);
ch=getc(fp);
}
fclose(fp);
fclose(fp1);
getch(); }
29
Rules for Defining Preprocessor
Every preprocessor must start with # symbol.
The preprocessor is always placed before main() function.
The preprocessor cannot have termination with semicolon.
There is no assignment operator in #define statement.
A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.
Below is the list of preprocessor directives that C language offers.
1. File Inclusion
2. Macro Substitution
3. Conditional Inclusion
1. File Inclusion
This is used to include an external file, which contains functions or some other macro definitions to our
source program.
Syntax
#include”Filename” and #include<Filename>
Where Filename is the name of the file that can be included in our source program.
When ‘filename’ is quoted, it searches for that file in current directory and then in standard directories.
When ‘filename’ is included in the angle brackets (< >), the included file is searched only in the
standard directory.
Example
#include<stdio.h>
#include”loop.c”
Where “stdio.h” is the file that contains standard I/O function in ‘C’ standard directory and “loop.c” is the
program written by the user.
Example Program
#include<stdio.h>
#include<conio.h>
#include "addition.txt"
void main()
{
int a,b;
printf("\n Enter the Numbers:");
scanf("%d%d",&a,&b);
printf("The Value is %d",add(a,b));
getch();
}
addition.txt
int add(int a,int b)
{
return(a+b);
}
Output:
Enter the Numbers: 7 4
The Value is 11
30
2. Macro Substitutions [NOV/DEC 2022]
This is used to define symbolic constants in the source program. The identifier or string or integer
defined is replaced by macro substitution.
ie., It is used to define and use integer, string, or identifier in the source program.
There are three types of macros.
Simple Macros
Augmented Macros
Nested Macros
(i). Simple Macros
It is commonly used to define symbolic constants
Syntax
# define identifier string/integer
Eg:
#define A 10
#define pi 3.14
#define CITY “chennai”
Example Program
#include<stdio.h>
#include<conio.h>
#define pi 3.14
#define CITY "chennai"
void main()
{
printf("The Value is %f",2*pi);
printf("\n The Value CITY is %s",CITY);
getch();
}
Output:
The Value is 6.280000
The Value CITY is Chennai
(ii). Augmented Macros
It is used to define more complex forms in the source program.
Syntax
#define identifier (v1,v2,….) string/integer
Eg:
#define cube(n) (n*n*n)
Example Program
#include<stdio.h>
#include<conio.h>
#define cube(n) (n*n*n)
void main()
{
printf("\n The Value of 3 cube is %d",cube(3));
getch();
}
31
Output:
The Value of 3 cube is 27
(iii). Nested Macro
Here one macro is used by another macro.
Eg:
#define a 3
#define sq a*a
Example Program
#include<stdio.h>
#include<conio.h>
#define a 3
#define sq a*a
void main()
{
printf("\n The Value is %d",sq);
getch();
}
Output:
The Value is 9
3. Conditional Inclusion
These are used to control the preprocessor with conditional statements.
The preprocessor directives are,
#if, #elif (else if) – It allows only constant expression. #elif establishes an if-else-if chain for multiple
compilation options.
#define – Used to define symbolic constant.
#ifdef – It is used to check the identifier was defined as a macro name.
#ifndef - It is used to check the identifier was not defined as a macro name.
#else – It allows only constant expression. If the result of the expression is TRUE, then block of
statement between #if and #endif is followed. If the result of the expression is FALSE, then block of
statement between #if and #endif is skipped.
#undef – Used to undefine a macro.
Example Program
#include<stdio.h>
#include<conio.h>
#define a 3
#ifdef a
#define c a+5
#endif
void main()
{
printf("\n The value C is %d",c);
getch();
}
Output: The value C is 8
32
UNIT II TWO MARKS – C PROGRAMMING – ADVANCED FEATURES
Structures – Union – Enumerated Data Types – Pointers: Pointers to Variables, Arrays and Functions – File
Handling – Preprocessor Directives.
1) Define Structure. What is a Structure? (Or) What do you mean by structure? (May/June, Nov / Dec
2016, 2017)
Structure is a collection of data items of different data types which are grouped together and
each element in a C structure is called member.
(Or)
A Structure is a collection of different data items that are stored under a common name.
2) How will you declare a structure?
The structure can be declared with the keyword struct following the name and opening braces
with data elements of different type, then closing brace with semicolon.
Syntax
struct structure_name
{
structure element 1;
structure element 2;
…………………….
…………………….
structure element n;
};
struct structure_name v1,v2……..vn;
Where v1,v2…vn are called as structure variables.
3) Write the rules for declaring a structure.
A structure must end with a semicolon.
Usually a structure appears at the top of the source program.
Each structure element must be terminated.
The members of the structure can be accessed using the structure variables along with dot (.)
operator.
4) How will you access the elements of a structure?
After declaring the structure type, variables and members, the member of the structure can be
accessed by using the structure variable along with the dot (.) operator.
Syntax: Structure_variable_name.member_name
Example
struct std
{
int no;
char name[15];
int marks;
};
struct std s;
For accessing the structure members from the above example.
s.no; s.name; s.marks;
Where ‘s’ is the structure variable.
5) Write the rules for initialization of a structure.
33
The individual data members of structure cannot be initialized.
The structure variables can be initialized at compile time only.
The order of data members in a structure must match the order of values in enclosed brackets.
The uninitialized data members can be initialized by default with zero (0) for int and float, ‘\0’
for character and strings.
6) What is Nested Structure?
It is a process of assigning one structure information into another structure of same type using
simple assignment statement.
7) What are the advantages of using array? Apr / May 2018
1. It is used to represent multiple data items of same type by using only single name.
2. It can be used to implement other data structures like linked lists, stacks, queues, trees,
graphs etc.
3. 2D arrays are used to represent matrices.
8) Compare array with structure. (Or) Differentiate between array and structure. (Dec/Jan 2014)
Array Structure
An array is a collection of similar data items Structure is a collection of different
of same type. data items of different type.
An array is a derived data type. It is a user defined data type.
An array behaves like a built-in data type. It must be declared and defined.
9) Define Union. (Or) What is Union? (Or) What is the purpose of unions in C? (May/June 2014) (Or)
State the importance of union. (May/June 2016) [Nov/Dec 2020][Apr/May 2021]
A Union is a collection of different data items that are stored under a common name. Here
same memory is shared by its members.
It is a derived data type and it is declared like structure.
In structure each member has its own storage location, whereas all the members of union use
the same location.
10) How will you declare a union?
Syntax
union union_name
{
union member 1;
union member 2;
…………………..
union member n;
};
union union_variable;
11) Difference between Structure and Union. Nov 2018
Structure Union
Structure is a collection of different data Structure is a collection of different
items of different type stored under a data items of different type.
common name. It is a derived data type.
It is a user defined data type. In union, all the members have a
In structure, each member has its own common storage location.
storage location. Members cannot be accessed at the
Members can be accessed at the same time. same time.
12) What is a Storage Class? (Or) What are Storage Classes? (April / May, Nov / Dec 2017)
34
A storage class defines the scope (visibility) and life time of variables and/or functions within a
C program.
What are the various types of storage classes in C? (Or) What are the storage classes available in C?
13) (April / May 2017)
There are following storage classes which can be used in a C program.
auto
register
static
extern
14) What is Pointer? (Or) Define Pointer. (Or) What is the use of Pointers? (or) Define a pointer and
initialize it. (Apr/May 2019) (Jan 2014), Nov / Dec 2016
Pointer is a variable which contains the memory address of another variable.
The memory address is the location where program instructions and data are stored; pointers
can be used to access and manipulate data stored in the memory.
It is always denoted by ‘*’ operator.
Pointer initialization int *a,b;
a=&b;
15) Write down the features of pointer. What are the advantages of using pointers in a program? Nov /
Dec 2017
It is efficient in handling data.
It is used for saving memory space.
It reduces the length and complexity of the program.
It provides dynamic memory allocation.
Two dimensional and multidimensional array representations are easy in pointers.
17) How will you declare a pointer? How pointer variable is initialized? Apr / May 2018
Pointer is a variable that contains the address of another variable.
Syntax: data_type *pointer-name;
Eg: int *a;
35
The indirection operator (*) returns the value of the variable stored in a pointer.
The address operator (&) returns the memory address of the variable.
26) What are the different types of arithmetic operations performed on pointers? (or)
List some of pointer manipulations allowed in C language. [Nov/Dec 2021]
Incrementing Pointer
Decrementing Pointer
Pointer Addition
Pointer Subtraction
Pointer Comparison
28) What are the various dynamic memory allocation functions? (April / May 2017)
malloc() - Used to allocate blocks of memory in required size of bytes.
36
free() - Used to release previously allocated memory space.
calloc() - Used to allocate memory space for an array of elements.
realloac() - Used to modify the size of the previously allocated memory space.
29) What is Preprocessor Directive? (Or) What is the use of preprocessor directives? (May/June 2014)
(Or) Define Pre-processor directives in C and list out few examples. (April / May 2015, 2018) Nov
2018 (Apr/May 2019)
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with “#”
symbol.
31) What are different types of preprocessor directives in C? (Or) Write any two preprocessor directive
in C. (Dec/Jan 2014) Nov 2018 (Apr/May 2019)
The different types of preprocessor directives in C language are,
File Inclusion
Macro Substitution
Conditional Inclusion
37
35) What is Simple Macros?
It is commonly used to define symbolic constants
Syntax
# define identifier string/integer
Eg:
#define A 10
#define pi 3.14
#define CITY “chennai”
41) What are two main ways a file can be organized? [NOV/DEC 2019]
Sequential file organization
Indexed file organization
42) Write the types of Files.
There are two types of files.
38
Text :contains ASCII codes only
Binary :can contain non-ASCII characters
Image, audio, video, executable, etc.
43) Write the modes of file handling or file operations. [NOV/DEC 2019]
Declare a file pointer variable.
fopen - open a file- specify how its opened (read/write) and type (binary/text).
fclose - close an opened file
fread - read from a file
fwrite - write to a file
fseek/fsetpos - move a file pointer to somewhere in a file.
ftell/fgetpos - tell you where the file pointer is located.
Exaple:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}
"ftell" returns the current position for input or output on the file
40
55) Write the function used in Random Access To File.
There is no need to read each record sequentially, if we want to access a particular record. C
supports these functions for random access file processing.
fseek()
ftell()
rewind()
56) What is the difference between sequential access and random access files.
[Nov/Dec2020][Apr/May2021]
Record In sequential access files, record Random access files, record sizes can
Sizes sizes are usually uniform be variable
41
Parameter Sequential Access Random Access
57) Can you subtract pointers from each other? State the reason. [Nov/Dec 2020][Apr/May 2021]
In C Programming we can subtract any integer number to Pointer variable. It is perfectly legal in c
programming to add integer to pointer variable.
Syntax:
ptr = initial_address - n * (sizeof(pointer_data_type))
For Example,
int *ptr , n;
ptr = &n ;
ptr = ptr - 3;
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10;
int *x, *y;
clrscr();
x = &a, y = &b;
printf(“%d”, (*x - *y));
getch();
}
58) What is enumerated data types? Write the syntax. [NOV/DEC 2022][Apr/May 2023]
Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant
integrals or integers that are given names by a user. The use of enum in C to name the integer values
makes the entire program easy to learn, understand, and maintain by the same or even different
programmer.
Syntax:
enum variablename {constant1, constant 2…constant n};
example:
The keyword ‘enum’ is used to declare new enumeration types in C and C++.
Variables of type enum can also be defined. They can be defined in two ways:
enum week{Mon, Tue, Wed};
enum week day;
// Or
enum week{Mon, Tue, Wed}day;
42
II YEAR / III SEMESTER
CS3353 C PROGRAMMING AND DATASTRUCTURES
(Regulation – 2021)
QUESTION BANK
UNIT 2
1. Discuss about Structures with suitable example.
2. Differentiate structures and union. Explain union with suitable example.
3. Explain pointer arithmetic with suitable example.
4. Explain about pointers, pointers to arrays and functions.
5. Discuss about file handling or file operations with suitable example.
6. Explain in detail about preprocessor directives with an example.
7. Write a note on enumerated data types with example.
43
UNIT III 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.
DATA STRUCTURE
Introduction:
Data Structure can be defined as the group of data elements which provides an efficient way of
storing and organizing data in the computer so that it can be used efficiently.
Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
Data Structures are widely used in almost every aspect of Computer Science i.e. operating System,
Compiler Design, Artificial intelligence, Graphics and many more.
A data structure is a set of domains D, a set of functions F and set of axioms A. this triple (D,F,A)
denotes the data structure d.
Types of data structure
Data structure can be divided into two basic types.
i. Preliminary data structure (or) primitive data structure.
ii. Secondary data structure (or) non primitive data structures
Page 2
4) Searching: The process of finding the location of an element within the data structure is called
Searching. There are two algorithms to perform searching, Linear Search and Binary Search.
5) Sorting: The process of arranging the data structure in a specific order is known as Sorting. There are
many algorithms that can be used to perform sorting, for example, insertion sort, selection sort, bubble
sort, etc.
6) Merging: When two lists List A and List B of size M and N respectively, of similar type of elements,
clubbed or joined to produce the third list, List C of size (M+N), then this process is called merging.
Application of data structures:
Data structures are widely applied in the following areas:
Compiler design
Operating system
Statistical analysis package
DBMS
Numerical analysis
Simulation
Artificial intelligence
Graphics
Definition
The abstract data type is a triple of D – set of domains, F – set of functions, A-Axioms in which only
what is to be done is mentioned but how is to be done is not mentioned.
In ADT, all the implementation details are hidden.
In short
ADT=Type + Function names + Behavior of each function
An Abstract Data Type (ADT) is:
o a set of values
o a set of operations, which can be applied uniformly to all these values
ADT operations
While modeling the problems the necessary details are separated out from the unnecessary details.
This process of modeling the problem is called abstraction.
Page 3
The model defines an abstract view to the problem.
Various abstract data types operations are
i. Create – creates the database
ii. Display – display all the elements of the data structure.
iii. Insertion – elements can be inserted at any desired position
iv. Deletion – desired element can be deleted from the data structure
v. Modification – modifies the desired elements value by any desired new value.
ADT Data Structures
The ADT operations are carried out with the help of data structure.
This part describes the structure of the data used in the ADT in an informal way.
Various data structure that can be used for ADT are Arrays, Set, Linked list, Stack, Queues and so on.
Examples
ADT for Set
If we want to write for a set of integers, then we will use following method
AbstractDatatype Set
{
Instances: Set is a collection of integer type of elements
Preconditions: none
Operations:
1. Store ( ): this operation is for storing the integer element in a set
2. Retrieve ( ): This operation is for retrieving the desired element from the given set
3. Display ( ): This operation is for displaying the contents of set
}
ADT for Arrays
AbstractDataTypes Array
{
Instances: An array A of some size, index I and total number of elements in the array n.
Operations:
1. Store() – this operations stores the desired elements at each successive location.
2. Display() – this operation displays the elements of the array.
}
List ADT
List is a collection of elements in sequential order.
In memory we can store the list in two ways, one way is we can store the elements in sequential
memory locations
This is known as arrays.
We can use pointers or links to associate the elements sequentially.
This is known as linked lists.
List is an ordered set of elements. The general form of the list is
A1 A2,A3.....AN
A1,- First element of the list
An,-Last element of the list
Page 4
N-Size of the list
Various operations performed on List:
Insert(X,5) - Insert the element X after the position 5.
Delete(X)- The element X is deleted
Find(X)- Returns the position of X.
Next (i)- Returns the position of its successor element i+1.
Previous (i)- Returns the position of its predecessor i-1.
Printlist– Contents of the list is displayed.
Makeempty –Makes the list empty.
Implementation of List ADT
o Array Implementation
o Linked List Implementation
o Cursor Implementation
Create Operation:
Create operation is used to create the list with n- number of elements. If n exceeds the
array’s maxsize, then elements cannot be inserted into the list. Otherwise the array elements are
stored in the consecutive array locations (i.e.) list [0], list [1] and so on.
void Create ( )
{
int i;
printf("\nEnter the number of elements to be added in the list:\t");
Page 5
scanf("%d",&n);
printf("\nEnter the array elements:\t");
for(i=0;i<n;i++)
scanf("%d",&list[i]);
}
If n=6, the output of creation is as follows:
list[6]
Insert Operation:
Insert operation is used to insert an element at particular position in the existing list. Inserting the
element in the last position of an array is easy. But inserting the element at a particular position in an
array is quite difficult since it involves all the subsequent elements to be shifted one position to the right.
Routine to insert an element in the array:
void Insert( )
{
int i,data,pos;
printf("\nEnter the data to be inserted:\t");
scanf("%d",&data);
printf("\nEnter the position at which element to be inserted:\t");
scanf("%d",&pos);
if (pos==n)
printf (“Array overflow”);
for(i = n-1 ; i >= pos ; i--)
list[i+1] = list[i];
list[pos] = data;
n=n+1;
Display();
}
Consider an array with 5 elements [ max elements = 10]
10 20 30 40 50
If data 15 is to be inserted in the 2nd position then 50 has to be moved to next index position, 40 has to be
moved to 50 position, 30 has to be moved to 40 position and 20 has to be moved to 30 position.
10 20 30 40 50
10 20 30 40 50
After this four data movement, 15 is inserted in the 2nd position of the array.
10 15 20 30 40 50
Page 6
Deletion Operation:
Deletion is the process of removing an element from the array at any position.
Deleting an element from the end is easy. If an element is to be deleted from any particular position,
it requires all subsequent element from that position is shifted one position towards left.
Routine to delete an element in the array:
void Delete( )
{
int i, pos ;
printf("\nEnter the position of the data to be deleted:\t");
scanf("%d",&pos);
printf("\nThe data deleted is:\t %d", list[pos-1]);
for(i=pos-1;i<n-1;i++)
list[i]=list[i+1];
n=n-1;
Display();
}
Consider an array with 5 elements [ max elements = 10 ]
10 20 30 40 50
If data 20 is to be deleted from the array, then 30 has to be moved to data 20 position, 40 has to be moved
to data 30 position and 50 has to be moved to data 40 position.
10 20 30 40 50
After this 3 data movements, data 20 is deleted from the 2nd position of the array.
10 30 40 50
Display Operation/Traversing a list
Traversal is the process of visiting the elements in a array.
Display( ) operation is used to display all the elements stored in the list. The elements are stored
from the index 0 to n - 1. Using a for loop, the elements in the list are viewed
Routine to traverse/display elements of the array:
void display( )
{
int i;
printf("\n**********Elements in the array**********\n");
for(i=0;i<n;i++)
printf("%d\t",list[i]);
}
Search Operation:
Search( ) operation is used to determine whether a particular element is present in the list or not.
Input the search element to be checked in the list.
Routine to search an element in the array:
void Search( )
{
int search,i,count = 0;
printf("\nEnter the element to be searched:\t");
Page 7
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(search == list[i])
count++;
}
if(count==0)
printf("\nElement not present in the list");
else
printf("\nElement present in the list");
}
Program for array implementation of List
#include<stdio.h>
#include<conio.h>
#define maxsize 10
int list[maxsize],n;
void Create();
void Insert();
void Delete();
void Display();
void Search();
void main()
{
int choice;
clrscr();
do
{
printf("\n Array Implementation of List\n");
printf("\t1.create\n");
printf("\t2.Insert\n");
printf("\t3.Delete\n");
printf("\t4.Display\n");
printf("\t5.Search\n");
printf("\t6.Exit\n");
printf("\nEnter your choice:\t");
scanf("%d",&choice); switch(choice)
{
case 1:
Create();
break;
case 2:
Insert();
break;
case 3:
Page 8
Delete();
break;
case 4:
Display();
break;
case 5:
Search();
break;
case 6:
exit(1);
default: printf("\nEnter option between 1 - 6\n");
break;
}
}
while(choice<7);
}
void Create()
{
int i;
printf("\nEnter the number of elements to be added in the list:\t");
scanf("%d",&n);
printf("\nEnter the array elements:\t");
for(i=0;i<n;i++)
scanf("%d",&list[i]);
Display();
}
void Insert()
{
int i,data,pos;
printf("\nEnter the data to be inserted:\t");
scanf("%d",&data);
printf("\nEnter the position at which element to be inserted:\t");
scanf("%d",&pos);
for(i = n-1 ; i >= pos ; i--)
list[i+1] = list[i];
list[pos] = data;
n+=1;
Display();
}
void Delete( )
{
int i,pos;
printf("\nEnter the position of the data to be deleted:\t");
Page 9
scanf("%d",&pos);
printf("\nThe data deleted is:\t %d", list[pos-1]);
for(i=pos-1;i<n-1;i++)
list[i]=list[i+1];
n=n-1;
Display();
}
void Display()
{
int i;
printf("\n**********Elements in the array**********\n");
for(i=0;i<n;i++)
printf("%d\t",list[i]);
}
void Search()
{
int search,i,count = 0;
printf("\nEnter the element to be searched:\t");
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(search == list[i])
{
count++;
}
}
if(count==0)
printf("\nElement not present in the list");
else
printf("\nElement present in the list");
}
Output
Array Implementation of List
1.create
2.Insert
3.Delete
4.Display
5.Search
6.Exit
Enter your choice: 1
Enter the number of elements to be added in the list: 5
Enter the array elements: 1 2 3 4 5
**********Elements in the array********** 1 2 3 4 5
Page 10
Array Implementation of List
1.create
2.Insert
3.Delete
4.Display
5.Search
6.Exit
Enter your choice: 2
Enter the data to be inserted: 3
Enter the position at which element to be inserted: 1
**********Elements in the array********** 3 1 2 3 4 5
Advantages of array implementation:
The elements are faster to access using random access 2.Searching an element is easier
Limitation of array implementation
An array store its nodes in consecutive memory locations.
The number of elements in the array is fixed and it is not possible to change the number of
elements.
Insertion and deletion operation in array are expensive. Since insertion is performed by pushing
the entire array one position down and deletion is performed by shifting the entire array one
position up.
Q3. Write a function that returns a pointer to the maximum value of an array of double’s. If the
array is empty, return NULL. (APR/MAY 2015)
#include <stdio.h>
#include <stdlib.h>
voidBigEl(double* arr, double arrSize);
voidBigEl(double* arr, double arrSize)
{
inti;
double maximum, *x;
maximum = arr[0];
for (i = 1; i<arrSize; i++)
{
if (arr[i]>maximum)
{
maximum = arr[i];
}
}
*x = maximum;
}
void main()
{
Page 11
doublemyarr[10];
inti;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i< 10; i++)
{
scanf("%d", &myarr[i]);
}
BigEl(myarr, 10);
}
Contents
Singly linked list
Doubly linked list
Circularly linked list
Doubly linked circular list
Procedure delete(X,L)
Procedure insert(P,X)
Linked list is a data structure. It can be used to implement other data structures.
Thus, it acts as building block to implement data structures like stacks, queues and their variations.
Page 12
In the above linked list, every node contains two parts- one integer and the other a pointer to the
next node.
The left part of the node which contains data may include a simple data type, an array or a
structure.
The right part of the node contains a pointer to the next node (or address of the next node in
sequence).
The last node will have no next node connected to it, so it will store a special value called NULL
Linked list contains a pointer variable, START which stores the address of the first node in the list.
The START node will contain the address of the first node; the next part of the first node will in turn
store the address of its next node.
If START = NULL, this means that the linked list is empty and contains no nodes.
In C, we will implement a linked list using the following code:
struct node
{
int data;
struct node *next;
};
The basic operations carried out in a linked list are
Creation of list
Insertion of list
Deletion of list
Modification of list
Traversal of List
Types of linked List
The various types of linked lists are:
Singly linked lists
Circularly linked lists
Doubly-linked lists
Dynamic allocation
The process of allocating memory to the variables during execution of the program or at run time is
known as dynamic memory allocation. C language has four library routines which allow this
function.
Dynamic memory allocation gives best performance in situations in which we do not know memory
requirements in advance. C provides four library routines to automatically allocate memory at the
run time.
Page 13
Difference between array and Linked List
Q5. Difference between array and Linked List. [Apr/May 2021]
Page 14
The node contains a pointer to the next node means that the node stores the address of the next
node in sequence.
Page 15
Insertion
S.no Operation Description
1 Insertion at It involves inserting any element at the front of the list. We just need to a
beginning few link adjustments to make the new node as the head of the list.
2 Insertion at end It involves insertion at the last of the linked list. The new node can be
of the list inserted as the only node in the list or it can be inserted as the last one.
3 Insertion after It involves insertion after the specified node of the linked list. We need to
specified node skip the desired number of nodes in order to reach the node after which
the new node will be inserted. .
To insert the node at the beginning, store the value of first newnode->next and address of newnode is to
be stored in first
a) Insertion of a node as a head node
node *insert_head(node *head )
{
node *New, *temp;
Page 16
New=get_node();
printf("\n Enter The element which you want to insert");
scanf("%d",&New-> data);
if(head == NULL) //There is no node in the linked list. That means the linked list is empty.
head=New;
else
{
temp=head;
New-> next =temp;
head=New;
}
return head;
}
Scanf(“%d”,&New->data)
Otherwise suppose linked list is already created like this Now we will insert a node at the end –
Insertion of a node as a last node
void insert_last( node *head)
{
node *New, *temp;
New=get_node();
printf("\n Enter The element which you want to insert");
scanf("%d",New->data);
if(head== NULL)
head=New;
else
{
temp=head;
while(temp-> next != NULL)
temp = temp-> next; // Finding the end of the linked list. Then temp will be a last node.
temp-> next = New;
New-> next = NULL;
}
}
If we want to insert 31 in the linked list which is already created we want to insert this 31 after node
Page 17
containing 30 then
To attach a node at the end of linked list assume that we have already created a linked list like this –
Now we will insert a new node after some node at intermediate position:
Insertion of a node after some node.
void insert_after(node *head)
{
int key;
node *temp, *New;
New= get_node();
printf("\n Enter The element which you want to insert");
scanf("%d",New-> data);
if(head == NULL)
{
head=New;
}
else
{
printf("\n Enter The element after which you want to insert the node");
scanf("%d",key);
temp=head;
do
{
if(temp-> data ==key)
{
New-> next =temp-> next;
temp->next=New;
return;
}
else
temp =temp-> next;
}while(temp!=NULL);
}
}
If we want to insert 31 in the linked list which is already created. We want to insert this 31 after node
Page 18
containing 30 then
SN Operation Description
1 Deletion at It involves deletion of a node from the beginning of the list. This is the
beginning simplest operation among all.
2 Deletion at the It involves deleting the last node of the list. The list can either be empty or
end of the list full.
3 Deletion after It involves deleting the node after the specified node in the list. we need
specified node to skip the desired number of nodes to reach the node after which the
node will be deleted. This requires traversing through the list.
Deletion of any element from the linked list
node *get_prev(node *head, int val)
{
node *temp,*prev;
int flag;
temp = head;
if(temp == NULL)
return NULL;
flag = FALSE;
prev=NULL;
while(temp!=NULL && !flag)
{
if(temp->data!=val)
{
Page 19
prev = temp;
temp = temp -> next;
}
else
flag = TRUE;
}
if(flag)
return prev;
else
return NULL;
}
Page 20
We want to delete node 30. Then we will search the node containing 30. Mark the node to be deleted
as temp. Then we will obtain previous node of temp Mark previous node as prev
Then
Now we will delete the temp node then the linked list will be
Free(temp);
Searching of desired element in the linked list
The search function is for searching the node containing desired value. We pass the head of the linked
list to this routine so that the complete linked list can be searched from the beginning,
node *search(node *head,int key)
{
node *temp;
int found;
temp = head;
if ( temp == NULL )
{
printf("The Linked List is empty\n");
getch( );
clrscr( );
}
found = FALSE;
while ( temp != NULL && found==FALSE)
{
if ( temp->data != key)
temp = temp -> next;
else
found = TRUE;
}
if ( found==TRUE )
{
printf("\nThe Element is present in the list\n");
Page 21
getch( );
return (temp);
}
else
{
printf("The Element is not present in the list\n");
getch( );
return NULL;
}
Consider that we have created a linked list as
Suppose key = 30 i.e. we want a node containing value 30 then compare temp->data and key value. If
there is no match then we will mark next node as temp
Hence print the message "The Element is present in the list". Thus in search operation the entire list
can be scanned in search of desired node and still, if required node is not obtained then we have to
print the message. "The Element is not present in the list".
Program for implementation of singly Linked List: Insertion and Deletion at the beginning
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
/Declaration Part*/
void insertbeg(int);
void deletebeg();
void display();
struct node
{
int element ;
struct node*next;
}*first=NULL;
void main()
{
int data,ch;
clrscr();
Page 22
while(1)
{
printf("\n 1.INSERT\n 2.DELETE\n 3.DISPLAY\n 4.EXIT\n");
printf("\n Choose any option:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n Enter some data to insert:");
scanf("%d",&data); insertbeg(data);
display();
break;
case 2:
printf("\nEnter some data to insert:");
scanf("%d",&data); insertbeg(data);
display();
break;
deletebeg();
display();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
}
}
}
/*Inserting a node at beginning*/
void insertbeg(int item)
{
struct node *newnode;
newnode=malloc(sizeof(struct node));
newnode->element=item;
newnode->next=NULL;
if(first==NULL)
{
first=newnode;
}
else
{
newnode->next=first;
Page 23
first=newnode;
}
}
/*Deleting a node from beginning*/
void deletebeg()
{
struct node* temp;
if(first==NULL)
{
printf("List is empty cannot be deleted");
exit(0);
}
temp=first;
first=first->next;
printf("The item deleted is :%d\n",temp->element);
free(temp);
}
Page 24
prevNode = curNode;
curNode = head;
}
head = prevNode; // Make last node as head
printf("SUCCESSFULLY REVERSED LIST\n");
}
}
OUTLINE
Doubly linked list
Features
Structure of doubly linked list
Example
Program
Definition
A doubly linked list or a two way linked list is a type of linked list which contains a pointer to the
next as well as previous node in the sequence.
Therefore, it consists of three parts.
The three parts are data, a pointer to the next node and a pointer to the previous node
Features of Doubly linked list
Two way access is possible (i.e.) we can start accessing nodes from start as well as from last.
Like singly linked list doubly linked list are linear but bidirectional.
Elements are accessed sequentially, no direct access is allowed.
Node Creation
In C language, the structure of a doubly linked list is given as,
struct node
{
struct node *prev;
int data;
struct node *next;
};
Structure of Doubly linked list
Page 25
Following are the important terms to understand the concept of doubly linked list.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link called Next.
Prev − Each link of a linked list contains a link to the previous link called Prev.
Linked List − A Linked List contains the connection link to the first link called First and to the last
link called Last.
Example of Doubly Linked List
Insertion of a node:
This can be done in three ways:
At the beginning: The new created node is insert in before the head node and head points to
the new node.
At the end: The new created node is insert at the end of the list and tail points to the new
node.
At a given position: Traverse the given DLL to that position(let the node be X) then do the
following:
1. Change the next pointer of new Node to the next pointer of Node X.
2. Change the prev pointer of next Node of Node X to the new Node.
3. Change the next pointer of node X to new Node.
4. Change the prev pointer of new Node to the Node X.
Deletion
Deletion of a node:
This can be done in three ways:
At the beginning: Move head to the next node to delete the node at the beginning and make
previous pointer of current head to NULL .
At the last: Move tail to the previous node to delete the node at the end and make next
Page 26
pointer of tail node to NULL.
At a given position: Let the prev node of Node at position pos be Node X and next node be
Node Y, then do the following:
1. Change the next pointer of Node X to Node Y.
2. Change the previous pointer of Node Y to Node X.
1. Creation of node
4. Insertion of a node
Page 27
Suppose we want to insert 31 after 30 then first search for node 30 call it as temp node. Then create a
node containing value 31.
Then
Page 28
Page 29
Advantage of DLL:
Deletion operation is easier
Finding the predecessor and successor node is easier
Disadvantages of DLL:
• More memory space requires since it has two pointers.
Advantages of DLL over singly linked list
• A DLL can be traversed in both forward and backward direction.
• The delete operation in DLL is more efficient if pointer to the node to be deleted is given.
In singly linked list, to delete a node, pointer to the previous node is needed. To get this previous
node, sometimes the list is traversed. In DLL, we can get the previous node using previous pointer.
Disadvantages of DLL over singly linked list
• Every node of DLL Require extra space for a previous pointer. It is possible to implement DLL with
single pointer though
• All operations require an extra pointer previous to be maintained. For example, in insertion, we
need to modify previous pointers together with next pointers. For example in following functions
for insertions at different positions, we need 1 or 2 extra steps to set previous pointer.
Page 30
In circular linked list address field of last node contain address of “first node“, that is First Node and
Last Nodes are adjacent.
Linked List is made circular by linking first and last node , so it looks like circular chain
Two way access is possible only if we are using “Doubly Circular Linked List”
Operations
In a circular linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display
Before we implement actual operations, first we need to setup empty list. First perform the following steps
before implementing actual operations.
Step 1 - Include all the header files which are used in the program.
Page 31
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Implement the main method by displaying operations menu and make suitable function
calls in the main method to perform user selected operation.
Insertion
We can insert at 3 different positions of a circular linked list:
Insertion at the beginning of the list: For insertion at the beginning of the circular linked list, we
will store the address of the first node and points to the last node of the list.
Insertion at the end of the list: For insertion at the end of the circular linked list, we will store the
address of the head node to the new node and make the last node a new node.
Insertion at the given position: For insertion at the given position, we will traverse the circular
linked list, and points the next of the new node to the next node.
Deletion
We can delete from 3 different positions of a circular linked list:
Delete the first node of the list: To delete the first node, transfer the head node to the next node
and free the memory of the first node.
Delete the last node of the list: To delete the last node of a circular list, find the second last node,
change the pointer to the next node and free the memory of the last node.
Page 32
Delete the node from any position: to delete the node from a given position, you need to traverse
the list and store the address of the previous node, and point the next of the current node to the
next node.
You can follow the given links for a better understanding of the operations of a circular linked list which
we have explained with the proper approach, dry run and implementation.
Types of circular linked list in data structures
Circular Linked lists are following two types:
Circular Singly Linked list:
In a circular singly linked list, the last node of the linked list is connected to the first node of the linked
list i.e. the last node of the linked list contains the pointer to the first node of the linked list. We can
traverse the circular singly linked list until we reach the same node where we started. There is no
beginning and end to the list.
Circular doubly linked list:
In a circular doubly linked list, the properties of both i.e. doubly linked list and circular linked list are
present. In other words, two consecutive nodes are linked or connected by the previous and next
pointer.
Advantages of Circular Linked List in data structures
We can traverse the entire list using any node as the starting point. It means that any node can be
the starting point. We can just end the traversal when we reach the starting node again.
Useful for the implementation of a queue. We don’t need to store two-pointers that point to the
front and the rear. Instead, we can just maintain a pointer to the last inserted node. By doing this.
We can always obtain the front as the next of last.
Some problems are circular and a circular data structure like a circular linked list is ideal for them.
Circular doubly linked lists are very useful when implementing the Fibonacci Heap and many
other advanced data structures.
Disadvantages of Circular Linked List in data structures
Finding the end of the list is more complex, as there is no NULL to mark the end.
Displaying a circular Linked List
We can use the following steps to display the elements of a circular linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last node
Step 5 - Finally display temp → data with arrow pointing to head → data.
Page 34
{
display();
}
if(ch==5)
{
break;
}
}
getch();
}
void create()
{
head=(struct circular *)malloc(sizeof(struct circular));
head->next=head;
printf("ENTER THE DATA");
scanf("%d",&head->i);
temp=head;
temp->next=(struct circular *)malloc(sizeof(struct circular));
temp=temp->next;
temp->next=head;
printf("ENTER THE DATA");
scanf("%d",&temp->i);
}
void insert()
{
intadd,t;
printf("\n\t ENTER ANY NUMBER BETWEEN 1 AND %d",cnt);
scanf("%d",&add);
p=head;
t=1;
while(t<add)
{
p=p->next;
t++;
}
printf("%d",p->i);
clrscr();
mid=(struct circular *)malloc(sizeof(struct circular));
printf("ENTER THE DATA");
scanf("%d",&mid->i);
mid->next=p->next;
p->next=mid;
}
Page 35
void display()
{
p=head;
printf("%d-->",p->i);
p=p->next;
while(p!=head)
{
printf("%d-->",p->i);
p=p->next;
}
}
void del(void)
{
intadd,t;
printf("\n\t ENTER ANY NUMBER BETWEEN 1 AND %d",cnt);
scanf("%d",&add);
p=head;
t=1;
while(t<add-1)
{
p=p->next;
t++;
}
printf("%d",p->i);
clrscr();
mid=p->next;
p->next=mid->next;
}
Page 36
Page 37
Page 38
Q17. Develop a C program to split a linked list into two sub lists containing odd and even ordered
elements in them respectively. (APR/MAY 2017)
#include <stdio.h>
#include <stdlib.h>
/* a node of the singly linked list */
struct Node
{
int data;
struct Node *next;
};
void EvenOdd(struct Node **head_ref)
{
struct Node *end = *head_ref;
struct Node *prev = NULL;
struct Node *curr = *head_ref;
/* Get pointer to the last node */
while (end->next != NULL)
end = end->next;
struct Node *new_end = end;
/* Consider all odd nodes before the first even node and move then after end */
while (curr->data %2 != 0 && curr != end)
{
new_end->next = curr;
curr = curr->next;
new_end->next->next = NULL;
new_end = new_end->next;
}
// 10->8->17->17->15
/* Do following steps only if there is any even node */
if (curr->data%2 == 0)
{
/* Change the head pointer to point to first even node */
head_ref = curr;
/* now current points to the first even node */
while (curr != end)
{
if ( (curr->data)%2 == 0 )
{
prev = curr;
curr = curr->next;
}
else
{
Page 39
/* break the link between prev and current */
prev->next = curr->next;
/* Make next of curr as NULL */
curr->next = NULL;
/* Move curr to end */
new_end->next = curr;
/* make curr as new end of list */
new_end = curr;
/* Update current pointer to next of the moved node */
curr = prev->next;
}
}
}
/* We must have prev set before executing lines following this statement */
else prev = curr;
/* If there are more than 1 odd nodes and end of original list is odd then move this node to end to
maintain same order of odd numbers in modified list */
if (new_end!=end && (end->data)%2 != 0)
{
prev->next = end->next;
end->next = NULL;
new_end->next = end;
}
return;
}
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning */
void push(struct Node** head_ref, intnew_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data =new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while (node!=NULL)
Page 40
{
printf("%d ", node->data);
node = node->next;
}
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Let us create a sample linked list as following
0->2->4->6->8->10->11 */
push(&head, 11);
push(&head, 10);
push(&head, 8);
push(&head, 6);
push(&head, 4);
push(&head, 2);
push(&head, 0);
printf("\nOriginal Linked list \n");
printList(head);
EvenOdd(&head);
printf("\nModified Linked list \n");
printList(head);
return 0;
}
APPLICATIONS OF LISTS
Q18. Explain the Applications of lists. (NOV/DEC 2014) (NOV/DEC 2019)
Linked Lists can be used to implement Stacks , Queues.
Linked Lists can also be used to implement Graphs. (Adjacency list representation of Graph).
Implementing Hash Tables :- Each Bucket of the hash table can itself be a linked list. (Open chain
hashing).
Undo functionality in Photoshop or Word . Linked list of states.
A polynomial can be represented in an array or in a linked list by simply storing the coefficient and
exponent of each term.
However, for any polynomial operation , such as addition or multiplication of polynomials , linked
list representation is more easier to deal with.
Linked lists are useful for dynamic memory allocation.
The real life application where the circular linked list is used is our Personal Computers, where
multiple applications are running.
Page 41
All the running applications are kept in a circular linked list and the OS gives a fixed time slot to all
for running. The Operating System keeps on iterating over the linked list until all the applications
are completed.
STACK ADT:
Definition of Stack:
Q1. Discuss about Stack ADT in detail. Explain any one application of Stack. [Nov/Dec 2014]
Q2. Develop an algorithm to implement stack ADT. Give relevant examples with diagrammatic
representations. [Nov/Dec 2016] [Apr/May 2019] (Apr/May 2021) [NOV/DEC 2022]
• Stack is a linear data structure in which the insertion and deletion operations are performed at only
one end.
• To add (push) an item to the stack, it must be placed on the top of the stack.
• To remove (pop) an item from the stack, it must be removed from the top of the stack too.
In stack, the insertion and deletion operations are performed based on LIFO (Last In First Out) or FILO
(First In Last Out) principle.
In a stack, the insertion operation is performed using a function called "push" and deletion operation
is performed using a function called "pop".
In the figure, PUSH and POP operations are performed at a top position in the stack. That means, both
the insertion and deletion operations are performed at one end (i.e., at Top)
Example
If we want to create a stack by inserting 10,45,12,16,35 and 50. Then 10 becomes the bottom-most
element and 50 is the topmost element. The last inserted element 50 is at Top of the stack as shown in
the image below
Syntax:
Abstract Data Type Stack
{
Instances: Stack is a collection of elements in which insertion and deletion of elements is done by one end
called top.
Operations
1. Push: By this operation one can push elements onto the stack. Before performing push we should
check whether stack is full or not.
Page 42
2. Pop: By this operation one can remove the elements from stack. Before popping the elements
from stack we should check whether stack is empty or not.
}
2.2 OPERATIONS
Q3. Explain the fundamental operations of Stack.
Q4. Write the function to check for stack as Full() or Empty(). (APR/MAY 2015)
The fundamental operations on stack are:
• Creating a Stack
• Inserting an element in the stack - PUSH
• Deleting an element in the stack - POP
• Checking which element is in the top of the stack – PEEK or TOP
• Checking whether the stack is empty or not - ISEMPTY
Operation Description
Stack Push The procedure of inserting a new element to the top of the stack is known as
Push Operation
Stack Overflow Any attempt to insert a new element in already full stack is results into Stack
Overflow
Stack Pop The procedure of removing element from the top of the stack is called Pop
Operation
Stack Any attempt to delete an element from already empty stack results into Stack
Underflow Underflow
Peek() The peek() function gets the top element of the stack, without deleting it.
isEmpty() The isEmpty() function checks whether the stack is empty or not.
isFull() The isFull() function is used to check whether the stack is full or not.
Two ways of implementation of Stack:
• Array implementation of stack
• Linked List implementation of stack.
When a stack is implemented using an array, that stack can organize an only limited number of
elements.
When a stack is implemented using a linked list, that stack can organize an unlimited number of
elements.
Page 43
Push Operation on Stack
The process of putting a new data element onto stack is known as a Push Operation. Push operation
involves a series of steps −
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.
Implementation
void push(int data) {
if(!isFull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}
Pop Operation on Stack
Removing an element from the stack, is known as a Pop Operation
A Pop operation may involve the following steps −
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
Implementation
int pop(int data) {
Page 44
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}
peek() - get the top data element of the stack, without removing it.
Algorithm of peek() function −
begin procedure peek
return stack[top]
end procedure
Implementation of peek() function −
int peek() {
return stack[top];
}
Page 45
end procedure
Implementation
bool isempty() {
if(top == -1)
return true;
else
return false;
}
Following table shows the Position of Top which indicates the status of stack:
Position of Top Status of Stack
-1 Stack is empty.
0 Only one element in a stack.
N-1 Stack is full.
N Stack is overflow. (Overflow state)
Page 47
if(top == -1)
printf("\nStack is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", stack[top]);
top--;
}
}
void display()
{
if(top == -1)
printf("\nStack is Empty!!!");
else{
int i;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
printf("%d\n",stack[i]);
}
}
Output
APPLICATIONS OF STACK:
Q9. Explain application of stack in detail. (Nov/Dec2015)
1. Expression Evaluation
2. Expression Conversion
i. Infix to Postfix
ii. Infix to Prefix
iii. Postfix to Infix
iv. Prefix to Infix
3. Backtracking
4. Memory Management
Page 48
5. Balancing Symbols
6. Storing function calls
a. Infix Expression
In infix expression, operator is used in between the operands.
The general structure of an Infix expression is as follows...
Operand1 Operator Operand2
Example
For example
1. (a+b)
2. (a+b) *(c-d)
3. (a+b/e) *(d+f)
b. Postfix Expression
In postfix expression, operator is used after operands. We can say that "Operator follows the
Operands".
The general structure of Postfix expression is as follows...
Operand1 Operand2 Operator
Example
Page 49
For example
1.ab+
2. ab + cd- *
3. ab + e / df + *
c. Prefix Expression
In prefix expression, operator is used before operands. We can say that "Operands follows the
Operator".
The general structure of Prefix expression is as follows...
Operator Operand1 Operand2
In prefix expression, there is no parenthesis used. All the corresponding operators come first and
then operands are arranged.
Example
For example
1. + ab
2. *+ ab - cd
3. */ + abe + df
Postfix Expression Evaluation [Apr/May 2021]
A postfix expression is a collection of operators and operands in which the operator is placed after
the operands. That means, in a postfix expression the operator follows the operands.
Postfix Expression has following general structure...
Operand1 Operand2 Operator
Example
Page 51
2. Consider postfix expression - AB+C - BA+ C$ - for A= 1, B= 2andC = 3
Now as per the algorithm of postfix expression evaluation, we scan the input from left to right.
If operand comes we push the m onto the stack and if were ad any operator, we must pop two
operands and perform the operation using that operator. Here $ is taken as exponential operator.
Page 52
Perform Subtraction 0-27=-27
Page 53
Example
Consider the following Infix Expression to be converted into Postfix Expression...
D=A+B*C
Step 1 - The Operators in the given Infix Expression : = , + , *
Step 2 - The Order of Operators according to their preference : * , + , =
Step 3 - Now, convert the first operator * ----- D = A + B C *
Step 4 - Convert the next operator + ----- D = A BC* +
Step 5 - Convert the next operator = ----- D ABC*+ =
Finally, given Infix Expression is converted into Postfix Expression as follows...
DABC*+=
Page 54
Page 55
The final Postfix Expression is as follows...
AB+CD-*
2. Example: Suppose we are converting 3*3/(4-1)+6*2 expression into postfix form.
Following table shows the evaluation of Infix to Postfix:
Expression Stack Output
3 Empty 3
* * 3
3 * 33
/ / 33*
( /( 33*
4 /( 33*4
- /(- 33*4
1 /(- 33*41
) - 33*41-
+ + 33*41-/
6 + 33*41-/6
* +* 33*41-/62
2 +* 33*41-/62
Empty 33*41-/62*+
So, the Postfix Expression is 33*41-/62*+
Problem1: Convert the Following expression into Infix to Prefix and Postfix Expression
Page 56
Convert the expression A-(B/C+(D%E*F)/G)*H to postfix form. Evaluate the given postfix expression
9 3 4 * 8 + 4 / -. [Nov/Dec 2018] [Apr/May 2019]
Page 57
Explain the procedure for string reversal using stack with suitable diagram. [Apr/May 2023]
Input: String.
Output: Reversed string.
Test cases:
Input: “Prepbytes”
Output: “setybpreP”
Explanation:
Reading the input string “Prepbytes” from right to left we get “setybpreP”.
Approach – Using Stack
The idea is to traverse the given string from left to right and push each character in the stack.
Then, pop the characters from the stack one by one and append them to a new string.
The newly created will be the reverse of the input string because of the LIFO (Last-in-first-out)
property of the stack data structure.
The last character pushed into the stack will be the first to get popped.
Algorithm
1. Initialize an empty stack and an array.
2. Traverse the given string from left to right
Push the current character to the stack
3. Initialize an empty StringBuilder
4. Pop from the stack one by one.
Append the current character at last.
5. Return the newly created StringBuilder as a string.
Dry Run:
Page 58
Page 59
Explain the procedure for balanced parenthesis checker using stack with suitable diagram.
[Apr/May 2023]
Balanced parentheses refer to an expression in which all opening and closing parentheses are
properly matched and nested.
A balanced expression ensures that the program can be executed without any errors.
To check for balanced brackets in an expression using stack in C programming, you need to
traverse the expression and keep track of the opening and closing parentheses using a stack data
structure.
If an opening parenthesis is encountered, it is pushed onto the stack, and if a closing parenthesis is
encountered, it is compared with the top element of the stack.
If the closing parenthesis matches the top element, the top element is popped, and the traversal
continues.
If the closing parenthesis does not match the top element or there are no more elements in the
stack, the expression is considered unbalanced.
Approach – Check for Balanced Brackets in an Expression using Stack
The idea is to use the LIFO functionality of the stack. As a stack is LIFO data structure, we will
remove every opening bracket (‘(‘, ‘{‘, ‘[‘), whenever we encounter the same type of closing bracket
(‘)’, ‘}’, ‘]’).
If for any opening bracket we don’t have a closing bracket, the opening bracket will remain in the
stack forever.
Similarly if we only have a closing bracket without a preceding opening bracket we will just push
the closing bracket into the stack and it will remain there forever.
So, at last after traversing the whole expression, if the stack is empty then it will mean that the
given expression is balanced, otherwise if the stack contains elements that would mean the given
expression was unbalanced.
Algorithm to Check Balanced Parentheses in C using Stack
1. Initialize an empty stack.
2. Iterate i from 0 to length(expression).
Store the current character in a variable ‘ch’.
If stack is empty: Push ‘ch’ to the stack
Page 60
Else if current character is a closing bracket and of the top of the stack contains an opening
bracket of the same type then remove the top of the stack: Else, push ‘ch’ to the stack
3. If the stack is empty, return true, else false.
Dry Run to Check for Balanced Brackets in an Expression using Stack
Input:“({[]})” Output:true
Page 61
Stack Expression Action
({[]}) Push
( {[]}) Push
({ []}) Push
({ }) Pop
( ) Pop
Empty
QUEUE ADT
Q15. Develop an algorithm to implement Queue ADT. Give relevant examples and diagrammatic
representations. [Nov 2016] [Apr/May 2023]
Q16. Write C Program to Implement Queue Functions using Arrays and Macros. (APR/MAY
2015)
Q17. Explain about Queue ADT in detail. Explain any one application of queue with suitable
example. [Nov/Dec 2014]
Queue is a linear data structure where the first element is inserted from one end called REAR and
deleted from the other end called as FRONT.
Front points to the beginning of the queue and Rear points to the end of the queue.
Queue follows the FIFO (First - In - First Out) structure.
According to its FIFO structure, element inserted first will also be removed first.
In a queue, one end is always used to insert data (enqueue) and the other is used to delete data
(dequeue), because queue is open at both its ends.
The enqueue() and dequeue() are two important functions used in a queue.
Example
Page 62
Queue after inserting 25, 30, 51, 60 and 85.
Operations on Queue
Operations Description
enqueue() This function defines the operation for adding an element into queue.
dequeue() This function defines the operation for removing an element from queue.
init() This function is used for initializing the queue.
Front Front is used to get the front data item from a queue.
Rear Rear is used to get the last item from a queue.
Queue data structure can be implemented in two ways. They are as follows...
Using Array
Using Linked List
When a queue is implemented using an array, that queue can organize an only limited number of
elements.
When a queue is implemented using a linked list, that queue can organize an unlimited number of
elements.
Page 63
Step 5 - Then implement main method by displaying menu of operations list and make suitable
function calls to perform operation selected by the user on queue.
i. enQueue(value) - Inserting value into the queue
In a queue data structure, enQueue() is a function used to insert a new element into the queue.
In a queue, the new element is always inserted at rear position.
The enQueue() function takes one integer value as a parameter and inserts that value into the queue.
We can use the following steps to insert an element into the queue.
Step 1 - Check whether queue is FULL. (rear == SIZE-1)
Step 2 - If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and terminate
the function.
Step 3 - If it is NOT FULL, then increment rear value by one (rear++) and
set queue[rear] = value.
Page 64
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
void enQueue(int value){
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("\nInsertion success!!!");
}
}
void deQueue(){
if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
void display(){
if(rear == -1)
printf("\nQueue is Empty!!!");
else{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}
}
Page 65
Output
TYPES OF QUEUE:
There are four types of Queue:
1. Simple Queue
2. Circular Queue
3. Priority Queue
4. Dequeue (Double Ended Queue)
PRIORITY QUEUE
Q25. Explain a priority queue using linked list. (or) Implement a priority queue using linked list.
(Nov/Dec 2019) [NOV/DEC 2022]
Priority queue contains data items which have some preset priority. While removing an element from
a priority queue, the data item with the highest priority is removed first.
In a priority queue, insertion is performed in the order of arrival and deletion is performed based on
the priority.
Page 67
pri_que[rear] = data;
return;
}
else
check(data);
rear++;
}
void check(int data) //Check Function - to check priority and place element
{
int i,j;
for (i = 0; i <= rear; i++)
{
if (data >= pri_que[i])
{
for (j = rear + 1; j > i; j--)
{
pri_que[j] = pri_que[j - 1];
}
pri_que[i] = data;
return;
}
}
pri_que[i] = data;
}
void delete_by_priority(int data) //Delete Function
{
int i;
if ((front==-1) && (rear==-1))
{
printf("\nQueue is empty no elements to delete");
return;
}
for (i = 0; i <= rear; i++)
{
if (data == pri_que[i])
{
for (; i < rear; i++)
{
pri_que[i] = pri_que[i + 1];
}
pri_que[i] = -99;
rear--;
if (rear == -1)
front = -1;
return;
}
}
printf("\n%d not found in queue to delete", data);
}
Page 68
void display_pqueue() //Display Function
{
if ((front == -1) && (rear == -1))
{
printf("\nQueue is empty");
return;
}
for (; front <= rear; front++)
{
printf(" %d ", pri_que[front]);
}
front = 0;
}
Output:
1. Insert
2. Display
3. Delete
/* function to get the intersection point of two linked lists head1 and head2 where head1 has d more nodes than head2 */
int _getIntesectionNode(int d, struct Node* head1, struct Node* head2);
/* function to get the intersection point of two linked lists head1 and head2 */
int getIntesectionNode(struct Node* head1, struct Node* head2)
{
int c1 = getCount(head1);
int c2 = getCount(head2);
int d;
/* function to get the intersection point of two linked lists head1 and head2 where head1 has d more nodes than head2
*/
int _getIntesectionNode(int d, struct Node* head1, struct Node* head2)
Page 70
{
int i;
struct Node* current1 = head1;
struct Node* current2 = head2;
Page 71
newNode->data = 15;
head1->next = newNode;
head2->next->next->next = newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = 30;
head1->next->next = newNode;
head1->next->next->next = NULL;
printf("The node of intersection is %d ", getIntesectionNode(head1, head2));
getchar();
}
Find the time complexity of the following code and explain how it is obtained (5) [Nov/Dec 2022]
Example:
For(i=0;i<n;i++)
{
For(j=0;j<n;j++)
{
Printf(“value of I=%d”+1);
}
}
Analysis
Clearly time complexity of above algorithm is θ(n 2) because in above algorithm the basic operation is
computation of R(k)[i, j].
This operation is located within two nested for loops.
The time complexity Warshall‘s algorithm is θ(n2).
Design a C program to add two distances in inch-feet system using structure. (7) [Nov/Dec 2022]
#include <stdio.h>
struct Distance {
int feet;
float inch;
} d1, d2, result;
int main() {
// take first distance input
printf("Enter 1st distance\n");
printf("Enter feet: ");
scanf("%d", &d1.feet);
printf("Enter inch: ");
scanf("%f", &d1.inch);
// adding distances
result.feet = d1.feet + d2.feet;
result.inch = d1.inch + d2.inch;
Page 72
result.inch = result.inch - 12.0;
++result.feet;
}
printf("\nSum of distances = %d\'-%.1f\"", result.feet, result.inch);
return 0;
}
Output:
Page 73
UNIT III LINEAR DATA STRUCTURES
Two Marks
1. Define Data Structure. What is Data Structure? (Nov/Dec 2016)
A data structure is logical way of storing and organizing data either in computer's memory or on
the disk storage so that it can be used efficiently.
2. List the classification of Data Structure. (Nov/Dec 2016)
There are two types of data structures:
• Linear Data Structure
• Non-linear data structure
3. Define Linear Data Structure.
Linear data structures are data structures having a linear relationship between its adjacent
elements. E.g. Linked List.
4. Define Non Linear Data Structure.
Non Linear data structures are data structures don’t have a linear relationship between its
adjacent elements, but have the hierarchical relationship.
e.g. Graph,Tree.
5. List out the various application areas of data structures.
• Compiler Design
• Operating System
• DBMS
• Simulation
• Artificial Intelligence
• Graphics
6. Define ADT and give an example. What is an ADT? (or) Write short notes on ADT. What are
Abstract Data Type (Nov/Dec 2014) (April/May 2008)(Apr/May 2015)(May/Jun2016) (Dec
2015/Jan 2016) (Apr/May 2017) (Nov/Dec 2016) (Nov/Dec 2019)
The Abstract Data Type (ADT) is a set of operations .They is mathematical abstractions and defines
how the set of operations are implemented. E.g.: Integer, real number
In ADT, all the implementation details are hidden. In short
ADT= Type + Function names + Behavior of each function.
7. What are the two parts of ADT?
The ADT contains
• Value definition
• Operator definition
8. What are the operations of ADT?
Union, Intersection, size, complement and find are the various operations of ADT.
9. What is meant by List ADT?
List ADT is a sequential storage structure .The general list is of the form a 1, a2, a3… an, and the size of
the list is 'n'.
a1- First element of List
an-Last Element of list
n-Size of list
10. What are the pitfalls encountered in singly linked list?
Following are the pitfalls encountered in singly linked list
Page 74
o 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.
o 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.
12. What is Linked List? (Or) What does the Linked List contain?(Apr/May 2015) (May/Jun2016)
(Nov/Dec 2019)
In a linked list, each element is called a node. Every node in the list points to the next node in the
list. Therefore, in a linked list every node contains two types of information:
• The data stored in the node
• A pointer or link to the next node in the list
13. Difference between array and Linked List. [Apr/May 2021]
Array Linked list
Size of any array is fixed Size of list is variable
It is necessary to specify the number of It is not necessary to specify the number of
elements during declaration elements during declaration
Insertion and deletions are difficult and Insertions and deletions are done in less
Costly time
It occupies less memory It occupies more memory
14. What are the advantages and disadvantages of using linked list?
Advantage:
• It provides quick insert, and delete operations
Disadvantage:
• Slower search operation and requires more memory space
15. What are the advantages and disadvantages of Linked list over arrays? (Dec 2015/Jan 2016)
(Apr/May 2017) (Nov/Dec 2018) (Apr/May 2019) (Apr/May 2021)[Apr/May 2023]
• Insertion & deletion are relatively easy in linked list.
• In link list we can create memory according to requirement, and so no wastage of Memory.
• The main disadvantage of linked list over array is access time to individual elements.
• Array is random-access, which means it takes O (1) to access any element in the array.
• Linked list takes O (n) for access to an element in the list in the worst case.
• Another advantage ADT of arrays in access time is special locality in memory.
• Arrays are defined as contiguous blocks of memory, and so any element will be physically near its
neighbors.
• This greatly benefits from modern CPU caching methods.
16. Why is doubly linked list more advantage than singly linked list?
In doubly linked list it is easy to manipulate the data and searching is faster by maintaining the
pointers in both the directions.
17. What are the various applications of linked list? (Apr/May 2015) (Apr/May 2021)
Page 75
• Polynomial ADT
• Radix sort
• Multi list
18. Define Polynomial ADT.[MAY/JUN 2014]
• A polynomial object is a homogeneous ordered list of pairs <exponent, coefficient>, where each
coefficient is unique.
• Operations include returning the degree, extracting the coefficient for a given exponent, addition,
multiplication, evaluation for a given input.
19. Write the advantages and disadvantages of doubly linked list. [NOV/DEC 2014]
Advantage:
Deletion operation is easier.
Finding the predecessor & Successor of a node is easier.
Disadvantage:
More Memory Space is required since it has two pointers.
21. What is Circular Linked List? Give example. [April/May 2008][Nov/Dec 2014]
Circularly linked list is a collection of nodes, where each node is a structure containing the element
and a pointer to a structure containing its successor.
The pointer field of the last node points to the address of the first node. Thus the linked list
becomes circular.
22. 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, which makes accessing of any node difficult
one.
23. State the advantages of circular lists over doubly linked list.
o 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.
o The main advantage of circular list over doubly linked list is that with the help of pointer field we
Page 76
Faster access to elements (when compared with dynamic data structures)
Add, remove or modify elements is not directly possible. If done, it is a resource consuming
process.
Fixed size.
Resources allocated at creation of data structure, even if elements are not contain any value.
Applications:
Linked Lists can be used to implement Stacks, Queues.
Linked Lists can also be used to implement Graphs. (Adjacency list representation of Graph).
Implementing Hash Tables. Each Bucket of the hash table can itself be a linked list.
28. Define Stack with an example (or) Define Stack Model. (Nov/Dec-2015) (Apr/May 2017)
A stack is a list in which all the insertion and deletion can be performed at only one position called the
top.
The stack is also otherwise called as Last in First out (LIFO) Model.
Eg: Arranging pile of coins.
29. List few applications of stack. Give any two applications of Stack. [April/May2008] [Nov/Dec 2014]
[Nov/Dec 2016] [Apr/May 2017] [Nov/Dec 2019]
• Balancing Symbols
• Infix to postfix conversion
• Expression evaluation
• Storing function calls
Eg: ab+,ab-cd+*ab+e/df+*
31. Write short notes on Prefix expression. (Apr/May2015)
In this type of expression the arrangements of operator and operand are as follows:
Eg: +ab,*-ab+cd,*/+abe+df
Page 77
32. What are the rules to be followed while converting from infix to postfix conversion? [Nov/Dec
2019]
There is certain rule which has to be followed while converting infix expression to postfix form:
• The expression is to be read from left to right.
• Read one character at a time from infix expression.
• Make use of stack to store the operators.
• There should not be any parentheses is in the postfix form
33. What are the postfix and prefix forms of the expression?
A+B*(C-D)/(P-R)
Postfix form: ABCD-*PR-/+
Prefix form: +A/*B-CD-PR
34. What is Queue? Define Queue. [Nov/Dec-2015] [Nov/Dec 2016] [Apr/May 2021]
A Queue is an ordered collection of items from which items may be deleted at one end called the front
of the queue and into which items may be inserted at the other end called rear of the queue. Queue is called as
First–in-First-Out (FIFO).
35. What are the fundamental operations performed with the Queue? [Apr/May 2021]
• Queue overflow
• Inserting an element in queue
• Queue underflow
• Deleting an element from queue
• Displaying the queue
36. What are the types of queues? [Apr/May 2021]
• Simple Queue
• Circular Queue
• Double ended Queues
• Priority Queue
37. List out the applications of queues. [Apr/May 2023]
• Serving requests of a single shared resource like (printer, disk, CPU), between two processes – Job
Scheduling
• Used in multitasking operating System
• Categorizing of data
• Simulation and Modeling
38. List out the difference between Linked stack and Linked Queue.
Stack Queue
Stack is a collection of items Queue is an ordered collection of items
Items are inserted & deleted at one end Items are deleted at one end called ‘front’ end of the
called ‘Top of the stack’. queue. Items are inserted at other end called ‘rear’ of
the queue.
It allows access to only one data item: the The first item inserted is the first to be removed
last item inserted. (FIFO).
This structure of accessing is known as Last This structure of accessing is known as First in First
in First out structure (LIFO) out structure (FIFO)
Page 78
• When we push the element onto the stack, the top is incremented. When we pop the element from the
stack the top is decremented.
40. What is stack? How it can be represented in “C” using arrays? [April/May 2008]
• Stack is a data structure in which both insertion and deletion occur at one end only.
• Stack is maintained with a single pointer to the top of the list of elements.
• The other name of stack is Last-in -First-out list. Associated with each stack is the top of stack, tos, which
is -1 for an empty stack (this is how an empty stack is initialized).
• To push some element x onto the stack, we increment tos and then set STACK [tos] = x, where STACK is
the array representing the actual stack.
• To pop, we set the return value to STACK [tos] and then decrement tos.
41. Write the two exceptional conditions of stack.
The two exceptional conditions of stack are overflow and underflow.
• Overflow- Attempt to insert an element when the stack is full is said to be overfull.
• Underflow – Attempt to delete an element, when the stack is empty is said to be underflow.
43. Convert the expression to equivalent Reverse Polish and Polish notations.
(i) A + (B-C/D)-E
Polish notations: -+A-B/CDE
Reverse Polish notations: ABCD/-+E-
(ii) ((A + B) * C – (D – E) ^ (F + G))
Polish notations: -*+ABC^-DE+FG
Reverse Polish notations: AB+C*DE-FG+^-
(iii) X+Y*(A-B)/(C-D)
Polish notations: +X/*Y-AB-CD
Reverse Polish notations: XYAB-*CD-/+
44. What are the postfix and prefix forms of the expression A+B*(C-D)/(E-F)?-[May/June
2012][Apr/May 2023]
Prefix expressions: +A/*B-CD-EF
Postfix expressions: ABCD-*EF-/+
45. Write the two exceptional conditions of queue.
The two exceptional conditions of queue are overflow and underflow.
Overflow- Attempt to insert an element when the queue is full is said to be overfull.
Underflow – Attempt to delete an element, when the queue is empty is said to be underflow.
46. What is a priority queue? What are priority queues? [May/June 2009, April/May 2010, Nov/Dec
2005] [Nov/Dec 2018][NOV/DEC2022]
Priority queue is a data structure that allows at least the following two operations.
Page 79
1. Insert-inserts an element at the end of the list called the rear.
2. Delete Min - Finds returns and removes the minimum element in the priority Queue.
Operations:
Insert
Delete Min
47. Explain the types of priority queue. What are the ways to implement priority queue? [Nov/Dec
2018]
Two types of queue are
a. Ascending Priority Queue - Collection of items into which item can be inserted arbitrarily & from
which only the smallest item can be removed.
b. Descending Priority Queue - Collection of items into which item can be inserted arbitrarily & from
which only the largest item can be removed
Page 80
CS3353 C PROGRAMMING AND DATASTRUCTURES
(Regulation – 2021)
QUESTION BANK
UNIT 3
1. What is list ADT using array based implementation? Explain with an example.
2. Explain the operations performed on SLL with examples.
3. Explain the operations performed on DLL with examples.
4. Explain the operations performed on CLL with examples.
5. Discuss about Stack ADT with suitable example.
6. Discuss about Queue ADT and its types with suitable example.
7. Solve a problem on expression evaluation using stack.
8. Solve a problem on expression conversion using stack.
9. Explain the procedure for balanced parenthesis checker using stack with suitable diagram.
Page 81
UNIT IV - NON LINEAR DATA STRUCTURES
Trees – Binary Trees – Tree Traversals – Expression Trees – Binary Search Tree – Hashing –
Hash Function – Separate Chaining – Open Addressing – Linear Probing – Quadratic Probing
– Double Hashing - Rehashing
TREE INTRODUCTION
Tree
• Tree is a non-linear, recursive data structure, which consists of nodes, connected with edges.
• A tree is a collection of nodes connected by directed (or undirected) edges. A tree can be empty
with no nodes or a tree is a structure consisting of one node called the root and zero or one or more
sub trees.
Page 1
• Root − Node at the top of the tree is called root. There is only one root per tree and one path from
root node to any node. Node A is a Root node.
• Parent – The node having further sub branches is called parent node. Node D is parent node of H & I.
• Child − A node directly connected to another node when moving away from the Root is called child
node. Node H & I are child node of parent node D.
• Leaf − Node which does not have any child node is called leaf node. Nodes F & G are Leaf Node
• Subtree − Subtree represents descendants of a node.
• Visiting − Visiting refers to checking value of a node when control is on the node.
• Traversing − Traversing means passing through nodes in a specific order.
• Levels − Level of a node represents the generation of a node. If root node is at level 0, then its next
child node is at level 1, its grandchild is at level 2 and so on.
• keys − Key represents a value of a node based on which a search operation is to be carried out for a
node.
• Descendant (or) Predecessor- A node reachable by repeated proceeding from parent to child.
• Ancestor (or) Successor- A node reachable by repeated proceeding from child to parent.
• Internal node - A node with at least one child.
• External node- A node with no children.
• Degree of the node- The number of sub trees attached to that node is called the degree of a node.
For example, degree of node D is 2.
D
H I
• Degree of tree – The maximum degree in the tree is degree of tree. For example, Node A has
maximum degree of 2.
• Edge- The connection between one node and another.
• Height of node - The height of a node is the number of edges on the longest path between that node
and a leaf.
• Height of tree - The height of a tree is the height of its root node. It is otherwise called as depth of
tree. Consider above tree representation, the height of tree is 3.
• Depth- The depth of a node is the number of edges from the node to the tree's root node.
• Forest - A forest is a set of n ≥ 0 disjoint trees.
• Siblings - In a tree data structure, nodes which belong to same Parent are called as SIBLINGS. In
simple words, the nodes with same parent are called as Sibling nodes.
Advantages of Tree
✓ Tree reflects structural relationships in the data.
✓ It is used to represent hierarchies.
✓ It provides an efficient insertion and searching operations.
✓ Trees are flexible. It allows to move subtrees around with minimum effort.
BINARY TREE ADT
Q1. Discuss about Binary tree in detail. Explain it types.
• A binary tree is defined as a tree in which no node can have more than two children.
Page 2
• The highest degree of any node is two. This indicates that the degree of a binary tree is either zero
or one or two.
• In the above fig., the binary tree consists of a root and two sub trees Tree Left & Tree Right.
• All nodes to the left of the binary tree are denoted as left subtrees and all nodes to the right of a
binary tree are referred to as right subtrees.
Implementation
• A binary tree has maximum two children; we can assign direct pointers to them.
• The declaration of tree nodes is same as in structure to that for doubly linked lists, in that a node is
a structure including the key information plus two pointers (left and right) to other nodes.
Page 3
b. Full Binary Tree:
• A full binary tree is a tree in which every node has zero or two children.
• The total number of nodes in binary tree are 2h+1 – 1, where h is a height of the tree. In above tree,
the height of tree h is 3. Hence 23+1 -1 = 24 – 1 = 16 -1 = 15 Nodes in the tree.
e. Skew tree
• A skew tree is a binary tree in which every node except the leaf has only one child node. There are
two types of skew tree, they are left skewed binary tree and right skewed binary tree.
i. Left skewed binary tree
✓ A left skew tree has node with only the left child. It is a binary tree with only left sub trees.
ii. Right skewed binary tree
Page 4
✓ A right skew tree has node with only the right child. It is a binary tree with only right sub trees.
Page 5
• Red - Black Tree is another variant of Binary Search Tree in which every node is colored either RED
or BLACK.
k. B tree:
• B-Tree is a self-balanced search tree with multiple keys in every node and more than two children
for every node.
(or)
• The B-tree is a generalization of a binary search tree in that a node can have more than two children.
l. B+ tree:
• A B+ tree is an n-array tree with a variable but often large number of children per node. A B+ tree
consists of a root, internal nodes and leaves. The root may be either a leaf or a node with two or
more children.
Comparison between General Tree and Binary Tree
Sl. General Tree Binary Tree
no
General tree has any number of A binary tree has not more than two
1
children. children
Evaluating any expression is difficult Evaluation of expression is easy in binary
2
in general trees. tree.
3 A general tree cannot be empty. A binary tree can be empty
There is no limit on the degree of a Nodes in a binary tree cannot have degree
4
node in a general tree. more than 2.
Subtrees of general trees are not Subtrees of binary trees are ordered
5
ordered
Page 6
typedef struct node
{
int data;
struct node *left;
struct node *right;
}bin;
b. Linear Representation:
• The elements are represented using arrays. For any element in position i, the left child is in
position 2i, the right child position (2i+1), and the parent is in position (i/2)
A B C D E F G
1 2 3 4 5 6 7
Page 7
A
D E F G
Theorem: A full node is a node with the two children. Prove that the number of full nodes plus
one is equal to the number of leaves in a binary tree.
Proof: To prove this consider following cases-
Case 1: Only one node in a tree with no children.
o Here, number of full nodes = 0
o Number of leaves = # (full nodes) + 1 = 0 + 1 = 1.
o The number of leaves = 1 i.e. node x itself.
Page 8
Q5. Explain the traversals of binary tree with example. [May/June 2012]
Q6. List the different types of tree traversal. Develop an algorithm for traversing a binary tree.
Validate the algorithm with suitable example. [Nov/Dec 2013]
Q7. Discuss the different methods traversing a binary tree with algorithm. [Apr/May 2015]
[Nov/Dec 2019] [Apr/May 2021]
• Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree Traversal.
• In a traversal of a binary tree, each element of the binary tree is visited exactly once.
• During the visit of an element, all action (make a clone, display, evaluate the operator, etc.) with
respect to this element is taken. The various traversals in binary tree are:
a. In-order Traversal (Left, Parent, Right)
b. Preorder Traversal (Parent, Left, Right)
c. Post-order Traversal (Left, Right, Parent)
d. Level Order Traversal (Top to Bottom, Left to Right)
In - Order Traversal (left child - root – right child)
✓ In In-Order traversal, the root node is visited between left child and right child.
✓ In this traversal, the left child node is visited first, then the root node is visited and later we go
for visiting right child node.
✓ This in-order traversal is applicable for every root node of all subtrees in the tree.
✓ This is performed recursively for all nodes in the tree.
First visit 'I' then go for its root node 'D' and later visit D's right child 'J'. With this we have
completed the left part of node B. Then visit 'B' and next B's right child 'F' is visited. With this we have
completed left part of node A. Then visit root node 'A'. With this we have completed left and root parts
of node A. Then we go for right part of the node A. In right of A again there is a subtree with root C. So
go for left child of C and again it is a subtree with root G. But G does not have left part so we visit 'G' and
then visit G's right child K. With this we have completed the left part of node C. Then visit root
node 'C' and next visit C's right child 'H' which is the right most child in the tree so we stop the process.
In-Order Traversal for above example of binary tree is
I-D-J-B-F-A-G-K-C-H
In the above example of binary tree, first we visit root node 'A' then visit its left child 'B' which is a
root for D and F. So we visit B's left child 'D' and again D is a root for I and J. So we visit D's left child 'I'
which is the left most child. So next we go for visiting D's right child 'J'. With this we have completed
root, left and right parts of node D and root, left parts of node B. Next visit B's right child 'F'. With this
we have completed root and left parts of node A. So we go for A's right child 'C' which is a root node for
G and H. After visiting C, we go for its left child 'G' which is a root for node K. So next we visit left of G,
but it does not have left child so we go for G's right child 'K'. With this we have completed node C's root
and left parts. Next visit C's right child 'H' which is the right most child in the tree. So we stop the
process.
Page 10
if (ptr)
{
cout << ptr->data;
preorder(ptr->left_child);
preorder(ptr->right_child);
}
}
Post - Order Traversal ( left child – right child - root )
✓ In Post-Order traversal, the root node is visited after left child and right child.
✓ In this traversal, left child node is visited first, then its right child and then its root node.
✓ This is recursively performed until the right most node is visited.
First visit left child 'I' then visit right child ‘J’ and later visit its root node 'D'. With this we have
completed the left part of node B. Then visits B's right child 'F' and root node 'B' is visited. With this we
have completed left part of node A. Then visits G’s right child node K and root node G is visited. After
visiting G, then visits C’s right child H and root node C is visited. With this we have completed left and
root parts of node A. Finally visit the root node ‘A’.
Page 11
Solution:
a. Preorder b. Inorder
Solution:
Inorder: 1 2 3 4 5 6 7
Preorder: 4 2 1 3 6 5 7
Postorder: 1 3 2 5 7 6 4
Program to Create Binary Tree and display using In-Order Traversal - C Programming
#include<stdio.h>
#include<conio.h>
struct Node{
int data;
struct Node *left;
struct Node *right;
};
struct Node *root = NULL;
int count = 0;
Page 12
struct Node* insert(struct Node*, int);
void display(struct Node*);
void main(){
int choice, value;
clrscr();
printf("\n----- Binary Tree -----\n");
while(1){
printf("\n***** MENU *****\n");
printf("1. Insert\n2. Display\n3. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("\nEnter the value to be insert: ");
scanf("%d", &value);
root = insert(root,value);
break;
case 2: display(root); break;
case 3: exit(0);
default: printf("\nPlease select correct operations!!!\n");
}
}
}
struct Node* insert(struct Node *root,int value){
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(root == NULL){
newNode->left = newNode->right = NULL;
root = newNode;
count++;
}
else{
if(count%2 != 0)
root->left = insert(root->left,value);
else
root->right = insert(root->right,value);
}
return root;
}
// display is performed by using Inorder Traversal
void display(struct Node *root)
{
if(root != NULL){
Page 13
display(root->left);
printf("%d\t",root->data);
display(root->right);
}
}
Output
Page 14
• The leaves of a binary expression tree are operands, such as constants or variable names, and
the other nodes contain operators.
• These particular trees happen to be binary, because all of the operations are binary, and
although this is the simplest case, it is possible for nodes to have more than two children.
• It is also possible for a node to have only one child, as is the case with the unary minus operator.
• An expression tree, T, can be evaluated by applying the operator at the root to the values
obtained by recursively evaluating the left and right subtrees.
Algebraic expressions
Page 15
If we apply all these strategies to the sample tree above, the outputs are:
Infix expression: (a+(b*c))+(d*(e + f))
Postfix Expression: a b c * + d e f + * +
Prefix Expression: + + a * b c * d + e f
Page 16
Creating a one-node tree
➢ Continuing, a '+' is read, and it merges the last two trees.
Expression tree a b + c d e + * *
BINARY SEARCH TREE ADT [Apr/May 2023]
Q10. Explain in detail about binary search tree. [May/June 2014]
Q11. Write the following routines to implement the basic binary search tree operations.
Page 17
(i) Perform search operation in binary Search Tree.
(ii) Find_min and Find_max (Nov/Dec 2018) (Apr/May 2019) [Nov/Dec 2019]
Q12. Write C functions to perform deletion in Binary search tree (Include all the cases).
[Apr/May 2021]
• Binary Search Tree is a binary tree in which every node contains only smaller values in its left sub
tree and only larger values in its right sub tree.
• A binary search tree is a binary tree. It may be empty. If it is not empty, it satisfies the following
properties:
a. Every element has a key, and no two elements have the same key, that is, the keys are unique.
b. The keys in a nonempty left subtree must be smaller than the key in the root of the subtree.
c. The keys in a nonempty right subtree must be larger than the key in the root of the subtree.
d. The left and right subtrees are also binary search trees.
Page 18
In a binary search tree, the search operation is performed with O(log n) time complexity. The search
operation is performed as follows
o Step 1: Read the search element from the user
o Step 2: Compare, the search element with the value of root node in the tree.
o Step 3: If both are matching, then display "Given node found!!!" and terminate the function
o Step 4: If both are not matching, then check whether search element is smaller or larger than that
node value.
o Step 5: If search element is smaller, then continue the search process in left subtree.
o Step 6: If search element is larger, then continue the search process in right subtree.
o Step 7: Repeat the same until we found exact element or we completed with a leaf node
o Step 8: If we reach to the node with search value, then display "Element is found" and terminate the
function.
o Step 9: If we reach to a leaf node and it is also not matching, then display "Element not found" and
terminate the function.
Routine for Search operation
Position Find( ElementType X, SearchTree T )
{
if( T == NULL )
return NULL;
if(X < T->element )
return( Find( X, T->left ) );
else
if( X > T->element )
return( Find( X, T->right ) );
else
return T;
}
Example:
To find an element 4 (X =4) in the below tree
✓ In the first figure, the element 4 is checked with root 6. 4 is less than 6. So goto the left subtree.
✓ In the second figure, the element 4 is checked with node 2. 4 is greater than 2. So goto the right
subtree.
✓ In the third figure, the element 4 is checked with node 4. The element is equal. So return 4.
a. FindMin
• This operation returns the position of the smallest element in the tree. To find the minimum
element, start at the root and go left as long as there is a left child. The stopping point is the
smallest element.
Page 19
Recursive routine for FindMin Non Recursive routine for
Position FindMin( SearchTree T ) FindMin
{ Position FindMin( SearchTree T )
if( T = = NULL ) {
return NULL; if( T != NULL )
else {
if( T->Left = = NULL ) while(T->Left!=NULL)
return T; {
else T = T->Left;
return FindMin ( T->Left ) ; } }}
return T; }
b. FindMax
• This operation returns the position of the largest element in the tree. To find the maximum
element, start at the root and go right as long as there is a right child. The stopping point is the
largest element.
Recursive routine for FindMax Non Recursive routine for
Position FindMax( SearchTree T ) FindMax
{ Position FindMax( SearchTree T )
if( T = = NULL ) {
return NULL; if( T != NULL )
else {
if( T-> Right = = NULL ) while(T->Right!=NULL)
return T; {
else T = T-> Right;
return FindMax ( T-> Right ) ; } }
} return T;
}
Page 20
Recursive routine to insert an element into a binary search tree
SearchTree Insert( ElementType X, }
SearchTree T ) else
{ {
if( T = = NULL ) if( X < T->Element )
{ /* Create and return a one-node tree */ T->Left = Insert( X, T->Left );
T = malloc ( sizeof (struct TreeNode) ); else
if( T != NULL ) if( X > T->Element )
{ T->Right = Insert( X, T->Right );
T-Element = X; return T;
T->Left = T->Right = NULL; }
}
Solved Problems:
1. Construct a Binary Search Tree by inserting the following sequence of numbers 10, 12, 5, 4,
20, 8, 7, 15 and 13
2. Construct the binary search tree from the following set of strings. MAR, MAY, NOV, AUG, APR,
JAN, DEC, JUL, FEB, JUN, OCT and SEP. Show all the steps.
Steps Construction Description
Page 21
1
JAN<MAR, JAN<AUG
6. Therefore attach JAN as right
child of AUG
Page 22
DEC<MAR, DEC>AUG
7. Therefore attach DEC as left
child of JAN
Before After
Deletion
b. Case 2: Deleting a node with one child Deletion
We use the following steps to delete a node with one child from BST...
Step 1: Find the node to be deleted using search operation
Step 2: If it has only one child, then create a link between its parent and child nodes.
Step 3: Delete the node using free function and terminate the function.
Example: Deletion of a node 4 with one child, before and after
Page 23
We use the following steps to delete a node with two children from BST...
Step 1: Find the node to be deleted using search operation
Step 2: If it has two children, then find the largest node in its left subtree (OR) the smallest node in
its right subtree.
Step 3: Swap both deleting node and node which found in above step.
Step 4: Then, check whether deleting node came to case 1 or case 2 else goto steps 2
Step 5: If it comes to case 1, then delete using case 1 logic.
Step 6: If it comes to case 2, then delete using case 2 logic.
Step 7: Repeat the same process until node is deleted from the tree.
Example: Deletion of a node 2 with two children, before and after
Solved Problems:
1: Draw a binary search tree for the following input list 60, 25, 75, 15, 50, 66, 33, 44. Trace the
algorithm to delete the nodes 25, 75, 44 from the tree. (May/Nov 2016) [Apr/May 2021]
Step1 : Insert 60 Step 2: Insert 25
2. Create Binary Search Tree (BST) for the following alphabets. Start from an empty BST. R, F, G, B, Z, U, P,
K, L. Delete keys B, U ,P and K one after the other and show the trees at each stage.
Solution:
Step 1: empty BST Step 2: Insert R
Page 25
Step 5: Insert B Step 6: Insert Z
Page 26
Step 3: Delete P Step 4: Delete K
APPLICATION OF TREES
✓ Manipulation of arithmetic expression
✓ Symbol table construction
✓ Syntax Analysis
✓ Grammar
✓ Expression Tree
✓ class hierarchy in Java
✓ file system
✓ storing hierarchies in organizations
Hashing
• Hashing is an implementation of hash table.
• It is a technique used to maps each key value into some number in the range from 0 to
H_TableSize.
• It is mainly used to perform insertion, deletion and finding an element in a constant average
time O(1) but it does not support any ordering such as FindMin and FindMax.
• There several hash methods are available such as Direct, Subtraction, Modulo division, Folding,
Midsquare, Random generation etc.
• Here we are going to use modulo division as hash function.
• Hashing is also known as Hashing Algorithm or Message Digest Function.
Page 27
• It is a technique to convert a range of key values into a range of indexes of an array.
• It is used to facilitate the next level searching method when compared with the linear or binary
search.
• Hashing allows to update and retrieve any data entry in a constant time O(1).
• Constant time O(1) means the operation does not depend on the size of the data.
• Hashing is used with a database to enable items to be retrieved more quickly.
Example
If the H_TableSize is 10 and key is 27, then
27 mod 10 = 7.
So the key 27 is placed in 7th index.
Page 28
Code For Simple Hash Function for String Input
int Hash(char *key,int TableSize)
{
int value=0;
while(*key!="\0")
value = value + *key++;
return value % TableSize;
}
Collision
• When two keys are hashed to same location, then this situation is called collision. This will be
avoided by using two simple methods.
Page 29
For first key: 437
H (437) = 437 % 10 = 7
The index for 437 is 7.
For key: 325
H (325) = 325 % 10 = 5
The index for 325 is 5.
For key: 175
H (175) = 175 % 10 = 5
The index for 175 is 5.
For key: 199
H (199) = 199 % 10 = 9
The index for 199 is 9.
For key: 171
H (171) = 171 % 10 = 1
The index for 171 is 1.
For key: 189
H (189) = 189 % 10 = 9
The index for 189 is 9.
For key: 127
H (127) = 127 % 10 = 7
The index for 127 is =7.
For key: 509
H (509) = 509 % 10 = 9
The index for 509 is 9.
Searching using Hashing
• If you want to search a data, first we calculate an index by using hashing and then go to that
location in the array and look down the list.
• There you see if that data is present in the list.
• The constant time required for this sear is O(1).
• For worst case, When every elements hashed to same location, in that we would be really doing
a straight linear search on the linked list, which means that the time required to search an
element is O(n).
Page 30
Disadvantages
• It requires pointer and this may slow down the process of inserting of an element into the table.
• It also needs the extra memory for linked list data structure.
• To overcome the disadvantages, an alternative method can be used to avoid the collision.
Linear Probing
• This is the simple method, sequentially tries the new location until an empty location is found in
the table.
• For example: inserting the keys {79, 28, 39, 68, 89} into closed hash table by using same function
and collision resolution technique as mentioned before and the table size is 10 ( for easy
understanding we are not using prime number for table size).
• The hash function is hi(X) = ( Hash(X) + F(i)) % TableSize for i = 0, 1, 2, 3,...etc.
Solution:
Page 31
= ((79%10)+0)%10
h0(28)
28 = (Hash(28)+F(0))%10 8
= ((28%10)+0)%10
h0(39) The first
= (Hash(39)+F(0))%10 9 collision
= ((39%10)+0)%10 occurs
39
h1(39) 0
= (Hash(39)+F(1))%10 0
= ((39%10)+1)%10
h0(68) The
= (Hash(68)+F(0))%10 8 collision
= ((68%10)+0)%10 occurs
h1(68) Again
= (Hash(68)+F(1))%10 9 collision
= ((68%10)+1)%10 occurs
68
h2(68) Again
= (Hash(68)+F(2))%10 0 collision
= ((68%10)+2)%10 occurs
h3(68) 1
= (Hash(68)+F(3))%10 1
= ((68%10)+3)%10
h0(89) The
= (Hash(89)+F(0))%10 9 collision
= ((89%10)+0)%10 occurs
h1(89) Again
= (Hash(89)+F(1))%10 collision
0
= ((89%10)+1)%10 occurs
89
h2(89) Again
= (Hash(89)+F(2))%10 1 collision
= ((89%10)+2)%10 occurs
h3(89) 2
= (Hash(89)+F(3))%10 2
= ((89%10)+3)%10
• The problem with linear probing is primary clustering.
• This is referred 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 that how many attempts are needed to
resolves the collision.
• These long paths affect the performance of hash table.
Quadratic Probing
• Quadratic probing is another open addressing method for resolving collision in the hash table.
• This method is used to eliminate the primary clustering problem of linear probing.
Page 32
• This technique works by considering of original hash index and adding successive value of an
arbitrary quadratic polynomial until the empty location is found.
• In linear probing, we would use H+0, H+1, H+2, H+3,.....H+K hash function sequence.
• Instead of using this sequence, the quadratic probing would use the another sequence is that
H+12, H+22, H+32,....H+K2.
• Therefore, the hash function for quadratic probing is
hi(X) = ( Hash(X) + F(i)2) % TableSize for i = 0, 1, 2, 3,...etc.
• Let us examine the same example that is given in linear probing:
Solution:
Page 33
h1(89) Again
= ( Hash(89) + F(1) ) % 10
2 0 collision
= ((89 % 10) + 1) % 10 occurs
h2(89)
= ( Hash(89) + F(2)2) % 10 3 3
= ((89 % 10) + 4) % 10
• 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
Double Hashing
• This is the last collision resolution techniques where we use two hash functions. For double
hashing, we have a hash function
hi = ( Hash(X) + F(i) ) % TableSize
where F(i)=i.hash2(X).
• This F(i) will generate the sequence such as hash2(X), 2hash2(X) and so on. We use second hash
function as
hash2(X) = R - (X mod R)
where R is the prime which is smaller than TableSize.
• Let us consider the same example in which we choose R=7.
Solution:
Page 34
= ( Hash(68) + F(0)) % 10 collision
= ((68 % 10) + 0) % 10 occurs
h1(68)
= ( Hash(68) + F(1)) % 10
0 0
= ((68 % 10) + 1(7-(68 % 7))) % 10
= (8 + 2) % 10 =10 % 10
h0(89) The
= ( Hash(89) + F(0)) % 10 9 collision
= ((89 % 10) + 0) % 10 occurs
h1(89)
Again
= ( Hash(89) + F(1)) % 10
0 collision
89 = ((89 % 10) + 1(7-(89 % 7))) % 10
occurs
= (9 + 2) % 10 =10 % 10
h2(89) 3 3
= ( Hash(89) + F(2)) % 10
= ((89 % 10) + 2(7-(89 % 7))) % 10
= (9 + 4) % 10=13 % 10
REHASHING
Q23. Explain Rehashing and extendible hashing. When to perform rehashing? Illustrate with
example. (Nov/Dec 2018) (Apr/May 2019)
Rehashing:
• As the name suggests, rehashing means hashing again.
Page 35
• Basically, when the load factor increases to more than its pre-defined value (default value of load
factor is 0.75), the complexity increases.
• So to overcome this, the size of the array is increased (doubled) and all the values are hashed
again and stored in the new double sized array to maintain a low load factor and low complexity.
EXTENDIBLE HASHING
Q23. Explain Rehashing and extendible hashing. When to perform rehashing? Illustrate with
Page 36
example. (Nov/Dec 2018) (Apr/May 2019)
• It is a type of hash system which treats a hash as a bit string, and uses a trie for bucket lookup.
• Because of the hierarchal nature of the system, re-hashing is an incremental operation (done one
bucket at a time, as needed). This means that time-sensitive applications are less affected by
table growth than by standard full-table rehashes.
Formulas
Let's assume that for this particular example, the bucket size is 1. The first two keys to be inserted,
k1 and k2, can be distinguished by the most significant bit, and would be inserted into the table as
follows:
1. the key size that maps the directory (the global depth), and
2. the key size that has previously mapped the bucket (the local depth).
Example
• Suppose that g=2 and bucket size = 3.
• Suppose that we have records with these keys and hash function h(key) = key mod 64:
Step 1:
Page 37
Step 2:
Step 3:
Step 4:
Step 5:
Page 38
Step 6:
Step 7:
Step 8:
Page 39
Step 9:
Step 10:
Page 40
Step 11:
Page 41
UNIT IV NON LINEAR DATA STRUCTURES
Two Marks
1. Define Data Structure. What is Data Structure? (Nov/Dec 2016)
A data structure is logical way of storing and organizing data either in computer's memory or on
the disk storage so that it can be used efficiently.
2. List the classification of Data Structure. (Nov/Dec 2016)
There are two types of data structures:
• Linear Data Structure
• Non-linear data structure
3. Define Linear Data Structure.
o Linear data structures are data structures having a linear relationship between its adjacent
elements. E.g. Linked List.
4. Define Non Linear Data Structure. (Nov/Dec 2013)
Non Linear data structures are data structures don’t have a linear relationship between its
adjacent elements, but have the hierarchical relationship.
e.g. Graph,Tree.
5. Define ADT and give an example. What is an ADT? (or) Write short notes on ADT. What are
Abstract Data Type (Nov/Dec 2014) (April/May 2008)(Apr/May 2015)(May/Jun2016) (Dec
2015/Jan 2016) (Apr/May 2017) (Nov/Dec 2016) (Nov/Dec 2019)
o The Abstract Data Type (ADT) is a set of operations .They is mathematical abstractions and
defines how the set of operations are implemented. E.g.: Integer, real number
o In ADT, all the implementation details are hidden. In short
ADT= Type + Function names + Behavior of each function.
6. Define tree.
• Tree is a non-linear, recursive data structure, which consists of nodes, connected with edges.
• A tree is a collection of nodes connected by directed (or undirected) edges. A tree can be empty
with no nodes or a tree is a structure consisting of one node called the root and zero or one or more
sub trees.
7. Give various implementation of tree. [May 2003]
The tree can be implemented by two ways.
1. Sequential Implementation: The tree is implemented using arrays.
2. Linked Implementation: The tree is implemented using linked list.
8. Explain the basic terminologies in tree.
• Path - A sequence of nodes and edges connecting a node with a descendant.
• Root − Node at the top of the tree is called root. There is only one root per tree and one path from
root node to any node.
• Parent – The node having further sub branches is called parent node.
• Child − A node directly connected to another node when moving away from the Root is called child
node.
• Leaf − Node which does not have any child node is called leaf node.
• Subtree − Subtree represents descendents of a node.
• Visiting − Visiting refers to checking value of a node when control is on the node.
• Traversing − Traversing means passing through nodes in a specific order.
Page 42
• Levels − Level of a node represents the generation of a node. If root node is at level 0, then its next
child node is at level 1, its grandchild is at level 2 and so on.
• keys − Key represents a value of a node based on which a search operation is to be carried out for a
node.
• Descendant (or) Predecessor- A node reachable by repeated proceeding from parent to child.
• Ancestor (or) Successor- A node reachable by repeated proceeding from child to parent.
• Internal node - A node with at least one child.
• External node- A node with no children.
• Degree of the node- The number of sub trees attached to that node is called the degree of a node.
For example, degree of node D is 2.
D
H I
B C
Page 44
Fig: Binary Tree
Binary tree node declarations [May 2010]
Struct treenode
{
int element;
struct treenode *left;
struct treenode *right;
};
20. Define a full binary tree.
• A full binary tree is a tree in which every node has zero or two children.
• The number of leaf nodes n in a complete binary tree can be found using formula n= 2 h, where n is
total number of leaf nodes and h is the height of binary tree.
• In above given tree h =3. Hence total 8 nodes (2h) are leaf nodes.
22. Define perfect binary tree.
• A perfect binary tree is a full binary tree in which all leaves are at the same depth or
same level. (This is ambiguously also called a complete binary tree.)
• A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are
at same level.
Page 45
• The total number of nodes in binary tree are 2h+1 – 1, where h is a height of the tree. In above tree,
the height of tree h is 3. Hence 23+1 -1 = 24 – 1 = 16 -1 = 15 Nodes in the tree.
23. What is meant by traversing?
Traversing a tree means processing it in such a way, that each node is visited only once.
24. What are the different types of traversing?
The different types of traversing are
a. Pre-order traversal-yields prefix from of expression.
b. In-order traversal-yields infix form of expression.
c. Post-order traversal-yields postfix from of expression.
25. What are the two methods of binary tree implementation?
Two methods to implement a binary tree are,
a. Linear representation.
b. Linked representation
26. Define pre-order traversal.
Pre-order traversal entails the following steps;
a. Visit the root node
b. Traverse the left subtree
c. Traverse the right subtree
27. Define post-order traversal.
Post order traversal entails the following steps;
a. Traverse the left subtree
b. Traverse the right subtree
c. Visit the root node
28. Define in -order traversal.
In-order traversal entails the following steps;
a. Traverse the left subtree
b. Visit the root node
c. Traverse the right subtree.
B C
D E F
DBEAFC
Page 46
30. Find the preorder traversal for the given diagram.
A
C
B
D E F G
ABDECFG
31. Find the postorder traversal for the given diagram.
C
B
D E DBECA
Page 47
36. Define Binary search tree. [May 2007, May 2008, Dec 2009]
• Binary Search Tree is a binary tree in which every node contains only smaller values in its left sub
tree and only larger values in its right sub tree.
• A binary search tree is a binary tree. It may be empty.
37. What will be the properties of binary search tree, if it is not empty?
It satisfies the following properties:
e. Every element has a key, and no two elements have the same key, that is, the keys are unique.
f. The keys in a nonempty left subtree must be smaller than the key in the root of the subtree.
g. The keys in a nonempty right subtree must be larger than the key in the root of the subtree.
h. The left and right subtrees are also binary search trees.
Page 48
than the root.
54. What are the advantages and disadvantages of Linear Probing? [Apr/May 2021]
The advantages of linear probing are as follows −
• Linear probing requires very less memory.
• It is less complex and is simpler to implement.
The disadvantages of linear probing are as follows −
• Linear probing causes a scenario called "primary clustering" in which there are large blocks of
occupied cells within the hash table.
• The values in linear probing tend to cluster which makes the probe sequence longer and
lengthier.
Page 49
55. What is Quadratic probing hashing in data structure?
Quadratic probing also is a collision resolution mechanism which takes in the initial hash which
is generated by the hashing function and goes on adding a successive value of an arbitrary quadratic
polynomial from a function generated until an open slot is found in which a value is placed.
62. What are the advantage and disadvantage of separate chaining and linear probing. (Nov/Dec
2018)
Hash tables resolve collisions through two mechanisms,
Page 50
1. Separate chaining or open hashing and
2. Open addressing or closed hashing.
• With linear probing (or any probing really) a deletion has to be "soft". This means you need to
put in a dummy value (often called a tombstone) that won't match anything the user could
search for (or) you would need to rehash every time. Rehashing when too many tombstones
build up is still advised or some strategy to defrag the graveyard.
• Separate chaining (each bucket is a pointer to a linked list of values) has the disadvantage that
you end up searching a linked list with all cache-related issues at hand.
• One other advantage of the probing method is that the values all live in the same array. This
makes copy-on-write very easy by just copying only the array. If you can be assured the original
is not modified by way of class invariant then a taking a snapshot is O(1) and can be done
without locking.
63. Why rehashing? [Apr/May 2023]
• Rehashing is done because whenever key value pairs are inserted into the map, the load factor
increases, which implies that the time complexity also increases as explained above. This might
not give the required time complexity of O(1).
• Rehash must be done, increasing the size of the bucket Array so as to reduce the load factor and
the time complexity.
Page 51
CS3353 C PROGRAMMING AND DATASTRUCTURES
(Regulation – 2021)
QUESTION BANK
UNIT 4
1. Discuss about Binary tree traversals with suitable examples.
2. What is the procedure to construct expression tree? Explain with suitable example.
3. Discuss about BST with suitable examples.
4. Explain in detail about collision resolution techniques with suitable examples.
5. What is hashing? Explain the need of hashing and hash function.
6. Explain about rehashing with an example.
Page 52
UNIT V - SORTING AND SEARCHING TECHNIQUES
Insertion Sort – Quick Sort – Heap Sort – Merge Sort – Linear Search – Binary Search.
SORTING
Definition: Sorting is a mechanism in which the data is arranged in increasing or decreasing
order.
There are two types of sorting techniques –
Internal sorting
External sorting
a. Internal Sorting: Internal sorting is a technique in which data resides in the memory of the
computer.
b. External Sorting : External sorting is a technique in which data resides in external or
secondary storage devices such as hard disk, floppy disk etc. When huge amount of data needs
to be sorted then this technique is applied.
Sorting Order
The sorting is a technique by which we expect the list of elements to be arranged as we
expect. Sorting order is nothing but the arrangement of the elements in some specific manner.
Usually the sorting order is of two types -
a. Ascending order: It is the sorting order in which the elements are arranged from low value to
high value. In other words elements are in increasing order.
For example: 10, 50, 40, 20, 30 can be arranged in ascending order after applying some sorting
technique
10, 20, 30, 40, 50
b. Descending order: It is the sorting order in which the elements are arranged from high value
to low value. In other words elements are in decreasing order. It is reverse of the ascending
order.
For example: 10, 50, 40, 20, 30 can be arranged in descending order after applying some sorting
technique as 50, 40, 30, 20, 10
Sorting Techniques
Sorting technique depends on the situation. It depends on two parameters.
1. Execution time of program that means time taken for execution of program.
2. Space that means space taken by the program.
Sorting techniques are differentiated by their efficiency and space requirements.
Sorting Stability
The sorting stability means comparing the records of same value and expecting them in
the same order even after sorting them.
For example:
(Pune, BalGandharva)
1
(Pune, Shaniwarwada)
(Nasik, Panchavati)
(Mumbai, Gateway-of-india)
Now in the above list, we will sort the list according to the first alphabet of the city. The
ascending order for the alphabets P(for Pune), N(for Nasik), M(for Mumbai) will be M, N, P. The
sorting stability can be achieved by arranging the records as follows.
(Mumbai, Gateway-Of-india)
(Nasik, Panchavati)
(Pune, BalGandharva)
(Pune, Shaniwarwada)
In the above list same record as Pune is twice. But we have preserved the original sequence as
it is after comparing them. Thus the stability is achieved in sorting the records.
Efficiency and Passes
The efficiency of sorting algorithms is denoted in terms of big oh notations.
Commonly there are Θ(n^2) and Θ(nlogn) time complexities.
The sorting techniques such as bubble sort, insertion sort, selection sort, shell sort has the
time complexity Θ(n^2) and the techniques such as merge sort, quick sort has the time
complexity as Θ(nlogn).
The quick sort is the fastest algorithm and bubble sort is the slowest one.
While sorting the elements in some specific order there is lot of arrangement of elements.
The phases in which the elements are moving to acquire their proper position is called
passes.
For example: 10, 30, 20, 50, 40
Pass 1: 10, 20, 30, 50, 40
Pass 2: 10, 20, 30, 40, 50
In the above method we can see that data is getting sorted in two passes distinctly.
Application of Sorting:
Humans usually prefer sorted data to read.
A sorted array is much easier to search in, e.g., using Binary Search.
Sorting makes it much easier to discover patterns or statistics of data items, such as the
median or other moments.
Sorting often helps in comparing lists (or sets), and performing operations like intersection
of sets, finding out if two lists contain the same elements, finding if there are duplicates in
a list, etc.
Types of Sorting
i. Bubble Sort
ii. Selection Sort
iii. Insertion Sort
iv. Shell Sort
v. Radix Sort
2
vi. Merge Sort
vii. Quick Sort
viii. Heap Sort
INSERTION SORT ALGORITHM
Q11. Explain insertion sort with its time complexity. (Nov/Dec 2010) (Nov/Dec 2014)
[NOV/DEC 2022]
Q12. Give the algorithm for insertion sort. (Apr/May 2011)
Q13. Give the routine for Insertion sort. Sort the following sequence using insertion sort 3, 10,
4, 2, 8, 6, 5, 1. [Apr/May 2021]
Algorithm
The insertion sort algorithm is performed using the following steps...
Step 1 - Assume that first element in the list is in sorted portion and all the remaining
elements are in unsorted portion.
Step 2: Take first element from the unsorted portion and insert that element into the
sorted portion in the order specified.
Step 3: Repeat the above process until all the elements from the unsorted portion are
moved into the sorted portion.
Example
3
4
Complexity of the Insertion Sort Algorithm
To sort an unsorted list with 'n' number of elements, we need to make (1+2+3+......+n-1) =
(n (n-1))/2 number of comparisons in the worst case.
If the list is already sorted then it requires 'n' number of comparisons.
Worst Case : O(n2)
Best Case : Ω(n)
Average Case : Θ(n2)
6
7
8
9
ANALYSIS
When pivot is chosen such that the array gets divided at the mid then it gives the best case
time complexity. The best case time complexity of quick sort is Θ (nlog2n).
The worst case for quick sort occurs when the pivot is minimum or maximum of all the elements
in the list. This can be graphically represented as –
This ultimately results in Θ (n^2) time complexity. When array elements are randomly distributed
then it results in average case time complexity, and it is Θ (nlog2 n).
C Program to sort the elements in ascending order using Quick Sort
#include <stdio.h>
#include<conio.h>
#include < stdlib.h>
10
#define SIZE 10
void Quick(int A[SIZE],int,int);
int partition(int A[SIZE],int,int);
void swap(int A[SIZE],int *,int *);
int n;
int main()
{
int i;
int A[SIZE];
clrscr();
printf("\n\t\t Quick Sort Method \n");
printf("\n Enter Total numbers to sort:");
scanf("%d" ,&n);
for(i=0;i<n;i++)
{
printf("\nEnter %dth number: ",i+1);
scanf("%d",&A[i]);
}
Quick(A,0,n-1);
printf("\n\n\t Sorted Array Is: \n");
for(i=0;i<n;i ++)
printf("\t%d ",A[i]);
getch();
return 0;
}
void Quick(int A[SIZE],int low,int high)
{
int m,i;
if(low<high)
{
m=Partition(A,low,high);
Quick(A,low,m-1);
Quick(A,m+1,high);
}
}
int Partition(int A[SIZE],int low,int high)
{
int pivot=A[low],i=low,j=high;
while(i<=j)
{
while(A[i]<=pivot)
i++;
11
while(A[j]>pivot)
j--;
if(i<j)
swap(A,&i,&j);
}
swap(A,&low,&j);
return j;
}
void swap(int A[SIZE],int *i,int *j)
{
int temp;
temp=A[*i];
A[*i]=A[*j];
A[*j]=temp;
}
Output:
Quick Sort Method
Enter Total numbers to sort: 5
Enter Element 30
Enter Element 50
Enter Element 10
Enter Element 20
Enter Element 40
Sorted Array, Is:
10 20 30 40 50
Example 1:
Explain the algorithm of quick sort by sorting the following set of numbers as an example. 42, 47,
52, 57, 62, 37, 32, 27, 22. Apr 2010, Nov 2016, 2017
Step: 1
Step: 2
As Array[i] > Array[pivot], i will not be incremented . As Array [j] < Array [pivot], j will not
be decremented. Just swap Array[i] and Array[j], Increment i, Decrement j
Step: 3
As Array[i]> Array [pivot], will not be incremented. As Array[j] < Array [pivot], j will not
be decremented. Just swap Array[i] and Array[j]. Then increment i and decrement j.
12
Step: 4
Step 8:
Now two sub list can be sorted independently
While Array[i] < Array [pivot] keep on incrementing as = .j, swap Array[j] and Array [pivot]
Step: 9
Step: 10
Sort the left sub list obtained in Step 9
Step: 11
Sort the left sub list obtained in Step 9, Swap Array [Pivot] and Array[j]
Step: 12
The Left sub list obtained in Step 7 is now sorted.
13
We will sort right sub list
Step: 14
Step: 15
Now sort the left sub list obtained in step 13
Example 4:
Sort the following using quick sort. 15, 25, 70, 07, 11, 65, 81, 57 Nov 2014
Step: 1
15 25 70 07 11 65 81 57
i/Pivot j
Step: 2
15 25 70 07 11 65 81 57
Pivot i j
Step: 3
15 11 70 07 25 65 81 57
Pivot i i j
15
Step: 4
15 11 07 70 25 65 81 57
Pivot i j
Step: 5
15 11 07 70 25 65 81 57
Pivot j i
Step: 6
07 11 15 70 25 65 81 57
Pivot j i
Again do the same procedure for LSA and RSA until all the elements are sorted.
Ans: 07 11 15 25 57 65 70 81
Example 5:
Explain the algorithm of quick sort by sorting the following set of numbers as an example. 32,
42, 47, 57, 62, 37, 67, 22, 32. Apr 2015
Step: 1
32 42 47 57 62 37 67 22 32
i / Pivot j
Step: 2
32 42 47 57 62 37 67 22 32
Pivot i j
Step: 3
32 32 47 57 62 37 67 22 42
Pivot i j
Step: 3
32 32 22 57 62 37 67 47 42
Pivot j i
Step: 4
22 32 32 57 62 37 67 47 42
Pivot j i
Again do the same procedure for LSA and RSA until all the elements are sorted.
Ans: 22 32 32 37 42 47 57 62 67
Example 6:
Discuss the quick sort algorithm and apply the same for the following numbers
90,77,60,99,55,88,66. Apr 2015
Step: 1
90 77 60 99 55 88 66
i /Pivot j
Step: 2
90 77 60 99 55 88 66
Pivot i j
Step: 3
90 77 60 66 55 88 99
16
Pivot j i
Step: 4
88 77 60 66 55 90 99
Pivot j i
Again do the same procedure for LSA and RSA until all the elements are sorted.
Ans: 55 60 66 77 80 90 99
Example 7
Give the trace of the algorithm for the following given set of numbers using quick sort 10, 100, 50,
75, 25, 150, 125, 115, 175, 110. Nov 2018
Step 1:
10 100 50 75 25 150 125 115 175 110
i/ Pivot j
Step 2:
10 100 50 75 25 150 125 115 175 110
Pivot i j
Step 3:
10 100 50 75 25 150 125 115 175 110
i / Pivot j
Step 4:
10 100 50 75 25 150 125 115 175 110
Pivot j i
Step 5:
10 25 50 75 100 150 125 115 175 110
Left Array j i(Right array)
Step 6:
10 25 50 75 100 150 125 115 175 110
Left Array Pivot i(Right array)
Step 7: Take Un Sorted Elements of Right Sub array
150 125 115 175 110
i / Pivot j
Step 8:
150 125 115 175 110
Pivot i j
Step 9:
150 125 115 110 175
Pivot j i
Step 10:
110 125 115 150 175
Left sub array Pivot
Step 11: Take un sorted left sub array
17
110 125 115
i/pivot j
Step 12:
110 115 125
pivot i j
Combine all the elements 10 25 50 75 100 110 115 125 150 175
HEAP SORT:
Heap sort is a sorting method discovered by J. W. J. Williams. It works in two stages.
1. Heap construction: First construct a heap for given numbers.
2. Deletion of maximum key: Delete root key always for (n - 1) times to remaining heap.
Hence we will get the elements in decreasing order.
For an array implementation of heap, delete the element from heap and put the deleted
element in the last position in array.
Thus after deleting all the elements one by one, if we collect these deleted elements in an
array starting from last index of array, we get a list of elements in a ascending order.
Let us understand this technique with the help of some example. Sort the following elements
using heap sort: 14, 12, 9, 8, 7, 10, 9 [NOV/DEC 2022]
18
19
20
21
Show the steps in the in-place* heap sort of 4, 7, 2, l, 3: show the steps in heap construction
and show the steps as the sort proceeds.
Solution:
22
Analysis:
Time complexity of heap sort is O (log n) in both worst and average case. Features of heapsort
23
Solution:
24
MERGE SORT
Q17. Write a function to perform merge sort. Give example. (Apr/May 2019) [NOV/DEC 2022]
Explain about the sorting algorithm that works based on divide and conquer technique. [Apr/May
2023]
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time
complexity being Ο(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted manner.
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.
Example
1. Consider the list of following unsorted elements
Solution:
We know that merge sort first divides the whole array iteratively into equal halves unless the
atomic values are achieved. We see here that an array of 8 items is divided into two arrays of
size 4.
25
This does not change the sequence of appearance of items in the original. Now we divide these
two arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the
color codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted
manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target
list of 2 values we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and
44 are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge
them into a list of found data values placing all in a sorted order.
After the final merging, the list should look like this
26
C Implementation
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
27
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
printf("Given array is \n");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf("\nSorted array is \n");
printArray(arr, arr_size);
return 0;
}
Output:
Given array is 12 11 13 5 6 7
Sorted array is 5 6 7 11 12 13
28
Insertion Sort Ω(n) Θ(n^2) O(n^2) O(1)
Selection Sort Ω(n^2) Θ(n^2) O(n^2) O(1)
Tree Sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(n)
Shell Sort Ω(n log(n)) Θ(n(log(n))^2) O(n(log(n))^2) O(1)
Bucket Sort Ω(n+k) Θ(n+k) O(n^2) O(n)
Radix Sort Ω(nk) Θ(nk) O(nk) O(n+k)
Counting Sort Ω(n+k) Θ(n+k) O(n+k) O(k)
Cubesort Ω(n) Θ(n log(n)) O(n log(n)) O(n)
5.1 SEARCHING
Q1.Explain in detail about linear search algorithm with an example. (Apr/May 2015)
Q2.Write the program for binary search and compute its complexity. (Apr/May 2015)
Q3.Discuss binary search and linear search in detail. (Nov/Dec 2015)
Q4.Explain binary search with sample program. (Apr/May 2016)
Q5.Write the algorithm to perform binary search on an array and demonstrate with an example.
(Nov/Dec 2016)
Q6.Develop an algorithm to perform binary search on an array of elements and demonstrate with
an example. (Apr/May 2017)
Q7.Distinguish between linear search and binary search. State and explain the algorithm for both
the search with example. (Nov/Dec 2018)
Search is a process of finding a value in a list of values. In other words, searching is the process
of locating given value position in a list of values.
There are two methods of searching -
a. Linear search
b. Binary search
30
Advantages of a linear search over binary search. [Apr/May 2023]
Will perform fast searches of small to medium lists. With today's powerful computers, small to
medium arrays can be searched relatively quickly.
The list does not need to sorted. Unlike a binary search, linear searching does not require an
ordered list.
Not affected by insertions and deletions. As the linear search does not require the list to be
sorted, additional elements can be added and deleted. As other searching algorithms may have
to reorder the list after insertions or deletions, this may sometimes mean a linear search will be
more efficient.
33
34
C Implementation of Binary Search
#include<stdio.h>
int binarySearch(int[], int, int, int);
void main ()
{
int arr[10] = {16, 19, 20, 23, 45, 56, 78, 90, 96, 100};
int item, location=-1;
printf("Enter the item which you want to search ");
scanf("%d",&item);
location = binarySearch(arr, 0, 9, item);
if(location != -1)
{
printf("Item found at location %d",location);
}
else
{
printf("Item not found");
}
}
int binarySearch(int a[], int beg, int end, int item)
{
int mid;
if(end >= beg)
{
mid = (beg + end)/2;
if(a[mid] == item)
{
return mid+1;
}
else if(a[mid] < item)
{
return binarySearch(a,mid+1,end,item);
35
}
else
{
return binarySearch(a,beg,mid-1,item);
}
}
return -1;
}
Output:
Enter the item which you want to search : 19
Item found at location 2
Each and every element is Compared The list is subdivided into two sub lists.
2. with the key element from the beginning of The key element is searched in the
the list. sub list.
3. Less efficient method. Efficient method.
Additional computation is required for
4. Simple to implement.
computing mid element.
36
UNIT V SORTING AND SEARCHING TECHNIQUES
Two Marks
2. What is sorting? How is sorting essential for data base applications? (Nov/Dec 2010)
Sorting is a technique for arranging data in particular order. Order means the arrangement of
data. The sorting order can be ascending or descending.
o Ordering: Arranging items of the same kind, class, nature, etc. in some ordered sequence,
o Categorizing: Grouping and labeling items with similar properties together (by sorts).
Many Database application queries need results ordered in a particular way.
3. What are the two main classifications of sorting based on the source of data?
Internal sorting
External sorting
9. Define Algorithm.
An algorithm is clearly specified set of simple instructions to be followed to solve a problem.
The algorithm forms a base for program.
21. How many passes does the insertion sort algorithm do to sort a list of 5 elements? What happens
in its ith pass? (Nov/Dec 2006)
Insertion sort iterates, consuming one input element each repetition, and growing a sorted
output list. On a repetition, insertion sort removes one element from the input data, finds the location
it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.
22. What is the application and time complexity of insertion sort? (Nov/Dec 2007) [NOV/DEC 2022]
One of the simplest methods to sort an array is an insertion sort.
An example of an insertion sort occurs in everyday life while playing cards.
To sort the cards in your hand you extract a card, shift the remaining cards, and then insert the
extracted card in the correct place.
This process is repeated until all the cards are in the correct sequence.
Both average and worst-case time is Θ (n2).
23. State the advantages and disadvantages of insertion sort. (Apr/May 2017)
Advantages:
Simple to implementation.
Efficient for (quite) small data sets.
Adaptive, i.e. efficient for data sets that are already substantially sorted: the time complexity is
O(n + d), where d is the number of inversions.
More efficient in practice than most other simple quadratic, i.e. O(n2) algorithms such as
selection sort or bubble sort; the best case (nearly sorted input) is O(n).
Stable, i.e. does not change the relative order of elements with equal keys
In-place, i.e. only requires a constant amount O(1) of additional memory space
Disadvantages:
It is less efficient on list containing more number of elements.
As the number of elements increases the performance of the program would be slow.
Insertion sort needs a large number of element shifts.
24. Define quick sort. List the advantages of quick sort. (Apr/May 2016)
In quick sort the array is split into two sub arrays. This splitting of the array is based on pivot
element. All the elements that are less than pivot should be in the left sub- array and all the elements
that are greater than the pivot should be in the right sub-array.
39
Advantages:
It requires less space.
It reduces unnecessary swaps and moves an item to a greater distance, in one move.
25. What is the time complexity of quick sort and binary search? (Nov/Dec 2014)
Algorithm Time Complexity Space Complexity
Best Average Worst Worst
Quick sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(log(n))
27. Which is the fastest sorting algorithm in practice? What is the average and worst running time
of it? (May/June 2011)
The fastest sorting algorithm in practice is quick sort.
The average case time complexity is Θ (log n) and the worst running time of it is Θ (n2).
28. State why quick sort is more efficient than merge sort. (Nov/Dec 2013)
Merge sort requires secondary memory to perform sorting.
While the quick sort is a in-place sorting method.
The merge sort is more towards the processing of elements.
Quick sort is more towards storing of elements.
These features make the quick sort more efficient than the merge sort.
29. Define merge sort. (or) Give the working method of Divide and Conquer in two simple steps.
(Apr/May 2011) (or) How elements are sorted using merge sort? (Nov/Dec 2015)
Merge sort is a sorting algorithm in which array is divided repeatedly. The sub arrays are
sorted independently and then these sub-arrays are combined together to form a final sorted list.
Merge sort on an input array with “n” elements consists of three steps:
Divide: Partition array into two sub lists s1 and s2 with n/2 elements each.
Conquer: Then sort sub list s1 and sub list s2.
Combine: Merge s1 and s2 into a unique sorted group.
30. Name the sorting technique which use the divide and conquer strategy. (Nov/Dec 2016) (or)
What is divide and conquer technique? How the elements are sorted using merge sort? (Nov/Dec
2016)
Divide and Conquer algorithm is based on dividing the problem to be solved into several,
smaller sub instances, solving them independently and then combining the sub instances solutions so
as to yield a solution for the original instance.
40
31. Mention the time complexities of merge sort and shell sort. (Nov/Dec 2006)
Algorithm Time Complexity
Best Average Worst
Merge sort Ω(n log(n)) Θ(n log(n)) O(n log(n))
Shell Sort Ω(n log(n)) Θ(n(log(n))^2) O(n(log(n))^2)
33. What are the steps involved in performing selection sort? [Apr/May 2021]
Step 1 - Select the first element of the list (i.e., Element at first position in the list).
Step 2: Compare the selected element with all the other elements in the list.
Step 3: In every comparison, if any element is found smaller than the selected element (for
Ascending order), then both are swapped.
Step 4: Repeat the same procedure with element in the next position in the list till the entire list
is sorted.
37. What is binary search? Which search is faster and why? (Apr/May 2016) (or) What is indexed
sequential search? (Nov/Dec 2009)
Binary search is simpler and faster than linear search. Binary search the array to be searched is
divided into two parts, one of which is ignored as it will not contain the required element One
essential condition for the binary search is that the array which is to be searched, should be arranged
in order.
38. With an example compute the number of comparisons required to search an element using
binary search. (Nov/Dec 2015)
N/2 Comparisons need to require searching an element using binary search.
39. Give difference between linear and binary search. (Apr/May 2019) [Apr/May 2021]
Sl. Linear Search Binary Search
No. For searching the element by using
The elements need to be arranged either
1. linear search method it is not required to
in ascending or descending order.
arrange the elements in some specific order
41
Each and every element is The list is subdivided into two sub lists.
2. Compared with the key element from the The key element is searched in the sub
beginning of the list. list.
3. Less efficient method. Efficient method.
Additional computation is required for
4. Simple to implement.
computing mid element.
40. What is the time complexity binary search? State the complexity of binary search. (Nov/Dec
2014) (Nov/Dec 2018)
Class Search algorithm
Worst-case Θ (log N)
Best-case Θ (1)
Average Θ (1 log N)
41. What is the worst case and best case number of comparisons in linear search? (Nov/Dec 2012)
In linear search if the entire lists of elements needs to be searched for locating the key elements
then the worst case number of comparisons are Θ (n) where n denotes the total number of elements in
the list. The best case numbers of comparisons are Θ (1).
43. Give the algorithm to search an element in an array using linear search. (Apr/May 2017)
void Search::Search(int key)
{
int flag=0, mark;
for(int i=0; i<n; i++)
{
if(a[i] ==key)
{
flag= 1;
}
}
if(flag==1)
cout < < "\n The element is present at location: "< <mark+ 1;
else
cout< <"\n The element is not present in the array";
}
Case Time
Complexity
Space Complexity
Space Complexity O(1)
Stable N0
52. Is Linear search is better than binary search? Why? [Apr/May 2023]
No. Because each and every element is compared with the key element from the
beginning of the list. It needs n- comparison when the key element is found at last index of an
array. Linear search is less efficient than binary search.
44
CS3353 C PROGRAMMING AND DATASTRUCTURES
(Regulation – 2021)
QUESTION BANK
UNIT 5
1. Explain in detail about Insertion sort with an example.
2. Discuss about quick sort with suitable example.
3. Solve a problem on heap sort with an example.
4. Elaborate merge sort with suitable example.
5. Discuss about linear search and Binary search with suitable example.
45