Bs1 CDS QB WITH ANSWER
Bs1 CDS QB WITH ANSWER
Bs1 CDS QB WITH ANSWER
UNIT –I
INTRODUCTION TO C LANGUAGE
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);
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.
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
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
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
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:
Output:
Types of Functions:
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:
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
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.
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
#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:
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;
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]
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:
#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
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:
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:
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:
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:
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.
[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.
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
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
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;
}
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()
{
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()
{
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);
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]
8 Define union and give the general syntax for union. Write a suitable
a [L3][CO2] [6M]
example.
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
#include<stdio.h>
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");
}
}
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
-1 Stack is 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.
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.
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
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
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.
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.
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.
Circular Queue
In a circular queue, the last element points to the first element making a circular link.
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
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'.
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
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
Here, the address of the last node consists of the address of the first node.
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;
}
}
UNIT –V
SEARCHING and SORTING
Algorithm
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
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.
#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.
#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:
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.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-
list.
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.
So we swap them.
Course Code: 20CS0501 R20
However, swapping makes 27 and 10 unsorted.
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.
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
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.
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 −
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.
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
5 11 12 13 6
5 11 12 13 6
Clearly, they are not sorted, thus perform swap between both
5 11 12 6 13
5 11 6 12 13
5 6 11 12 13
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 −
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.
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]