0% found this document useful (0 votes)
33 views287 pages

CS3353 - Notes 2 Marks and 16 Marks

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

CS3353 - Notes 2 Marks and 16 Marks

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

UNIT I NOTES - C PROGRAMMING FUNDAMENTALS

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.

DIFFERENT DATA TYPES IN C


Explain the various data types available in C with example. (Or) Discuss the basic data types in C.
(May/June 2016, 2018)
Examine the various data types in C with an example. (Apr/May 2019)
Data types
 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.
 Data types are used to specify the types of data that are going to process within the program.
Classification of data types
5
 C supports different types of data types. They are,
1. Primary Data Type or Primitive data type or basic data type or Built-in data type or pre defined data
type – int, float, char, double
2. User Defined Data Type – Typedef, enum
3. Derived Data Type – array, pointer, struct, union
4. Empty Data Type - void
Primary Data Type or Primitive data type or Basic data type or Built-in data type or Pre defined data type
The primary data types are divided into the following,
1. Integer Data Type
 Integer data type allows a variable to store numeric values.
 The keyword is used to define integer data type is “int”.
 The storage size of integer data type is 2 or 4 or 8 byte.
Eg., int a;
Signed Integer Unsigned Integer
 It occupies 2 bytes in memory.  It also occupies 2 bytes in memory.
 It ranges from -32768 to 32767.  It ranges from 0 to 65535.
 Control string used is %d or %L.  Control string used is %u.
 Eg: int a=2;  Eg: unsigned long b;
long int b=2; unsigned short int c;
2. Character Data Type
 Character data type allows a variable to store only one character.
 Storage size of character data type is 1 byte. We can store only one character using character data type.
 The keyword is used to define character data type is “char”.
Eg: char a;
Signed Char Unsigned Char
 It occupies 1 byte in memory.  It occupies 1 byte in memory.
 It ranges from -128 to 127.  It ranges from 0 to 255.
 Control String used is %c.  Control String used is %c.
3. Floating Point Data Type
Floating point data type consists of 2 types. They are,
 Float
 double
float
 Float data type allows a variable to store decimal values.
 Storage size of float data type is 4 byte.
 These are numbers which contain fractional parts, both positive and negative.
 The keyword used to define float data type is, float.
 It ranges from (3.42-38) to (3.42+38).
 Control String used is %f.
Eg: float a;
double
 Double data type is also same as float data type which allows up-to 10 digits after decimal.
 The keyword used to define double variables is double.
 The range for double data type is from 1E–37 to 1E+37.
 It also occupies 8 bytes in memory.
6
Eg: double a;
User Defined Data Type
 The keyword used to define user defined data type is “typedef”.
 The main advantage is it increases the program’s readability.
 The typedef is an advance feature in C language which allows us to create an alias or new name for an
existing type or user defined type.
 The syntax of typedef is as follows:
 Syntax: typedef data_type new_name;
typedef: It is a keyword.
data_type: It is the name of any existing type or user defined type created using structure/union.
new_name: alias or new name you want to give to any existing type or user defined type.
 Let's take an example:
typedef int myint;
 Now myint is an alias of int. From now on we can declare new int variables using myint instead
of int keyword.
Derived Data Type
 Derived data types are created by using predefined data types (int, char, float, double) only.
 Array, pointer, structure and union are called as derived data types in C language.
Empty Data Type
 Void is an empty data type that has no value.
 This can be used in functions and pointers.
Example Program
#include<stdio.h>
main()
{
int sum;
float money;
char letter;
double pi;
sum = 10; /* assign integer value */
money = 2.21; /* assign float value */
letter = 'A'; /* assign character value */
pi = 2.01E6; /* assign a double value */
printf("value of sum = %d\n", sum );
printf("value of money = %f\n", money );
printf("value of letter = %c\n", letter );
printf("value of pi = %e\n", pi );
}
Output
Value of sum = 10
Value of money = 2.210000
Value of letter = A
Value of pi = 2.010000e+06

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

OPERATORS AND EXPRESSION


OPERATORS IN C LANGUAGE
What are the various operators available in C? Discuss each one of them with suitable illustrations.
(Nov/Dec 2014) [Nov/Dec 2020][Apr/May 2021]
Explain the different types of operators available in C. (April/May 2015) (Nov/Dec 2015) (May/June 2016)
Explain various operators in C language in detail. (April / May 2017)
Explain the different types of operators available in C with example. (Nov / Dec 2017)
List all the operators in C with an example for each. (Apr/May 2019) [Nov/Dec 2019]
Operators
 An operator is a symbol that specifies an operation to be performed on the operands.
Operand
 It is a data item on which operators perform operation.
 Eg: a+b
Here, a, b -> Operands + ->Operator
Various Types of Operator
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

Type Operator Meaning For example

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

Decrement — Decrement by one — x or x —


Arithmetic Operators
 C allows basic arithmetic operations like addition, subtraction, multiplication and division.
 Arithmetic Operators are,
 + , - , * , / , %.
Arithmetic operators are classified as
Unary Arithmetic:
 It requires only one operand.
Eg: +x, -y
Binary Arithmetic:
 It requires two operands.
Eg: a+b, a%b, etc.
Integer Arithmetic:
 It requires both operands are integer values for arithmetic operation.
Eg: a+b a=5, b=2, a+b = 5+2=7
Floating Point Arithmetic:
 It requires both operands are float type for arithmetic operation.
Eg: a+b, a=6.5 b=3.5 , a+b, 6.5+3.5 = 10
Sample Program:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a=5, b=10, c;

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 AND

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

Precedence Operator Description Associativity

() Parentheses (function call)

[] Array Subscript (Square Brackets)

1 . Dot Operator Left-to-Right

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus


2 Right-to-Left
!,~ Logical NOT, Bitwise complement

(type) Cast Operator

15
Precedence Operator Description Associativity

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

< , <= Relational less than, less than or equal to


6 Left-to-Right
> , >= Relational greater than, greater than or equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

14 *= , /= Multiplication, division assignment Right-to-Left

%= , &= Modulus, bitwise AND assignment

^= , |= Bitwise exclusive, inclusive OR assignment

16
Precedence Operator Description Associativity

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right

 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

Unformatted Input / Output Statements


 These statements are used to input/output a single/group of characters from/to the input/output
devices.
Unformatted Input Statements
getchar() function
 A single character can be given to the computer using ”C” input library function getchar().
 It reads a single character from a standard input device.
 Syntax: char variable=getchar();
getc() function
 It is used to accept a single character from the standard input to character variable.
 Syntax: character variable=getc();
gets() function
 It is used to read the string from the standard input device.
 Syntax: gets(char type of array variable);
Unformatted Output Statements
putchar() function
 It is used to display one character at a time on the standard output device.
 Syntax: putchar(character variable);
putc() function
 It is used to display a single character in a character variable to standard output device.
 Syntax: putc(character variable);
puts() function
 It is used to display / write the string to the standard output device.
 Syntax: puts(char type of array variable);
Formatted Input / Output Statements
18
 These statements are used read the data from the keyboard and write the data to the monitor.
Formatted Input Statements
 Reads the formatted data from the keyboard.
scanf() function
 It is used to read information from the standard input device.
 scanf() function starts with a string argument and may contain additional arguments.
 scanf() requires conversion symbol(control string) to identify the data to be read during execution of
the program.
 Syntax: scanf(“control string”,&var1,&var2…..&varn);
Eg: scanf(“%d %f %c”,&a,&b,&c);
Rules for writing scanf() function
 The control string must begin with (%) sign and must be within quotations.
 If there is a number of input data items, items must be repeated by commas and must begin with (&)
sign except for string input.
 The control string and the variables going to input should match with each other.
Formatted Output Statements
 Writes the formatted data to the monitor.
printf() function
 printf() is formatted output function.
 It is used to print the result message on the output screen.
 It prints all types of data values.
 It must have termination with semicolon.
Syntax:
printf(“control string”,var1,var2,……var n);
Rules for writing printf() function
 Place appropriate headings in the output.
 The Variable must be separated by comma and need not be begin with &sign.
 The control string and variables must match in their order.
 The control string must be in quotation.
 The printf statement is terminated by semicolon (;).
Example Program for unformatted I/O functions
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
char a[10];
puts(“Enter a String:”);
gets(a);
puts(“Answer=”);
puts(a);
getch();
}
Output:
Enter a String: MECH

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;

The continue statement


 When a continue statement is encountered inside any C loop, the control is automatically transferred to
the beginning of the loop.
Syntax
continue;

The goto statement


 It is used to transfer the control unconditionally from one place to another place in the program.
 When a goto statement is encountered inside a loop, the control is transferred to the beginning.
 It requires a label to identify the place to move the execution.
 A label is a valid variable name and must be ended with colon (:).
Syntax
goto label;
………….
………….
label:
(Or)
label:
………..
goto label;
Difference between Break and Continue statement
Break Continue

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.

ELEMENTS OF USER-DEFINED FUNCTION


Explain in detail about the elements of user defined function. (Or) Explain the following with suitable
examples. (i) Function Declaration (Dec/Jan 2014)
 To write an efficient user-defined function, the programmer must familiar with the following three
elements.
 Function Definition
 Function Declaration
 Function Call
Function Definition
 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;
}
30
Function Declaration
 A function declaration tells the compiler about a function's name, return type, and parameters.
Syntax: return_type function name(parameters list);
Rules for declaring a function
 The list of parameter must be separated by comma.
 If the function does not return any value, then the return type void is must.
 If there are no parameters, simply place void in braces.
 The data type of actual and formal parameters must match.
Example
int max(int num1, int num2);
 Parameter names are not important in function declaration only their type is required.
int max(int, int);
Function Call
 A function can be called by simply specifying the name of the function, return value and parameters if
presence.
Syntax
function name();
function name(parameter);
return value=function name(parameter);
Eg:
fun(); - Function without argument and return value
fun(a,b); - Function with argument
c=fun(a,b); - Function with argument and return value
How Function Works
 Once a function is called the control passes to the called function.
 The working of calling function is temporarily stopped.
 When the execution of called function is completed then the control returns back to the calling function
and execute the next statement.

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

PARAMETER PASSING METHODS


Explain in detail about parameter passing methods.
Explain in detail about call by value and call by reference. Apr / May 2018 [Nov/Dec 2021]
Explain the following with suitable examples. (i) Call by Reference, Call by Value. (Dec/Jan 2014)
Explain the concept of pass by reference with suitable example. (May/June 2014)
What is a function in C? Discuss about call by value and call by reference with illustrations. (May/June
2014) (Nov/Dec 2015)
Explain the pass by reference with an example. (May/June 2016) (Or) Explain the concept of parameter
passing by value and reference between functions in detail with example program. Nov / Dec 2016 (April /
May 2017)
Write a C program to swap the content of two variables using pointer. Nov / Dec 2017
Write a C program to get two numbers and exchange the numbers using call by value and call by reference.
Nov 2018 [Nov/Dec 2020][Apr/May 2021]
Illustrate pass by value and pass by reference in functions with an example. (Apr/May 2019)
 Function is good programming style in which we can write reusable code that can be called whenever
require.
 Whenever we call a function then sequence of executable statements gets executed. We can pass some
of the information to the function for processing called argument / parameter.
There are two ways that the parameters can be passed to a function. They are,
 Call by Value (Pass by Value)
 Call by Reference (Pass by Reference / Address / Pointers)
Call by Value
 This method copies the values of actual parameters into the formal parameters of the function.
 ie., xerox copy of original parameter is created and passed to the called function.
 Here, the changes to the formal parameter do not affect the actual parameter.
Example Program to swap the values stored in two integer variables. Apr / May 2018
#include<stdio.h>
#include<conio.h>
void swap(int a, int b); //Function Definition
36
int main()
{
int a=50, b=70;
clrscr();
printf(“Before swapping”);
printf(“a=%d”,a);
printf(“b=%d”,b);
swap(a, b); // Calling Function
printf(“After swapping”);
printf("\n a: %d",a);
printf("\n b: %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=50 b=70
 In the above example, a and b are the original values and xerox copy of these values is passed to the
function and is copied into formal parameter a and b variable of same function respectively.

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

RECURSION [NOV/DEC 2022]


What is recursion? Give an example. (Dec/Jan 2014) [Nov/Dec 2019] [Nov/Dec 2021]
What is recursion? Explain a recursive function with suitable example. (Nov/Dec 2014) (Nov/Dec 2015)
Write a C program to find the factorial of a given number using recursive function. Nov 2018 [Nov/Dec
2020][Apr/May 2021]
 Recursion is a process of calling the same function itself again and again until some condition is
satisfied.
 It is a programming technique that allows the programmer to express the operations in terms of
themselves.
Syntax
return-type recursive_funct (argument list)
{
statements;
... ... ...
recursive_funct (actual argument);
... ... ...
}
How Recursive Function Works?

Example Program: Factorial of a number using recursion


#include<stdio.h>
#include<conio.h>
int factorial(int);
void main()
{
int n;
clrscr();
printf("\n Enter a Number:");
scanf("%d",&n);
39
printf("\n The Factorial of %d is %d",n,factorial(n));
getch();
}
int factorial(int n)
{
if(n==1)
return 1;
else
return (n*factorial(n-1));
}
Output:
Enter a Number: 5
The Factorial of 5 is 120
Example 2: Fibonacci Series using recursion
#include <stdio.h>
int main()
{
int num;
printf("Enter the number of elements to be in the series : ");
scanf("%d", &num);
int i;
for (i = 0; i < num; i++)
{
printf("%d, ", fibonacci(i));
}
return 0;
}
int fibonacci(int num)
{
if (num == 0)
{
return 0;
}
else if (num == 1)
{
return 1; }
else
{
return fibonacci(num - 1) + fibonacci(num - 2);
}
}
Advantages of recursion
1. The code may be easier to write.
2. To solve such problems which are naturally recursive such as tower of Hanoi.
3. Reduce unnecessary calling of function.

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.

Infinite recursion occurs if the step in


recursion doesn't reduce the problem to a
smaller problem. It also becomes infinite An infinite loop occurs when the condition in
recursion if it doesn't convert on a specific the loop doesn't become False ever.
condition. This specific condition is known
as the base case.

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

Initializing a Two Dimensional Array


 Like one dimensional array, the values can be initialized to the two dimensional arrays at the time
declaration.
Syntax:
data_type array_name[row size][column size] = {List of Values};
Eg:
int stud[3][2] = {
{6680, 80},
{6681, 85},
{6682, 87}
};
(Or)
int stud[3][2] = {6680, 80, 6681, 85, 6682, 87};
Example Program (To print two dimensional array row by row)
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j;
int x[2][2]= { {1,50},
{2,75}
};
clrscr();
44
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
Multi Dimensional Arrays (or) n – Dimensional arrays
 Like one and two dimensional array ‘C’ language allows multidimensional arrays.
 ie., it has three or more dimensions is called multidimensional array.
Syntax:
data_type array_name[size1][size2]……….size[n];
Eg:
int a[3][3][3];
float b[4][4][4][4];

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

ARRAY OF CHARACTERS (STRING)


 A string is a collection of characters.
 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’};
a b c \0

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.

2) Mention the features and applications of C. [Nov/Dec 2020][Apr/May 2021]


 C is a general purpose, structured programming language.
 C is a powerful, efficient, compact & flexible.
 C is highly portable. C is robust language.
 C is middle level language. It supports low level & high level language.
 C programs are fast and efficient.
 C language allows dynamic memory allocation.
3) Write the structure of C program. (Apr /May 2018) (Apr/May 2019)

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.

In this if the user wants to use a particular


There is no such kind of requirement to add library function then the user has to add the
the particular library. particular library of that function in header
file of the program.

Execution of the program begins from the Execution of the program does not begin from
user-define function. the library function.

Example: sum(), fact(),…etc. Example: printf(), scanf(), sqrt(),…etc.

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.

43) Define return statement.


 The return statement may or may not send back some values to the calling function.
Syntax: return; (Or) return(expression);
44) What are the parameter passing methods available in C?
There are two ways that the parameters can be passed to a function. They are,
 Call by Value / Pass by Value
 Call by Reference / Pass by Reference
45) Differentiate 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


• This method copies the values of function call.
actual parameters into the formal • This method copies the addresses of
parameters of the function. actual parameters into the formal
• Here, the changes to the formal parameters of the function.
parameter do not affect the actual • Any changes to the formal parameter
parameter. will affect the actual parameter.
• Changes to the formal parameter is • Changes to the formal parameter is
temporary permanent
• Eg: swap(a,b); • Eg: swap(&a,&b);

46) Define recursion. [Apr/May 2023]


 Recursion is a process of calling the same function itself again and again until some condition
is satisfied.
 It is a programming technique that allows the programmer to express the operations in terms
of themselves.
Syntax
return-type recursive_funct (argument list)
{
statements;
... ... ...
recursive_funct (actual argument);
... ... ...
}
47) What will be the output of the following program. [NOV/DEC 2022]
63
#include<stdio.h>
int main()
{
float x=0.1;
if(x==0.1)
printf(“if”);
else if(x==0.1f)
printf(“else if”);
else
printf(“else”);
}
Output: if
48) List out the advantages of recursion.
Advantages of recursion
1. The code may be easier to write.
2. To solve such problems which are naturally recursive such as tower of Hanoi.
3. Reduce unnecessary calling of function.
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.
49) List out the disadvantages of recursion.
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.
50) Write the applications of recursion.
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)
51) Tabulate recursion Vs iteration.

Recursion Iteration

Recursion uses the selection structure. Iteration uses the repetition structure.

Infinite recursion occurs if the step in


recursion doesn't reduce the problem to a
smaller problem. It also becomes infinite An infinite loop occurs when the condition in
recursion if it doesn't convert on a specific the loop doesn't become False ever.
condition. This specific condition is known
as the base case.

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.

V.R.S. College of Engineering and Technology, Arasur – 607 107


(Reaccredited by NAAC and an ISO 9001:2008 Recertified Institution)

Department of Electrical and Electronics Engineering


II YEAR / III SEMESTER
CS3353 C PROGRAMMING AND DATASTRUCTURES
(Regulation – 2021)
QUESTION BANK
65
UNIT I
1. Explain in detail about Data types in C with suitable examples.
2. Discuss about types of operators in C with suitable examples.
3. List the types of decision making or conditional statements and explain with suitable examples.
4. Explain about Branching and looping statements with suitable examples.
5. What is recursion? Explain recursive function with suitable examples.
6. Define array. Explain the types of array with suitable examples.
7. What is variable? Explain variables with an example.
8. Write a C Programs for factorial, Fibonacci series, Matrix multiplication, Matrix addition &
Subtraction and Transpose of Matrix.

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

Example Program (/* Calculate Employee Salary using Structures*/)


Write a C program to store the employee information using structure and search a particular employee
using employee number. (May/June 2014)
Write algorithm and a C program using unions, to prepare the employee pay roll of a company. Nov / Dec
2017
Illustrate the representation of structures and unions for an employee record having empid, emp-name,
DOB, Basicpay, allowances, deductions with their operations in C. (Apr/May 2019)
#include<stdio.h>
#include<conio.h>
struct employee {
char name[15];
int empid;
float bsal;
float nsal;
float gross;
};
void main() {
struct employee emp;
float hra,da,tax;
clrscr();
printf("\n Employee Details");
printf("\n Enter the Employee Name:");
scanf("%s",&emp.name);
printf("\n Enter the Employee ID:");
scanf("%d",&emp.empid);
printf("\n Enter the Basic Salary:");
scanf("%f",&emp.bsal);
hra=((10*emp.bsal)/100);
da=((35*emp.bsal)/100);
emp.gross=emp.bsal+hra+da;
emp.net=emp.gross-tax;
printf("\n Employee Name:%s",emp.name);
printf("\n Employee ID:%d",emp.empid);
printf("\n Employee Basic Salary:%f",emp.bsal);

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

Program using Structure and Union


#include<stdio.h>
#include<conio.h>
struct student
{
int a;
int b;
char c;
}s;
union student1
{
int a;
int b;
char c;
}s1;
void main()
{
printf("\n The size of structure is %d",sizeof(s));
printf("\n The size of union is %d",sizeof(s1));
getch();
}
Output:
The size of structure is 5
The size of union is 2

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)

Data Older Address stored in Next Address stored in pointer after


Type pointer incrementing (ptr++)

int 1000 1002

float 1000 1004

char 1000 1001

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)

Data Older Address Next Address stored in pointer


Type stored in pointer after incrementing (ptr–)

int 1000 0998

float 1000 0996

char 1000 0999

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

ARRAY AND POINTER


Explain in detail about Array and Pointer with an example. Nov / Dec 2016, Apr / May 2018
 Arrays are closely related to pointers in C programming but the important difference between them is
that, a pointer variable can take different addresses as value whereas; in case of array it is fixed.
Eg: int a[5]={1,2,3,4,5};
Memory Address a[0] a[1] a[2] a[3] a[4]
Value 1 2 3 4 5
Base Address 4000 4002 4004 4006 4008
Explanation
 a[5] means the array ‘a’ has 5 elements and of integer data type.
 The base address (Assume 4000) of the array starts with 0th element of the array.
 The array is in integer type, the integer will have 2 bytes and hence the address of the next address
element is incremented by 2.
Example
#include<stdio.h>
int main()
{
char c[4];
int i;
for(i=0;i<4;++i)
{

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;

ARRAYS AND FUNCTIONS


Explain the procedure to pass an array as argument to a function with an example program.
[Apr/May 2023]
Methods to Pass an Array as an Argument
Arrays can be passed to function using either of two ways.
1. Passing array as a pointer variable
2. void foo(int* array)
3. Passing array as reference
4. void foo(int array[])

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.

C Function to Sort the Array


#include<stdio.h>
void BubbleSort(int array[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (array[j] < array[i])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
// no need to return array because,
// array is passed by reference
}
void main()
{
int arr[6] = {1, 4, 6, 2, 6, 5};
// passing array to the function
BubbleSort(arr, 6);
printf("Sorted array = ");
int i = 0;
for (i = 0; i < 6; i++)
{
printf("%d, ", arr[i]);
}
}
Output:
Sorted array = 1, 2, 4, 5, 6, 6,
In this example, we pass an array to a function in C, and then we perform our sort inside the
function. Because we have passed the array by reference, changes on the array persist when the
program leaves the scope of the function.
Returning an Array from a Function
We can return an array from a function in C using four ways
1. Returning the array passed to function
2. Returning dynamically created array
3. Return array using static array
20
4. Returning array using struct
For the first three cases, we can return the array by returning a pointer pointing to the base address of
the array.
1. Returning the array passed in the function
int* foo(int array[])
{
// do something
return array;
}
2. Returning Dynamically Created Array
Dynamically create an array inside the function and then return a pointer to the base address of this
array.
#include<malloc.h>
int* foo(int n)
{
// creating an array of n numbers
int *array = (int*)malloc(n * sizeof(int));;
// do something with the array
return array;
}
Function declaration to accept one dimensional array
To accept one dimensional array our function declaration will look like the following.
returnType functionName(type arr[], type size);
Example:
float findAverage(int arr[], int size);
 In the above function declaration we have a function by the name findAverage.
 The first parameter is of type int and takes one dimensional integer array.
 The second parameter of int type is for the size of the array i.e., number of elements.
 The return type of this function is set to float so, it will return a floating point value.
Passing one dimensional array to function
 To pass a one dimensional array we simply write the name of the array variable as the
function argument.
 For example, if we want to store marks of a student in 5 papers then we can create an integer
array of size 5 and type int and give it a name lets say, score.
int score[5] = {90, 80, 70, 75, 85};
 In the following example we are passing a one dimensional array of type int and by the
name score to the findAverage() function.

The complete code is given below.


#include <stdio.h>
float findAverage(int [], int);
int main(void)
{
int score[5] = {90, 80, 70, 75, 85};
int papers = 5;
float avg = findAverage(score, papers);
printf("Average: %f\n", avg);

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

2. Open a file using the fopen() function. [NOV/DEC 2022]


 The file open function (fopen) serves two purposes:
 It makes the connection between the physical file and the stream.
 It creates “a program file structure to store the information” C needs to process the file.
 To open a file using the fopen() function.
 Its syntax is,
FILE *fopen(const char *fname,const char* mode);

3.Close the file using the fclose() and fflush() functions.


 Closing and Flushing Files
 The file must be closed using the fclose() function.
 Its prototype is ,
Syntax int fclose(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);

 fread reads a specified number of equal-sized


 data items from an input stream into a block.
ptr = Points to a block into which data is read
size = Length of each item read, in bytes
n = Number of items read
stream = file pointer

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

Detecting the end of a file:


 When reading from a text-mode file character by character, one can look for the end-of-file character.
 The symbolic constant EOF is defined in stdio.h as -1, a value never used by a real character.

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

/* Program to display the content of the file */


void main()
{
FILE *fp;
int ch;
clrscr();
fp=fopen("ex_file4.c","r");
if(fp==NULL)
printf(“File is not available”);
ch=getc(fp);
while(ch!=EOF)
{
printf("%c",ch);
ch=getc(fp);
}
fclose(fp);
getch();
}
/* read and write the content of the file using fprintf() and fscanf() functions */ [NOV/DEC 2022]
void main()
{
28
FILE *fptr;
char name[20];
int age;
float salary;
clrscr();
/* open for writing */
fptr = fopen("abc.txt", "w");
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %f\n", salary);
getch();
fclose(fptr);
}
PREPROCESSOR DIRECTIVES
Discuss about the preprocessor directives in C. (Or) Write short notes on #include, #endif statement.
(Nov/Dec 2014) [Nov/Dec 2020][Apr/May 2021]
Write short notes on #include, #ifndef, #endif statements. (Nov/Dec 2015)
Describe about the preprocessors with suitable example. (May/June 2016), Nov / Dec 2016 [Apr/May 2023]
 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.

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.

16) What are the advantages of pointer?


 It is more compact and efficient code.
 It is used to achieve clarity and simplicity.
 It enables us to access the memory directly.

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;

18) What is indirection operator?


 Asterisk (*) indirection operator is used along with pointer variable while dereferencing the
pointer variable.
 Asterisk operator is also called as value at operator.
 When used with pointer variable, it refers to variable being pointed to; this is called as
Dereferencing of Pointers.
19) What is the difference between the indirection and address operators? (Or) What is an address
operator and indirection operator? (Nov / Dec 2014) (Nov / Dec 2015)

35
 The indirection operator (*) returns the value of the variable stored in a pointer.
 The address operator (&) returns the memory address of the variable.

20) What does null pointer mean?


 A pointer is said to be a null pointer when its right side value is 0.
 A null pointer can never point to a valid data. For checking a pointer, if it is assigned to 0, then
it is a null pointer and is not valid.

21) What is a Character Pointer?


 A character pointer can also be used to access character arrays and string constants in the same
way as accessing numeric arrays using their respective pointer variable.
Syntax: char *pointer_character;

22) Define Array of Pointers.


 Array notation is a form of relative addressing.
 The compiler treats the subscripts as a relative offset from the beginning of the array.
 When a pointer variable is set to the start of an array and is incremented to find the next
element, absolute addressing is being implemented.
23) What is the role of pointer in call by reference? [Apr/May 2023]
Instead of value the address is passed from calling function to called function The role of pointer is to
access and retrieve the value from the pointed address in called function.
24) What is Pointer to Pointer?
 Here one pointer stores the address of another pointer variable.
Example:
int x=10,*a,**b;
a=&x;
b=&a;
25) How is pointer arithmetic done? (May/June 2016)
 Pointers arithmetic is done by adding, subtracting, comparing, incrementing and decrementing
the values assigned to the pointer variables.

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

27) What is Dynamic Memory Allocation? (April / May 2017)


 The process of allocating memory at runtime is known as dynamic memory allocation.
 Library routines known as "memory management functions" are used for allocating and freeing
memory during execution of a program.
 These functions are defined in stdlib.h.

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.

30) What are the rules for defining preprocessor directive?


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

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

32) Define File Inclusion. [Nov/Dec 2019]


 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.
Example
#include<stdio.h> - compiler searches in the standard library.
#include”loop.c” – Compiler searches in the current directory.

33) What is Macro Substitution?


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

34) What are the different types of macro substitution?


There are three types of macros. They are,
 Simple Macros
 Argumented Macros
 Nested Macros

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”

36) What is Argumented 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)
37) What is Conditional Inclusion? [NOV/DEC 2022]
What is the use of #define preprocessor? (Nov/Dec 2014) (Nov / Dec 2015)
These are used to control the preprocessor with conditional statements.
The preprocessor directives are,
#define – Used to define symbolic constant.
#ifdef – Used to test macro condition.
#else – Used to specify alternative in #ifdef.
#undef – Used to undefine a macro.

38) Define file.


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

39) How is a file stored?


– Stored as sequence of bytes, logically contiguous.
(may not be physically contiguous on disk).

40) Why files are needed? [APR/MAY 2019]


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

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.

44) What is 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 concern about them.
FILE *file_pointer_name;
Eg : FILE *fp
45) What is Open a file using the fopen() function? [Nov/Dec2021]
 The file open function (fopen) serves two purposes:
 It makes the connection between the physical file and the stream.
 It creates “a program file structure to store the information” C needs to process the file.
 To open a file using the fopen() function.
 Its syntax is,
FILE *fopen(const char *fname,const char* mode);
46) Write about Close the file using the fclose() and fflush() functions.
 Closing and Flushing Files
 The file must be closed using the fclose() function. Its prototype is ,
Syntax int fclose(FILE *fp);
47) List down the modes of fopen.

48) What is 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);
49) How to detecting the end of a file?[Apr/May2021][Nov/Dec2020]
 When reading from a text-mode file character by character, one can look for the end-of-file character.
39
 The symbolic constant EOF is defined in stdio.h as -1, a value never used by a real character.
Eg: while((c=getc(fp)!=EOF).
50) Write a c program to read a string to text file. [Nov/Dec2021]
/* 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();
}
51) What is end of file?
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:

Exaple:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}

52) Define fseek().


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
53) What is ftell()?
syntax:
offset = ftell( file pointer );

 "ftell" returns the current position for input or output on the file

54) List the types of file processing.


 Sequential access
 Random access

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]

Parameter Sequential Access Random Access

Sequential access files are


slower compared to random Random access files, on the other
Access access files since accessing a hand, allow direct access to specific
Speed specific record requires reading records, resulting in faster access
through all the previous records times.
in the file

Sequential access files allow Random access files allow direct


Access
access to records in a sequential access to specific records using an
Method
manner index, record number, or key.

Sequential access files store


Record records in a specific order, Random access files do not have any
Ordering usually the order in which they specific order of storing records.
were added to the file.

Inserting a new record in a Random access files may require


Insertion of sequential access file is relocating other records to maintain
New Record relatively easy since new records the order so insertion becomes hard
are added to the end of the file. as compared to sequential access.

Sequential access files require


Memory Random access files require more
less memory than random access
Requiremen memory because of indexing
files since they do not need to
ts information
store any indexing information.

Random access files offer higher


search flexibility than sequential
Search Search flexibility is limited in
access files since they allow for direct
Flexibility sequential access file.
access to specific records based on
various search criteria

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

File Sequential access files are


Random access files are typically
Organizatio typically organized in a linear
indexed.
n fashion

Examples Text files, Logs Database, Spreadsheet

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

a. Linear Data Structures:


 A data structure is called linear if all of its elements are arranged in the linear order.
 In linear data structures, the elements are stored in non-hierarchical way where each element has
the successors and predecessors except the first and last element.
Static and dynamic data structure:
Static data structure:
 If a data structure is created using static memory allocation, ie. data structure formed when the
number of data items are known in advance ,it is known as static data static data structure or fixed
size data structure.
Dynamic data structure:
 If the data structure is created using dynamic memory allocation i.e data structure formed when
the number of data items are not known in advance is known as dynamic data structure or variable
size data structure.
Page 1
Types of Linear Data Structures are given below:
i. Arrays:
 An array is a collection of similar type of data items and each data item is called an element of the
array.
 The data type of the element may be any valid data type like char, int, float or double.
 The array can be one dimensional, two dimensional or multidimensional.
ii. Linked List:
 Linked list is a linear data structure which is used to maintain a list in the memory.
 It can be seen as the collection of nodes stored at non-contiguous memory locations.
 Each node of the list contains a pointer to its adjacent node.
 The order may be LIFO(Last In First Out) or FILO(First In Last Out).
iii. Stack:
 Stack is a linear list in which insertion and deletions are allowed only at one end, called top.
 A stack is an abstract data type (ADT), can be implemented in most of the programming languages.
 It is named as stack because it behaves like a real-world stack, for example: -deck of cards etc.
iv. Queue:
 Queue is a linear list in which elements can be inserted only at one end called rear and deleted only
at the other end called front.
 It is an abstract data structure, similar to stack.
 Queue is opened at both end therefore it follows First-In-First-Out (FIFO) methodology for storing
the data items.
b. Non Linear Data Structures:
 This data structure does not form a sequence i.e. each item or element is connected with two or
more other items in a non-linear arrangement.
 The data elements are not arranged in sequential structure (ie) arranged in hierarchical manner.
Types of Non Linear Data Structures are given below:
i. Trees:
 Trees are multilevel data structures with a hierarchical relationship among its elements known as
nodes.
 The bottommost nodes in the hierarchy are called leaf node while the topmost node is called root
node. Each node contains pointers to point adjacent nodes.
ii. Graphs:
 Graphs can be defined as the pictorial representation of the set of elements (represented by
vertices) connected by the links known as edges.
 A graph is different from tree in the sense that a graph can have cycle while the tree cannot have
the one.
Operations on data structure
1) Traversing: Traversing the data structure means visiting each element of the data structure in order to
perform some specific operation like searching or sorting.
2) Insertion: Insertion can be defined as the process of adding the elements to the data structure at any
location.
3) Deletion: The process of removing an element from the data structure is called Deletion. We can delete
an element from the data structure at any random location.

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

ABSTRACT DATA TYPES (ADTs)


Q1. Explain in detail about ADT. [NOV/DEC 2022]

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

ARRAY IMPLEMENTATION OF LIST


Q2. What are the various operations on array? Write a procedure to insert an element in the
middle of the array. (Nov/Dec 2018)
 Array is collection of similar data elements in contiguous memory location.
 Insertion and deletion are more expensive and takes more time
 Find and print list operation takes constant time.
 Memory space is wasted

The basic operations performed on a list of elements are


 Creation of List.
 Insertion of data in the List
 Deletion of data from the List
 Display all data’s in the List
 Searching for a data in the list
Declaration of Array:
#define maxsize 10
int list[maxsize], n ;

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

LINKED LIST IMPLEMENTATION


Q4. Explain in detail about linked list implementation. [Apr/May 2021] [NOV/DEC 2022]

Contents
 Singly linked list
 Doubly linked list
 Circularly linked list
 Doubly linked circular list
 Procedure delete(X,L)
 Procedure insert(P,X)

 Insertion and deletion operations can be performed using linked list.


 A linked list is a linear collection of data elements.
 These data elements are called nodes.
 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:
o The data stored in the node.
o A pointer or link to the next node in the list
Node

 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]

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 Costly Insertions and deletions are done in less time
It occupies less memory It occupies more memory
Applications of Linked List
 Polynomial ADT
 Radix sort
 Multilists

SINGLY LINKED LIST


Q6. Illustrate the algorithm to create the singly linked list and perform all the operations on
the created list. Write [NOV/DEC2015] (NOV/DEC 2019)
Q7. What is singly linked list? Write a C program that uses functions to perform the following
operation on singly list with suitable diagrammatic representations. Consider all cases
(i) Insertion (ii) Deletion (iii) Traversal in both ways (NOV/DEC 2016)
Q8. Write C code for singly linked list with insert, delete, display operations using structure
pointer. (MAY/JUNE 2016)
Q9. What are the ways to insert a node in linked list? Write an algorithm for inserting a node
before a given node in a linked list. (NOV/DEC 2018)

Singly linked list


 Singly linked list has collection of nodes.
 Each node has two fields.
 First field is the data field
 Second field is the link field.
 The link field contains the pointer, which points to the next node in the list.
 The first node in the linked list is pointed to by the head pointer.
 The last node in the list has a link field containing a NULL flag indicating “end of list”.

Definition of Singly linked list:


 A singly linked list is the simplest type of linked list in which every node contains some data and a
pointer to the next node of the same data type.

Page 14
 The node contains a pointer to the next node means that the node stores the address of the next
node in sequence.

Operations on Singly linked list


 Insert a new node at the beginning
 Delete a new node at the beginning
 Display the elements in the Linked List
Creating a New Node
• If starting node is not available then “first” = NULL and Create new node.
• In the created node fill data into “data field“ and “pointer” or “next field” as NULL.
• Attach this newly created node to start
• Make new node as starting node
Node Creation
struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node *));
Create a new node

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

As we will search for the key value 30, key = 30

Thus desired node gets inserted at desired position.


Deletion:

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

void dele(node **head)


{
node *temp, *prev ;
int key;
temp=*head;
if(temp==NULL)
{
printf("\n The list is empty\n");
getch();
clrscr( );
return;
}
//Main function
printf("\n Enter the data of the node you want to delete: ");
scanf("%d",key);
temp=search(*head,key);
if(temp!=NULL)
{
prev=get_prev(*head,key);
if(prev==NULL)
{
prev->next=temp->next;
free(temp);
}
else
{
*head=temp->next;
free(temp);
}
printf("\nThe Element is deleted\n");
getch();
clrscr();
}
}
We have

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

Another case is, if we want to delete a head node then-

This can be done using the following statement

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

/* Reverse the order of nodes of a singly linked list */


void reverseList()
{
struct node *prevNode, *curNode;
if(head != NULL)
{
prevNode = head;
curNode = head->next;
head = head->next;
prevNode->next = NULL; // Make first node as last node
while(head != NULL)
{
head = head->next;
curNode->next = prevNode;

Page 24
prevNode = curNode;
curNode = head;
}
head = prevNode; // Make last node as head
printf("SUCCESSFULLY REVERSED LIST\n");
}
}

DOUBLY LINKED LIST [NOV/DEC 2022] [Apr/May 2023]


Q10. Describe the creation of a doubly linked list and appending the list. Give relevant coding
in C. (NOV/DEC 2014)
Q11. Illustrate the necessary algorithms to implement doubly linked list and perform all the
operations on the created list. (NOV/DEC 2016)
Q12. Illustrate the algorithm to implement the doubly linked list and perform all the
operations on the created list. [MAY/JUN 2016] [Apr/May 2021]
Q13. Write a function to delete the node n from the given doubly linked list. (Apr/May 2019)
p <-> q <-> r <-> n <-> s <-> t <-> z <->

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

Operations on Double Linked List


In a double linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display
Insertion
In a double linked list, the insertion operation can be performed in three ways as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the 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

For the first time flag = 0

If we want to attach node 30 then

This we can continue to create a doubly linked list.


2. Display of Doubly linked list
We assign head node address to temp node.

while (temp -> next ! = NULL)


{
temp = temp -> next; // display data at temp node
}
This will display 10 20 30 as a doubly linked.
3. Deletion of a node in doubly linked list

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.

CIRCULAR LINKED LIST


Q14. Write C code for Circular link list with create, insert, delete, display operations using
structure pointer. (APR/MAY 2015) [Apr/May 2021]
Q15. Write a procedure to deleting the last node from a circular linked list. (NOV/DEC 2018)
 A circular doubly linked list or a circular two way linked list is a more complex type of linked list
which contains a pointer to the next as well as previous node in the sequence.
 The circular doubly linked list does not contain NULL in the previous field of the first node and the
next field of the last node. Rather, the next field of the last node stores the address of the first node
of the list, i.e; START. Similarly, the previous field of the first field stores the address of the last
node.

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”

 Sequential movement is possible


 Since a circular doubly linked list contains three parts in its structure, it requires more space
per node and for more expensive basic operations.
 However, it is easy to manipulate the elements of the list as it maintains pointers to nodes in
both the directions.
 The main advantage of using a circular doubly linked list is that it makes searches twice as
efficient.
 Circular Linked List is divided into two Categories.
o Singly Circular Linked List
o 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.

/*Program for Circular Linked List*/


#include<stdio.h>
#include<conio.h>
struct circular
Page 33
{
inti;
struct circular *next;
};
struct circular *temp;
struct circular *head;
struct circular *p;
struct circular *mid;
struct circular *move;
int cnt=0;
void create(void);
void insert(void);
void display(void);
void del(void);
void main()
{
int ch=0;
clrscr();
while(ch!=5)
{
printf("\n1.CREATE");
printf("\n2.INSERT");
printf("\n3.DELETE");
printf("\n4.DISPLAY");
printf("\n5.EXIT");
scanf("%d",&ch);
if(ch==1)
{
create();
cnt++;
cnt++;
}
if(ch==2)
{
insert();
cnt++;
}
if(ch==3)
{
del();
cnt--;
}
if(ch==4)

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

Q16. Program to Merge two linked list

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

Basic features of Stack


1. Stack is an ordered list of similar data type.
2. Stack is a LIFO(Last in First out) structure or we can say FILO(First in Last out).
3. push() function is used to insert new elements into the Stack and pop() function is used to remove
an element from the stack. Both insertion and removal are allowed at only one end of Stack
called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state
if it is completely empty.

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

isfull() - check whether the stack is full or not


Algorithm of isfull() function −
begin procedure isfull
if top equals to MAXSIZE
return true
else
return false
endif
end procedure
Implementation of isfull() function
bool isfull() {
if(top == MAXSIZE)
return true;
else
return false;
}

isEmpty()-checks whether the stack is empty or not


Algorithm of isempty() function −
begin procedure isempty
if top less than 1
return true
else
return false
endif

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)

Performing Push and Pop operation

Implementation of Stack Using Array:[Apr/May 2021]


#include<stdio.h>
#include<conio.h>
#define SIZE 10
Page 46
void push(int);
void pop();
void display();
int stack[SIZE], top = -1;
void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
void push(int value)
{
if(top == SIZE-1)
printf("\nStack is Full!!! Insertion is not possible!!!");
else{
top++;
stack[top] = value;
printf("\nInsertion success!!!");
}
}
void pop()
{

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

EVALUATING ARITHMETIC EXPRESSIONS


Q10. Explain in detail about evaluation of arithmetic expressions.
Evaluate the following arithmetic expression using stack. 2*(4+3)-5. [Apr/May 2023]
Expressions
 An expression is a collection of operators and operands that represents a specific value.
 operator is a symbol which performs a particular task like arithmetic operation or logical operation or
conditional operation etc.,
 Operands are the values on which the operators can perform the task.
 Here operand can be a direct value or variable or address of memory location.
 One of the applications of stack is conversion of expression
Expression Types
Based on the operator position, expressions are divided into THREE types. They are as follows...
 Infix Expression
 Postfix Expression
 Prefix Expression

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

Postfix Expression Evaluation using Stack Data Structure


A postfix expression can be evaluated using the Stack data structure. To evaluate a postfix expression
using Stack data structure we can use the following steps...
 Read all the symbols one by one from left to right in the given Postfix Expression
 If the reading symbol is operand, then push it on to the Stack.
 If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop operations and store the
two popped operands in two different variables (operand1 and operand2). Then perform reading
symbol operation using operand1 and operand2 and push result back on to the Stack.
 Finally! perform a pop operation and display the popped value as final result.
Page 50
Example
1. Consider the following Expression...

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

CONVERSION FROM INFIX TO POSTFIX EXPRESSION


Q11. Write an algorithm to convert the infix to postfix expression. [Dec 2015/Jan 2016]
[NOV/DEC 2022]
Q12. Write an algorithm to convert the infix to postfix expression using Stack. [Apr/May 2017]
Q13. Write the procedure to convert the infix expression to postfix expression and steps involved
in evaluating the postfix expression. 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]
[Apr/May 2021]
Convert the following arithmetic expression in infix form to post fix form using stack:
A+B/C+D*(E-F)^G [Apr/May 2023]
 Any expression can be represented using three types of expressions (Infix, Postfix, and Prefix).
 We can also convert one type of expression to another type of expression like Infix to Postfix, Infix to
Prefix, Postfix to Prefix and vice versa.
 To convert any Infix expression into Postfix or Prefix expression we can use the following procedure...
 Find all the operators in the given Infix Expression.
 Find the order of operators evaluated according to their Operator precedence.
 Convert each operator into required type of expression (Postfix or Prefix) in the same order.

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*+=

Infix to Postfix Conversion using Stack Data Structure


To convert Infix Expression into Postfix Expression using a stack data structure, We can use the following
steps.
1. Read all the symbols one by one from left to right in the given Infix Expression.
2. If the reading symbol is operand, then directly print it to the result (Output).
3. If the reading symbol is left parenthesis '(', then Push it on to the Stack.
4. If the reading symbol is right parenthesis ')', then Pop all the contents of stack until respective left
parenthesis is poped and print each poped symbol to the result.
5. If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However, first pop
the operators which are already on the stack that have higher or equal precedence than current
operator and print them to the result.
Example
Consider the following Infix Expression...
(A+B)*(C-D)
The given infix expression can be converted into postfix expression using Stack data Structure as follows...

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]

Now replacing backward we get

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

( ) Pop

Empty

As the stack is empty, hence the given expression was balanced.

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.

QUEUE DATA STRUCTURE USING ARRAY


 A queue data structure can be implemented using one dimensional array.
 The queue implemented using array stores only fixed number of data values.
 The implementation of queue data structure using array is very simple.
 Just define a one dimensional array of specific size and insert or delete the values into that array
by using FIFO (First In First Out) principle with the help of variables 'front' and 'rear'.
 Initially both 'front' and 'rear' are set to -1.
 Whenever, we want to insert a new value into the queue, increment 'rear' value by one and then
insert at that position.
 Whenever we want to delete a value from the queue, then delete the element which is at 'front'
position and increment 'front' value by one.

Queue Operations using Array


Queue data structure using array can be implemented as follows...
Before we implement actual operations, first follow the below steps to create an empty queue.
 Step 1 - Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
 Step 2 - Declare all the user defined functions which are used in queue implementation.
 Step 3 - Create a one dimensional array with above defined SIZE (int queue[SIZE])
 Step 4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front = -1,
rear = -1)

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.

ii. deQueue() - Deleting a value from the Queue


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

iii. display() - Displays the elements of a Queue


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

Implementation of Queue Datastructure using Array


#include<stdio.h>
#include<conio.h>
#define SIZE 10
void enQueue(int);
void deQueue();
void display();
int queue[SIZE], front = -1, rear = -1;
void main()
{
int value, choice;
clrscr();
while(1){

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.

Example: Program for Priority Queue


#include <stdio.h>
#include <stdlib.h>
#define MAX 5
void insert_by_priority(int);
void delete_by_priority(int);
void create();
void check(int);
void display_pqueue();
int pri_que[MAX];
int front, rear;
Page 66
void main()
{
int n, ch;
printf("\n1 Insert");
printf("\n2 Delete");
printf("\n3 Display");
printf("\n4 Exit");
create();
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nInsert Element : ");
scanf("%d",&n);
insert_by_priority(n);
break;
case 2:
printf("\nEnter Element to Delete : ");
scanf("%d",&n);
delete_by_priority(n);
break;
case 3:
display_pqueue();
break;
case 4:
exit(0);
default:
printf("\n Invalid Choice");
}
}
}
void create() //Create Function
{
front = rear = -1;
}
void insert_by_priority(int data) //Insert Function
{
if (rear >= MAX - 1)
{
printf("\nQueue is Overflow");
return;
}
if ((front == -1) && (rear == -1))
{
front++;
rear++;

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

Difference between Priority Queue and Normal Queue


Q26. Difference between double ended queue and circular queue. [May/Jun 2016]
In a queue, the first-in-first-out rule is implemented whereas, in a priority queue, the values are
removed on the basis of priority. The element with the highest priority is removed first.

APPLICATIONS OF QUEUE [Apr/May 2021]


 Batch processing in an operating system To implement Priority Queues.
 Priority Queues can be used to sort the elements using Heap Sort. Simulation and Mathematics user
Queueing theory.
 Computer networks where the server takes the jobs of the client as per the queue strategy.
 When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk
Scheduling.
 When data is transferred asynchronously (data not necessarily received at same rate as sent)
between two processes. Examples include IO Buffers, pipes, file IO, etc.
Page 69
 Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
 In real life scenario, Call Center phone systems uses Queues to hold people calling them in an order,
until a service representative is free.
 Handling of interrupts in real-time systems. The interrupts are handled in the same order as they
arrive i.e First come first served.
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists.
The new list should be made with its own memory – the original lists should not be changed. A dummy node can be
used to solve this. (10) [NOV/DEC 2022]
Example:
Input:
First linked list: 1->2->3->4->6
Second linked list 2->4->6->8
Output: 2->4->6
The elements 2,4,6 are common in both the list so they appear in the intersection list.
Develop a program to solve the above problem
#include <stdio.h>
#include <stdlib.h>

// Link list node


struct Node
{
int data;
struct Node* next;
};

// Function to get the counts of node


// in a linked list
int getCount(struct Node* head);

/* 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;

if (c1 > c2)


{
d = c1 - c2;
return _getIntesectionNode(d, head1, head2);
}
else
{
d = c2 - c1;
return _getIntesectionNode(d, head2, head1);
}
}

/* 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;

for (i = 0; i < d; i++)


{
if (current1 == NULL)
{
return -1;
}
current1 = current1->next;
}

while (current1 != NULL &&


current2 != NULL)
{
if (current1 == current2)
return current1->data;
current1 = current1->next;
current2 = current2->next;
}
return -1;
}
/* Takes head pointer of the linked list and returns the count of nodes in the list */
int getCount(struct Node* head)
{
struct Node* current = head;
int count = 0;
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
// Driver code
int main()
{
/* Create two linked lists
1st 1->2->3->14->6
2nd 2->4->6->8
2->4->6 is the intersection point */
struct Node* newNode;
struct Node* head1 = (struct Node*)malloc(sizeof(struct Node));
head1->data = 10;
struct Node* head2 = (struct Node*)malloc(sizeof(struct Node));
head2->data = 3;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = 6;
head2->next = newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = 9;
head2->next->next = newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));

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

// take second distance input


printf("\nEnter 2nd distance\n");
printf("Enter feet: ");
scanf("%d", &d2.feet);
printf("Enter inch: ");
scanf("%f", &d2.inch);

// adding distances
result.feet = d1.feet + d2.feet;
result.inch = d1.inch + d2.inch;

// convert inches to feet if greater than 12


while (result.inch >= 12.0) {

Page 72
result.inch = result.inch - 12.0;
++result.feet;
}
printf("\nSum of distances = %d\'-%.1f\"", result.feet, result.inch);
return 0;
}
Output:

Enter 1st distance


Enter feet: 23
Enter inch: 8.6

Enter 2nd distance


Enter feet: 34
Enter inch: 2.4

Sum of distances = 57'-11.0"

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.

11. Distinguish between linear and non-linear data structures.


Linear data structures are the data structures in which data is arranged in a list or in a straight
sequence. Examples: Arrays, List, Stack, Queue.
Non-linear data structures are the data structures in which data may be arranged in a hierarchical
manner. Examples: Trees, Graphs.

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.

20. List the limitations of array based implementation of list ADT.


 Insertion or deletion operations are expensive as it requires more data movement. Find and
print list operation takes constant time
 Even if array is dynamically allocated, the list considerably wastes the memory space.

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

can access head node quickly.


24. What is meant by Multi-list?
o More complicated application of linked list is multi-list.
o It is useful to maintain student registration, Employee involved in different projects,
o Multi-list saves space but takes more time to implement.
25. What is Static Linked List? State any applications of it. (Apr/May 2015)
Static linked list are a prominent example of a static data structure.
Static linked lists share following characteristics

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.

26. State the advantages of ADT. (Nov/Dec 2018)


Advantages:
(i) Data structures allow information storage on hard disks.
(ii) Provides means for management of large dataset such as databases or internet indexing
services.
(iii) Necessary for design of efficient algorithms.
27. Illustrate the differences between linear linked list and circular linked list. (Apr/May 2019)
Linked list is a linear data structure which consists of group of nodes in a sequence. Each node has
got two parts , a data part- which stores the data and a address part- which stores the address of the
next node. Hence forming a chain like structure. Linked list are used to create trees and graphs.
Circular linked list : In circular linked list the last node address part holds the address of the first
node hence forming a circular chain like structure.

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

30. Write short notes on Postfix expression. (Apr/May2015)


In this type of expression the arrangements of operator and operand are as follows:

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)

39. Define Stack Pointer. [Nov/Dec2009, April/May 2010]


• Stack pointer is used to store the address of the element at the top of the stack and returns its value when
it is called. Stack pointer is also known as Top pointer.

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.

42. List the application of Stack. [Nov/Dec2009, May/June 2009]


1. Balancing parentheses.
2. Postfix Expression.
3. Infix to postfix conversion
4. Function calls.
5. Reversing the strings.
6. 8 Queen Problem.

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

48. State any two application of queue. [Nov/Dec 2007][MAY/JUN 2014]


 In operating system for scheduling jobs, priority queues are used.
 In local Area Network multiple computers share few printers. Then these pointers accumulate jobs in a
queue.
 For categorizing data, queues are used.
 In simulation and modeling queues are used.

49. Compare and contrast stack and queue. [Nov/Dec 2011]


 A stack is generally First In, Last Out, and a queue is First In First Out. Item can be added or removed
only at one end in stack and in a queue insertion at the rear and deletion from the front.
 The basic operation of stack are 'push' and 'pop', on other hand of queue are 'enqueue' and 'dequeue'.

50. List few applications of doubly linked list. [NOV/DEC 2022]


 Navigation System
 Undo and redo operation
 Tree data structure

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.

✓ A is the root node.


✓ D is the parent of H & I.
✓ G is the sibling of F.
✓ H & I are the children of D.
✓ F, G, H, I & J are external nodes or leaves.
✓ A, B, C, D & E are internal nodes.
✓ The depth (level) of Node D is 2.
✓ The height of the tree is 3.
✓ The degree of node B is 2 (or) node E is 1.
✓ The degree of Tree is 2.
✓ Node D, H & I are Sub Tree.
✓ For Node I, Node D is the Descendant (or) Predecessor node.
✓ For Node C, Node F is the Ancestor (or) Successor node.
Hierarchical Data and Trees
• The element at the top of the hierarchy is the root.
• Elements next in the hierarchy are the children of the root.
• Elements next in the hierarchy are the grandchildren of the root, and so on.
• Elements that have no children are leaves
Following are important terms with respect to tree.
• Path - A sequence of nodes and edges connecting a node with a descendant.

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.

Binary Tree node declaration


typedef struct tree_node *tree_ptr;
struct tree_node
{
element_type element1;
tree_ptr left1; tree_ptr right1;
};
typedef tree_ptr TREE;
Types of Tree:
a. Binary Tree:
• Finite collection of elements / nodes that is either empty or consists of a root and two disjoint
binary trees called the left sub tree and right sub tree.

Fig: Binary Tree

Fig: Not a Binary Tree

Page 3
b. Full Binary Tree:
• A full binary tree is a tree in which every node has zero or two children.

c. Complete Binary Tree:


• Every non leaf node has exactly two children but all leaves are not necessary at the same level. A
complete binary tree is one where all levels have the maximum number of nodes except the last
level. The last level elements should be filled from left to right.
• 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 below given tree h =3. Hence total 8 nodes (2h) are leaf nodes.

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

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

f. Extended Binary Tree


✓ Extended binary tree consists of replacing every null subtree of the original tree with special nodes.
✓ Empty circle represents internal node and filled circle represents external node.
✓ The nodes from the original tree are internal nodes and the special nodes are external nodes.
✓ Every internal node in the extended binary tree has exactly two children and every external node is a
leaf. It displays the result which is a complete binary tree.

g. Binary search tree:


• A binary search tree relies on the property that keys that are less than the parent are found in the
left sub tree, and keys that are greater than the parent are found in the right sub tree.
(or)
• 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.
h. AVL tree:
• An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self balancing
binary search tree. In an AVL tree, the heights of the two child sub trees of any node differ by at most
one; if at any time they differ by more than one, rebalancing is done to restore this property.
(or)
• AVL tree is a self balanced binary search tree. That means, an AVL tree is also a binary search tree
but it is a balanced tree. A binary tree is said to be balanced, if the difference between the heights of
left and right subtrees of every node in the tree is either -1, 0 or +1.
i. Splay tree:
• Splay Tree is a self - adjusted Binary Search Tree in which every operation on an element rearrange
the tree so that the element is placed at the root position of the tree.
j. Red black tree:

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

Representation of Binary Tree:


Q2. How can binary tree representation using array? Write the routines to perform insertion
and deletion in a tree. [Apr 2017]
There are two ways for representing binary tree they are.
a. Linear Representation (or) Array Representation
b. Linked Representation
a. Linked Representation
• In binary tree each node will have left child, right child and data field.

• In a double linked list, every node consists of three fields.


• First field for storing left child address, second for storing actual data and third for storing right
child address.
• Let us see the ‘C’ structure of the node in a binary tree

Page 6
typedef struct node
{
int data;
struct node *left;
struct node *right;
}bin;

Advantages of Linked Representation:


• This representation is superior to our array representation as there is no wastage of memory.
And so there is no need to have prior knowledge of depth of the tree. Using dynamic memory
concept one can create as many memory (nodes) as required. By chance if some nodes are
unutilized one can delete the node by making the address free.
• Insertions and deletions which are the most common operations can be done without moving
the other nodes.
Disadvantages of Linked Representation:
• This representation does not provide direct access to a node and special algorithms are
required.
• This representation needs additional space in each node for storing the left and right sub trees.

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

B C Fig: Linear Representation

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.

Case 2: Two nodes with one node having one child.


o Here number of full nodes = 0.
o Number of leaves = Number of full nodes + 1 = 0 + 1 = 1
o Here node y is a leaf node.

Case 3: One node with two children Here x is a full node.


o Number of full nodes = 1.
o Number of leaves = Number of full nodes + 1= 1+ 1.
o Here node y and x are two leaves in the tree.
o The above three cases denote that: Number of full nodes plus one is equal to the number
of leaves in a binary tree.

TRAVERSALS IN BINARY TREE: [Apr/May 2023]


Q3. Explain the tree traversals. Give all the essential aspects. [Nov/Dec 2010]
Q4. Write an algorithm for preorder, inorder and postorder traversals of a binary tree. [N/D
11]

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

Recursive routine for inorder traversal


Algorithm:
1. if tree is not empty then
a. Traverse the left subtree in inorder
b. Visit the root
c. Traverse the right subtree in inorder.
Page 9
Recursive function:
void inorder(ptr_node ptr)
{
if(ptr)
{
inorder (ptr->left_child);
cout << ptr->data;
inorder (ptr->right_child);
}
}

Pre - Order Traversal (root - left child - right Child)


✓ In Pre-Order traversal, the root node is visited before left child and right child nodes.
✓ In this traversal, the root node is visited first, then its left child and later its right child.
✓ This pre-order traversal is applicable for every root node of all subtrees in the tree.

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.

Pre-Order Traversal for above example binary tree is


A-B-D-I-J-F-C-G-K-H
Recursive routine for preorder traversal
Algorithm:
1. if tree is not empty then
a. Visit the root
b. Traverse the left subtree in preorder
c. Traverse the right subtree in preorder.
Recursive function:
void preorder (ptr_node ptr)
{

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

Post-Order Traversal for above example binary tree is


I-J-D-F-B-K-G-H-C-A

Recursive routine for post order traversal


Algorithm:
1. if tree is not empty then
a. Traverse the left subtree in postorder
b. Traverse the right subtree in postorder.
c. Visit the root
Recursive function:
void postorder(ptr_node ptr)
{
if (ptr)
{ postorder(ptr->left_child);
postorder(ptr->right_child);
cout << ptr->data;
}}
Example: 1. Number the following binary tree to traverse it in. a. Preorder b. Inorder [N/D 12]

Page 11
Solution:
a. Preorder b. Inorder

2. Find the traversal for the given binary tree.

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

3.4 EXPRESSION TREE [Apr/May 2023]


Q8. What are expression Trees. Write the procedure for constructing an expression Tree.
(Nov/Dec 2018)
Q9.How can you construct a expression tree? Describe your answer with an example. (Nov/Dec
2015) (Nov/Dec 2018)
• Expression tree is a binary tree in which each internal node corresponds to operator and each
leaf node corresponds to operand.
• A binary expression tree is a specific kind of a binary tree used to represent expressions.
• Two common types of expressions that a binary expression tree can represent are algebraic and
boolean.
• These trees can represent expressions that contain both unary and binary operators.
• Each node of a binary tree, and hence of a binary expression tree, has zero, one, or two children.
• An expression and expression tree shown below
a + (b * c) + d * (e + f)

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

Binary algebraic expression tree equivalent to ((5 + z) / -8) * (4 ^ 2)


Expression Tree is a special kind of binary tree with the following properties:
• Each leaf is an operand. Examples: a, b, c, 6, 100
• The root and internal nodes are operators. Examples: +, -, *, /, ^
• Subtrees are subexpressions with the root being an operator.
There are different types of expression formats:
• Prefix expression
• Infix expression and
• Postfix expression
3.4.1 Traversal Techniques
There are 3 standard traversal techniques to represent the 3 different expression formats.
a. Inorder Traversal
• We can produce an infix expression by recursively printing out
✓ the left expression,
✓ the root, and
✓ the right expression.
b. Postorder Traversal
• The postfix expression can be evaluated by recursively printing out
✓ the left expression,
✓ the right expression and
✓ then the root
c. Preorder Traversal
• We can also evaluate prefix expression by recursively printing out:
✓ the root,
✓ the left expressoion and
✓ the right expression.

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

3.4.2 Construction of Expression Tree:


We consider that a postfix expression is given as an input for constructing an expression tree. Following
are the step to construct an expression tree:
• Read one symbol at a time from the postfix expression.
• Check if the symbol is an operand or operator.
• If the symbol is an operand, create a one node tree and pushed a pointer onto a stack
• If the symbol is an operator, pop two pointer from the stack namely T1 & T2 and form a new tree
with root as the operator, T1 & T2 as a left and right child
• A pointer to this new tree is pushed onto the stack
Example
➢ The input in postfix notation is: a b + c d e + * * Since the first two symbols are operands, one-node
trees are created and pointers to them are pushed onto a stack. For convenience the stack will grow
from left to right.

Stack growing from left to right


➢ The next symbol is a '+'. It pops the two pointers to the trees, a new tree is formed, and a pointer to
it is pushed onto the stack.

Formation of a new tree


➢ Next, c, d, and e are read. A one-node tree is created for each and a pointer to the corresponding
tree is pushed onto the stack.

Page 16
Creating a one-node tree
➢ Continuing, a '+' is read, and it merges the last two trees.

Merging two trees


➢ Now, a '*' is read. The last two tree pointers are popped and a new tree is formed with a '*' as the
root.

Forming a new tree with a root


➢ Finally, the last symbol is read. The two trees are merged and a pointer to the final tree remains on
the stack.

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.

Example of the Binary Search Tree:

Comparison between binary tree and binary search tree


Binary tree Binary search tree
A tree is said to be a binary tree if it A binary search tree is a binary tree in which the
has atmost two children. It does key values in the left node is less than the root and
not have any order. the key values in the right node is greater than the
root.

Operations on a Binary Search Tree


The following operations are performed on a binary search tree
1. Search
2. Insertion
3. Deletion

Search Operation in BST

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

Insertion Operation in BST


In a binary search tree, the insertion operation is performed with O(log n) time complexity. In
binary search tree, new node is always inserted as a leaf node. The insertion operation is performed as
follows
o Step 1: Create a new Node with given value and set its left and right to NULL.
o Step 2: Check whether tree is Empty.
o Step 3: If the tree is Empty, then set set root to newNode.
o Step 4: If the tree is Not Empty, then check whether value of new Node is smaller or larger than the
node (here it is root node).
o Step 5: If new Node is smaller than or equal to the node, then move to its left child. If new Node is
larger than the node, then move to its right child.
o Step 6: Repeat the above step until we reach to a leaf node (e.i., reach to NULL).
o Step 7: After reaching a leaf node, then insert the new Node as left child if new Node is smaller or
equal to that leaf else insert it as right child.

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

As MAY > MAR attach it as


2.
right child of MAR.

NOV > MAR, similarly


NOV>MAY
3.
Therefore attach it as right
child of MAY

AUG<MAR therefore attach it


4.
as left child of MAR

APR < MAR, similarly


APR<AUG
5.
Therefore attach it as left
child of AUG

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

Deletion Operation in BST [Apr/May 2021]


Q12. Write C functions to perform deletion in Binary search tree (Include all the cases).
[Apr/May 2021]
In a binary search tree, the deletion operation is performed with O(log n) time complexity. Deleting a
node from Binary search tree has following three cases.
Case 1: Deleting a Leaf node (A node with no children)
Case 2: Deleting a node with one child
Case 3: Deleting a node with two children

a. Case 1: Deleting a leaf node


We use the following steps to delete a leaf node from BST.
Step 1: Find the node to be deleted using search operation
Step 2: Delete the node using free function (If it is a leaf) and terminate the function.
Example: Deletion of node 3

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

c. Case 3: Deleting a node with two children

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

Deletion routine for binary search tree


SearchTree Delete( ElementType X, SearchTree T->Element = TmpCell->Element;
T) T->Right = Delete( T->Element, T->Right
{ );
Position TmpCell; }
if( T = = NULL ) else /* One or zero child */
Error("Element not found"); {
else TmpCell = T;
if( X < T->Element ) /* Go left */ if( T->Left = = NULL ) /* Only a right child
T->Left = Delete( X, T->Left ); */
else T = T->Right;
if( X > T->Element ) /* Go right */ if( T->Right = = NULL ) /* Only a left child
T->Right = Delete( X, T->Right ); */
else /* Found element to be deleted */ T = T->Left;
if( T->Left && T->Right ) /* Two children */ free(TmpCell );
{ /* Replace with smallest in right subtree */ }
TmpCell = FindMin( T->Right ); return T;
}

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

Step 3: Insert 75 Step 4: Insert 15


Page 24
Step 5: Insert 50 Step 6: Insert 66

Step 7: Insert 33 Step 8: Insert 44

Delete the Nodes 25,75,44 from the tree


Step 1: Delete the node 25 Step 2: Delete the node 75

Step 3: Delete the node 44

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

Step 3: Insert F Step 4: Insert G

Page 25
Step 5: Insert B Step 6: Insert Z

Step 7: Insert U Step 8: Insert P

Step 9: Insert K Step 10: Insert L

Delete Keys B, U and L


Step 1: Delete B Step 2: Delete U

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

DATA STRUCTURES - HASH TABLE


Q19. Consider a hash table with 9 slots. The hash function is h(k) = k mod 9. The following keys
are inserted in the order 15, 38, 8, 5, 20, 33, 14, 30. Draw the contents of the hash table when
the collisions are resolved by
i) Chaining
ii) Linear Probing
iii) Double hashing. The second hash function h2(x) = 7 – (x mod 7). [Apr/May 2021]
• Hash table is a data structure which stores data in an array format of fixed in size.
• In hash table, the data is stored in the form of key / value pair.
• Using of hash function, it computes an index of an array where the data value to be stored.
• If the table size is referred to as H_TableSize, then the table have a range from 0 to H_TableSize-1
indexes in which each index is unique.

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.

Hash Function [Apr/May 2023]


• A fixed process converts a key to a hash key is known as a Hash Function.
• This function takes a key and maps it to a value of a certain length which is called a Hash value or
Hash.
• Hash value represents the original string of characters, but it is normally smaller than the
original.
• It transfers the digital signature and then both hash value and signature are sent to the receiver.
• Receiver uses the same hash function to generate the hash value and then compares it to that
received with the message.
• If the hash values are same, the message is transmitted without errors.
• Suppose, if the inputs are integer, then the key mod H_TableSize gives the index in which the
keys are to be placed.

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.

Code for Simple Hash Function


int Hash(int key,int TableSize)
{
return key % TableSize;
}

Simple Hash Function for String Input


Usually the keys are strings, so that we need to take care for choosing hash function. When the
input is a string, then we add the ASCII value of each character in the string and use hash function
(value mod TableSize) to get the index in which this string will be inserted.

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.

OPEN HASHING (OR) SEPARATE CHAINING


Q20.Explain in detail about Separate Chaining. (Apr/May 2019)
• This method maintains a list of all elements that are hashed to same location.
• It needs a small modification to the hash data structure.
• Instead of storing the element into the array, hash table uses linked list, they will be stored in the
linked lists.
• For easy use, the lists have header. Now each index of an array points to one of the linked list.
• Suppose, if we insert an element into the hash table, it is added to the linked list at the
corresponding index in the array.
• Hence the collisions are no longer occurred, because the linked list has no limit on its length.
Open Hashing Example
Q21. Given input {437, 325, 175, 199, 171, 189, 127, 509} and a hash function h(x) = x(mod 10),
show the resulting. (Nov/Dec 2018) [Apr/May 2021]
• Given input {437, 325, 175, 199, 171, 189,127,509} and a hash function H(X) = X mod 10, Show
the resulting for separate chaining hash table.
Solution:

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.

CLOSED HASHING (or) OPEN ADDRESSING


Q22. Explain Open Addressing in detail. (Nov/Dec 2018) (Apr/May 2019) [Apr/May 2021]
• This is another method in which the elements are hashed to the table itself.
• In open addressing, if two elements hash to the same location, this is known as collision, then
alternative location are chosen until an empty location is found.
• The hash function for open addressing is given that
hi(X) = ( Hash(X) + F(i)) % TableSize
with F(0) = 0, F(1)=1, F(2)=2,..etc
• Where Hash(X) = X % TableSize and the function F(i) is called the collision resolution strategy.
• Actually the open addressing needs a large table than separate hashing because all data will be
stored inside the hash table.
• This is also called closed hashing.
• There are three collision resolution techniques:
1. Linear Probing
2. Quadratic Probing
3. Double Hashing

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:

Key Hash Function h(X) Index Collision Alt Index


h0(79)
79 9
= (Hash(79)+F(0))%10

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:

Key Hash Function h(X) Index Collision Alt Index


h0(79)
79 = ( Hash(79) + F(0)2) % 10 9
= ((79 % 10) + 0) % 10
h0(28)
28 = ( Hash(28) + F(0)2) % 10 8
= ((28 % 10) + 0) % 10
h0(39) The first
= ( Hash(39) + F(0)2) % 10 9 collision
= ((39 % 10) + 0) % 10 occurs
39
h1(39)
= ( Hash(39) + F(1)2) % 10 0 0
= ((39 % 10) + 1) % 10
h0(68) The
= ( Hash(68) + F(0)2) % 10 8 collision
= ((68 % 10) + 0) % 10 occurs
h1(68) Again
68 = ( Hash(68) + F(1)2) % 10 9 collision
= ((68 % 10) + 1) % 10 occurs
h2(68)
= ( Hash(68) + F(2)2) % 10 2 2
= ((68 % 10) + 4) % 10
h0(89) The
89 = ( Hash(89) + F(0)2) % 10 9 collision
= ((89 % 10) + 0) % 10 occurs

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:

Key Hash Function h(X) Index Collision Alt Index


h0(79)
79 = ( Hash(79) + F(0)) % 10 9
= ((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)
= ( Hash(39) + F(1)) % 10
2 2
= ((39 % 10) + 1(7-(39 % 7))) % 10
= (9 + 3) % 10 =12 % 10
68 h0(68) 8 The

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

Difference between Separate Chaining and Open Addressing


S.No. Separate Chaining Open Addressing
1. All the keys are stored only inside the
Keys are stored inside the hash table as
hash table. No key is present outside the
well as outside the hash table.
hash table.
2. The number of keys to be stored in the The number of keys to be stored in the
hash table can even exceed the size of hash table can never exceed the size of
the hash table. the hash table.
3. Deletion is easier. Deletion is difficult.
4. Extra space is required for the pointers
No extra space is required.
to store the keys outside the hash table.
5. Cache performance is poor. Cache performance is better.
This is because of linked lists which This is because here no linked lists are
store the keys outside the hash table. used.
6. Some buckets of the hash table are
Buckets may be used even if no key
never used which leads to wastage of
maps to those particular buckets.
space.
7. All the keys are stored only inside the
Keys are stored inside the hash table as
hash table. No key is present outside the
well as outside the hash table.
hash table.

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.

Fig: Closed hash table with linear Probing


with input 13,15,6,24 Fig: Closed hash table with linear
Probing
After 23 is inserted

Fig: Closed hash table after Rehashing


Why rehashing?
• 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 bucketArray so as to reduce the load factor and
the time complexity.
How Rehashing is done?
Rehashing can be done as follows:
• For each addition of a new entry to the map, check the load factor.
• If it’s greater than its pre-defined value (or default value of 0.75 if not given), then Rehash.
• For Rehash, make a new array of double the previous size and make it the new bucketarray.
• Then traverse to each element in the old bucketArray and call the insert() for each so as to insert
it into the new larger bucket array.

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

• Degree of tree – The maximum degree in the tree is degree of tree.


• 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.
• Depth- The depth of a node is the number of edges from the node to the tree's root node.
• Forest - Forest can be defined as the set of disjoint trees which can be obtained by deleting the root
node and the edges which connects root node to the first level node.
• 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.
9. What do you mean by level of the tree? [Nov/Dec 2019]
o The root node is always considered at level zero, and then its adjacent child is supposed to be at
level 1 and so on.
A

B C

o Here, node A is at level 0 nodes B and C are at level 1.


10. Define terminal nodes in a tree.
• A node that has no children is called as a terminal node. It is also referred as a leaf node. These
nodes have degree has zero.
11. Define non-terminal nodes in a tree
• All intermediate nodes that traverse the given tree from its root node to the terminal nodes are
referred as non terminal nodes.
12. What is meant by directed tree?
• Directed tree is an acyclic diagraph which has one node called its root with indegree 0 while all
other nodes have indegree I.
Page 43
13. What is an ordered tree?
• In a directed tree if the ordering of the nodes at each level is prescribed then such a tree is called
ordered tree.
14. Define forest of tree.
• A tree may be defined as forest in which only a single node (root) as no predecessors. Any forest
consists of a collection of trees.
15. What is the length of the path in a tree?
o The length of the path is the number of edges on the path. In a tree there is exactly one path form
the root to each node.
16. Give the difference 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
17. Give the application of trees. [Nov/Dec 2011]
✓ Manipulation of arithmetic expression
✓ Symbol table construction
✓ Syntax Analysis
✓ Grammar
✓ Expression Tree
✓ class hierarchy in Java
✓ file system
✓ storing hierarchies in organizations
18. List out the various types of tree
• Binary Tree
• Full Binary Tree
• Complete Binary Tree
• Perfect Binary Tree
• Skew tree
• Binary search tree
• AVL tree
• Splay tree
• Red black tree
• B tree
• B+ tree
19. Define binary tree and give the binary tree node structure. [May, Dec. 2004, Dec 2012]
• Finite collection of elements / nodes that is either empty or consists of a root and two disjoint
binary trees called the left sub tree and right sub tree.

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.

21. Define complete binary tree. [Nov/Dec 2005]


• Every non leaf node has exactly two children but all leaves are not necessary at the same level. A
complete binary tree is one where all levels have the maximum number of nodes except the last
level. The last level elements should be filled from left to right.

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

29. Find the inorder traversal for the given diagram.


A

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

32. State the properties of a binary tree.


✓ The maximum number of nodes on level n of the binary tree is 2n-1 where n>=1.
✓ The maximum number of nodes in a binary tree of height n is 2n-1 where n>=1.
✓ For any non empty tree nl =nd+1 where nl is the number of leaf nodes and nd is the number of
nodes of degree 2.
33. What are the applications of binary tree?
Binary tree is used in data processing.
a. File index schemes
b. Hierarchical database management system
34. List the Operation defined on binary tree. [May 2009]
The basic operations on a binary tree are
1) To create a binary tree
2) To display a data in each node of binary tree.
3) To insert any node in the tree as a left child or right child of some node.
4) To delete a node from binary tree.
35. Define 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.
(or)
✓ The tree in which each node is attached as a left child of parent then it is called Left Skewed tree.
ii. Right skewed binary tree
✓ A right skew tree has node with only the right child. It is a binary tree with only right sub trees.
(or)
✓ The tree in which each node is attached as a right child of parent then it is called Right Skewed
tree.

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.

38. List the application of the BST.


• To implement balanced trees. One of the oldest forms of balanced search trees is the AVL tree.
• Implementation of Priority Queue (Heaps) and Splay trees.
39. Define balanced search tree.
• Balanced search tree have the structure of binary tree and obey binary search tree properties
with that it always maintains the height as O(log n) by means of a special kind of rotations. Eg.
AVL, Splay, B-tree.
40. List out the steps involved in deleting a node from a binary search tree.
In a binary search tree, the deletion operation is performed with O(log n) time complexity. Deleting
a node from Binary search tree has following three cases.
Case 1: Deleting a Leaf node (A node with no children)
Case 2: Deleting a node with one child
Case 3: Deleting a node with two children
41. Give the comparison between binary tree and binary search tree. [APR/MAY 2017]
Binary tree Binary search tree
A tree is said to be a binary tree if it A binary search tree is a binary tree in which the
has atmost two children. It does key values in the left node is less than the root
not have any order. and the key values in the right node is greater

Page 48
than the root.

47. Define lazy deletion.


When an element is to be deleted, it is left in the tree itself and marked as being deleted. This is
called as lazy deletion and is an efficient procedure if duplicate keys are present in the binary search
tree, because the field that keeps count of the frequency of appearance of the element can be
decremented of the element can be decremented.

48. What do you mean by hashing in data structure?


Hash Table is a data structure which stores data in an associative manner. In a hash table, data is
stored in an array format, where each data value has its own unique index value. ... Thus, it becomes a
data structure in which insertion and search operations are very fast irrespective of the size of the data.
49. What is the use of hashing in data structure?
In computing, a hash table (hash map) is a data structure which implements an associative array
abstract data type, a structure that can map keys to values. A hash table uses a hash function to
compute an index into an array of buckets or slots, from which the desired value can be found.
50. What is hashing function in data structure?
A hash function is any function that can be used to map data of arbitrary size to data of a fixed
size. The values returned by a hash function are called hash values, hash codes, digests, or simply
hashes.
51. What is separate chaining hashing in data structure?
Separate chaining is a hashing technique in which there is a list to handle collisions. So there are
many elements at the same position and they are in a list. The sequences are maintained in a linked list.
52. What are the advantages and disadvantages of separate chaining?
The advantages of separate chaining hashing are as follows −
• Separate chaining technique is not sensitive to the size of the table.
• The idea and the implementation are simple.
The disadvantages of separate chaining hashing are as follows −
• Keys are not evenly distributed in separate chaining.
• Separate chaining can lead to empty spaces in the table.
• The list in the positions can be very long.
53. What is Linear Probing?
Linear probing is a simple collision resolution technique for resolving collisions in hash tables,
data structures for maintaining collection of values in a hash table. If there is a collision for the position
of the key value then the linear probing technique assigns the next free space to the value.

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.

56. What are the advantages and disadvantages of Quadratic Probing?


The advantages of quadratic probing are as follows −
• Quadratic probing is less likely to have the problem of primary clustering and is easier to
implement than Double Hashing.
The disadvantages of quadratic probing are as follows −
• Quadratic probing has secondary clustering. This occurs when 2 keys hash to the same location,
they have the same probe sequence. So, it may take many attempts before an insertion is being
made.
• Also probe sequences do not probe all locations in the table.

57. What is double hashing?


Double hashing is also a collision resolution technique when two different values to be searched
for produce the same hash key.
It uses one hash value generated by the hash function as the starting point and then increments
the position by an interval which is decided using a second, independent hash function. Thus here there
are 2 different hash functions.

58. What are the advantages and disadvantages of Double hashing?


The advantage of double hashing is as follows −
• Double hashing finally overcomes the problems of the clustering issue.
The disadvantages of double hashing are as follows:
• Double hashing is more difficult to implement than any other.
• Double hashing can cause thrashing.

59. What is open addressing hashing in data structure?


Open addressing, or closed hashing, is a method of collision resolution in hash tables. Double
hashing in which the interval between probes is fixed for each record but is computed by another hash
function.
60. What is rehashing in data structure? [Apr/May 2023]
In computing, a hash table (hash map) is a data structure that implements an associative array
abstract data type, a structure that can map keys to values. A hash table uses a hash function to
compute an index into an array of buckets or slots, from which the desired value can be found.
61. What is Extendible Hashing? (Apr/May 2019)
A hash table in which the hash function is the last few bits of the key and the table refer to
buckets. Table entries with the same final bits may use the same bucket. If a bucket overflows, it splits,
and if only one entry referred to it, the table doubles in size. If a bucket is emptied by deletion, entries
using it are changed to refer to an adjoining bucket, and the table may be halved.

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.

64. How Rehashing is done?


Rehashing can be done as follows:
• For each addition of a new entry to the map, check the load factor.
• If it’s greater than its pre-defined value (or default value of 0.75 if not given), then Rehash.
• For Rehash, make a new array of double the previous size and make it the new bucket array.
• Then traverse to each element in the old bucket Array and call the insert() for each so as to
insert it into the new larger bucket array.
65. How to resolve null links in a binary tree? (Apr/May 2019)
Each node will have 2 pointers (may or may not be null). So the tree will have 2n pointers.
There are n nodes. Excluding the root node, every node must have a pointer pointing to it, i.e., n-1 not-
null pointers.
66. The depth of complete binary tree is 8 and computes the number of nodes in leaf. (Apr/May
2019)
A complete binary tree is a binary tree where all the levels have maximum number
of nodes except possibly the last level. The depth of complete binary tree of n nodes will be Dn=log 2
(n+1) where Dn is the height or depth of the tree and n is the number of nodes.
No. of leaf : 18

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]

 Insertion sort algorithm arranges a list of elements in a particular order.


 In insertion sort algorithm, every iteration moves an element from unsorted portion to
sorted portion until all the elements are sorted in the list.
 Insertion sort is the simple sorting algorithm which is commonly used in the daily lives
while ordering a deck of cards.
 In this algorithm, we insert each element onto its proper place in the sorted array.
 This is less efficient than the other sort algorithms like quick sort, merge sort, etc.

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)

Implementation of Insertion Sort Algorithm using C Programming Language


#include<stdio.h>
#include<conio.h>
void main(){
int size, i, j, temp, list[100];
printf("Enter the size of the list: ");
scanf("%d", &size);
printf("Enter %d integer values: ", size);
for (i = 0; i < size; i++)
scanf("%d", &list[i]);
//Insertion sort logic
for (i = 1; i < size; i++) {
temp = list[i];
j = i - 1;
while ((temp < list[j]) && (j >= 0)) {
list[j + 1] = list[j];
j = j - 1;
}
list[j + 1] = temp;
}
printf("List after Sorting is: ");
5
for (i = 0; i < size; i++)
printf(" %d", list[i]);
getch();
}
Output

5.5.5 COMPARISON OF BUBBLE SORT AND INSERTION SORT


 In bubble sort each neighboring element is compared whereas in insertion sort the
elements are inserted at appropriate places in the array.
 The number of swaps needed by bubble sort is more than that of insertion sort.
 However, due to simplicity of bubble sort its code size is very small. Furthermore,
insertion sort is very efficient for sorting nearly sorted lists, when compared with the
bubble sort.

QUICK SORT [Nov/Dec 2019] [NOV/DEC 2022]


Write a C++ code to implement quick sort with suitable example. Nov 2014
Explain quick sort in detail. Nov 2015
Write C++ program to implement quick sort. Nov 2016
Write a C Program to sort the following set of numbers using quick sort algorithm. Find the Time
complexity of the same. Give the trace of the algorithm for the following given set of numbers. 10,
100, 50, 75, 25, 150, 125, 115, 175, 110. Nov 2018 [Apr/May 2021]
Sort the following values using quick sort: 35, 40, 45, 50, 55, 30, 25, 20, 15. Illustrate each step of the
sorting process. [Apr/May 2023]
Quick sort is sorting algorithms that uses the divide and conquer strategy. In this method division
is dynamically carried out. The three steps of quick sort are as follows:
Algorithm:
Divide: Split the array into two sub arrays that each element in the left sub array is less than or
equal the middle element and each element in the right sub array is greater than the middle
element. The splitting of the array into two sub arrays is based on pivot element. All the elements
that are less than pivot should be in left sub array and all the elements that are more than pivot
should be in right sub array.
Conquer: Recursively sort the two sub arrays.
Combine: Combine all the sorted elements in a group to form a list of sorted elements.
Consider an array A [i] where i is ranging from 0 to n - 1 then we can formulize the division of
array elements as

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

Swap Array[i] and Array [j]


Step: 5

Swap Array[i] and Array[j]


Step: 6

As j < i, swap Array[Low] and Array[j]


Step: 7

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

Go on incrementing i if Array[i] < Array [pivot]


Step: 13

Step: 14

Step: 15
Now sort the left sub list obtained in step 13

Swap Array[i] and Array[j]

Thus we get sorted sub list.


Step: 16
Combine the entire sub list we get

This is a sorted list.


Example 2:
Sort the following values using Quick sort and estimate its time and space complexity : 65
70 75 80 85 60 55 50 45. Illustrate each step of the sorting process.
Solution:
Pass 1
(55, 50, 45) 60 (65 70 75 80 85)
Pass 2
45 (55, 50) (65, 70, 75, 80, 85)
Pass 3
45, 50, 55 (65, 70, 75, 80, 85)
Pass 4
45 50 55 65 (70 75 80 85)
Pass 5
45 50 55 65 70 (75 80 85)
Pass 6
45 50 55 65 70 75 (80 85)
14
Pass 7
45 50 55 65 70 75 80 (85)
Pass 8
45 50 55 65 70 75 80
Example 3:
Sort the following values using quick sort and estimate its time and space complexity 65, 70, 75, 80,
85, 60, 55, 50, 45. Nov 2013
Step: 1
65 70 75 80 85 60 55 50 45
i / Pivot j
Step:2
65 70 75 80 85 60 55 50 45
Pivot i j
Step: 3
65 45 75 80 85 60 55 50 70
Pivot i j
Step: 4
65 45 50 80 85 60 55 75 70
Pivot i j
Step: 5
65 45 50 55 85 60 80 75 70
Pivot i j
Step: 6
65 45 50 55 60 85 80 75 70
Pivot j i
Step: 7
60 45 50 55 65 85 80 75 70
Pivot j i
Again do the same procedure for LSA and RSA until all the elements are sorted.
Ans: 45, 50, 55, 60, 65, 70, 75, 80, 85

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.

Step by Step Process


The Heap sort algorithm to arrange a list of elements in ascending order is performed using following steps...
 Step 1 - Construct a Binary Tree with given list of Elements.
 Step 2 - Transform the Binary Tree into Min Heap.
 Step 3 - Delete the root element from Min Heap using Heapify method.
 Step 4 - Put the deleted element into the Sorted list.
 Step 5 - Repeat the same until Min Heap becomes empty.
 Step 6 - Display the sorted list.

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:

Stage I : Heap construction

Stage II: Deletion of root

22
Analysis:
Time complexity of heap sort is O (log n) in both worst and average case. Features of heapsort

1. The time complexity of heap sort is 0 (n log n).


2. This is an in-place sorting algorithm. That means it does not require extra storage space while
sorting the elements.
3. For random input it works slower than quick sort.
4. Heap sort is not a stable sorting method.
5. The space complexity of heap sort is O (1). As it does not require any extra storage tosort
Example 2.10.2 Give the heap that result when starting with empty heap, nodes are inserted
successively for the keys.
EA S YQ U ES T I O N

Assume alphanumeric ordering of the keys.

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

2. Consider the list of following unsorted elements

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

5.9 ANALYSIS OF SORTING ALGORITHMS


Q18.Compare worst case best case and time complexity of various sorting techniques. (N/D 2009)

Algorithm Time Complexity Space Complexity


Best Average Worst Worst
Quick sort Ω(n log(n)) Θ(n log(n)) O(n^2) O(log(n))
Merge sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(n)
Tim sort Ω(n) Θ(n log(n)) O(n log(n)) O(n)
Heap sort Ω(n log(n)) Θ(n log(n)) O(n log(n)) O(1)
Bubble Sort Ω(n) Θ(n^2) O(n^2) O(1)

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

5.1.1 LINEAR SEARCH ALGORITHM (SEQUENTIAL SEARCH ALGORITHM)


Q1.Explain in detail about linear search algorithm with an example. (Apr/May 2015) [Apr/May
2023]
 Linear search algorithm finds a given element in a list of elements with O(n) time complexity
where n is total number of elements in the list.
 This search process starts comparing search element with the first element in the list.
 If both are matched then result is element found otherwise search element is compared with the
next element in the list.
 Repeat the same until search element is compared with the last element in the list, if that last
element also doesn't match, then the result is "Element not found in the list".
 The search element is compared with element by element in the list.
Linear search is implemented using following steps...
29
 Step 1 - Read the search element from the user.
 Step 2 - Compare the search element with the first element in the list.
 Step 3 - If both are matched, then display "Given element is found!!!" and terminate the function
 Step 4 - If both are not matched, then compare search element with the next element in the list.
 Step 5 - Repeat steps 3 and 4 until search element is compared with last element in the list.
 Step 6 - If last element in the list also doesn't match, then display "Element is not found!!!" and
terminate the function.
Example
Consider the following list of elements and the element to be searched...

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.

C Implementation of Linear Search


#include<stdio.h>
void main ()
{
int a[10] = {10, 23, 40, 1, 2, 0, 14, 13, 50, 9};
int item, i,flag;
31
printf("\nEnter Item which is to be searched\n");
scanf("%d",&item);
for (i = 0; i< 10; i++)
{
if(a[i] == item)
{
flag = i+1;
break;
}
else
flag = 0;
}
if(flag != 0)
{
printf("\nItem found at location %d\n",flag);
}
else
{
printf("\nItem not found\n");
}
}
Output:
Enter Item which is to be searched : 20
Item not found
Enter Item which is to be searched : 23
Item found at location 2

5.1.2 BINARY SEARCH ALGORITHM


Q2.Write the program for binary search and compute its complexity. (Apr/May 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)
 Binary search algorithm finds a given element in a list of elements with O(log n) time
complexity where n is total number of elements in the list.
 The binary search algorithm can be used with only a sorted list of elements. That means the
binary search is used only with a list of elements that are already arranged in an order.
 The binary search cannot be used for a list of elements arranged in random order.
 This search process starts comparing the search element with the middle element in the list.
32
 If both are matched, then the result is "element found".
 Otherwise, we check whether the search element is smaller or larger than the middle element in
the list.
 If the search element is smaller, then we repeat the same process for the left sublist of the
middle element.
 If the search element is larger, then we repeat the same process for the right sublist of the
middle element.
 We repeat this process until we find the search element in the list or until we left with a sublist
of only one element.
 And if that element also doesn't match with the search element, then the result is "Element not
found in the list".
Binary search is implemented using following steps...
 Step 1 - Read the search element from the user.
 Step 2 - Find the middle element in the sorted list.
 Step 3 - Compare the search element with the middle element in the sorted list.
 Step 4 - If both are matched, then display "Given element is found!!!" and terminate the
function.
 Step 5 - If both are not matched, then check whether the search element is smaller or larger than
the middle element.
 Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5 for the
left sublist of the middle element.
 Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5 for the
right sublist of the middle element.
 Step 8 - Repeat the same process until we find the search element in the list or until sublist
contains only one element.
 Step 9 - If that element also doesn't match with the search element, then display "Element is
not found in the list!!!" and terminate the function.
Example [NOV/DEC 2022]
Consider the following list of elements and the element to be searched...

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

5.1.3 Comparison between Linear & Binary Search


Q7.Distinguish between linear search and binary search. (Nov/Dec 2018)[Apr/May 2021]
[NOV/DEC 2022]

Sl. Linear Search Binary Search


No. For searching the element by using The elements need to be arranged
1. linear search method it is not required to either in ascending or descending
arrange the elements in some specific order order.

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

1. What is meant by sorting? (Apr/May 2015)


Sorting:
Sorting is a technique for arranging data in particular order. Order means the arrangement of
data. The sorting order can be ascending or descending. The ascending order means arranging the
data in increasing order where as descending order means arranging the data in decreasing order.

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

4. What is meant by external sorting? (Nov/Dec 2019)


 This is a sorting technique in which there is a huge amount of data and it reside on secondary
devices while sorting.
 Example: Merge Sort, Multi way merge, Poly phase merge.

5. What is meant by internal sorting? (Nov/Dec 2019)


 This is a type of sorting technique in which data resided on main memory of computer
 Example: Insertion Sort, Selection sort, shell sort, bubble sort, heap sort, quick sort, etc.

6. What are the various factors to be considered in deciding a sorting algorithm?


 Programming time
 Execution time of the program
 Memory needed for program environment

7. Differentiate between stable and unstable sort. (May/June 2012)


Stable Sorting Un Stable Sorting
In stable sorting if the same value elements are In the unstable sorting the orders of the
present in the list then the order of the elements similar value elements get changed.
remain the same even after the sorting.

8. List the types of sorting techniques. (Apr/May 2013), (Apr/May 2016)


 Insertion sort
 Merge Sort
 Quick Sort
 Radix Sort
37
 Heap Sort
 Selection sort
 Bubble sort

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.

10. What is complexity analysis?


It is the analysis of the amount of memory and time an algorithm requires to completion.
There are two types of Complexity
 Space Complexity
 Time Complexity

11. Define space complexity.


Space complexity of an algorithm is the amount of memory it needs to run to completion.

12. What is time complexity? (Apr/May 2015)


Time complexity is the amount of computer time an algorithm requires to run to completion.

13. What does asymptotic notation mean?


Asymptotic notations are terminology that is introduced to enable us to make meaningful
statements about the time and space complexity of an algorithm.
The different notations are
 Big – Oh notation
 Omega notation
 Theta notation.

14. Define best case of an algorithm.


It is the shortest time that an algorithm will use over all instances of size n for a given problem
to produce the result.

55. What is meant by Efficiency and Passes?


 The efficiency of sorting algorithms is denoted in terms of big oh notations
 Commonly there are Θ (n^2) and Θ (N log N) time complexities.

16. Define dynamic programming. (Apr/May 2010), (Nov/Dec 2010)


Dynamic programming algorithm is a general class of algorithms which solve problems by
solving smaller versions of the problem, saving the solutions to the small problems and then
combining them to solve the larger problems.

17. Define Bubble sort.


Bubble sort is the one of the easiest sorting method. In this method each data item is compared
with its neighbor and if it is an descending sorting, then the bigger number is moved to the top of all
The smaller numbers are slowly moved to the bottom position. Hence it is also called as the exchange
sort.
38
18. What is the average efficiency of heap sort?
The average efficiency of heap sort is Θ (N (log2 N)) where, n is the number of elements sorted.

19. Define insertion sort.


Successive element in the array to be sorted and inserted into its proper place with respect to
the already sorted element.

20. What are the advantages of insertion sort?


 Simple to implement and this method is efficient when we want to sort small number of
elements and this method has excellent performance on almost sorted list of elements.
 More efficient than most other simple Θ (n^2) algorithms such as selection sort or bubble sort.
 This is a stable.

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

26. Define radix sort. (Nov/Dec 2019)


 Radix sort is one of the sorting algorithms used to sort a list of integer numbers in order.
 In radix sort algorithm, a list of integer numbers will be sorted based on the digits of individual
numbers.
 Sorting is performed from least significant digit to the most significant digit.
Radix sort algorithm requires the number of passes which are equal to the number of digits
present in the largest number among the list of numbers.

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.

34. What is meant by Searching?


Searching is the technique for finding particular element from the set.

35. Mention the various types of searching techniques in C.


 Linear search
 Binary search

36. What is linear search?


In Linear Search the list is searched sequentially and the position is returned if the key element
to be searched is available in the list, otherwise -1 is returned. The search in Linear Search starts at the
beginning of an array and move to the end, testing for a match at each item.

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

42. What is the time complexity of linear search? (Nov/Dec 2016)


Class Search algorithm
Worst-case O(n)
Best-case O(1)
Average O(n)

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

42. What is Heap sort?


42
Heap sort is one of the sorting algorithms used to arrange a list of elements in order. Heap sort
algorithm uses one of the tree concepts called Heap Tree. In this sorting algorithm, we
use Max Heap to arrange list of elements in Descending order and Min Heap to arrange list
elements in ascending order.

43. Write the algorithm or procedure for heap sort.


The Heap sort algorithm to arrange a list of elements in ascending order is performed using
following steps...
Step 1 - Construct a Binary Tree with given list of Elements.
Step 2 - Transform the Binary Tree into Min Heap.
Step 3 - Delete the root element from Min Heap using Heapify method.
Step 4 - Put the deleted element into the Sorted list.
Step 5 - Repeat the same until Min Heap becomes empty.
Step 6 - Display the sorted list.

45. What is a heap?


A heap is a complete binary tree, and the binary tree is a tree in which the node can have the
utmost two children. A complete binary tree is a binary tree in which all the levels except the last
level, i.e., leaf node, should be completely filled, and all the nodes should be left-justified.

46. Write the time complexity of heap sort.


Heap sort complexity
Now, let's see the time complexity of Heap sort in the best case, average case, and worst case.
We will also see the space complexity of Heap sort.

Case Time
Complexity

Best Case O(n logn)

Average O(n log n)


Case
Worst O(n log n)
Case
47. Write the space complexity of heap sort.

Space Complexity
Space Complexity O(1)

Stable N0

The space complexity of Heap sort is O(1).

48. Write the working of heap sort.


Working of Heap Sort
1. Since the tree satisfies Max-Heap property, then the largest item is stored at the root node.
2. Swap: Remove the root element and put at the end of the array (nth position) Put the last item
of the tree (heap) at the vacant place.
43
3. Remove: Reduce the size of the heap by 1.
4. Heapify: Heapify the root element again so that we have the highest element at root.
5. The process is repeated until all the items of the list are sorted.

49. Differences between internal sorting and external sorting


S.No Internal sorting External sorting
Internal sorting is done in internal External sorting is done in external
1
memory memory like hard disk or magnetic tape
The internal sorting can reside in main The external sorting can reside in
2
memory secondary memory
Internal sorting takes input only which
External sorting can take as much as large
3 can be fit into its memory. i.e. it takes
input
small input
Example: Heap sort, Bubble sort, Example: Merge sort, Tag sort, Four tape
4 Selection sort, Quick sort, Shell sort, sort, Polyphase sort, external radix sort
Insertion sort, Bucket sort and External merge sort

50. Differentiate Quick sort with Merge sort.


S.No Quick Sort Merge sort
An efficient sorting algorithm. Serving
An efficient, general purpose.
1 as a systematic method for placing the
Comparison based sorting algorithms
elements or an array in order
Sorts the elements by comparing each Divides the array into two sub arrays(n/2)
2
element with the pivot again and again until one element is left.
3 Suitable for small arrays Work for any type of array
4 Works faster for small data sets Works in consistent speed for all datasets
5 Requires minimum space Requires more space
6 Not efficient for large arrays More efficient

51. List the disadvantages of linear search. [Nov/Dec 2022]

 In linear search, it needs more space and time complexity


 In linear search, if the key element is the last element and the search is from first element that is a worst
case.

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

You might also like