Bs1 CDS QB WITH ANSWER

Download as pdf or txt
Download as pdf or txt
You are on page 1of 96

Course Code: 20CS0501 R20

SIDDARTHA INSTITUTE OF SCIENCE AND TECHNOLOGY::PUTTUR


(AUTONOMOUS)
Siddharth Nagar, Narayanavanam Road – 517583
QUESTIONBANK

Subject withCode:(20CS0501)C Programming and Data Structures


Course &Branch:B.Tech–Common to EEE,ME and ECE
Year&Sem :I-B.Tech&II Sem Regulation:R20

UNIT –I
INTRODUCTION TO C LANGUAGE

1 Determine the C language elements with example. [L3][CO1] [12M]


 C is a high-level programming developed in 1972 by Denni‘s Richie at AT&T
Bell Laboratories
 The following are the ‗c‘ language elements:
◦ Preprocessor
◦ Function main
◦ Reserved Words
◦ Standard Identifiers
◦ User-Defined Identifiers
◦ Upper case and Lower case Letters
Preprocessor:
 The c program has two parts:
◦ Preprocessor directives and
◦ Main functions
 The preprocessor directives are commands that give instructions to the c
preprocessor.
 A preprocessor directives begin with a number symbol(#) as its first nonblank
character.
 The two most common directives are:
◦ #include and
◦ #define
 C implementation contains collection of useful functions and symbols called ―
Libraries‖
 The ANSI (American National Standard Institute)standard for c requires certain
Standard Libraries.
 Each Library has a standard header file whose name ends with the symbols .h
 The #include directive gives a program access to a library.
Ex:
#include<stdio.h>
Function Main:
The main function contains two headings:
int
main (void)
 It is the beginning of the main function where program execution begin.
 The remaining lines of the program fro the body of the function which is
enclosed in braces { }
 A function body has two parts
 Declaration statements
 Executable statements
Syntax:
Int
Main (void)
{
function body
}
Course Code: 20CS0501 R20
Example:
Void main()
{
printf(―HelloWorld!‖);
getch();
}
Reserved words:
 Each line contains a number of different words classified as reserved words,
identifiers from standard libraries, and names for memory cells.
Reserved words Meaning
Int Integer
Void Indicates that the main function receives no
data
Double Indicates that the memory cells stores real
number
Return Returns control form the main function to the
OS
Identifiers:
Identifiers are the names provided to the variables
Standard Identifiers:
 Standard identifiers are ―printf‖ and ―Scanf‖
 These are the names of operations defined in the standard input/output library
User defined identifiers:
 Choosing own identifiers called ―user Defined Identifiers‖
 User defined identifiers are used to provide name to memory cells
 Some rules followed by the when declare the identifiers:
 Identifiers must consist only of letters, digits and underscores.
 Identifiers cannot begin with a digit.
 A C reserved word cannot be used as an identifier.
 An identifiers defined in a c standard library should not be redefined.
Identifiers can be of
 valid identifiers
 invalid identifiers
Containing syntax rules for identifiers are called “valid Identifiers”, the identifiers
without any syntax rules are called “invalid Identifiers”
Uppercase and Lowercase Letters:
 All reserved words in c and the names of all standard library functions use only
lowercase letters and uppercase letters in c used in “micro constant”.
2 a Define a Variable. What are the rules for declaring a variable? [L1][CO1] [6M]
Variable:
 Variables are used to store the value during the execution of a program.
 The name itself means, the value of variable can be changed hence the name
―Variable―.
 The variables are stored in Main Memory i.e. RAM (size depending on the
data type).
 In C Programming we always have to declare variable before we can use
them.
 Note that the space is allocated to variable in memory during execution or
run-time.
 The variable declaration in c program communicate to the c compiler, its
computational results is called variable.
 The variable declaration begins with an identifiers that are compiler the type
of data.
Syntax:
int variable_list;
double variable_list;
char variable_list;
Course Code: 20CS0501 R20
Rules for defining variables
1. A variable can have alphabets, digits, and underscore.
2. A variable name can start with the alphabet, and underscore only. It can‘t start
with a digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword, e.g. int, goto , etc.
b Explain in detail about the data types in C. [L2][CO1] [6M]
data types:
 A data types is a set of values and a set of operations on those values.
 It specifies the type of the data, the size of data and about the range of data.

Data Types Size Range


Int 2 -32,768 to 32,767
Unsigned int 2 0 to 65,535
Signed int 2 -32,768 to 32,767
Short 2 -32,768 to 32,767
Unsigned short 2 0 to 65,535
Signed short 2 -32,768 to 32,767
Long 4 -2,147,483,648 to 2,147,483,647
Unsigned long 4 0 to 4,294,967,295
Signed long 4 -2,147,483,648 to 2,147,483,647
Char 1 -128 to 127
Unsigned char 1 0 to 255
Signed char 1 -128 to 127
Float 4 3.4E -38 to 3.4E +38
Double 8 1.7E -308 to 1.7E +308
Long double 10 -1.7E4932 to +1.7E4932

 In c language, data types are classified into 3 types they are:


 Data type int
 Data type double
 Data type char
 Data type float

1. Data type int:


 Integers are whole numbers.
 Int type is used to represent integers in c.
 Int data type can be
 Unsigned int
 Signed
 Short
 Unsigned short Int
 Signed short Short
 Long long
 Unsigned long
 Singed long
 The size or range integer type is in between -32768 to -32767.
Example program:
#include<stdio.h>
Void main()
{
Int a,b,c;
Clrscr();
Printf(―enter a,b value:\n‖):
Scanf(―%d%d‖,&a,&b);
C=a+b;
Printf(―sum of a,b values is:%d‖,c);
Getch();
}
2. Data type double:
Course Code: 20CS0501 R20
 The double is used to represent real numbers
 Ex:3.14159
 This datatype are used to perform the common arithmetic operations
 Ex: Float z=1.64
 The size of double is
3. Data type float:
 A real number has an integral part and a fractional part that are separated by
decimal point.
 Real number specified by another datatype called float
 Ex:3.14159
 This datatype are used to perform the common arithmetic operations
 Ex: double a;
Float z=1.64
 The size of float is 3.4E -38 to 3.4E +38.
4. Datatype char:
 Char is used to represent an individual character values.
 It can be letter, a digit or a special symbol.
 Char type value is enclosed in ‗_‘ (single quotes).
 Ex: char ans=‘a‘;
 The size of char is -128 to 127
Example :
#include<stdio.h>
Void main()
{
int a=10;
char b=‘s‘;
float c=2.88;
double d=28.888;
printf(―integer datatype:%d\n‖,a);
printf(―character datatype:%c\n‖,b);
printf(―float datatype:%f\n‖,c);
printf(―double float datatype:%1f\n‖,d);
getch();
}

3 a Describe the Structure of C Program with an example. [L1][CO2] [6M]


 Each program begins with Pre-processor directive that serve to provide
information about functions from standard libraries.
Directives are:
#include
#define
 Every statement must end with semicolon.
General form of C:

Pre-processor directives:
 Pre-processor directives should not end with semicolon (;)
 Main function is defined after the Pre-processor directives.
 An open brace ({) signal is used or acts as the beginning of the main
Course Code: 20CS0501 R20
function.
 Within the body declaration and executable part is present.
 The end of the main function body is marked by a closing curly brace (}).
 We can write more than one statement on a line
 Ex: printf(―enter distance in mile‖);
scanf(―%f‖,&miles);
Program style:
 Blank spaces are used to improve the style of program. A blank space is
required between consecutive words in a program line.
Comments in programs:
 To make a programmer or any user easy to understand the program by using
―comments‖.
 Comments are used to describe the purpose of the program, the use of
identifiers.
 Comments are part of the ―program documentation‖.
Syntax:

Ex:
 /* this is a one-line or partial line comments*/
 /*
 This is a multiple-line comment in which the stars.
 * not immediately proceeded or followed by slashes
 */
 Program should begin with a header section that consists of comments by
specify
 The programmers name
 The date of the current version
 A brief description of what the program does

b Explain about Input and Output functions with examples. [L2][CO2] [6M]
 Data can be stored in memory in two different ways.
o Assigning value to variable
o Copying the data form an input device into a variable.
 The data transfer from the outside world into memory is called an “input
operation”.
 After execution, a program performs computations and stores the results in
memory.
 These program results can be displayed to the program user by an “output
operation”.
 All input/output operations in c are performed by special program units
called ―input/output functions‖.
 The most common input/output functions are standard input/output library
which can be access through preprocessor directives.
#include<stdio.h>
 Input and output functions are specified with
o Scanf(Input function)
o Printf(output function)
 in c, a function call is used to call or activate function, function can be called
using input/output functions i.e.,
o printf
o scanf
Course Code: 20CS0501 R20
printf function:
Print
Function argument list
.
printf(“that equals %f kilometer\n”,kms);

 The statement calls function printf (pronounced ―printeff‖) display a line of


program output.
 A function call consists of two parts
o The function name
o The function arguments, enclosed in parameter.
 The above argument printf consist of format string (in quotes) and a print
list (the variable).
Ex: the above function call displays that equals 16.090 kilometers.
 %f is the placeholder for variable.
 A place holder always begins with the symbol %. In above example the data
type is float.
 Place holders can be specified as follows:
Place holder Variable type Function use
%c Char Printf/scanf
%d Int Printf/scanf
%f Float Printf/scanf
%lf Double Printf/scanf
 Format string can have multiple place holders.
 The format string also contains the newline escape sequence “\n”.
 It begins with the backslash character \n is used to indicates the next position
on the screen where information will be displayed.
Ex:
Printf (―here is fist line \n‖);
Printf (―\n and this is second\n‖);
Output:
Here is first line
And this is second
 Printf function is also used to display “prompting message or prompt”.
Syntax:
Printf (format string, print list);
Or
Printf (format string);
The scanf function:
 the statements
Ex: scanf (―%f‖, &miles);
 The statements calls function scanf (pronounced “scaneff”) to copy data
into the variable.
 It copies the data form the standard input devices the standard input devices
is keyboard.
 The format string ―%f‖ consists of a single placeholder that tells scanf what
kind of data copy into the variable.
 The format string the name of each variable is to be given a value is
preceded by ampersand character (&).
 The ―&‖ is the c address operator.
 The ―&‖ operator tells the scanf function where to find each variable into
which it is to store new value.
 If ―&‖ is omitted, scanf would know only a variable current value not its
location in memory.
 When scanf executes, the program pauses until the required data are entered.

The function calls scanf syntax:


Course Code: 20CS0501 R20
Scanf (format string, input list);
Ex: scanf (―%c%d‖, &initial, &age);
The return statement:
return (0);
 It is used to transfer control form your program to the operating system.
 The value in parameter, 0 is considered the result of function mains
execution, & indicates program executed without error.
4 List out the various operators available in C with examples. [L1][CO4] [12M]
 An operator is a symbol that informs to the computer to perform a particular
task.
 The data items that operators act upon are called ―operands‖.
 If the operator requires only one operant then it is called ―unary operator‖. If it
requires two then it is called ―Binary Operator‖.
 ‗C‘ language supports a different set of operators which are listed below.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Increment / Decrement Operators
 Bit wise Operators
 Unary Operators
 Conditional Operators
 Special Operators
1. Arithmetic Operator:
 Arithmetic Operators are used to performing mathematical calculations like
addition (+), subtraction (-), multiplication (*), division (/) and modulus (%).
There are two types of arithmetic operators they are:
o Binary operators
o Unary operators
Binary operators:
o A binary operator is an operator that operates on two operands and
manipulates them to return a result.
o Operators are represented by special characters or by keywords and
provide an easy way to compare numerical values or character strings.

Operator Description Examples


+ Addition 2+2=4
- Subtraction 5-3=2
* Multiplication 2*5=10
/ Division 10/2=5
% Modulus 11%3=2

Example:
Void main()
{
int a = 10,b = 15, result;
result = a+b;
printf("Welcome to TechVidvan Tutorials...\n");
printf("Addition: a+b = %d \n",result);
result = a-b;
printf("Subtraction: a-b = %d \n",result);
result = a*b;
printf("Multiplication: a*b = %d \n",result);
result = a/b;
printf("Division: a/b = %d \n",result);
result = a%b;
printf("Modulo Division: %d \n",result);

getch();
Course Code: 20CS0501 R20
}

Unary operators:
o Unary operators are operators that act upon a single operand to produce
a new value.

Operator Description Examples


++ Increment a++
-- Decrement a--
& Address operator &a
sizeOf Gives the sizeOf operator sizeOf()

i. Minus (-):
It is unary minus which is used to indicate or change the algebraic sign of
value.
ii. Increment (++) and Decrement (--):
The ++ operator adds one to its operand, -- subtracts one from its operand.
Ex: ++10
--10
Example:
/*sample program to show the effect of increment operator */
Void main()
{
Int a,z,x=10,y=20;
Clrscr();
Z=x*y++;
A=x*y;
Printf(―\n%d%d‖,z,a);
}
Output:
200
210
iii. sizeOf() and & operator:
 The sizeOf operator gives the bytes occupied by a valuable.
 The & operator prints address of the variable in memory
/* sample program to use & and sizeOf () operator*\
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int x=2;
Float y=2;
clrscr();
printf(―\n sizeOf (x)=%d bytes‖,sizeOf(z));
printf(―\n sizeOf(y)=%d bytes‖,sizeOf(y));
printf(―\n address of x=%u and y=%u‖,&x,&y);
}
Output:
sizeOf (x)=2
sizeOf (y)=4
address of x=4066 and y=25096

2. Relational Operators:
 These operators are used to distinguish between two values. It is used to provide
relationship between two expressions.
 If the result is true then it returns value ‗1‘ (true) otherwise ‗0‘ (false).
Operator Description Example Return value
> Greaterthan 5>4 1
< Lessthan 5<4 0
<= Lessthan or equal to 10<=10 1
Course Code: 20CS0501 R20
>= Greaterthan or equal to 11>=5 1
== Equal to 2==3 0
!= Not equal to 3!=3 0
Example:
/* a sample c program to use relational operators*/
#include<stdio.h>
#include<conio.h>
Void main()
{
Clrscr();
Printf(―\n condition:Return value\n‖);
printf(―\n 10!=10:%5d‖,10!=10);
printf(―\n 10==10:%5d‖,10!=10);
printf(―\n 10>=10:%5d‖,10>=10);
printf(―\n 10<=10:%5d‖,10<=10);
printf(―\n 10!=9:%5d‖,10!=9);
getch();
}
Output:
Condition: Return value
10!=10:0
10==10:1
10>=10:1
10<=10:1
10!=9:1

3. Logical Operators:
 The logical relationship between the two expressions is checked with
logical operator.
 After checking the condition it provides.
o Logical true (1) or
o Logical false (0)
Operator Description Example Return value
&& Logical AND 5>3&&5<10 1
|| Logical OR 8>5||8<2 1
! Logical NOT 8!=8 0
The rules of logical operators are:
1. The logical AND (&&) operator provides true result when both expressions are
true otherwise 0.
2. The logical Or(||) operator provides true result when one of the expression is true
otherwise 0.
3. The logical NOT(!) provides 0, if condition is true otherwise it.
/* a sample program to illustrate the use of logical operator*/
#include<stdio.h>
#include<conio.h>
Void main()
{
Clrscr();
Printf(―\n condtion:Return value\n‖);
Printf(‗\n 5>3&&5>10:%5d‖,5>3&&5<100;
Printf(―\n 8>5||8<2:%5d‖,8>5||8<2);
Printf(―\n !(8==8):%5d‖,!(8==8));
}
Output:
Condition:Return value
5>3&&5>10:1
8>5||8<2:1
!(8==8):0
5 a Write a C Program to find the sum of individual digits of positive integer. [L6][CO3] [6M]
Course Code: 20CS0501 R20
#include<stdio.h>
#include<conio.h>
void main()
{
int n ,r ,s=0;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&n);
while(n>0)
{
r=n%10;
s=s+r;
n=n/10;
}
printf("\n Sum of the digits is = %4d",s);
getch();
}
Input:
Enter the number: 256
Output:
Sum of the digits is = 13
b Explain about precedence and associativity in C. [L2][CO1] [6M]
 Every operator has a precedence value.
 An expression containing more than one operator is known as complex
expression.
 Complex expressions are executed according to precedence of operators.
 Associativity specifies the order in which the operators are evaluated with
the precedence, associatively is two ways they are:
◦ Left-to-right
◦ Right-to-left
 Left-to-right associatively executes on expression starting from left and
moving towards rights.
 Right-to-left associatively proceeds from right to left
Operator Operations Associativity Precedence
() Function call
Array
[]
Expression
Structure Left to Right 1st
Operator
Structure
.
Operator
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Not Operator
one's
~ Right to Left 2nd
complement
* Pointer Operator
Address
&
Operator
sizeof size of an object
type typecast
* multiplication Left to Right 3rd
Course Code: 20CS0501 R20
/ Division
Modular
%
division
+ Addition
SUBTRACTIO Left to Right 4th
-
N
<< Leftshift
Left to Right 5th
>> Rightshift
< Lessthen
Lessthen or
<=
equal to
Left to Right 6th
> Greaterthen
Greaterthen or
>=
equal to
== Equality
Left to Right 7th
!= Inequality
& BitwiseAND Left to Right 8th
^ BitwiseXOR Left to Right 9th
| Bitwise OR Left to Right 10th
&& Logical AND Left to Right 11th
|| Logical OR Left to Right 12th
Conditional
?: Right to Left 13th
operator
=,*=,- Assignemnt
Right to Left 14th
=,&=,+=,^=,|=,<<=,>>= operator
Comma
, Right to Left 15th
Operator
6 Define a type conversion. What are different types of type‘s conversions .explain
a [L1][CO2] [6M]
with example?
 A type cast is basically a conversion from one type to another.
 There are two types of type conversion:
◦ Implicit conversion (Automatic Conversion)
◦ Explicit conversion (user manual or user defined )
Implicit conversion:
 Implicit conversion also called as Automatic conversion)
 C performs automatic conversions of type in order to evaluate the
expression. This is called implicit type conversion.

Example:
// An example of implicit conversion
#include<stdio.h>
void main()
{
int x = 10; // integer x
char y = 'a'; // character c ASCII a=97
float z; // float z
clrscr();
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
Course Code: 20CS0501 R20
}
OUTPUT:
x = 107, z = 108.000000

Explicit conversion:
 Explicit conversion also called user define conversion)
 In explicit type conversion we decide what type we want to convert the
expression.

Example:
// C program to demonstrate explicit type casting
#include<stdio.h>
void main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
clrscr();
printf("sum = %d", sum);
getch();
}
Output:
sum = 2
b Write a C Program to find the given number is even or odd. [L6][CO3] [6M]
/* Write a C Program to find the given number is even or odd.*/
#include<stdio.h>
void main()
{
int n;
clrscr();
printf(―enter an integer:\n‖);
scanf(―%d‖,&n);
If(n%==2)
{
printf(―%d is an even number‖,n);
}
else
{
printf(―%d is an odd number‖,n);
}
getch();
}
Input:
Enter an integer:
12
Output:
12 is even number

7 Examine with examples of different decision statements in C. [L3][CO2] [12M]


Decision Statements:
 A program is nothing but the execution of sequence of one or more instructions.
 In some situations one has to change the order of the execution of statements
based on the conditions this is said to be decision making condition to see
whether a particular condition is satisfied or not
 Four types of Decision statements they are
o Simple If statements
o If-else statements
o If-else-if ladder statements
o Switch () case statements
1. Simpe If statements:
Course Code: 20CS0501 R20
 Simple If statement is used to executes a set of command lines or one command
line when the logical condition is true
Syntax:
If(condition)/*no semi-colon*/
{
statemet-1;
}
 Statement is executed only when the condition is true, incase false the compiler
skips the line.
 The statements should not contain semi-colon(;)
Void main()
{
int v;
clrscr();
printf(―enter the number:‖);
scanf(―%d‖,&v);
if(v<10) (10<10)
printf(―\n number is lessthan 10);
sleep(2);
}
Output:
enter the number:9
number is lessthan 10
2. If-else statements:
 The if-else statement is used to perform two operations for a single condition.
 The if-else statement is an extension to the if statement using which, we can
perform two different operations, i.e.,
 one is for the correctness of that condition, and the other is for the incorrectness
of the condition.
Syntax:
if(expression)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}
Example:
#include<stdio.h>
int main()
{
int number=0;
Clrscr();
printf("enter a number:");
scanf("%d",&number);
if(number%2==0) 11%2
{
printf("%d is even number",number);
}
else
{
printf("%d is odd number",number);
}
return 0;
}
3. The if-else-if ladder:
 The if-else-if ladder statement is an extension to the if-else statement.
 It is used in the scenario where there are multiple cases to be performed for
different conditions.
 In if-else-if ladder statement, if a condition is true then the statements defined in
Course Code: 20CS0501 R20
the if block will be executed, otherwise if some other condition is true then the
statements defined in the else-if block will be executed, at the last if none of the
condition is true then the statements defined in the else block will be executed.
 There are multiple else-if blocks possible.
Syntax:
if(condition-1) false
{
//code to be executed if condition1 is true
}else if(condition2) true
{
//code to be executed if condition2 is true
}
else if(condition-3) false
{
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
#include<stdio.h>
Void main()
{
int n;
clrscr();
printf(―enter a n value:\n‖);
scanf(―%d‖,&n);
if(n<10)
{
printf(― %d less than 10‖);
}
else if(n>10)
{
printf(―%d greater than 10‖);
}
else if(n==10)
{
printf(―%d equal to 10‖);
}
else
{
printf(―invalid‖);
}
getch();
}
4. Switch statement:
 The switch statement in C is an alternate to if-else-if ladder statement which
allows us to execute multiple operations for the different possible values of a
single variable called switch variable.
 We can define various statements in the multiple cases for the different values of
a single variable.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
Course Code: 20CS0501 R20
......

default:
code to be executed if all cases are not matched;
}
Example:
#include<stdio.h>
int main()
{
int day;
printf("Enter day number: ");
scanf("%d", &day);
switch(day)
{
case 1: printf("SUNDAY.");
break;
case 2: printf("MONDAY.");
break;
case 3: printf("TUESDAY.");
break;
case 4: printf("WEDNESDAY.");
break;
case 5: printf("THURSDAY.");
break;
case 6: printf("FRIDAY.");
break;
case 7: printf("SATURDAY.");
break;
default: printf("INVALID DAY.");
break;
}
return(0);
}
To establish the following statements
8 a. if Statement
b. if else Statement
[L3][CO2] [12M]
c. else if ladder
d. Nested if statements

a.If statements:
 Simple If statement is used to executes a set of command lines or one command
line when the logical condition is true
Syntax:
If(condition)/*no semi-colon*/
{
statemet-1;
}
 Statement is executed only when the condition is true, incase false the compiler
skips the line.
 The statements should not contain semi-colon(;)
Void main()
{
int v;
clrscr();
printf(―enter the number:‖);
scanf(―%d‖,&v);
if(v<10) (10<10)
printf(―\n number is lessthan 10);
sleep(2);
}
Course Code: 20CS0501 R20
Output:
enter the number:9
number is lessthan 10
b. If-else statements:
 The if-else statement is used to perform two operations for a single condition.
 The if-else statement is an extension to the if statement using which, we can
perform two different operations, i.e.,
 one is for the correctness of that condition, and the other is for the incorrectness
of the condition.
Syntax:
if(expression)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}
Example:
#include<stdio.h>
int main()
{
int number=0;
Clrscr();
printf("enter a number:");
scanf("%d",&number);
if(number%2==0) 11%2
{
printf("%d is even number",number);
}
else
{
printf("%d is odd number",number);
}
return 0;
}
c. if-else-if ladder:
 The if-else-if ladder statement is an extension to the if-else statement.
 It is used in the scenario where there are multiple cases to be performed for
different conditions.
 In if-else-if ladder statement, if a condition is true then the statements defined in
the if block will be executed, otherwise if some other condition is true then the
statements defined in the else-if block will be executed, at the last if none of the
condition is true then the statements defined in the else block will be executed.
 There are multiple else-if blocks possible.
Syntax:
if(condition-1) false
{
//code to be executed if condition1 is true
}else if(condition2) true
{
//code to be executed if condition2 is true
}
else if(condition-3) false
{
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Course Code: 20CS0501 R20
Example:
#include<stdio.h>
Void main()
{
int n;
clrscr();
printf(―enter a n value:\n‖);
scanf(―%d‖,&n);
if(n<10)
{
printf(― %d less than 10‖);
}
else if(n>10)
{
printf(―%d greater than 10‖);
}
else if(n==10)
{
printf(―%d equal to 10‖);
}
else
{
printf(―invalid‖);
}
getch();
}

d.Nested if statements:
 A nested if in C is an if statement that is the target of another if statement.
 Nested if statements mean an if statement inside another if statement.
 Yes, both C and C++ allow us to nested if statements within if statements, i.e,
we can place an if statement inside another if statement.
Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
// C program to illustrate nested-if statement
#include <stdio.h>

int main()
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
Course Code: 20CS0501 R20
return 0;
}
9 Discover the different looping statements with suitable examples. [L4][CO2] [12M]
Loop Statement:
A loop is defined as a block of statement which are repeatedly executed for certain
number of times.
Steps in Loop:
 Loop variable
 Initialization
 Increment/Decrement
Loop variable: it is a variable used in loop
Initialization: it is the first step. Each time the updated value is checked by the loop.
Increment/Decrement: it is the numerical value added or subtracted to the variable in
each round of the loop
There are three loop in c:
i. For loop
ii. While loop
iii. Do-while loop
For loop:
 The for loop allows to execute the set of instruction until a certain condition is
satisfied.
Syntax:
For(initialization;test condition;increment/decrement)
{
Statement1;
Statement2;
--------------
--------------
}
 In initialization value is initialized into the variable.
 The test condition is a relational expression that determines whether the
conditions is true or false.
 Re-evaluation or increment/decrement, decides now to make changes in loop
whether to increase or decrease.
 There are various formats of for loop.
Syntax Output Remark
For(;;) Initialize loop No arguments
For(a=0;a<=20) Initialize loop A is neither increment or decre
For(a=0;a<=10;a++) Display value A is increased from 0 to 10
Fpr(a=20;a>=2-;a--) Display value A is decreased from 10 to 0

/*printf the first five numbers starting from one together with their square*/
Void main()
{
int i;
clrscr();
for(i=0;i<5;i++)
printf(―\n number:%5d,its square:%8d‖,i,i*i);
}
Output:
Number:1 its square:1
Number:2 its square:4
Number:3 its square:9
Number:4 its square:16
Number:5 its square:25
Nested for loop:
 In nested for loops one or more for statements are included in the body of the
loop.
 C allows multiple for loops in the nested form.
/* write a program to perform subtraction of two loop variables*/
Course Code: 20CS0501 R20
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,sub;
Clrscr();
For(a=3;a>=1;a--)
{
For(b=1;b<=2;b++)
{
Sub=a-b;
Printf(―a=%d b=%d a-b=%d\n‖,a,b,sub);
}
}
}
Output:
a=3 b=1 a-b=2
a=3 b=2 a-b=1
a=2 b=1 a-b=1
a=2 b=2 a-b=0
a=1 b=1 a-b=0
a=1 b=2 a-b=-1
while loop:
 the test condition may be any expression. The loop statement will be executed if
the condition is true i.e the test condition is evaluated and and if the condition is
true, then body of the loop is executed.
Syntax:
While(test condition)
{
Body of the loop;
}
1. The test condition is evaluated and if it is true, the body of the loop is
loop is executed
2. on execution of the body, test condition is respectively checked and if it
is true the body is executed.
3. the process of execution of the body will be continue till the test
condition becomes false.
4. The control is transferred out of the loop.
/* write a program to print the string “ you have learnt c program” 9 times using
while loop*/
Void main()
{
Int x=1;
While(x<10)
{
Printf(―\n you have learnt c program‖);
X++;
}
}
Output:
You have learnt c program
You have learnt c program
You have learnt c program
You have learnt c program
You have learnt c program
You have learnt c program
You have learnt c program
You have learnt c program
You have learnt c program
Course Code: 20CS0501 R20
Do-while loop:
 the difference between while and do-while loop is in the place where the
condition is to be tested.
 In do-while, the condition is checked at the end of the loop.
 The do-while loop will executed atleast one time even if the condition is false
initially.
 The do-while loop will executes until the condition becomes false.
/*sample program to use the do-while loop and display a message this is do-while
loop for 5 times*/
Void main()
{
int i=1;
clrscr();
do
{
printf(―\n this is do-while loop‖);
i++;
}
while(i<=5);
}
Output:
This is do-while loop
This is do-while loop
This is do-while loop
This is do-while loop
This is do-while loop

10 Write a C Program to Perform Arithmetic Operations using Switch


a [L6][CO3] [6M]
Statement
PROGRAM:
#include<stdio.h>
Void main()
{
int a,b;
char op;
clrscr();
printf("\nEnter the operator:");
scanf("%c",&op);
printf("Enter the two numbers:");
scanf("%d%d",&a,&b);
switch(op)
{
case '+': printf("\nAdding two numbers:%d",a+b);
break;
case '-': printf(―\n Subtracting two numbers:%d, a-b);
break;
case „*‟: printf(―\n multiplying two numbers: %d‖, a*b);
break;
case '/': printf("\nDividing two numbers:%d",a/b);
break;
case '%': printf("\nModulous operation:%d",a%b);
break;
}
getch();
}
Input:
Enter the two numbers: 6 3
Enter the operator: +
Output:
Adding two numbers: 9
Course Code: 20CS0501 R20
b Differentiate break and continue statements. [L4][CO2] [6M]
Break Statement Continue Statement
i. The Break statement is used to exit i.The continue statement is not
from the loop constructs. used to exit from the loop
constructs.
ii.The break statement is usually used ii.The continue statement is not
with the switch statement, and it can used with the switch statement,
also use it within the while loop, do- but it can be used within the
while loop, or the for-loop. while loop, do-while loop, or
for-loop.
iii.Terminate the program iii.Never terminates the program
Syntax: Syntax:
break; Continue;
Course Code: 20CS0501 R20
UNIT –II
ARRAYS, FUNCTIONS and STRINGS

1 Define an Array. Write the syntax for declaring and initializing array with
a [L6][CO2] [6M]
example.
 An array is a collection of two or more adjacent memory cells called Array
elements, that are associated with a particular symbolic name.‘
Ex: double x[8];
 It instructs the compiles to associate eight memory cells with the name x
 Array elements are enclosed in square bracket or array subscript.
Ex: double x[8];
16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5
X[0] X[1] X[2] X[3] X[4] X[5] X[6] X[7]

 The subscripted variable X[0] may be used to reference. The initial or 0th
element of the array x.
 X[1] is the next element, &X[1] is the last element.
 Based on above example, the statement that manipulates Array X.

Statements Explanation
Printf(‗%f‖,X[0]); Display the value of X[0], which is 16.0
X[3]=25.0; Stores the value in X[3].
Sum X[0]+X[1]; Stores the sum of X[0] and X[1] which is 28.0
variable sum.
Sum=X[2]; Adds X[2] to sum the new sum is 34.0.
X[3]+=1.0; Adds 1.0 to X[3] the new is 26.0.
X[2]=*X[0]+X[1]; Stores the sum of X[0] and X[1] in X[2].

Example:
We declare two arrays for student records.
int id[NUM_STUDENT];
Double gpa[NUM.STUDENT];
If NUM STUDENTS have specified as macros constant then
#define NUM.STUDENTS 50

2.71
3.09
2.98
.

1.68
1.92

Array Initialization:
 We can initialize a simple variable as
int sum=0;
But while initializing array we provided with variable name followed by
subscript with values.
int
prime[]={2,3,5,7,9,11,17,19,23,29,35,37,41,43,47,53,59,61,71,73,79,83,89,91
};
syntax of array declaration:
datatype name[size]; /* uninitialized */
datatype name[size]={initialization list};
b Create a C program for displaying largest element in array. [L6][CO4] [6M]
Program:
Course Code: 20CS0501 R20
#include <stdio.h>
void main()
{
int size, i, largest;
printf("\n Enter the size of the array: ");
scanf("%d",&size);
int array[size];
printf("\n Enter %d elements of the array: \n", size);
for(i =0; i < size; i++)
{
scanf("%d",&array[i]);
}
largest = array[0];
for(i =1; i < size; i++)
{
if(largest < array[i])
largest = array[i];
}
printf("\n largest element present in the given array is : %d", largest);
getch();

}
Output:
Enter the size of the array: 5
Enter 5 elements of the array:
12
56
34
78
100

largest element present in the given array is: 100


2 What is 2D array? Construct asyntax for declaring and initializing 2D array
a [L6][CO3] [6M]
with example.
2D Array:
 The two-dimensional array can be defined as an array of arrays.
 The 2D array is organized as matrices which can be represented as the
collection of rows and columns.

Declaration of 2D Array :
Syntax:
data_type array_name[rows][columns];
Example:
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Program:
#include<stdio.h>
Void main ( )
{
int a[3][3] ,i,j;
printf ("enter elements of array");
for ( i=0; i<3; i++)
{
for (j=0;j<3; j++)
{
scanf("%d", &a[i] [j]);
}
}
printf("elements of the array are");
for ( i=0; i<3; i++)
Course Code: 20CS0501 R20
{
for (j=0;j<3; j++)
{
printf("%d\t", a[i] [j]);
}
printf("\n");
}
}
Output:
Enter elements of array:
123456789
Elements of the array are
123
456
789
Initialization of 2D Array :
 In the 1D array, we don't need to specify the size of the array if the declaration
and initialization are being done simultaneously.
 However, this will not work with 2D arrays.
 We will have to define at least the second dimension of the array.
Syntax:

data_type array_name[rows][columns]={initialization_list};

Example:

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

program:

#include<stdio.h>
void main ( )
{
int a[3][3] = {10,20,30,40,50,60,70,80,90};
int i,j;
printf ("elements of the array are");
for ( i=0; i<3; i++)
{
for (j=0;j<3; j++)
{
printf("%d \t", a[i] [j]);
}
printf("\n");
}
}
Output:

elements of the array are:


10 20 30
40 50 60
70 80 90

b Create a C program for displaying smallest element in array. [L6][CO4] [6M]


Program:
Course Code: 20CS0501 R20
#include<stdio.h>
#include<conio.h>
voidmain()
{
inta[30],i,n,small;
clrscr();
printf(" Enter Number of Elements in Array :\n");
scanf("%d",&n);
/* Read Elements in an array */
printf(" \n Enter the Elements:\n ");
for(i=0 ; i < n ; i++)
scanf("%d",&a[i]);
small = a[0];

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


{
if( a[i] < small )
small = a[i];
}
printf(" Smallest Element in the Array is : %d",small);
getch();
}

Output:

Enter Number of Elements in Array :


5
Enter the Elements:
1
3
2
6
5
Smallest Element in the Array is : 1
3 a Define function. Classify the types of functions with an example. [L4][CO1] [6M]
Function:
 A function is a block of code that performs a specific task.
 Suppose, you need to create a program to create a circle and color it. You can
create two functions to solve this problem:
o create a circle function
o create a color function
 Dividing a complex problem into smaller problem makes our program easy to
understand and reuse.

Types of Functions:

There are two types of functions in C programming:

Library Functions:
 Library Functions are the functions which are declared in the C header files
such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
 If you try to use printf() without including the stdio.h header file, you will get
Course Code: 20CS0501 R20
an error.

Example:
/* To compute the square root of a number, you can use the sqrt() library function.
The function is defined in the math.h header file.*/

#include <stdio.h>
#include <math.h>
void main()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);
// Computes the square root of num and stores in root.
root = sqrt(num);
printf("Square root of %.2f = %.2f", num, root);
getch();
}
Output:
Enter a number: 12
Square root of 12.00=3.46
1. User-defined functions:

 User-defined functions are the functions which are created by the C


programmer, so that he/she can use it many times.
 It reduces the complexity of a big program and optimizes the code.

Example:

#include <stdio.h>
int addNumbers(int a, int b); // function prototype
void main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
getch();
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
Output:
Enters two numbers: 4 6
Sum=10
b Create a C program to swap two numbers using functions. [L6][CO3] [6M]
// C program to swap two numbers
#include<stdio.h>
void main()
{
int a, b, temp;
printf("Enter a value:\n ");
scanf("%d", &a);
printf("Enter b value:\n");
scanf("%d", &b);
// value of a is assigned to temp
Course Code: 20CS0501 R20
temp = a;
// value of second is assigned to a
a = b;
// value of temp (initial value of a) is assigned to b
b = temp;
// %.d displays number value of a
printf("\n After swapping, a value is = %d", a);
printf("After swapping, b value is = %d", b);
getch();
}
Output:
Enter a value: 10
Enter b value: 20

After swapping, a value is = 20


After swapping, b value is = 1

4 What are the different categories of functions? Explain with example. [L2][CO2] [12M]
Categories of functions:
 All the C functions can be called either with arguments or without arguments in a
C program.
 These functions may or may not return values to the calling function.
 Depending on the arguments and return values functions are classified into 4
categories:
1. Function without arguments and without a return value.
2. Function with arguments and without a return value.
3. Function without arguments and with a return value.
4. Function with arguments and with a return value.

1. Function without arguments and without a return value.


 These functions in which no parameters are passed from calling function to
called function and and no values are returned from called function to
calling.
Example:
#include<stdio.h>
void greatNum(); // function declaration
void main()
{
greatNum(); // function call
getch();
}
void greatNum() // function definition
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j)
{
printf("The greater number is: %d", i);
}
else
{
printf("The greater number is: %d", j);
}
}
Output:
Enter 2 numbers that you want to compare... 9 4
The greater number is: 9

2. Function with arguments and without a return value:


Course Code: 20CS0501 R20
 These functions in which parameters are passed from calling function to
called function and no values are returned from called function to calling.
Example:
#include <stdio.h>
void largest(int, int);
void main()
{
int p, q;
printf("Enter two numbers : ");
scanf("%d%d" , &p, &q);
largest(p, q);
}
void largest(int x, int y)
{
if (x > y)
{
printf("Largest element = %d\n", x);
}
else
{
printf("Largest element = %d\n", y);
}
}
Output:
Enter two numbers: 1
10
Largest element = 10

3. Function without arguments and with a return value:


 These functions in which no parameters are passed from calling function to
called function and and values are returned from called function to calling.

Example:

#include <stdio.h>
int sum(void);
void main()
{
printf("\nSum of two given values = %d\n", sum());
}
int sum()
{
int a, b, total;
printf("Enter two numbers : ");
scanf("%d%d", &a, &b);
total = a + b;
return total;
}

Output:
Enter two numbers: 1
2
Sum of two given values = 3

4. Function with arguments and with a return value:


 These functions in which parameters are passed from calling function to
called function and values are returned from called function to calling.
Course Code: 20CS0501 R20
Example:

#include <stdio.h>
int largest(int, int, int);
void main()
{
int a, b, c;
printf("Enter three numbers : ");
scanf("%d%d%d" , &a, &b, &c);
printf(" Largest of the given three numbers = %d\n", largest(a, b, c));
}
int largest(int x, int y, int z)
{
if ((x > y) && (x > z))
{
return x;
}
else if (y > z)
{
return y;
}
else
{
return z;
}
}

Output:

Enter three numbers: 1


4
7
Largest of the given three numbers = 7

5 a Distinguish between call by value and call by referencewith an examples [L4][CO3] [6M]
Call by value:


In call by value method, the value of the actual parameters is
copied into the formal parameters. In other words, we can say that
the value of the variable is used in the function call in the call by
value method.
 In call by value method, we cannot modify the value of the actual
parameter by the formal parameter.
 In call by value, different memory is allocated for actual and
formal parameters since the value of the actual parameter is
copied into the formal parameter.
 The actual parameter is the argument which is used in the
function call whereas formal parameter is the argument which is
used in the function definition.
Example:

#include <stdio.h>
void swap(int , int);
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
Course Code: 20CS0501 R20
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;

printf("After swapping values in function a = %d, b = %d\n",a,b);


// Formal parameters, a = 20, b = 10
}

Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

call by reference:
 In call by reference, the address of the variable is passed into the
function call as the actual parameter.
 The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is passed.
 In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function are
performed on the value stored at the address of the actual parameters,
and the modified value gets stored at the same address.

Example:
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
Course Code: 20CS0501 R20
Difference between call by value and call by reference in c
No. Call by value Call by reference
1 A copy of the value is passed into An address of value is passed into the
the function function
2 Changes made inside the function Changes made inside the function
are limited to the function only. validate outside of the function also.
The values of the actual The values of the actual parameters
parameters do not change by do change by changing the formal
changing the formal parameters. parameters.
3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory location
location
b How to use Array as Function argument. Explain with an example [L1][CO4] [6M]

6 a Differentiate local and global variable with example. [L2][CO1] [6M]

Global Variable Local Variable


Global variables are declared outside all the Local Variables are declared within
function blocks. a function block.
The scope remains throughout the program. The scope is limited and remains
within the function only in which
they are declared.
Any change in global variable affects the Any change in the local variable
whole program, wherever it is being used. does not affect other functions of
the program.
A global variable exists in the program for A local variable is created when the
the entire time the program is executed. function is executed, and once the
execution is finished, the variable is
destroyed.
It can be accessed throughout the program It can only be accessed by the
by all the functions present in the program. function statements in which it is
declared and not by the other
functions.
If the global variable is not initialized, it If the local variable is not
takes zero by default. initialized, it takes the garbage
value by default.
Global variables are stored in the data Local variables are stored in a stack
segment of memory. in memory.
We cannot declare many variables with the We can declare various variables
same name. with the same name but in other
functions.
b Describe about type qualifiers in C. [L1][CO2] [6M]
Type Qualifier:

 Type qualifiers are the keywords that can be prepared to variable to change
their accessibility.
 We can type qualifiers are used to change the properties of variable.
 There are two types of type qualifiers variable c programming language:
o Constant qualifier
o Volatile qualifier

Constant qualifier:
 The constant qualifier is used to declare a variable read-only (constant), its
value may not be changed and it can be declared by sing const keyword.
 It helps to prevent accidental change of the value.
 To declare a constant, include the const keyword before or after the data type.
Syntax:
Course Code: 20CS0501 R20
Const data_type constant_name=value;
Or
data_type const constant_name=value;
Example:
#include <stdio.h>
void main()
{
const int i = 5;
i = 10; //error
i++; //error
getch();
}
 In the above code, we have used the const keyword with the variable ―i―.
 When we will try to modify it we will get the compiler error because we can
not assign value to const int.
Volatile qualifier:
 The volatile qualifier is used to declare a variable that can be changed
explicitly.
 It tells the compiler that the variables value may change at any time.
 It is very useful for embed programming to keep the updated very useful value
that can be updated form the various interrupts.
 To declare a volatile variable, include the volatile keyword before or after the
data type.
Syntax:
volatile data_type constant_name=value;
Or
data_type volatile constant_name=value;

Example:

#include <stdio.h>
void main()
{
volatile int data = 5;
int *ptr = (int*)(&data);
*ptr =4;
printf("%d\n", data);
getch();
}
Output:
4
7 a Differentiate the storage classes in C language. [L4][CO1] [6M]
Storage Classes:
Storage classes in C are used to determine the lifetime, visibility, memory location,
and initial value of a variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register

Storage Storage
Default Value Scope Lifetime
Classes Place
Garbage Within function
auto RAM Local
Value
Till the end of the main program
Globa
extern RAM Zero Maybe declared anywhere in the
l
program
Till the end of the main program,
static RAM Zero Local Retains value between multiple
functions call
Course Code: 20CS0501 R20
Garbage Within the function
register Register Local
Value

1.Automatic:
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they
are defined.
o The scope of the automatic variables is limited to the block in which they are
defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the
block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

Example:
#include <stdio.h>
void main()
{
int a; //auto
char b;
float c;
clrscr();
printf("%d %c %f",a,b,c); // printing initial default value of automatic
variables a, b, and c.
getch();
}
Output:
garbage garbage garbage

2.Static:
o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which
they are defined.
o A same static variable can be declared many times but can be assigned at only
one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.

Example:
#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f w
ill be printed.
}
Output:
0 0 0.000000 (null)
3.Register:
o The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
o We cannot dereference the register variables, i.e., we cannot use &operator for
the register variable.
o The access time of the register variables is faster than the automatic variables.
Course Code: 20CS0501 R20
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the
CPU register. However, it is compilers choice whether or not; the variables
can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables cannot be stored into the register since we cannot use more
than one storage specifier for the same variable.

Example:
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial
default value of a is 0.
printf("%d",a);
}
Output: 0

4.External
o The external storage class is used to tell the compiler that the variable defined
as extern is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere in
the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we cannot initialize
the external variable within any block or method.
o An external variable can be declared many times but can be initialized at only
once.
o If a variable is declared as external then the compiler searches for that variable
to be initialized somewhere in the program which may be extern or static. If it
is not, then the compiler will show an error.

Example :
#include <stdio.h>
int main()
{
extern int a;
printf("%d",a);
}
Output:

main.c:(.text+0x6): undefined reference to `a'


collect2: error: ld returned 1 exit status
b Create a C program for factorial of a given numberusing recursion. [L6][CO3] [6M]
Program:

#include<stdio.h>
void main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",number, fact);
getch();
Course Code: 20CS0501 R20
}
Output:
Enter a number: 5
Factorial of 5 is: 120
8 a Determine any four preprocessor commands. [L3][CO1] [6M]
 In c programming language, preprocessor directive is step performed
before the actual source code compilation.
 It is not part of the compilation. preprocessor directives in c
programming language are used to define and replace tokens in the
text and also used to insert the contents of the files into the source file.
 When we try to compile a program, preprocessor commands are
executed first and then the program gets compiled.
 Every preprocessor command begins with # symbol we can also
create preprocessor command with parameters.
1. #define:
 #define is used create symbolic constants (known as macros) in c
programming language.
 This processor command can also be used with parameterized macro.
Syntax:
#define token value
Example Program:
#include<stdio.h>
#define PI 3.1415
Void main()
{
Printf(―%f‖,PI);
}
2. #Ifdef:
 Ifdef returns True if the macro is defined and returns FALSE if
the macro is not defined.
3. #if:
 #if uses the values of specified macro for condition a1
compilation.
4. #else:
 #else is an alternative for # if
5. #elif:
 #elif is a #else followed by #if in one statement
6. #endif:
 #endif is used terminate preprocessor conditional macro.
7. #include:
 #include is used to insert specific header file into c program
8. #error:
 #error is used to print error message on stderr.
9. Pragma:
 #progma is used to issue a special command to the compiler.
10. #ifndef:
 #ifndef returns TRUE if the specified macro is not defined
otherwise returns FALSE

b Create a program for finding the sum ofan array element. [L6][CO3] [6M]
Program:

#include <stdio.h>

void main()
{
Course Code: 20CS0501 R20
int a[100];
int i, n, sum=0;
printf("\n\nFind sum of all elements of array:\n");
printf("--------------------------------------\n");
printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&a[i]);
}
for(i=0; i<n; i++)
{
sum += a[i];
}
printf("Sum of all elements stored in the array is : %d\n\n", sum);
}
Output:
Find sum of all elements of array:
--------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 2
element - 1 : 5
element - 2 : 8
Sum of all elements stored in the array is : 15
9 a Create a program to check whether given string is palindrome or not. [L6][CO4] [6M]
Program:

#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
{
printf("palindrome number ");
}
else
{
printf("not palindrome");
}
getch();

Output:
Course Code: 20CS0501 R20
Input 1:
Enter the number=151
Output 1:
Palindrome number
Input 2:
enter the number=5621
Output 2:
not palindrome number

b Create a program for addition oftwomatrices. [L6][CO4] [12M]


Program:
#include <stdio.h>
#include <conio.h>
void main()
{
int a[2][3],b[2][3],c[2][3],i,j;
clrscr();
printf("\nENTER VALUES FOR MATRIX A:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nENTER VALUES FOR MATRIX B:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<2;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nTHE VALUES OF MATRIX C ARE:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf("%5d",c[i][j]);
printf("\n");
}
getch();
}
Output:
ENTER VALUES FOR MATRIX A:
1 2 3
4 5 6
ENTER VALUES FOR MATRIX B:
2 4 6
5 3 8
THE VALUES OF MATRIX C ARE:
3 6 9
9 8 14
10 Define String. Explain the different string handling functions with example. [L2][CO2] [12M]
String:
 Strings are defined as an array of characters.
 The difference between a character array and a string is the string is
terminated with a special character ‗\0‘.
No. Function Description
1 strlen(string_name) Returns the length of string name.
Copies the contents of source string
2 strcpy(destination, source)
to destination string.
Concats or joins first string with
3 strcat(first_string, second_string)
second string. The result of the
Course Code: 20CS0501 R20
string is stored in first string.
Compares the first string with
4 strcmp(first_string, second_string) second string. If both strings are
same, it returns 0.
5 strrev(string) Returns reverse string.
Returns string characters in
6 strlwr(string)
lowercase.
Returns string characters in
7 strupr(string)
uppercase.

1. strlen:
 The strlen() function returns the length of the given string. It doesn't count
null character '\0'.
Syntax:
strlen(string_name);
Program:
#include<stdio.h>
#include <string.h>
void main()
{
char ch[20]={'c', 'o', 'm', 'p', 'u', 't', 'e', 'r', '\0'};
printf("Length of string is: %d",strlen(ch));
getch();
}
Output:
Length of string is: 8
2. Strcpy:
 The strcpy(destination, source) function copies the source string in
destination.

Syntax:

strcpy(destination, source);
program:
#include<stdio.h>
#include <string.h>
void main()
{
char ch[20]={'c', 'o', 'm', 'p', 'u', 't', 'e', 'r', '\0'};
char ch2[20];
strcpy(ch2,ch);
printf("Value of second string is: %s",ch2);
getch();
}
Output:
Value of second string is: computer
3. Strcat:

The strcat(first_string, second_string) function concatenates two strings and result


is returned to first_string.

Syntax:

strcat(first_string, second_string);
Course Code: 20CS0501 R20
program:

#include<stdio.h>
#include <string.h>
void main()
{
char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
char ch2[10]={'c', '\0'};
strcat(ch,ch2);
printf("Value of first string is: %s",ch);
getch();
}
Output:
Value of first string is: helloc
4. Strcmp:
The strcmp(first_string, second_string) function compares two string and returns 0
if both strings are equal.
Syntax:
strcmp(first_string, second_string)
program:
#include<stdio.h>
#include <string.h>
void main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
getch();
}

Output:

Enter 1st string: hello


Enter 2nd string: hello
Strings are equal

5. strrev:
The strrev(string) function returns reverse of the given string. Let's see a simple
example of strrev() function.
Syntax:
strrev(string);
program:
#include<stdio.h>
#include <string.h>
void main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
Course Code: 20CS0501 R20
printf("\nReverse String is: %s",strrev(str));
getch();
}
Output:
Enter string: computer
String is: computer
Reverse String is: retupmoc

6. Strlwr:
The strlwr(string) function returns string characters in lowercase. Let's see a simple
example of strlwr() function.
Syntax:
strlwr(string)
program:
#include<stdio.h>
#include <string.h>
void main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nLower String is: %s",strlwr(str));
getch();
}
Output:

Enter string: COMPuter


String is: COMPuter
Lower String is: computer

7. Strupr:
The strlupr(string) function returns string characters in uppercase.
Syntax:
strlwr(string)
program:
#include<stdio.h>
#include <string.h>
void main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nUpper String is: %s",strupr(str));
getch();
}
Output:

Enter string: computer


String is: computer
Lower String is: COMPUTER
Course Code: 20CS0501 R20

UNIT –III
POINTERS, STRUCTURES & UNIONS

1
a Define pointer. Write the syntax for declaring pointer with example. [L6][CO2] [4M]
Pointer:
 A pointer is a memory variable that stores a memory address pointer
can have any name that is legal for other variables.
 Those declared in the same fashion like other variables but it is
always denoted by „*‟ pointer.
Pointer Declaration with syntax:
Syntax:
Datatype *variable_name;
Example:
int *x;
float *f;
Char *y;
 In the first statement ‗x‘ is an integer pointer and it tells to the
compiler that it holds the address of any integer variable.
 In the same way f and y have float and character pointer.
 The indirection operator (*) is also called the deference operator.
When a pointer is deferred the value at that address stored by the
pointer is retrieved.
 Normal variable provides indirect access to the values of the
variables.
 The indirection operator (*) is used in two district way with pointers,
declaration and deference.
 When a pointer is declared, the star indicates that it is a pointer not
normal variable.
 When the pointer is deferred the indirection operator indicates that
the value at that memory location stored in the pointer is to be
accessed rather than the address itself.
 Indication operator (*) is the same operator that can be used as the
multiplication operator.
 The ‗&‘ is the address operator and it represents the address of the
variables. ―%u‖ is used with printf() function for printing the
address of variables.
Example program:
/* program to display the value of variable and its location using
pointer*/

#include<stdio.h>
void main()
{
int v=10,*p;
clrscr();
p=&v;
printf(―address of v=%u‖,p);
printf(―values of v=%d‖,*p);
printf(―address of p=%u‖,&p);
getch();
}
Course Code: 20CS0501 R20
b Explain the concept of array of pointers with examples. [L2][CO2] [8M]
Array of Pointers:
 C language also supports array of pointers. It is nothing but a
collection of address.
 We store address of variables for which we have to declare an array
as a pointer.
/* write a program to store address of different elements of an array
using array of pointers*/
#include<stdio.h>
#include<conio.h>
void main()
{
int *[3];
int j[3]={5,10,15},k;
for(k=0;k<3;k++)
i[k]=j+k;
clrscr();
printf(―\n\t address elements\n‖);
for(k=0;k<3;k++)
{
printf(―\n\t%u‖,i[k]);
printf(\t %7d\n‖,*(i[k]);
}
}
Output:
Address element
4060 5
4062 10
4064 15
Explanation:
 *i[3] is declared as an array of pointer using first for loop address of
various elements of array are assigned to ‗*i[i]‘.
The second for loop picks up the address from ‗*[]‘ and display the value
present at that location
2 List out features of pointers? Write a C program to print address of a
a [L1][CO1] [6M]
variable.
Features of pointers:
 Pointers save the memory space
 Execution time with pointers is faster because data is manipulated
with the address ,direct access to memory.
 The memory is accessed efficiently with the pointers the pointers
assign the memory space and it also release.
 Pointers are used with data structures. They are useful for
representing two dimensional and multi-dimensional analysis.

/*C program to print address of a variable*/


#include <stdio.h>
void main()
{
int a;
int *pt;
printf("Pointer Example Program : Print Pointer Address\n");
a = 10;
pt = &a;
printf("\n[a ]:Value of A = %d", a);
Course Code: 20CS0501 R20
printf("\n[*pt]:Value of A = %d", *pt);
printf("\n[&a ]:Address of A = %p", &a);
printf("\n[pt ]:Address of A = %p", pt);
printf("\n[&pt]:Address of pt = %p", &pt);
printf("\n[pt ]:Value of pt = %p", pt);
getch();
}
Output:
Pointer Example Program : Print Pointer Address

[a ]:Value of A = 10
[*pt]:Value of A = 10
[&a ]:Address of A = 0060FF0C
[pt ]:Address of A = 0060FF0C
[&pt]:Address of pt = 0060FF08
[pt ]:Value of pt = 0060FF0C
b Explain the concept of pointer to pointers with examples. [L2][CO1] [6M]
Pointer to pointer:
 Pointer is known as a variable containing address of another
variable.
 Pointer variables also have an address.
 The pointer variables containing address of another pointer variable
is called as pointer to pointer.
 The pointer variable containing address of another pointer variables
is called as pointer to pointer
 This chain can be continued to any extent.
/* write a program to print value of a variable through pointer and
pointer to pointer*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a=2,*p,**q;
p=&a;
q=&p;
clrscr();
printf(―\n value of a=%d address of a=%u‖,a,&a);
printf(―\n through * p value of a a=%d address of a=%d‖,*p,p);
printf(―\n through **q value of a=%d address of a=%d‖,**q,*q);
getch();
}
Output:
Value of a=2 address of a=4056
Value *p value a=2 address of a=4056
Value **q value of a=2 address of a=4056
Explanation:
 In the above program variable ‗p‘ is declared as a pointer the
variable ‗q‘ is declared as pointer to another pointer.
 Hence they are declared as ‗*p‘ and ‗**q‘ respectively.

3 a Explain the concept of void pointers with examples. [L2][CO1] [6M]


Void pointer:
 Pointers can also be declared as void type.
 Void pointers cannot be dereferred without explicit type conversion.
 This is because, being void the compiler cannot determine the size of
Course Code: 20CS0501 R20
the object that the pointer points to through void pointer declaration
is possible, void variable declaration is not allowed.
/* write a program to declare a void pointer*/
#include<stdio.h>
#include<conio.h>
int p;
float d;
char c;
void *pt=&p;
void main(void)
{
Clrscr();
*(int*)pt=12;
Printf(―\n p=%d‖,p);
Pt=&d;
*(float*)pt=5.4;
Printf(―\n r=%f‖,d);
Pt=&c;
*(char*)pt=‘s‘;
Printf(―\n c=%c‖,c);
getch();
}

Output:
P=12
R=5.4
C=5

Explanation:
 In the above example variable p, d and c are variable of type int,
float and char respectively.
 Pointer pt is a pointer of type void. All these variables are declared
before main().
 The pointer is initialized with the address of integer variable p, the
pointer p points to variable x.

b Distinguish pointers and arrays with some example programs. [L4][CO3] [6M]
Difference between Arrays and pointers

 An array is a collection of elements of similar data type whereas the


pointer is a variable that stores the address of another variable.
 An array size decides the number of variables it can store whereas; a
pointer variable can store the address of only one variable in it.
 Arrays can be initialized at the definition, while pointers cannot be
initialized at the definition.
 Arrays are static in nature which means once the size of the array is
declared, it cannot be resized according to users requirement.
Whereas pointers are dynamic in nature, which means the memory
allocated can be resized later at any point in time.
 Arrays are allocated at compile time while pointers are allocated at
runtime.

Example:
#include <stdio.h>
void printElement(char* q, int index)
Course Code: 20CS0501 R20
{
printf("Element at index(%d) is: %c\n", index, *(q+index));
}
void main()
{
char arr[] = {'A', 'B', 'C'};
char* p = arr;
printf("Size of arr[]: %d\n", sizeof(arr));
printf("Size of p: %d\n", sizeof(p));
printf("First element using arr is: %c\n", arr[0]);
printf("First element using p is: %c\n", *p);
printf("Second element using arr is: %c\n", arr[1]);
printf("Second element using p is: %c\n", *(p+1));
printElement(p, 2);
getch();
}
Output:
Size of arr[]: 3
Size of p: 8
First element using arr is: A
First element using p is: A
Second element using arr is: B
Second element using p is: B
Element at index(2) is: C

4 Describe about dynamic memory management functions in C. [L2][CO1] [12M]


Dynamic memory management functions in C:
 In static memory allocation memory is allocated to the variables and
arrays at compile time.
 Allocating memory to the objects at runtime is called ―Dynamic memory
allocation.
 To access the dynamic data pointers are used.
Memory management functions:

There are four types of functions for dynamic memory allocation they are:
 malloc()-memory allocation
 calloc()-contigous allocation
 realloc()
 free()
First three functions are used to allocate memory and the one is to free the
memory. The standard library function for these functions is ‗stdio.h‘.
1. malloc() or memory allocation:
 malloc() stands for memory allocation.
 It allocated a single block of memory of specified size.
 It returns NULL if memory is insufficient.
 Malloc() function returns the address of first byte in the allocated
memory if memory is sufficient.

Syntax:
Ptr=(cast_type*)malloc(byte_size)

Example:
P=(int*)malloc(50*sizeof(int));

#include <stdio.h>
Course Code: 20CS0501 R20
#include <stdlib.h>
void main()
{

int* ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
if (ptr == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}
else
{
printf("Memory successfully allocated using malloc.\n");
for (i = 0; i < n;i++)
{
ptr[i] = i + 1;
}

printf("The elements of the array are: ");


for (i = 0; i < n;i++)
{
printf("%d, ", ptr[i]);
}
}

getch();
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
2. Calloc() or contiguous memory:
Calloc() function stands for contiguous allocation.
It allocates/reserves a multiple block of memory of same size.
The allocated memory space is initialized to zero.
It returns NULL if memory is insufficient.
Syntax:
Void* calloc(size-t element_count,size-t element_size)
Example:
#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


n = 5;
Course Code: 20CS0501 R20
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()


ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


// allocated by calloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array


for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

3. Realloc():
 “realloc” or “re-allocation” method in C is used to dynamically
change the memory allocation of a previously allocated memory.
 In other words, if the memory previously allocated with the help of
malloc or calloc is insufficient, realloc can be used to dynamically
re-allocate memory.
 re-allocation of memory maintains the already present value and new
blocks will be initialized with the default garbage value.
Syntax:
ptr = realloc(ptr, newSize);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using calloc()
ptr = (int*)calloc(n, sizeof(int));

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
Course Code: 20CS0501 R20
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
// Get the new size for the array
n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));
// Memory has been successfully allocated
printf("Memory successfully re-allocated using realloc.\n");
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
free(ptr);
}

return 0;
}
4. free():
 “free” method in C is used to dynamically de-allocate the memory.
 The memory allocated using functions malloc() and calloc() is not
de-allocated on their own.
 Hence the free() method is used, whenever the dynamic memory
allocation takes place.
 It helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
Course Code: 20CS0501 R20
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.\n");
// Memory has been successfully allocated
printf("\nMemory successfully allocated using calloc.\n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}
Course Code: 20CS0501 R20
5 a How to pass a pointer to a function? Explain. [L2][CO4] [6M]

Define structure and give the general syntax for structure. Write a suitable
b [L1][CO2] [6M]
example.
Course Code: 20CS0501 R20
6 a How do you define structure within a structure? Explain with an example. [L2][CO2] [6M]

b Compare between structure and array. [L2][CO2] [6M]


Course Code: 20CS0501 R20
7 a How to declare and initialize a structure? Mention with an example. [L2][CO3] [6M]
Course Code: 20CS0501 R20
b What is the use of period operator in structures? Give an example. [L1][CO3] [6M]

8 Define union and give the general syntax for union. Write a suitable
a [L3][CO2] [6M]
example.
Course Code: 20CS0501 R20

b Describe the bit fields concept. [L2][CO1] [6M]


Bit Fields:
 In C, we can specify size (in bits) of structure and union members.
 The idea is to use memory efficiently when we know that the value of a
field or group of fields will never exceed a limit or is within a small range.
For example, consider the following declaration of date without the use of bit
fields.
Example:
#include <stdio.h>
// A simple representation of the date
struct date {
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n",sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
Size of date is 12 bytes
Date is 31/12/2014

Discuss below terms with examples:


9 a. Nested structures. [L2][CO4] [12M]
b. Arrayof structures.
a. Nested structure:
A nested structure in C is a structure within structure. One structure can be declared
inside another structure in the same way structure members are declared inside a
structure.
Syntax:
struct name_1
{
member1;
member2;
.
.
Course Code: 20CS0501 R20
membern;
struct name_2
{
member_1;
member_2;
.
.
member_n;
}, var1
} var2;
Example:
// C program to implement
// the above approach
#include <stdio.h>
#include <string.h>
// Declaration of the
// dependent structure
struct Employee
{
int employee_id;
char name[20];
int salary;
};
// Declaration of the
// Outer structure
struct Organisation
{
char organisation_name[20];
char org_number[20];
// Dependent structure is used
// as a member inside the main
// structure for implementing
// nested structure
struct Employee emp;
};
// Driver code
int main()
{
// Structure variable
struct Organisation org;
// Print the size of organisation
// structure
printf("The size of structure organisation : %ld\n",sizeof(org));
org.emp.employee_id = 101;
strcpy(org.emp.name, "CSE");
org.emp.salary = 400000;
strcpy(org.organisation_name,"Computer");
strcpy(org.org_number, "GFG123768");
// Printing the details
printf("Organisation Name : %s\n",org.organisation_name);
printf("Organisation Number : %s\n",org.org_number);
printf("Employee id : %d\n",org.emp.employee_id);
printf("Employee name : %s\n",org.emp.name);
printf("Employee Salary : %d\n",org.emp.salary);
}
b. Arrayof structures:
 A structure may contain elements of different data types – int, char, float,
double, etc.
 It may also contain an array as its member.
 Such an array is called an array within a structure. An array within a structure
Course Code: 20CS0501 R20
is a member of the structure and can be accessed just as we access other elements
of the structure.
Example:
// C program to demonstrate the
// use of an array within a structure
#include <stdio.h>
// Declaration of the structure candidate
struct candidate {
int roll_no;
char grade;
// Array within the structure
float marks[4];
};
// Function to displays the content of
// the structure variables
void display(struct candidate a1)
{
printf("Roll number : %d\n", a1.roll_no);
printf("Grade : %c\n", a1.grade);
printf("Marks secured:\n");
int i;
int len = sizeof(a1.marks) / sizeof(float);
// Accessing the contents of the
// array within the structure
for (i = 0; i < len; i++)
{
printf("Subject %d : %.2f\n",i + 1, a1.marks[i]);
}
}
// Driver Code
int main()
{
// Initialize a structure
struct candidate A= { 1, 'A', { 98.5, 77, 89, 78.5 } };
// Function to display structure
display(A);
return 0;
}
10 a Illustrate the use of typedef with suitable example. [L3][CO1] [6M]
Typedef:
 The C programming language provides a keyword called typedef, which
you can use to give a type a new name.
 Following is an example to define a term BYTE for one-byte numbers
Syntax:
typedef unsigned char BYTE;
Example:
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( )
{
Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming ");
book.book_id = 6495407;
Course Code: 20CS0501 R20
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
return 0;
}
b Distinguish between the structure and union. [L4][CO3] [6M]
Course Code: 20CS0501 R20

UNIT –IV
DATA STRUCTURES and LINKED LIST

1 a What is data structure? Explain the linear and nonlinear data structure in detail. [L2][CO1] [6M]
Data Structures : A data structure is a specialized format for organizing and
storing data.
Characteristics of DS:
1. Correctness---DS Implementation should Implement its interface
2. Time Complexity---Running time OR Execution time.
3. Space Complexity---Memory Usage of a system.
Execution Time Cases:
1. Worst case--- it takes maximum time execution
2. Average case--- it takes Average time execution
3. Best case---- it takes minimum time execution

Basic Operations:
i. Traversing
ii. Searching
iii. Insertion
iv. Deletion
v. Sorting
vi. Merging

b What is a stack? Design the representation of stacks. [L3][CO5] [6M]


Stacks
Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data
structure that allows adding and removing elements in a particular order. Every time an
element is added, it goes on the top of the stack, the only element that can be removed is
the element that was at the top of the stack, just like a pile of objects.

Basic features of Stack


1. Stack is an ordered list of similar data type.
2. Stack is a LIFO structure. (Last in First out).
3. push() function is used to insert new elements into the Stack and pop() is used to
delete an element from the stack. Both insertion and deletion are allowed at only one
Course Code: 20CS0501 R20
end of Stack called Top.
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.
Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to stack -
letter by letter - and then pop letters from the stack.
There are other uses also like : Parsing, Expression Conversion(Infix to Postfix,
Postfix to Prefix etc) and many more.
What are various operations that can be performed on stack? Explain with an
2 [L2][CO5] [12M]
example.
Stacks
Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data
structure that allows adding and removing elements in a particular order. Every time an
element is added, it goes on the top of the stack, the only element that can be removed is the
element that was at the top of the stack, just like a pile of objects.

Basic features of Stack


1. Stack is an ordered list of similar data type.
2. Stack is a LIFO structure. (Last in First out).
3. push() function is used to insert new elements into the Stack and pop() is used to delete
an element from the stack. Both insertion and deletion are allowed at only one end
of Stack called Top.
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.
Implementation of Stack
Stack can be easily implemented using an Array or a Linked List. Arrays are quick, but are
limited in size and Linked List requires overhead to allocate, link, unlink, and deallocate, but
is not limited in size. Here we will implement Stack using array.

#include<stdio.h>

int MAXSIZE =8;


int stack[8];
int top =-1;
Course Code: 20CS0501 R20
int isempty(){

if(top ==-1)
return1;
else
return0;
}

int isfull(){

if(top == MAXSIZE)
return1;
else
return0;
}
int peek(){
return stack[top];
}

int pop(){
int data;

if(!isempty()){
data = stack[top];
top = top -1;
return data;
}else{
printf("Could not retrieve data, Stack is empty.\n");
}
}

int push(int data){

if(!isfull()){
top = top +1;
stack[top]= data;
}else{
printf("Could not insert data, Stack is full.\n");
}
}
int main(){
// push items on to the stack
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);
printf("Element at top of the stack: %d\n",peek());
printf("Elements: \n");
// print stack data
while(!isempty()){
int data = pop();
printf("%d\n",data);
}
printf("Stack full: %s\n", isfull()?"true":"false");
printf("Stack empty: %s\n", isempty()?"true":"false");

return0;
}
Course Code: 20CS0501 R20

Position of Top Status of Stack

-1 Stack is Empty

0 Only one element in Stack

N-1 Stack is Full

N Overflow state of Stack

Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to stack -
letter by letter - and then pop letters from the stack.
There are other uses also like : Parsing, Expression Conversion(Infix to Postfix, Postfix to
Prefix etc) and many more.
3 Construct an empty stack and perform PUSH operation for any five elements.
a Also performPOP operation for two elements and show the value on top of the [L6][CO5] [6M]
stack.
What is stack?
First, let us see the properties of data structures that we already do know and build-up
our concepts towards the stack.
Array: Its a random-access container, meaning any element of this container can be
accessed instantly
Linked List: It's a sequential-access container, meaning that elements of this data
structure can only be accessed sequentially
A Stack is a data structure following the LIFO(Last In, First Out)
principle.

If you have trouble visualizing stacks, just assume a stack of books.


In a stack of books, you can only see the top book
 If you want to access any other book, you would first need to remove the
books on top of it
 The bottom-most book in the stack was put first and can only be removed at
the last after all books on top of it have been removed.

PUSH Operation
Push operation refers to inserting an element in the stack. Since there‘s only one
position at which the new element can be inserted — Top of the stack, the new element
is inserted at the top of the stack.
POP Operation
Course Code: 20CS0501 R20
Pop operation refers to the removal of an element. Again, since we only have access to
the element at the top of the stack, there‘s only one element that we can remove. We
just remove the top of the stack. Note: We can also choose to return the value of the
popped element back, its completely at the choice of the programmer to implement
this.
PEEK Operation
Peek operation allows the user to see the element on the top of the stack. The stack is
not modified in any manner in this operation.
isEmpty: Check if stack is empty or not
To prevent performing operations on an empty stack, the programmer is required to
internally maintain the size of the stack which will be updated during push and pop
operations accordingly. isEmpty() conventionally returns a boolean value: True if size
is 0, else False.
PUSH Operation
What changes are made to the stack when a new element is pushed?
 A new element is inserted on top
 The value of top increases by 1

What if the stack is filled to its capacity?


We shall check if the stack if full before inserting a new element and throw an error if
it is.
Now, let us implement this simply
voidpush(int item)
{
if ( top == capacity - 1 )
print("Stack overflow!" )
else
{
arr[top+1] = item
top = top + 1
}
}
POP Operation
Let‘s try one more: Pop().
What changes are made to the stack internally for a pop operation?
 The top element is removed
 The value of top is decreased by 1
Course Code: 20CS0501 R20
Voidpop()
{
if ( isEmpty() == True )
print("Stack is empty!" )
else
top = top - 1}

Peek and isEmpty Operation


Peek and isEmpty are quite simple to implement. We need to steer clear of exceptions
though.
intpeek()
{
if ( isEmpty() == True )
{
print("Stack is empty!" )
return -1
}
else
return arr[top]
}
bool isEmpty()
{
if ( top == -1 )
return True
else
return False
}
b What do you mean by stack overflow and stack underflow [L1][CO4] [6M]
Stacks
Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data
structure that allows adding and removing elements in a particular order. Every time an
element is added, it goes on the top of the stack, the only element that can be removed
is the element that was at the top of the stack, just like a pile of objects.

Basic features of Stack


1. Stack is an ordered list of similar data type.
2. Stack is a LIFO structure. (Last in First out).
3. push() function is used to insert new elements into the Stack and pop() is used
to delete an element from the stack. Both insertion and deletion are allowed at
only one end
of Stack called Top.
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.
What is a queue? What are various operations that can be performed on them?
4 [L2][CO5] [12M]
Explain with an example.
Queues
Queue is also an abstract data type or a linear data structure, in which the first element is
Course Code: 20CS0501 R20
inserted from one end called REAR(also called tail), and the deletion of exisiting element
takes place from the other end called as FRONT(also called head). This makes queue as
FIFO data structure, which means that element inserted first will also be removed first.
The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.

Basic features of Queue


1. Like Stack, Queue is also an ordered list of elements of similar data types.
2. Queue is a FIFO( First in First Out ) structure.
3. Once a new element is inserted into the Queue, all the elements inserted before the new
element in the queue must be removed, to remove the new element.
4. peek( ) function is oftenly used to return the value of first element without dequeuing it.

Applications of Queue
Queue, as the name suggests is used whenever we need to have any group of objects in an
order in which the first one coming in, also gets out first while the others wait for there turn,
like in the following scenarios :
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order
as they arrive, First come first served.

Implementation of Queue
Queue can be implemented using an Array, Stack or Linked List. The easiest way of
implementing a queue is by using an Array. Initially the head(FRONT) and the tail(REAR)
of the queue points at the first index of the array (starting the index of array from 0). As we
add elements to the queue, the tail keeps on moving ahead, always pointing to the position
where the next element will be inserted, while the head remains at the first index.
Course Code: 20CS0501 R20

When we remove element from Queue, we can follow two possible approaches (mentioned
[A] and [B] in above diagram). In [A] approach, we remove the element at head position, and
then one by one move all the other elements on position forward. In approach [B] we remove
the element from head position and then move head to the next position.
In approach [A] there is an overhead of shifting the elements one position forward every time
we remove the first element. In approach [B] there is no such overhead, but whener we move
head one position ahead, after removal of first element, the size on Queue is reduced by one
space each time.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAX 6
int intArray[MAX];
int front =0;
int rear =-1;
int itemCount =0;
int peek(){
return intArray[front];
}
bool isEmpty(){
return itemCount ==0;
}
bool isFull(){
return itemCount == MAX;
}
int size(){
return itemCount;
}
void insert(int data){
if(!isFull()){
if(rear == MAX-1){
rear =-1;
}
intArray[++rear]= data;
itemCount++;
}
}
int removeData(){
int data = intArray[front++];
Course Code: 20CS0501 R20
if(front == MAX){
front =0;
}
itemCount--;
return data;
}
int main(){
/* insert 5 items */
insert(3);
insert(5);
insert(9);
insert(1);
insert(12);
// front : 0
// rear : 4
// ------------------
// index : 0 1 2 3 4
// ------------------
// queue : 3 5 9 1 12
insert(15);
// front : 0
// rear : 5
// ---------------------
// index : 0 1 2 3 4 5
// ---------------------
// queue : 3 5 9 1 12 15

if(isFull()){
printf("Queue is full!\n");
}
// remove one item
int num = removeData();
printf("Element removed: %d\n",num);
// front : 1
// rear : 5
// -------------------
// index : 1 2 3 4 5
// -------------------
// queue : 5 9 1 12 15
// insert more items
insert(16);
// front : 1
// rear : -1
// ----------------------
// index : 0 1 2 3 4 5
// ----------------------
// queue : 16 5 9 1 12 15
// As queue is full, elements will not be inserted.
insert(17);
insert(18);
// ----------------------
// index : 0 1 2 3 4 5
// ----------------------
// queue : 16 5 9 1 12 15
printf("Element at front: %d\n",peek());
printf("----------------------\n");
printf("index : 5 4 3 2 1 0\n");
printf("----------------------\n");
printf("Queue: ");
while(!isEmpty()){
int n = removeData();
Course Code: 20CS0501 R20
printf("%d ",n);
}
}
Output
Queue is full!
Element removed: 3
Element at front: 5
----------------------
index : 5 4 3 2 1 0
----------------------
Queue: 5 9 1 12 15 16
5 a Distinguish between stacks and queue. [L4][CO1] [6M]
Parameter Stack Data Structure Queue Data Structure

Basics It is a linear data structure. The It is also a linear data


objects are removed or inserted structure. The objects are
at the same end. removed and inserted from
two different ends.

Working It follows the Last In, First Out It follows the First In, First
Principle (LIFO) principle. It means that Out (FIFO) principle. It means
the last inserted element gets that the first added element
deleted at first. gets removed first from the
list.

Pointers It has only one pointer- the top. It uses two pointers (in a
This pointer indicates the simple queue) for reading and
address of the topmost element writing data from both the
or the last inserted one of the ends- the front and the rear.
stack. The rear one indicates the
address of the last inserted
element, whereas the front
pointer indicates the address of
the first inserted element in a
queue.

Operations Stack uses push and pop as two Queue


of its operations. The pop uses enqueue and dequeue as
operation functions to remove two of its operations. The
the element from the list, while dequeue operation deletes the
the push operation functions to elements from the queue, and
insert the element in a list. the enqueue operation inserts
the elements in a queue.

Structure Insertion and deletion of It uses two ends- front and


elements take place from one rear. Insertion uses the rear
end only. It is called the top. end, and deletion uses the
front end.

Full Condition When top== max-1, it means When rear==max-1, it means


Examination that the stack is full. that the queue is full.

Empty When top==-1, it indicates that When front = rear+1 or


Condition the stack is empty. front== -1, it indicates that the
Examination queue is empty.

Variants A Stack data structure does not A Queue data structure has
have any types. three types- circular queue,
Course Code: 20CS0501 R20
priority queue, and double-
ended queue.

Visualization You can visualize the Stack as a You can visualize a Queue as
vertical collection. a horizontal collection.

Implementatio The implementation is simpler The implementation is


n in a Stack. comparatively more complex
in a Queue than a stack.

b State any two applications of stacks and queues? [L1][CO5] [6M]


Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to stack -
letter by letter - and then pop letters from the stack.
There are other uses also like : Parsing, Expression Conversion(Infix to Postfix,
Postfix to Prefix etc) and many more.

Applications of Queue
Queue, as the name suggests is used whenever we need to have any group of objects in
an order in which the first one coming in, also gets out first while the others wait for
there turn, like in the following scenarios :
1. Serving requests on a single shared resource, like a printer, CPU task scheduling
etc.
2. In real life, Call Center phone systems will use Queues, to hold people calling them
in an order, until a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same
order as they arrive, First come first served.
6 Explain about various types of queues with suitable examples. [L2][CO4] [12M]
Queues
Queue is also an abstract data type or a linear data structure, in which the first element is
inserted from one end called REAR(also called tail), and the deletion of exisiting element
takes place from the other end called as FRONT(also called head). This makes queue as
FIFO data structure, which means that element inserted first will also be removed first.
The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.

There are four different types of queues:


 Simple Queue
 Circular Queue
 Priority Queue
 Double Ended Queue
Simple Queue
In a simple queue, insertion takes place at the rear and removal occurs at the front. It strictly
follows the FIFO (First in First out) rule.

Circular Queue
In a circular queue, the last element points to the first element making a circular link.

The main advantage of


Course Code: 20CS0501 R20
a circular queue over a simple queue is better memory utilization. If the last position is full
and the first position is empty, we can insert an element in the first position. This action is
not possible in a simple queue.
Priority Queue
A priority queue is a special type of queue in which each element is associated with a
priority and is served according to its priority. If elements with the same priority occur, they
are served according to their order in the queue.

Deque (Double Ended Queue)


In a double ended queue, insertion and removal of elements can be performed from either
from the front or rear. Thus, it does not follow the FIFO (First In First Out) rule.

7 Explain about various types of linked lists with suitable examples. [L2][CO6] [12M]
Linked list :A linked list is a linear collection of data elements, called nodes, pointing to the
next node by means of a pointer. It is a data structure consisting of a group of nodes which
together represent a sequence.

Linked lists are among the simplest and most common data structures. They can be used to
implement several other common abstract data types,
including lists stacks, queues, associative arrays, and S-expressions, though it is not
uncommon to implement the other data structures directly without using a list as the basis of
implementation.

Advantages:
 Linked lists are a dynamic data structure, which can grow and be pruned, allocating and
de allocating memory while the program is running.
 Insertion and deletion node operations are easily implemented in a linked list.
 Linear data structures such as stacks and queues are easily executed with a linked list.
 They can reduce access time and may expand in real time without memory overhead.
Disadvantages:
 They use more memory than arrays because of the storage used by their pointers.
 Nodes in a linked list must be read in order from the beginning as linked lists are
inherently sequential access.
 Nodes are stored in contiguously, greatly increasing the time required to access individual
elements within the list, especially with a CPU cache.
 Difficulties arise in linked lists when it comes to reverse traversing. For instance, singly
linked lists are cumbersome to navigate backwards. and while doubly linked lists are
somewhat easier to read, memory is wasted in allocating space for a back-pointer.
Linked list Types:
1. Singly linked list
2. Doubly linked list
3. Circular Linked list
1.Singly linked list:
Course Code: 20CS0501 R20
Singly linked lists contain nodes which have a data field as well as a 'next' field, which
points to the next node in line of nodes. Operations that can be performed on singly linked
lists include insertion, deletion and traversal.
A singly linked list whose nodes contain two fields: an integer value and a link to the next
node

2.Doubly linked list


Main article: Doubly linked list
In a 'doubly linked list', each node contains, besides the next-node link, a second link
field pointing to the 'previous' node in the sequence. The two links may be called 'forward('s')
and 'backwards', or 'next' and 'prev'('previous').

A doubly linked list whose nodes contain three fields: an integer value, the link forward to the
next node, and the link backward to the previous node
A technique known as XOR-linking allows a doubly linked list to be implemented
using a single link field in each node. However, this technique requires the ability to do bit
operations on addresses, and therefore may not be available in some high-level languages.
Many modern operating systems use doubly linked lists to maintain references to
active processes, threads, and other dynamic objects.A common strategy for rootkits to evade
detection is to unlink themselves from these lists.
3.Circular Linked list
In the last node of a list, the link field often contains a null reference, a special value used
to indicate the lack of further nodes. A less common convention is to make it point to the first
node of the list; in that case the list is said to be 'circular' or 'circularly linked'; otherwise it is
said to be 'open' or 'linear'.

A circular linked list


Explain the following single linked list operations:

8 a.Insertion of a node [L2][CO6] [12M]


b.Deletion of node
c.Searching an element
Linked list :A linked list is a linear collection of data elements, called nodes, pointing to the
next node by means of a pointer. It is a data structure consisting of a group of nodes which
together represent a sequence.

Linked lists are among the simplest and most common data structures. They can be used to
implement several other common abstract data types,
including lists stacks, queues, associative arrays, and S-expressions, though it is not
uncommon to implement the other data structures directly without using a list as the basis of
implementation.
Course Code: 20CS0501 R20
Advantages:
 Linked lists are a dynamic data structure, which can grow and be pruned, allocating and
de allocating memory while the program is running.
 Insertion and deletion node operations are easily implemented in a linked list.
 Linear data structures such as stacks and queues are easily executed with a linked list.
 They can reduce access time and may expand in real time without memory overhead.
Disadvantages:
 They use more memory than arrays because of the storage used by their pointers.
 Nodes in a linked list must be read in order from the beginning as linked lists are
inherently sequential access.
 Nodes are stored in contiguously, greatly increasing the time required to access individual
elements within the list, especially with a CPU cache.
 Difficulties arise in linked lists when it comes to reverse traversing. For instance, singly
linked lists are cumbersome to navigate backwards. and while doubly linked lists are
somewhat easier to read, memory is wasted in allocating space for a back-pointer.
Linked list Types:
1. Singly linked list
2. Doubly linked list
3. Circular Linked list
1.Singly linked list:
Singly linked lists contain nodes which have a data field as well as a 'next' field, which
points to the next node in line of nodes. Operations that can be performed on singly linked
lists include insertion, deletion and traversal.
A singly linked list whose nodes contain two fields: an integer value and a link to the next
node

2.Doubly linked list


Main article: Doubly linked list
In a 'doubly linked list', each node contains, besides the next-node link, a second link
field pointing to the 'previous' node in the sequence. The two links may be called 'forward('s')
and 'backwards', or 'next' and 'prev'('previous').

A doubly linked list whose nodes contain three fields: an integer value, the link forward to the
next node, and the link backward to the previous node
A technique known as XOR-linking allows a doubly linked list to be implemented
using a single link field in each node. However, this technique requires the ability to do bit
operations on addresses, and therefore may not be available in some high-level languages.
Many modern operating systems use doubly linked lists to maintain references to
active processes, threads, and other dynamic objects.A common strategy for rootkits to evade
detection is to unlink themselves from these lists.
3.Circular Linked list
In the last node of a list, the link field often contains a null reference, a special value used
to indicate the lack of further nodes. A less common convention is to make it point to the first
node of the list; in that case the list is said to be 'circular' or 'circularly linked'; otherwise it is
said to be 'open' or 'linear'.
Course Code: 20CS0501 R20

A circular linked list

Explain the following operations in double linked list


i) Create an emptylist
ii) Inserttheelements10and20atthefront ofthelist.
9 [L2][CO6] [12M]
iii) Insert the element 30 at the middle of the list.
iv) Insert the element 15, 45 at the end of thelist.
v) Delete the middle element from the list.
// Linked list operations in C
#include <stdio.h>
#include <stdlib.h>
// Create a node
struct Node {
int data;
struct Node* next;
};
// Insert at the beginning
void insertAtBeginning(struct Node** head_ref, int new_data) {
// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the data


new_node->data = new_data;
new_node->next = (*head_ref);
// Move head to new node
(*head_ref) = new_node;
}
// Insert a node after a node
void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
printf("the given previous node cannot be NULL");
return;
}
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}
// Insert the the end
void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL) last = last->next;
last->next = new_node;
return;
}
// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;
if (temp != NULL && temp->data == key) {
Course Code: 20CS0501 R20
*head_ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
// If the key is not present
if (temp == NULL) return;
// Remove the node
prev->next = temp->next;
free(temp);
}
// Search a node
int searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;
while (current != NULL) {
if (current->data == key) return 1;
current = current->next;
}
return 0;
}
// Sort the linked list
void sortLinkedList(struct Node** head_ref) {
struct Node *current = *head_ref, *index = NULL;
int temp;
if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;
while (index != NULL) {
if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}
// Print the linked list
void printList(struct Node* node) {
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}
// Driver program
int main() {
struct Node* head = NULL;
insertAtEnd(&head, 10);
insertAtBeginning(&head, 20);
insertAtBeginning(&head, 30);
insertAtEnd(&head, 15);
insertAfter(head->next, 45);
Course Code: 20CS0501 R20
printf("Linked list: ");
printList(head);
printf("\nAfter deleting an element: ");
deleteNode(&head, 30);
printList(head);
int item_to_find = 30;
if (searchNode(&head, item_to_find)) {
printf("\n%d is found", item_to_find);
} else {
printf("\n%d is not found", item_to_find);
}
sortLinkedList(&head);
printf("\nSorted List: ");
printList(head);
}
Output:
Linked list: 30 20 45 10 15
After deleting an element: 20 45 10 15
30 is not found
Sorted List: 10 15 20 45
Explain briefly about circular linked list and circular double linked list with suitable
10 [L2][CO6] [12M]
example.
Circular Linked List
A circular linked list is a type of linked list in which the first and the last nodes are also
connected to each other to form a circle.
There are basically two types of circular linked list:

1. Circular Singly Linked List

Here, the address of the last node consists of the address of the first node.

2. Circular Doubly Linked List


Here, in addition to the last node storing the address of the first node, the first node will also
store the address of the last node.

1. Circular Singly Linked List

In circular linked list the pointer of the last node points to the first node. It can be
implemented as
o Singly linked circular list
o Doubly linked circular list
Singly linked circular list
Structure Declaration
struct node
{
int Element;
struct node *Next;
};
Routine to insert an element in the beginning
Course Code: 20CS0501 R20
void Insert_beg(int X, List L)
{
struct node *Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode !=NULL)
{
Newnode→Element=x;
Newnode→Next=L→Next;
L→Next= Newnode;
}
}
Routine to insert an element in the middle
void Insert_mid(int X, List L,Position P)
{
struct node *Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode !=NULL)
{
Newnode→Element=x;
Newnode→Next=P→Next;
P→Next= Newnode;
}
}
Routine to insert an element in the last
void Insert_last(int X, List L)
{
struct node *Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode !=NULL)
{
P=L;
while(P→Next!=L)
P=P→Next;
Newnode→Element=x;
P→Next= Newnode;
Newnode→Next=L;
}
}

Routine to delete an element from the beginning


void dele_First(List L)
{
Position Temp;
Temp= L→Next;
L→Next= Temp→Next;
free(Temp);
}
Routine to delete an element from the middle
void dele_mid(int X,List L)
{
Position P,Temp;
P=FindPrevious(X,L);
if(!isLast(P,L))
{
Temp= P→Next;
P→Next= Temp→Next;
free(Temp);
}
}
Routine to delete an element in the last
Course Code: 20CS0501 R20
void dele_last(int X, List L)
{
Position P,Temp;
P=L;
while(P→Next→Next!=L)
P=P→Next;
Temp=P→Next;
P→Next= L;
Free(Temp);
}
2.Circular Doubly Linked List
A doubly linked circular list is a doubly linked list in which the forward link of the last
node points to the first node and backward link of the first node points to the last node of the
list.
Structure Declaration
struct node
{
int Element;
struct node *FLINK;
struct node *BLINK;
};
Routine to insert an element at the beginning
void Insert_beg(int X, List L)
{
Position Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode!=NULL)
{
Newnode→Element = X;
Newnode→Flink = L→Flink;
L→Flink→Blink = Newnode;
L→Flink = Newnode;
Newnode →Blink=L;
}
}
Routine to insert an element in the middle
void Insert_mid(int X, List L,Position P)
Position Newnode;
Newnode=malloc(sizeof(struct node));
if(Newnode!=NULL)
{
Newnode→Element = X;
Newnode→Flink = P→Flink;
P→Flink→Blink = Newnode;
P→Flink = Newnode;
Newnode →Blink=P;
}
}
Routine to insert an element at the last
void Insert_last(int X, List L)
{
Position Newnode,P;
Newnode=malloc(sizeof(struct node));
if(Newnode!=NULL)
{
P=L;
While(P→Flink!=NULL)
P= P→Flink;
Newnode→Element = X;
P→Flink = Newnode;
Newnode→Flink = L;
Course Code: 20CS0501 R20
Newnode →Blink=P;
L→Blink = Newnode;
}
}
Routine to delete an element from the beginning
void dele_first(List L)
{
Position Temp;
if(L→Flink! = NULL)
{
Temp= L→Flink ;
L→Flink = Temp→Flink;
Temp→Flink→Blink = L;
free(Temp);
}
}
Routine to delete an element from the middle
void dele_mid(int X,List L)
{
Position P,Temp;
P=FindPrevious(X);
if(!isLast(P,L)
{
Temp= P→Flink ;
P→Flink = Temp→Flink;
Temp→Flink→Blink = P;
free(Temp);
}
}
Routine to delete an element from the last
void dele_last(List L)
{
Position Temp;
P=L;
While(P→Flink!= L)
P= P→Flink;
Temp= P;
P→Blink →Flink = L;
L→Blink = P→Blink;
free(Temp);
}
Course Code: 20CS0501 R20

UNIT –V
SEARCHING and SORTING

1 a Compare binary search and linear search techniques. [L4][CO1] [6M]


Linear Search Binary Search
In linear search input data need not to In binary search input data need to be
be in sorted. in sorted order.
It is also called sequential search. It is also called half-interval search.
The time complexity of linear The time complexity of binary
search O(n). search O(log n).
Multidimensional array can be used. Only single dimensional array is used.
Linear search performs equality Binary search performs ordering
comparisons comparisons
It is less complex. It is more complex.
It is very slow process. It is very fast process.
b Explain Linear Search with Algorithm? [L4][CO2] [6M]
Linear search is a very simple search algorithm. In this type of search, a sequential
search is made over all items one by one. Every item is checked and if a match is
found then that particular item is returned, otherwise the search continues till the end
of the data collection.

Algorithm

Linear Search ( Array A, Value x)

Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Course Code: 20CS0501 R20

What do you mean by Searching? Explain sequential search and binary search
2 [L3][CO6] [12M]
with suitable example.
Searching:
 Searching is the process of finding a given value position in a list of values.
 It decides whether a search key is present in the data or not.
 It is the algorithmic process of finding a particular item in a collection of items.
 It can be done on internal data structure or on external data structure.

Searching Techniques

To search an element in a given array, it can be done in following ways:

1. Sequential Search
2. Binary Search

1. Sequential Search
 Sequential search is also called as Linear Search.
 Sequential search starts at the beginning of the list and checks every element of the list.
 It is a basic and simple search algorithm.
 Sequential search compares the element with all the other elements given in the list. If
the element is matched, it returns the value index, else it returns -1.
Course Code: 20CS0501 R20

The above figure shows how sequential search works. It searches an element or value
from an array till the desired element or value is not found. If we search the element 25,
it will go step by step in a sequence order. It searches in a sequence order. Sequential
search is applied on the unsorted or unordered list when there are fewer elements in a
list.

The following code snippet shows the sequential search operation:

function searchValue(value, target)


{
for (var i = 0; i < value.length; i++)
{
if (value[i] == target)
{
return i;
}
}
return -1;
}
searchValue([10, 5, 15, 20, 25, 35] , 25); // Call the function with array and number to
be searched

Example: Program for Sequential Search

#include <stdio.h>
int main()
{
int arr[50], search, cnt, num;
printf("Enter the number of elements in array\n");
scanf("%d",&num);
printf("Enter %d integer(s)\n", num);
for (cnt = 0; cnt < num; cnt++)
scanf("%d", &arr[cnt]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (cnt = 0; cnt < num; cnt++)
{
if (arr[cnt] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, cnt+1);
break;
}
}
if (cnt == num)
printf("%d is not present in array.\n", search);

return 0;
}
Output:
Course Code: 20CS0501 R20

2. Binary Search
 Binary Search is used for searching an element in a sorted array.
 It is a fast search algorithm with run-time complexity of O(log n).
 Binary search works on the principle of divide and conquer.
 This searching technique looks for a particular element by comparing the middle most
element of the collection.
 It is useful when there are large number of elements in an array.

 The above array is sorted in ascending order. As we know binary search is applied on
sorted lists only for fast searching.
For example, if searching an element 25 in the 7-element array, following figure shows
how binary search works:

Binary searching starts with middle element. If the element is equal to the element that
we are searching then return true. If the element is less than then move to the right of the
list or if the element is greater than then move to the left of the list. Repeat this, till you
find an element.

Example: Program for Binary Search

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

void main()
{
int f, l, m, size, i, sElement, list[50]; //int f, l ,m : First, Last, Middle
clrscr();
printf("Enter the size of the list: ");
scanf("%d",&size);
printf("Enter %d integer values : \n", size);
for (i = 0; i < size; i++)
scanf("%d",&list[i]);
Course Code: 20CS0501 R20
printf("Enter value to be search: ");
scanf("%d", &sElement);
f = 0;
l = size - 1;
m = (f+l)/2;

while (f <= l) {
if (list[m] < sElement)
f = m + 1;
else if (list[m] == sElement) {
printf("Element found at index %d.\n",m);
break;
}
else
l = m - 1;
m = (f + l)/2;
}
if (f > l)
printf("Element Not found in the list.");
getch();
}

Output:

Enter the size of the list :5


Enter 5 integer values
10
30
20
50
40
Enter value to be search:20
Element found at index 2.
3 Write binary search algorithm for finding given element is in the list or not. [L6][CO6] [12M]
Searching is the process of finding some particular element in the list. If the element is
present in the list, then the process is called successful, and the process returns the
location of that element. Otherwise, the search is called unsuccessful.
Linear Search and Binary Search are the two popular searching techniques. Here we will
discuss the Binary Search Algorithm.
Binary search is the search technique that works efficiently on sorted lists. Hence, to
search an element into some list using the binary search technique, we must ensure that
the list is sorted.
Binary search follows the divide and conquer approach in which the list is divided into
two halves, and the item is compared with the middle element of the list. If the match is
found then, the location of the middle element is returned. Otherwise, we search into
either of the halves depending upon the result produced through the match.
Algorithm
1. Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_bound'
is the index of the first array element, 'upper_bound' is the index of the last array elemen
t, 'val' is the value to search
2. Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
3. Step 2: repeat steps 3 and 4 while beg <=end
4. Step 3: set mid = (beg + end)/2
5. Step 4: if a[mid] = val
6. set pos = mid
7. print pos
8. go to step 6
9. else if a[mid] > val
10. set end = mid - 1
11. else
Course Code: 20CS0501 R20
12. set beg = mid + 1
13. [end of if]
14. [end of loop]
15. Step 5: if pos = -1
16. print "value is not present in the array"
17. [end of if]
18. Step 6: exit
Working of Binary search
Now, let's see the working of the Binary Search Algorithm.
To understand the working of the Binary search algorithm, let's take a sorted array. It
will be easy to understand the working of Binary search with an example.
There are two methods to implement the binary search algorithm -
o Iterative method
o Recursive method
The recursive method of binary search follows the divide and conquer approach.
Let the elements of array are -

Let the element to search is, K = 56


We have to use the below formula to calculate the mid of the array -
1. mid = (beg + end)/2
So, in the given array -
beg = 0
end = 8
mid = (0 + 8)/2 = 4. So, 4 is the mid of the array.

Now, the element to search is found. So algorithm will return the index of the element
matched.
4 Define sorting. Explain any three sorting techniques? [L4][CO2] [12M]
Course Code: 20CS0501 R20
An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate
place and then it has to be inserted there.
1. insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array). This algorithm is not suitable for large data sets as its
average and worst case complexity are of Ο(n2), where n is the number of items.

How Insertion Sort Works?


We take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-
list.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.

It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see
that the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the
sorted sub-list remains sorted after swapping.

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.

These values are not in a sorted order.

So we swap them.
Course Code: 20CS0501 R20
However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.

We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.

This process goes on until all the unsorted values are covered in a sorted sub-list. Now
we shall see some programming aspects of insertion sort.
Algorithm
Now we have a bigger picture of how this sorting technique works, so we can derive
simple steps by which we can achieve insertion sort.
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

2.Selection sort:
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place
comparison-based algorithm in which the list is divided into two parts, the sorted part at
the left end and the unsorted part at the right end. Initially, the sorted part is empty and
the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues
moving unsorted array boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case
complexities are of Ο(n2), where n is the number of items.

How Selection Sort Works?


Consider the following depicted array as an example.

For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the
lowest value.
Course Code: 20CS0501 R20

So we replace 14 with 10. After one iteration 10, which happens to be the minimum
value in the list, appears in the first position of the sorted list.

For the second position, where 33 is residing, we start scanning the rest of the list in a
linear manner.

We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.

After two iterations, two least values are positioned at the beginning in a sorted manner.

The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −
Course Code: 20CS0501 R20

Now, let us learn some programming aspects of selection sort.


Algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

3.Merge sort:
Merge sort is a sorting technique based on divide and conquer technique. With worst-
case time complexity being Ο(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted
manner.

How Merge Sort Works?


To understand merge sort, we take an unsorted array as the following −
Course Code: 20CS0501 R20
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.

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 −

Now we should learn some programming aspects of merge sorting.


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.
5 Discuss the algorithm to sort the elements using exchange sort. [L2][CO2] [12M]
The exchange sort is similar to its cousin, the bubble sort, in that it compares elements
of the array and swaps those that are out of order. (Some people refer to the "exchange
sort" as a "bubble sort".) The difference between these two sorts is the manner in which
they compare the elements. The exchange sort compares the first element with each
following element of the array, making any necessary swaps.
Course Code: 20CS0501 R20

When the first pass through the array is complete, the exchange sort then takes the
second element and compares it with each following element of the array swapping
elements that are out of order. This sorting process continues until the entire array is
ordered.

Let's examine our same table of elements again using an exchange sort for descending
order. Remember a "pass" is defined as one full trip through the array comparing and if
necessary, swapping elements

Array at beginning: 84 69 76 86 94 91
After Pass #1: 94 69 76 84 86 91
After Pass #2: 94 91 69 76 84 86
After Pass #3: 94 91 86 69 76 84
After Pass #4: 94 91 86 84 69 76
After Pass #5 (done): 94 91 86 84 76 69

The exchange sort, in some situations, is slightly more efficient than the bubble sort. It
is not necessary for the exchange sort to make that final complete pass needed by the
bubble sort to determine that it is finished.

//Exchange Sort Method for Descending Order (integers)


public static void ExchangeSort ( int [ ] num )
{
int i, j, temp; //be sure that the temp variable is the same "type" as the array
for ( i = 0; i < num.length - 1; i ++ )
{
for ( j = i + 1; j < num.length; j ++ )
{
if( num[ i ] < num[ j ] ) //sorting into descending order
{
temp = num[ i ]; //swapping
num[ i ] = num[ j ];
num[ j ] = temp;
}
}
}
}
When completed, the array will be in descending order and can be printed from
main.
Course Code: 20CS0501 R20
6 a Order the following numbers using merge sort : 45,34,12,46,27,56,11,87,6,33,28. [L4][CO6] [6M]

b Explain insertion sort with an example. [L3][CO6] [6M]


Insertion sort is a simple sorting algorithm that works similar to the way you sort
playing cards in your hands. The array is virtually split into a sorted and an
unsorted part. Values from the unsorted part are picked and placed at the correct
position in the sorted part.
Characteristics of Insertion Sort:
 This algorithm is one of the simplest algorithm with simple implementation
 Basically, Insertion sort is efficient for small data values
 Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are
already partially sorted.
Working of Insertion Sort algorithm:
Consider an example: arr[]: {12, 11, 13, 5, 6}
First Pass:
 Initially, the first two elements of the array are compared in insertion sort.

12 11 13 5 6

 Here, 12 is greater than 11 hence they are not in the ascending order and 12 is
not at its correct position. Thus, swap 11 and 12.
 So, for now 11 is stored in a sorted sub-array.

11 12 13 5 6

Second Pass:
 Now, move to the next two elements and compare them
Course Code: 20CS0501 R20
11 12 13 5 6

 Here, 13 is greater than 12, thus both elements seems to be in ascending order,
hence, no swapping will occur. 12 also stored in a sorted sub-array along with
11
Third Pass:
 Now, two elements are present in the sorted sub-array which are 11 and 12
 Moving forward to the next two elements which are 13 and 5

11 12 13 5 6

 Both 5 and 13 are not present at their correct place so swap them

11 12 5 13 6

 After swapping, elements 12 and 5 are not sorted, thus swap again

6
11 5 12 13

Here, again 11 and 5 are not sorted, hence swap again

5 11 12 13 6

here, it is at its correct position


Fourth Pass:
 Now, the elements which are present in the sorted sub-array are 5, 11 and 12
 Moving to the next two elements 13 and 6

5 11 12 13 6

 Clearly, they are not sorted, thus perform swap between both

5 11 12 6 13

 Now, 6 is smaller than 12, hence, swap again

5 11 6 12 13

 Here, also swapping makes 11 and 6 unsorted hence, swap again

5 6 11 12 13

 Finally, the array is completely sorted.


Course Code: 20CS0501 R20
7 Sort the following numbers using selection sort : 45,25,10,2,9,85,102,1 [L4][CO6] [12M]
Course Code: 20CS0501 R20
8 Explain the algorithm for merge sort and give a suitable example. [L3][CO6] [12M]
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.
How Merge Sort Works?
To understand merge sort, we take an unsorted array as the following −

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.

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 −

Now we should learn some programming aspects of merge sorting.


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.

9 Explain the algorithm for quick sort and give a suitable example. [L5][CO6] [12M]
Quick sort is a fast sorting algorithm used to sort a list of elements. Quick sort algorithm
is inventedby C.A.R.Hoare.
The quick sort algorithm attempts to separate the list of elements into two parts and then
Course Code: 20CS0501 R20
sort each part recursively. That means it use divide and conquer strategy. In quick sort,
the partition of the list is performed based on the element called pivot. Here pivot
element is one of the elements in the list.

The list is divided into two partitions such that "all elements to the left of pivot are
smaller than the pivot and all elements to the right of pivot are greater than or
equal to the pivot".
Step by Step Process
In Quick sort algorithm, partitioning of the list is performed using following steps...

 Step 1 - Consider the first element of the list as pivot (i.e., Element at first
position in the list).
 Step 2 - Define two variables i and j. Set i and j to first and last elements of the
list respectively.
 Step 3 - Increment i until list[i] > pivot then stop.
 Step 4 - Decrement j until list[j] < pivot then stop.
 Step 5 - If i < j then exchange list[i] and list[j].
 Step 6 - Repeat steps 3,4& 5 until i > j.
 Step 7 - Exchange the pivot element with list[j] element.

Following is the sample code for Quick sort...


Quick Sort Logic
//Quick Sort Logic
void quickSort(int list[10],int first,int last){
int pivot,i,j,temp;

if(first < last){


pivot = first;
i = first;
j = last;

while(i < j){


while(list[i] <= list[pivot] && i < last)
i++;
while(list[j] && list[pivot])
j--;
if(i < j){
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}

temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
quickSort(list,first,j-1);
quickSort(list,j+1,last);
}
}

Example:
Course Code: 20CS0501 R20
Course Code: 20CS0501 R20
10 a Explain the difference between merge sort and quick sort. [L5][CO2] [6M]
Basis For Comparison Quick Sort Merge Sort
Partitioning of the The splitting of a list of Array is always
elements in the array elements is not divided into half (n/2).
necessarily divided into
half.
Worst case complexity O(n2) O(n log n)
Works well on Smaller array Operates fine in any
type of array.
Speed Faster than other sorting Consistent speed in all
algorithms for small data type of data sets.
set.
Additional storage space Less More
requirement
Efficiency Inefficient for larger More efficient
arrays.
Sorting method Internal External
b Sort the following numbers using selection sort : 24,9,29,14,19,27,50,10,30 [L4][CO6] [6M]

Prepared by: Dr.E.Murali,P.Devaki,G.Ravi Kumar,D.Janani.

You might also like