Programming and Data Structures I
Programming and Data Structures I
Programming and Data Structures I
A Course Material
on
Programming and Data Structures I
By
S.Archana
Assistant Professor
Computer Science and Engineering Department
Quality Certificate
Subject Code:CS6202
Year/Sem:I/II
Name: Mrs.S.Archana
This is to certify that the course material being prepared by Mrs.S.Archana is of the
adequate quality. She has referred more than five books and one among them is from
abroad author.
Seal: Seal:
SYLLABUS
OBJECTIVES:
OUTCOMES:
CONTENTS
1 Unit – I 7
2 Unit – II 48
3 Unit – III 86
4 Unit – IV 124
5 Unit – V 148
Prequiste
UNIT I
C PROGRAMMING FUNDAMENTALS- A REVIEW
PART-A
{
i++;
}while(i<=100);Here the value of i is incremented and then the condition is checked.
Example:
int fact(int n)
{
if(n==0||n==1)
return 1;
else
return(n*fact(n-1));
}
uses more memory than iteration Iteration consume less memory Recursion makes
code smaller Iteration makes code longer.
13. What are function pointers in C? Explain with example April/May 2015[CO1,L2]
A pointer to a function commonly known as function pointer is a variable that points to
the starting address of the function.
Example:
int(*ptr)(int)=fun;
fun is the name of the function the address of which is assigned to the pointer. fun can
be called as (*ptr)(5);
14. With the help of printf function show how C handles functions with variable
number of arguments. May/June 2014[CO1,L1]
A function that accepts a variable number of arguments is called a variable argument
function. printf is a variable argument function which accepts one or more arguments ,
first one being char * and no constraint on the remaining type of arguments. The
following calls are valid:
printf("Hello\n"); Displays Hello
printf("%d",a); Displays integer value of a
printf(%d %f",a,b); Displays integer a and floating point b
15. What are the macros used in variable argument functions? [CO1,L1]
va_list
va_start
va_arg
va_end
They are available in stdarg.h
PART-B
1. CONDITIONAL STATEMENTS
Explain the various conditional statements in C language with example in detail
Nov/Dec2014/ Nov/Dec 2015 [CO1,L2]
Conditional statements(Branching statements) are used to execute a statement or a
group of statement based on certain conditions. The ability to control the flow of our
program, letting it make decisions on what code to execute, is valuable to the
programmer. One of the important functions of the conditional statement is that it allows
the program to select an action based upon the user's input.
Following are the conditional statements:
if
if else
else if
switch
goto
IF STATEMENT
If the test expression is true then, statements for the body if, i.e, statements inside
parenthesis are executed. But, if the test expression is false, the execution of the
statements for the body of if statements are skipped.
Syntax:
if (test expression){
statement/s to be executed if test expression is true;
}
Flowchart:
Example of if statement:
Write a C program to print the number entered by user only if the number entered
is
negative.
#include <stdio.h>
void main()
{
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);
if(num<0) /* checking whether number is less than 0 or not. */
printf("Number=%d\n",num);
/*If test condition is true, statement above will be executed, otherwise it will not be
executed */
IF ..ELSE:
The if...else statement is used, if the programmer wants to execute some code, if the
test expression is true and execute some other code if the test expression is false.
Syntax of if...else:
if (test expression)
statements to be executed if test expression is true;
else
statements to be executed if test expression is false;
Flowchart of if...else statement:
}
Output 1
Enter a number you want to check.
25
25 is odd.
Output 2
Enter a number you want to check.
2
2 is even.
printf("Result: %d>%d",numb1,numb2);
elseprintf("Result: %d>%d",numb2,numb1);
}
Output 1
Enter two integers to check.
5
3
Result: 5>3
Output 2
Enter two integers to check.
-4
-4
Result: -4=-4
SWITCH....CASE STATEMENT:
If a programmar has to choose one among many alternatives if...else can be used but,
this makes programming logic complex. This type of problem can be handled in C
programming using switch...case statement.
Syntax of switch...case:
switch (expression)
{
case constant1:
codes to be executed if expression equals to constant1;
break;
case constant2:
codes to be executed if expression equals to constant3;
break;
.
default:
codes to be executed if expression doesn't match to any cases;
}
In switch...case, expression is either an integer or a character. If the value of switch
expression matches any of the constant in case, the relevant codes are executed and
control
moves out of the switch...case statement. If the expression doesn't match any of the
constant
in case, then the statements in the default section are executed.
Example of switch...case statement:
Write a program that asks user an arithmetic operator('+','-','*' or '/') and two
operands and perform the corresponding calculation on the operands.
/* C program to demonstrate the working of switch...case statement */
/* Program to create a simple calculator for addition, subtraction, multiplication and
division
*/
# include <stdio.h>
int main(){
char operator;
float num1,num2;
printf("Enter operator +, - , * or / :\n");
operator=getche();
printf("\nEnter two operands:\n");
scanf("%f%f",&num1,&num2);
switch(operator)
{
case '+':
printf("num1+num2=%.2f",num1+num2);
break;
case '-':
printf("num1-num2=%.2f",num1-num2);
break;
case '*':
printf("num1*num2=%.2f",num1*num2);
break;
case '/':
printf("num2/num1=%.2f",num1/num2);
break;
default:
/* if operator is other than +, -, * or /, error message is shown */
printf(Error! operator is not correct");
break;
}
return 0;
}
break;
}
return 0;
}
OUTPUT:
Enter operator +, -, * or / :
/
Enter two operators:
34
3
num2/num1=11.33
Notice break statement at the end of each case, which cause switch...case statement to
exit. If break statement is not used, all statements below that case statement are also
executed.
GOTO:
In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
Syntax of goto statement:
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto
statement,the control of the program will jump to the label: and executes the code/s
after it.
Example of goto statement:
/* C program to demonstrate the working of goto statement. It finds the average of the
given numbers after a negative number is encountered or after the total count is
reached*/
# include <stdio.h>
void main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program jumps to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
}
Output:
Maximum no. of inputs: 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average: 7.07
2. CONTROL STATEMENTS
Explain the various control statements in C language with example in detail
Nov/Dec 2014[CO1,L2]
Control statements enable us to specify the flow of program control; ie, the order in
which the instructions in a program must be executed. They make it possible to make
decisions, to perform tasks repeatedly or to jump from one section of code to another.
They are as follows:
1. Branching statements(Discussed above)
2. Iteration(or)Looping statements
3. Jump statements
Iteration statements:
Iteration statements are used to execute a particular set of instructions repeatedly until
a particular condition is met or for a fixed number of iterations.
THE FOR STATEMENT:
The for statement or the for loop repeatedly executes the set of instructions that
comprise the
body of the for loop until a particular condition is satisfied.
Syntax:
for(initialization; termination; increment/decrement)
{
//statements to be executed
}
The initialization expression, which initializes the looping index. The looping index
controls the looping action. The initialization expression is executed only once, when the
loop begins.
The termination expression, which represents a condition that must be true for the
loop to continue execution. The increment/decrement expression is executed after
every iteration to update the value of the looping index.
The following program uses the for loop to print the Fibonacci series: 0,1,1,2,3,5,8,13 …
to n terms.
#include<stdio.h>
int main()
{
int i,n, a, b, sum=0;
printf("Enter the number of terms:");
scanf("%d",&n); a=0; b=1;
printf("%d %d",a,b);
for(i=2;i<n;i++)
{
sum=a+b;
printf(" %d",sum);
a=b;
b=sum;
}
return 0;
}
Output:
Enter the number of terms:
5
01123
{
int n, a,sum=0;
printf("\n Enter a number:");
scanf("%d", &n);
while(n>0)
{
a=n%10; //extract the digits of the number
sum=sum+a; //sum the digits
n=n/10; //calculate the quotient of a number when divided by 10.
}
printf("\n Sum of the digits=\t %d",sum);
return 0;
}
Output:
Enter a number
123
Sum of the digits= 6
The above program uses the while loop to calculate the sum of the digits of a number.
int n, a,sum=0;
printf("n Enter a number:");
scanf("%d", &n);
do
{
a=n%10;
sum=sum+a;
n=n/10;
}while(n>0);
printf("n Sum of the digits=t %d",sum);
return 0;
}
Output:
Enter a number
123
Sum of the digits = 6
However, the do-while statement should be used only in situations where the loop must
execute atleast once whether or not the condition is true.A practical use of the do-while
loop is in an interactive menu-driven program where the menu is presented at least
once, and then depending upon the choice of the user, the menu is displayed again or
the session is terminated.
Jump statements:
Break statement:
The syntax of break statement is break;The break statement can appear only inside or
as a body of a switch statement or a loop. A break statement terminates the execution
of the nearest enclosing switch or the nearest enclosing loop. The execution resumes
with the statement present next to the terminated switch statement or the terminated
loop.
Example 1:
#include<stdio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
break;
printf(―%d ‖,i);
}
if(i<11)
printf(―\nPremature termination\n‖);
}
Output:
1234
Premature termination
Example 2:
/* Program to check whether the no is prime or not*/
#include<stdio.h>
main()
{
int n,i;
printf(―Enter the number\n‖);
scanf(―%d‖,&n);
for(i=2;i<n;i++)
{
if(n%i==0)/*check if divisible by any no represented by i*/
break;
}
if(i==n)
printf(―N umber is prime\n‖);
else
printf(―Number is not prime\n‖);
}
Output:
Enter the number 9
Number is not prime
Continue Statement:
Syntax:
The syntax of the continue statement is
continue;
A continue statement terminates the current iteration of the loop. On execution of the
continue statement the program control is immediately transferred to the header of the
loop.
Example:
/*Program to display the odd numbers from 1 to 10*/
#include<stdio.h>
main()
{
int i;
for(i=1;i<=10;i++)
{
if(i%2==0)
continue;
printf(―%d ―,i);
}
}
Output:
13579
For even numbers, the printf statement is ignored and therefore odd numbers are only
displayed.
3. TYPES OF FUNCTIONS
a. What are functions? Explain the different types of functions with
examples[CO1,L2]
A function is a self contained program segment that carries out some specific, well
defined task. A function takes some data from main () and returns a value.There are two
types of function.
They are:
· Library function: Library functions are the in-built function in C programming system.
For example:printf()
· User defined function: C allows programmer to define their own function according to
their requirement. These types of functions are known as user-defined functions.
For example: sum().
Elements of user defined function: In order to write an efficient user defined
function,the programmer must be familiar the following three elements:
Function Declaration: Like the normal variable the function must be declared before it
is defined and called or invoked.
Syntax :
return_type function_name(arg1, arg2,..........)
Example : int add(int x, int y); OR int add(int,int);
b. Function Definition: It is the process of specifying and establishing the user defined
function by specifying all its elements and characteristics.
Syntax:
return_type function_name(arg1,arg2............)
{
Local variable declaration
___________
Body of the function
___________
Return(expr);
}
Example:
int add(int a,int b)
{
int c;
c=a+b;
return(c);
}
Function Call: The function can be simply called by specifying the name of the
function,return value and parameters if present.
Syntax:
function_name();
OR
function_name(arg1,arg2..............)
OR
return_value=function_name(arg1,arg2..............);
Example:
add();
OR
add(x,y);
OR
z=add(x,y);
Every C program begins from main() and program starts executing the codes inside
main() function. When the control of program reaches to function_name() inside
main()function.
The control of the program jumps to void function_name() and executes the codes
inside it.When all the codes inside that user-defined function are executed, control of
the program jumps to the statement just after function_name() from where it is called as
given below:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int c,a,b;
int add(int,int);
clrscr();
printf("Enter the values of a and b to perform addition:");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The sum is %d",c);
getch();
}
int add(int a1, int b1)
{
return(a1+b1);
}
Output:
Enter the values of a and b to perform addition: 2 3
The sum is 5
The user defined functions can be broadly classified into four types as below:
void add()
{
int a,b,c;
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
c=a+b;
printf("The addition of %d and %d is %d", a,b,c);
}
Output:
Enter the values of a and b 2 3
The addition of 2 and 3 is 5
b. Function with argument and without return type: In this prototype data is
transferred from calling function to called function i.e. the called program receives some
data from the calling program and does not send back any value to the calling program.
Such functions are partly dependent on the calling function.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void add(int,int);
int a,b;
clrscr();
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
add(a,b);
getch();
}
void add(int a1,int b1)
{
int c;
c=a1+b1;
printf("The addition of %d and %d is %d", a1,b1,c);
}
Output:
Enter the values of a and b 2 3
The addition of 2 and 3 is 5
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int add(int,int);
int a,b,c;
clrscr();
printf("Enter the values of a and b");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The addition of %d and %d is %d",a,b,c);
getch();
}
int add(int a1,int b1)
{
return(a1+b1);
}
Output:
Enter the values of a and b 2 3
The addition of 2 and 3 is 5
d. Function without argument and with return type: In this prototype the calling
program cannot pass any argument to the called program but the called program may
send some return value to the calling program.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int add();
int c;
clrscr();
c=add();
12.4333
For example,
int add(int,int);
When the above function is declared the following statements are allowed
int(*atr)(int,int)=add;
(or)
int(*atr)(int,int);
atr=add;
5. ARRAYS
a. Write Short notes on array[CO1,L2]
C programming language provides a data structure called the array, which can store a
fixedsize sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of
variables of the same type. Instead of declaring individual variables, such as number0,
number1, ..., and number99,you declare one array variable such as numbers and use
numbers[0], numbers[1], and ...,numbers[99] to represent individual variables. A specific
element in an array is accessed by an index. All arrays consist of contiguous memory
locations. The lowest address corresponds to the first element and the highest address
to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows:
double balance[10];
Now balance is a variable array which is sufficient to hold upto 10 double numbers.
Initializing Arrays:
We can initialize array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of
elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is
created.
Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
Following is the pictorial representation of the same array we discussed above:
The above statement will take 10th element from the array and assign the value to
salary variable. Following is an example which will use all the above mentioned three
concepts viz.declaration, assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Two-dimensional array:
The array which is used to represent and store data in two dimensions called two
dimensional array.
Declaration of 2-d array
Syntax: <data type> <array name> [row size] [column size];
1 2 8 5 2 3 8 4 1 6 Unique Elements 1 2 8 5 3 4 6
iii. Write a C program to find sum of two matrix of order 2*2 using arrays. Get the
elements of matrix from the user. Nov/Dec 2015[CO1,L3]
#include<stdio.h>
main()
{
int a[2[2],b[2][2],c[2][2],i,j;
printf(―Enter the elements of the first matrix\n‖);//Get the first matrix
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(―%d‖,&a[i][j]);
}
}
printf(―Enter the elements of the second matrix\n‖);//Get the second matrix
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(―%d‖,&b[i][j]);
}
}
printf(―The resultant matrix after addition is:\n‖);//Addition of two matrices
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf(―%d\t‖,c[i][j]);
}
printf(―\n‖);
}
}
6. PREPROCESSOR OPERATORS
Explain the C preprocessor operators each with a neat example that is used to
create macros April/May 2015[CO1,L2]
The C Preprocessor is not part of the compiler, but is a separate step in the
compilation process.In simplistic terms, a C Preprocessor is just a text substitution tool
and they instruct compiler to do required pre-processing before actual compilation.
The important points for writing preprocessor directives are as follows :
All preprocessor commands begin with a pound symbol (#). It must be the first
Nonblank character.
A new line character ends the pre-processor directive.
Preprocessor directives can appear anywhere in a program but are generally placed
at the beginning of a program.
The pre-processor operates under the following pre-processor directives:
a. File inclusion
File inclusion directive tells the preprocessor to replace the directive with the content of
the file specified in the directive. It is used to include the header files which contains the
prototypes of the library functions and the definitions of the predefined constants..
#include<filename>:
It searches the prespecified list of directories for the source file and text embeds the
entire content of the source file in place of itself.
#include ―filename‖ :
It searches the file in the current working directory. If the search fails it is taken as
#include<filename>. If it still fails, it will show the error.
b. Macro substitution
A macro is a facility provided by the C preprocessor by which a token can be replaced
by the user-defined sequence of characters. Macros are defined with the help of the
define directive.The identifier name immediately following the define directive is called
the macro name.
Types of Macros:
Example:
#include<stdio.h>
#define PI 3.14
main()
{
int r=5;
printf(―Area of the circle is %f\n‖,PI*r*r);
}
Output:
Area of the circle is 78.5
Example:
#include<stdio.h>
#define SQR(x) ((x)*(x))
main()
{
int side=5;
printf(―Areaof the square is %d\n‖,SQR(side));
}
Output:
Area of the square is 25
c. Conditional compilation:
Conditional Compilation means that a part of a program is compiled only if a certain
condition comes out to be true. The available directives are as follows:
Example:
#include <stdio.h>
main()
{
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );
}
When the above code in a file test.c is compiled and executed, it produces the following
result:
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
7. C PROGRAMS
a. Write a C program to find all the roots of a quadratic equation. April/May
2015[CO1,L3]
#include <stdio.h>
#include <math.h> /* This is needed to use sqrt() function.*/
int main()
{
float a, b, c, determinant, r1,r2, real, imag;
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
determinant=b*b-4*a*c;
if (determinant>0)
{
r1= (-b+sqrt(determinant))/(2*a);
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
}
else if (determinant==0)
{
r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
}
else
{
real= -b/(2*a);
imag = sqrt(-determinant)/(2*a);
printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag);
}
return 0;
}
Output 1:
Enter coefficients a, b and c: 2.3
4
5.6
Roots are: -0.87+1.30i and -0.87-1.30i
Output 2:
Enter coefficients a, b and c: 4
1
0
Roots are: 0.00 and -0.25
}
return &a[index];
}
Output:
Input number of elements in array
5
Enter 5 double values
20.3
32.5
43.7
32.7
65.3
The maximum element is 65.3 present in address
void checkpalin(int n)
{
int temp=n,rem,reverse;
while(temp!=0)
{
rem=temp%10;
reverse=reverse*10+rem;
temp/=10;
}
/* Checking if number entered by user and it's reverse number is equal. */
if(reverse==n)
printf("%d is a palindrome.",n);
else
printf("%d is not a palindrome.",n);
}
}
}
}
void main()
{
int a[10][10],b[10][10],r1,c1,r2,c2,i,j;
int (*p)(int [][10],int[][10],int,int,int,int)=multiply;
printf(―Enter the no. of rows and columns of first matrix\n‖);
scanf(―%d %d‖,&r1,&c1);
printf(―Enter the no. of rows and columns of second matrix\n‖);
scanf(―%d %d‖,&r2,&c2);
printf(―Enter the elements of the first matrix\n‖);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf(―%d‖,&a[i][j]);
}
}
printf(―Enter the elements of the second matrix\n‖);
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf(―%d‖,&b[i][j]);
}
}
(*p)(a,b,r1,c1,r2,c2);
}
Output:
Enter the no. of rows and columns of first matrix
2
2
Enter the no. of rows and columns of second matrix
2
3
Enter the elements of the first matrix
1111
Enter the elements of the second matrix
UNIT-II
C PROGRAMMING ADVANCED FEATURES
PART-A
1. Compare arrays and structures.[CO2,H1]
Arrays Structures
An array is a collection of data items of same data type.A structure is a collection of
data items of different data types.Arrays can only be declared. Structures can be
declared and defined.There is no keyword for arrays. The keyword for structures is
struct An array name represents the address of the starting element.A structure name is
known as tag.int a[10]; struct student
{
int rno;
char name[20];
};
union student
{
int rno;
char name[20];
};--Memory is allocated for 20 bytes alone.
Structures and Unions - File handling concepts – File read – write – binary and Stdio -
File Manipulations
Example: struct result
{
int marks;
float avg;
char grade;
}std;
9. Define fseek()?[CO2,L1]
fseek() will position the file pointer to a particular byte within the file. The file pointer is a
parameter maintained by the operating system and determines where the next read will
come from or to where the next write will go.int fseek(FILE *fp, long int offset, int
whence)
fp − This is the pointer to a FILE object that identifies the stream.
offset − This is the number of bytes to offset from whence.
Whence − This is the position from where offset is added
(SEEK_SET,SEEK_CUR,SEEK_END)
13. What is the functions used to move the file pointer to the beginning of the file
and to know the current position of the file pointer? [CO2,L1]
rewind(fp); - Move the pointer fp to the beginning of the file
ftell(fp): - Tells the current position of the file pointer fp
14. What are the statement used for reading a file?. Write a simple program to
read the numbers from a file and display numbers. Nov/Dec 2014/Nov/Dec
2015[CO2,L3]
fscanf(fp,format specifier,arguments);
fp - File pointer referring to the file from which the content is read.
Program:
#include<stdio.h>
void main()
{
int n;
FILE *fp;
fp=fopen(―Input.txt‖,‖r‖);
while(!feof(fp))
{
fscanf(fp,‖%d‖,&n);
printf(―%d\n‖,n);
}}
15. What is the difference between getc() and getchar()? Explain. April/May
2015[CO2,H1]
The difference between getchar()and getc(FILE *stream)is that, getc can read input
from any stream, while getchar can only read from the standard input. Thus you can say
that getchar()=getc(stdin).
PART-B
1. STRUCTURES
Explain the concept of structures with example. Nov/Dec 2014[CO2,L2]
Structures:
A structure is a collection of variables under a single name and provides a convenient
way of grouping several pieces of related information together. Unlike arrays, it can be
used for the storage of heterogenous data. There are three aspects of working with
structures:
1. Defining a structure type, i.e., creating a new data type
2. Declaring variables of the new data type
3. Using and performing operations on the objects of the structure type.
1. Defining a structure:
Syntax:
struct tag_name
{
type member_name1;
type member_name2;
…..
}variable name;
A structure definition consists of keyword struct followed by an identifier known as tag-
name and structure declaration list enclosed within the braces. The newly created type
is visible,after its definition, only in the scope in which it is defined. Structure declaration
list consists of declarations of one or more variables of different types known as
structure members or fields.
Example:
struct book
{
char title[25];
char author[20];
int pages;
float price;
};
Two different structure types may contain members of the same name without any
conflict.Structure definition does not reserve any space in the memory. It is not possible
to initialize the members during definition.
int pages;
float price;
}b1,b2;
(or)
struct book
{
char title[25];
char author[20];
int pages;
float price;
};
struct book b1,b2;
b1 and b2 are declared as structure variables. The members of a structure object can
be initialized using initialization list. The order of initializers must match the order of
structure members in the structure definition.
struct book b={"ABC","XYZ",200,320.50};
Operations on structures:
Operations are classified into two categories:
1. Aggregate Operations:
It treats an operand as an entity and operates on the entire operand as a whole instead
of operating on its constituent members. The four aggregate operations are
i. Accessing members:
Direct member access operator(dot operator)
Syntax:
structure_object_name.structure_member_name
The members can be accessed by using dot operator along with variable name like b1.
title to refer to the title of the variable book b1.
ii. Assigning a structure object to a structure variable
A structure variable can be assigned with or initialized with a structure object. The
assignment operator assigns values of all the members of the object on its right side to
the corresponding members of the structure variable on the left side.
#include<stdio.h>
struct book
{
char title[25];
char author[20];
int price;
};
main()
{
struct book b1={"ABC","XYZ",200};
struct book b2=b1;//b1 members are copied one by one to b2.
}
2. Segregate operations:
Operations on individual members can be performed as like normal objects as shown in
the following example. The given example is to create two book structure variables and
increase the number of pages and price accordingly.
struct book
{
char title[25];
char author[20];
int pages;
float price;
};
main()
{
struct book b1,b2;
printf(―Enter the title,author,pages and price of book1\n‖);
gets(b1.title);
gets(b1.author);
scanf(―%d %f‖,&b1.pages,&b1.price);
printf(―Enter the title,author,pages and price of book2\n‖);
gets(b2.title);
gets(b2.author);
scanf(―%d %f‖,&b2.pages,&b2.price);
printf(―Pages are increased by 100\n‖);
printf(―Cost is increased by 10 %\n‖);
b1.pages+=100;
b2.pages+=100;
b1.price+=110/100*b1.price;
b2.price+=110/100*b2.price;
printf(―Book1 has %d pages\n‖,b1.pages);
printf(―Book1 price is %f \n‖,b1.price);
printf(―Book2 has %d pages\n‖,b2.pages);
{
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i)
{
printf("\nInformation for roll number %d:\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
return 0;
}
Output:
Enter information of students:
For roll number 1
Enter name: Tom
Enter marks: 98
For roll number 2
Enter name: Jerry
Enter marks: 89
.
.
.
Displaying information of students:
Information for roll number 1:
Name: Tom
Marks: 98
Pointers to structures:
The general form of declaring a pointer to structure is struct tag_name * identifier name
The address of the structure variable is assigned to the pointer and the members can
be accessed using indirect member access operator (->) also known as arrow operator.
The members can also be accessed using dot operator as shown in the following
example.
Example:
struct coord
{
int x,y;
};
main()
{
struct coord pt={2,3};
struct coord *ptr=&pt;// Pointer is declared
// Accessing of members through pointers
printf(―Co-ordinates are (%d,%d)\n‖,(*ptr).x,(*ptr).y);
printf(―Co-ordinates are (%d,%d)\n‖,ptr->x,ptr->y);
}
Output:
Coordinates are (2,3)
Coordinates are (2,3)
Advantages:
1. It is easier to manipulate the pointer to structures than manipulating structures
themselves. Passing a pointer to a structure as an argument to a function is efficient
compared to passing a structure to a function as the size of the pointer is less than the
actual variable.
2. Data structures use pointers to structures and particularly self-referential structures
which is a type of structure where it contains a pointer to an instance of itself.
Example:
struct node
{
int data;
struct node *ptr;
};
It refers to a node in data structure which contains a member as pointer to itself.
Nested Structures:
A structure can be nested within another structure. The member access operator is
used to access the members of structure members.
For example, name structure can be nested within phone book entry structure in any
one of the following two ways.
Example:
struct name
{
char fname[20];
char lname[20];
};
struct pb_entry
{
struct name pname;
char mobile_no[15];
};
Or
struct pb_entry
{
struct name
{
char fname[20];
char lname[20];
}pname;
char mobile_no[15];
};
/* The following code creates two phone book entries and displays the information*/
main()
{
struct pb_entry p1,p2;
printf(―Enter the name of person1\n‖);
/* Accessing the member of nested structure using dot operator*/
scanf(―%s%s‖, p1.pname.fname,p1.pname.lname);
printf(―Enter the mobile no of person1\n‖);
gets(p1.mobile_no);
printf(―Enter the name of person2\n‖);
scanf(―%s%s‖, p2.pname.fname,p2.pname.lname);
printf(―Enter the mobile no of person1\n‖);
gets(p2.mobile_no);
record.percentage = 86.5;
func(record);
return 0;
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}
2. UNIONS
Explain the concept of Union with example. April/May 2015[CO2,L2]
Like structures, Unions are used to create the user defined data types. A union is a
collection of one or more variables, possibly of different data types. In structures
separate memory is allocated to each member while in unions, all the members of an
object share the same memory. A union object is used only if one of its constituent
members is to be used at a time.In such a situation it proves to be memory efficient
when compared to structures.
#include <stdio.h>
union job { //defining a union
char name[32];
float salary;
int worker_no;
}u;
struct job1 {
char name[32];
float salary;
int worker_no;
}s;
int main(){
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
return 0;
}
Output:
size of union = 32
size of structure = 40
Output
Enter name
Hillary
Enter salary
1234.23
Displaying
Name: (Garbage value will be displayed)
Salary: 1234.2
Initially, Hillary will be stored in u.name and other members of union will contain
garbage value. But when user enters value of salary, 1234.23 will be stored in u.salary
and other members will contain garbage value. Thus in output, salary is printed
accurately but, name displays some random string.
Since the members of a union object share the memory in an overlapped fashion, only
one member at a time can be assigned a value. Accessing the value of that member
gives a meaningful result, but accessing other members gives a garbage value.
The following program uses structure and union to get and display the student details.
#include<stdio.h>
#include<conio.h>
void main() {
struct student {
char name[30];
char sex;
int rollno;
float percentage;
};
union details {
scanf("%c", &set.st.sex);
printf("\nEnter percentage :");
scanf("%f", &set.st.percentage);
printf("\nThe student details are : \n");
printf("\name : %s", set.st.name);
printf("\nRollno : %d", set.st.rollno);
printf("\nSex : %c", set.st.sex);
printf("\nPercentage : %f", set.st.percentage);
getch();
}
Output:
Enter details:
Enter name : Pritesh
Enter rollno: 10
Enter sex: M
Enter percentage: 89
The student details are:
Name : Pritesh
Rollno : 10
Sex : M
Percentage : 89.000000
usually opened for only one kind of operation (reading, writing, or appending) at any
given time.
Similarly, since text files only process characters, they can only read or write data one
character at a time.
Binary files:
A binary file is no different to a text file. It is a collection of bytes. In C Programming
Language a byte and a character are equivalent. Hence a binary file is also referred to
as a character stream. Binary files can be either processed sequentially or, depending
on the needs of the application they can be processed using random access
techniques. In C Programming Language, processing a file using random access
techniques involves moving the current file position to an appropriate place in the file
before reading or writing data.
File pointer:
A file pointer is a pointer to a structure, which contains information about the file,
including its name, current position of the file, whether the file is being read or written,
and whether errors or end of the file have occurred. The user does not need to Know
the details, because the definitions obtained from stdio.h include a structure declaration
called FILE. The only declaration needed for a file pointer is symbolized by FILE *fp;
This says that fp is the file pointer that points to a FILE structure.
File operations:
Opening Files:
We can use the fopen( ) function to create a new file or to open an existing file, this call
will initialize an object of the type FILE, which contains all the information necessary to
control the stream.
Following is the prototype of this function call:
FILE *fopen( const char * filename, const char * mode );
Here, filename is string literal, which you will use to name your file and access mode
can have one of the following values:
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing, if it does not exist then a new file is created. Here our
program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode, if it does not exist then a new file is
created. Here our program will start appending content in the existing file content.
Closing a File
To close a file, use the fclose( ) function.
The prototype of this function is:int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the
file. This function actually, flushes any data still pending in the buffer to the file, closes
the file,and releases any memory used for the file. The EOF is a constant defined in the
header file stdio.h.
Reading a File
Following is the simplest function to read a single character from a file:
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return
value is the character read, or in case of any error it returns EOF. The following
functions allow you to read a string from a stream:
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n - 1 characters from the input stream referenced by
fp. It copies the read string into the buffer buf, appending a null character to terminate
the string. If this function encounters a newline character '\n' or the end of the file EOF
before they have read the maximum number of characters, then it returns only the
characters read up to that point including new line character.
We can also use int fscanf(FILE *fp, const char *format, ...) function to read strings
from a file but it stops reading after the first space character encounters. It can also be
used to read variables of different data types also. For
example,fscanf(fp,"%d%c%s",&a,&b,c); - Used to read integer variable a, character
variable b and
string c.
Writing a File
Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream
Referenced by fp. It returns the written character written on success otherwise EOF if
there is an error.You can use the following functions to write a null-terminated string to a
stream:int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns
a nonnegative value on success, otherwise EOF is returned in case of any error. You
can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string
into a file. It can also be used to display variables of different data types also.
fprintf(fp,"%d\t%c\t%s",a,b,c); - Used to display integer variable a, character variable b
and string c.
char stuff[25];
int index;
fp = fopen("TENLINES.TXT","w"); /* open for writing */
strcpy(stuff,"This is an example line.");
for (index = 1; index <= 10; index++)
fprintf(fp,"%s Line number %d\n", stuff, index);
fclose(fp); /* close the file before ending program */
}
After the program is executed the following is written to the file TENLINES.TXT
This is an example line Line number 1
This is an example line Line number 2
This is an example line Line number 3
This is an example line Line number 4
This is an example line Line number 5
This is an example line Line number 6
This is an example line Line number 7
2. Reading:
#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c;
fp = fopen("prog.c","r");
c = fgetc(fp) ;
while (c!= EOF)
{
putchar(c);
c = getc(fp);
}
fclose(fp);
}
File ―prog.c‖ is opened in read mode and the file is read character by character till
EOF
character and displayed in the screen.
3. Writing
#include <stdio.h>
int main()
{
FILE *fp;
file = fopen("file.txt","w");
/*Create a file and add text*/
fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
fclose(fp); /*done!*/
return 0;
}
file.txt contains the line ―This is just an example‖ after the program is executed.
4. Appending
#include <stdio.h>
int main()
{
FILE *fp
file = fopen("file.txt","a");
fprintf(fp," %s","This is just an example :)"); /*append some text*/
fclose(fp);
return 0;
}
file.txt before execution
Hello
file.txt after execution
Hello This is just an example
Other functions:
rewind()
void rewind(FILE *fp);
We can position a file's current location to the start of the file using rewind().
The following example shows the usage of rewind() function.
#include <stdio.h>
int main()
{
char str[] = "This is a C program";
FILE *fp;
int ch;
/* First let's write some content in the file */
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
fp = fopen( "file.txt" , "r" );
while(!feof(fp))// Displays the contents in the file
{
ch = fgetc(fp);
printf("%c", ch);
}
rewind(fp);//Rewinds the file pointer to the beginning
printf("\n");
while(!feof(fp))//Displays again the contents of the file
{
ch = fgetc(fp);
printf("%c", ch);
}
fclose(fp);
return(0);
}
Let us assume we have a text file file.txt that have the following content −
This is a C program
Now let us compile and run the above program to produce the following result −
This is a C program
This is a C program
fseek()
int fseek(FILE *stream, long offset, int whence);
The fseek() function is used to set the file position indicator for the stream to a new
position.This function accepts three arguments. The first argument is the FILE stream
pointer returned by the fopen() function. The second argument ‗offset‘ tells the amount
of bytes to seek. The third argument ‗whence‘ tells from where the seek of ‗offset‘
number of bytes is to be done.The available values for whence are SEEK_SET,
SEEK_CUR, or SEEK_END. These three values (in order) depict the start of the file, the
current position and the end of the file.Upon success, this function returns 0, otherwise
it returns -1.
The following example shows the usage of fseek() function.
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is a program", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
Let us compile and run the above program that will create a file file.txt with the following
content. Initially program creates the file and writes This is a C program but later we had
reset the write pointer at 7th position from the beginning and used puts() statement
which over-write the file with the following content C programming Language.
This is C Programming Language
ftell()
long int ftell(FILE *stream)
This function returns the current value of the position indicator. If an error occurs, -1L is
returned, and the global variable errno is set to a positive value.
The following program demonstrates the use of ftell. It displays the total size of the file
in bytes.
#include <stdio.h>
int main ()
{
FILE *fp;
int len;
fp = fopen("file.txt", "r");
if( fp == NULL )
{
perror ("Error opening file");
return(-1);
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("Total size of file.txt = %d bytes\n", len);
return(0);
}
Let us assume we have a text file file.txt, which has the following content −
This is a C program
Now let us compile and run the above program that will produce the following result if
file has above mentioned content otherwise it will give different result based on the file
content −
Total size of file.txt = 19 bytes
4. PROGRAMS IN STRUCTURES
a. Write a C program that uses functions to perform the following operations
using structure[CO2,L3]
i. Reading a complex number
ii. Writing a complex number
iii. Addition of two complex numbers
iv. Multiplication of two complex numbers May/June 2014/April/May 2015/Nov/Dec
2015
#include<stdio.h>
#include<conio.h>
struct complex
{
double r,i;
};
void read(struct complex *);
struct complex add(struct complex *,struct complex *);
struct complex mul(struct complex *,struct complex *);
struct complex div(struct complex *,struct complex *);
void write(struct complex *);
void main()
{
struct complex a,b,c,d,e;
int opern;
clrscr();
printf(―Enter first complex number\n‖);
read(&a);
printf(―Enter second complex number\n‖);
read(&b);
printf("\n\n \t\t\t***** MAIN MENU *****");
printf("\n\n Select your option: \n 1 : ADD\n 2 : MULTIPLY\n 3 : DIVIDE\n\n\t\t
Enter your Option\n");
scanf("%d",&opern);
switch(opern)
{
/*addition of complex number*/
case 1:
c=add(&a,&b);
printf("Sum=%.1f+%.1fi",c.real,c.imag);
break;
printf("Division Result=%.1f+%.1fi",c.real,c.imag);
break;
default:
printf(―Wrong choice\n‖);
}
}
void read(struct complex *x)
{
printf("Enter Real Part : ");
scanf("%d",&(x->r));
printf("Enter Imag Part : ");
scanf("%d",&(x->i));
}
struct complex add(struct complex *x,struct complex *y)
{
struct complex z;
z.r=x->r+y->r;
z.i=x->i+y->i;
return(z);
}
struct complex mul(struct complex *x,struct complex *y)
{
struct complex z;
z.r=(x->r)*(y->r)-(x->i)*(y->i);
z.i=(x->r)*(y->i)+(x->i)*(y->r);
return(z);
}
struct complex div(struct complex *x,struct complex *y)
{
struct complex z;
z.r=((x->r)*(y->r)+(x->i)*(y->i))/((y->r)*(y->r)+(y->i)*(y->i));
z.i=((x->i)*(y->r)-(x->r)*(y->i))/ ((y->r)*(y->r)+(y->i)*(y->i));
return(z);
}
Output:
Enter first complex number
Enter Real Part : 10
Enter Imag Part : 12
Enter second complex number
Enter Real Part : 13
Enter Imag Part : 32
***** MAIN MENU *****
}s[20];
void main()
{
int ch;
while(1)
{
clrscr();
printf("\n*********************");
printf("\n BANKING ");
printf("\n*********************");
printf("\n1-Creation");
printf("\n2-Deposit");
printf("\n3-Withdraw");
printf("\n4-Balance Enquiry");
printf("\n5-Exit");
printf("\nEnter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1: creation();
break;
case 2: deposit();
break;
case 3: withdraw();
break;
case 4: bal();
break;
case 5: exit(0);
default: printf("Enter 1-5 only");
getch();
}
}
}
void creation()
{
printf("\n*************************************");
printf("\n ACCOUNT CREATION ");
printf("\n*************************************");
scanf("%d",&no);
for(b=0;b<i;b++)
{
if(s[b].no == no)
m = b;
}
if(s[m].no == no)
{
printf("\n Account Number : %d",s[m].no);
printf("\n Name : %s",s[m].name);
printf("\n Deposit : %f",s[m].dep);
printf("\n How Much Deposited Now:");
scanf("%f",&aa);
s[m].dep+=aa;
printf("\nDeposit Amount is :%f",s[m].dep);
getch();
}
else
{
printf("\nACCOUNT NUMBER IS INVALID");
getch();
}
}
void withdraw()
{
int no,b=0,m=0;
float aa;
printf("\n*************************************");
printf("\n WITHDRAW ");
printf("\n*************************************");
printf("\nEnter your Account Number");
scanf("%d",&no);
for(b=0;b<i;b++)
{
if(s[b].no == no)
m = b;
}
if(s[m].no == no)
{
printf("\n Account Number : %d",s[m].no);
printf("\n Name : %s",s[m].name);
printf("\n Deposit : %f",s[m].dep);
printf("\n How Much Withdraw Now:");
scanf("%f",&aa);
if(s[m].dep<aa+500)
{
printf("\nCANNOT WITHDRAW YOUR ACCOUNT HAS MINIMUM BALANCE");
getch();
}
else
{
s[m].dep-=aa;
printf("\nThe Balance Amount is:%f",s[m].dep);
}
}
else
{
printf("INVALID");
getch();
}
getch();
}
void bal()
{
int no,b=0,m=0;
float aa;
printf("\n*************************************");
printf("\n BALANCE ENQUIRY ");
printf("\n*************************************");
printf("\nEnter your Account Number");
scanf("%d",&no);
for(b=0;b<i;b++)
{
if(s[b].no == no)
m = b;
}
if(s[m].no==no)
{
printf("\n Account Number : %d",s[m].no);
printf("\n Name : %s",s[m].name);
printf("\n Deposit : %f",s[m].dep);
getch();
}
else
{
printf("INVALID");
getch();
}
}
Output:
*********************
BANKING
*********************
1-Creation
2-Deposit
3-Withdraw
4-Balance Enquiry
5-Exit
*********************
BANKING
*********************
1-Creation
2-Deposit
3-Withdraw
4-Balance Enquiry
5-Exit
b. Write a C program to read the contents of a file "in.txt" from first to last and
write the contents to "out.txt".[CO2,L3]
#include <stdio.h>
void main()
{
FILE *fp,*fr;
char ch;
clrscr();
//in.txt is opened for reading and out.txt is opened for writing
fp=fopen(―in.txt‖,‖r‖);
fr=fopen(―out.txt‖,‖w‖);
while(!feof(fp))//Counting the number of characters in the file
{
ch=fgetc(fp);
fputc(ch,fr);
}
fclose(fp);
fclose(fr);
}
c. Write a C program to read the contents of a file "in.txt" from last to first and
write the contents to "out.txt". May/June 2014[CO2,L3]
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
void main()
{
FILE *fp,*fr;
char ch;
int i=-1,j=0;
clrscr();
//in.txt is opened for reading and out.txt is opened for writing
fp=fopen(―in.txt‖,‖r‖);
fr=fopen(―out.txt‖,‖w‖);
while(!feof(fp))//Counting the number of characters in the file
{
ch=fgetc(fp);
j++;
}
fseek(fp,i,SEEK_END);
while(1)
{
/* Reading a character from input file and writing to output */
ch=fgetc(fp);
fputc(ch,fr);
i--;
/*Move the file pointer one character before the current position*/
fseek(fp,i,SEEK_END);
if(-i>j)// All the characters are read from the file
break;
}
fclose(fp);
fclose(fr);
}
e. Write a program to read a file and count the number of characters and lines in
it Nov/Dec 2015[CO2,H1]
#include<stdio.h>
#include<conio.h>
void main()
{
int noc=0,now=0,nol=0;
FILE *fr;
char fname[20],ch;
clrscr();
UNIT – III
PART A
1. What is an abstract data type? Nov/Dec 2006 , Nov/Dec 2014, May/June
2005 Nov / Dec 2011
Define ADT. Apr / May 2015
What is ADT? Give Example. Apr / May 2008, Nov / Dec 2015
Define Abstract Data type (ADT). May / June 2007
What is the advantage of ADT? May / June 2014[CO3,L1]
An Abstract Data Type (ADT) is defined as a mathematical model of the data objects
that make up a data type as well as the functions that operate on these objects. The
definition of ADT has the following two parts:
(i) Description of the way in which components are related to each other.
(ii)Statements of operations that can be performed on that data type.
Example: Objects such as lists, sets and graphs.
Logical behavior of ADT is defined by a set of values and a set of operations.
Advantages:
Robust
Encapsulation
Localization of change
Flexibility
3. What is a Circular Linked List? List its advantages. Nov / Dec 2014[CO3,L1]
A Circular linked list is a linked list in which the head element's previous pointer points
to the tail element and the tail element's next pointer points to the head element.
In a circularly linked list, all nodes are linked in a continuous circle, without using NULL.
Next Next Next
Data Data Data
Advantages:
It allows traversing the list starting at any point.
It allows quick access to the first and last records.
Circularly doubly linked list allows traversing the list in both directions.
4. Define a List. Mention any two operations that are performed on a list. Nov /
Dec 2006
List the operations and implementations of List ADT. May / June 2006[CO3,L1]
List is a sequential data structure. A list or sequence is an abstract data type that
represents an ordered sequence of values. List is a linear collection of data items.
The general form of the list is A1, A2, A3,.....,AN
where A1 - First element of the list,
AN - Last element of the list,
N - Size of the list.
If the element at position i is Ai then its successor is Ai+1 and its predecessor is Ai-1.
Operations:
Create a list
Insert an element in the list
Delete an element from the list
Return the position of the element in the list
Display the contents of the list
Make the list empty.
Implementations:
Array implementation
Linked list implementation
Cursor based implementation
5. Should arrays or linked lists be used for the following types of applications?
Justify your answer. May / June 2014[CO3,H1]
(a) Many search operations in sorted list - Array. It is a linear data structure and
supports searching easily.
(b) Many search operations in unsorted list.- Linked List. Pointer traversal so searching
is easier.
6. What is a static and dynamic linked list? State any two applications of Linked
list. Apr / May 2015[CO3,L1]
Static Linked List – data structure has a fixed size.
Dynamic Linked List - data structure is dynamic. It grows and shrinks dynamically.
Applications of linked list:
Polynomial ADT
Radix Sort
Multilist
Array
Stack& Queue
7. Distinguish between linear and non-linear data structures. Nov / Dec 2010
Feature Linear Data Structure[CO3,H1]
Non Linear Data Structure Organization of data
Data elements are not organized in a sequential fashion.Data elements are not
organized in a sequential fashion.
Construction
Data elements in a linear data structure are traversed one after the other Nonlinear data
structures are constructed by attaching a data element to several other data elements
Implementation
Easy to implement Difficult to implement.
Examples
arrays, linked lists, stacks and
queues
Trees and Graphs
8. Write the syntax of calloc() and realloc() and mention its application in linked
list. April/May 2015[CO3,L2]
calloc () function is used to allocate space in memory during the execution of the
program. But calloc () initializes the allocated memory to zero.
calloc (number, sizeof(int));
realloc () function modifies the allocated memory size by malloc () and calloc ()
functions to new size.If enough space doesn‘t exist in memory of current block to
extend, new block is allocated for the full size of reallocation, then copies the existing
data to new block and then frees the old block.
realloc (pointer_name, number * sizeof(int));
PART – B
1. DOUBLY LINKED LIST
Write an algorithm to perform insertion and deletion on a doubly linked list.
(16) Nov / Dec 2015 & (16) May / June 2014
Describe the creation of doubly linked list and appending the list. Give relevant
coding in C. (16) Nov / Dec 2014[CO3,L3]
Doubly Linked List:
A doubly linked list is a two-way list in which all nodes will have two links. This
helps in accessing both successor node and predecessor node from the given node
position. It provides bi-directional traversing.Prev Next Prev Next Prev Next NULL Data
Data Data NULL Prev Next Prev Next Prev Next Data Data Data Each node contains
three fields:
Left link.
Data.
Right link.
The left link points to the predecessor node and the right link points to the successor
node.The data field stores the required data.Many applications require searching
forward and backward through nodes of a list. For example searching for a name in a
telephone directory would need forward and backward scanning thru a region of the
whole list.
The basic operations in a double linked list are:
Creation.
Insertion.
Deletion.
Traversing.
Structure of a doubly linked list:
The beginning of the double linked list is stored in a "start" pointer which points to the
first node. The first node‘s left link and last node‘s right link is set to NULL.
Figure 3.1.1 Doubly Linked List
A doubly linked list is shown in fig.3.1. The following code gives the structure definition:
Figure 3.1.2. Structure definition, double link node and empty list
struct dlinklist
{
struct dlinklist *left;
int data;
struct dlinklist *right;
};
typedef struct dlinklist node;
node * start = NULL;
Node:
Left Data right
Empty list: start
Creating a node for Doubly Linked List
Creating a doubly linked list starts with creating a node. Sufficient memory has to be
allocated for for creating a node. The information is stored in the memory, allocated by
using the malloc() function. The function getnode() is used for creating a node, After
allocating memory for the structure of type node, The information for the item has to be
read from the user and set left field to NULL and right field also set to NULL.
start=newnode;
}
}
Inserting a node at the end:
The following steps are followed to insert a new node at the end of the list:
Step 1: Get the new node using getnode()
newnode=getnode();
Step2 : a) If the list is empty then start = newnode.
b) If the list is not empty follow the steps given below:
temp = start;
while(temp -> right != NULL)
temp = temp -> right;
temp -> right = newnode;
newnode -> left = temp;
The function dbl_insert_end(), is used for inserting a node at the end. Figure 3.6 shows
inserting a node into the double linked list at the end.
Figure 3.1.6. Inserting a node at the end
ROUTINE TO INSERT AN ELEMENT AT THE END OF A LIST
void dll_insert_end()
{
node *newnode, *temp;
newnode=getnode();
if(start==NULL)
start=newnode;
else
{
temp=start;
while(temp->right!=NULL)
temp=temp->right;
temp->right=newnode;
newnode->left=temp;
}
}
Inserting a node at an intermediate position:
The following steps are followed, to insert a new node in an intermediate position in the
list:
Get the new node using getnode().
newnode=getnode();
Ensure that the specified position is in between first node and last node. If not,
specified position is invalid. This is done by countnode() function.
Store the starting address (which is in start pointer) in temp and prev
pointers. Then traverse the temp pointer upto the specified position followed by prev
pointer.
After reaching the specified position, follow the steps given below:
newnode -> left = temp;
newnode -> right = temp -> right;
temp -> right -> left = newnode;
temp -> right = newnode;
The function dbl_insert_mid(), is used for inserting a node in the intermediate
position. Figure 3.7 shows inserting a node into the double linked list at a specified
intermediate position other than beginning and end.
Figure 3.1.7. Inserting a node at an intermediate position
}
printf(―\n not in intermediate position‖)
}
Deleting a node at the beginning:
The following steps are followed, to delete a node at the beginning of the list:
If list is empty then display ‗Empty List‘ message.
If the list is not empty, follow the steps given below:
temp = start;
start = start -> right; start -> left = NULL; free(temp);
The function dbl_delete_beg(), is used for deleting the first node in the list. Figure
3.8 shows deleting a node at the beginning of a double linked list.
while(i<pos)
{
temp=temp->right;
i++;
}
temp->right->left=temp->left;
temp->left->right=temp->right;
free(temp);
printf(―\n node deleted‖);
}
else
{
printf(―\n not intermediate position‖);
getch();
}
}
}
Traversal and displaying a list (Left to Right):
To display the information, you have to traverse the list, node by node from the first
node,
until the end of the list is reached. The function traverse () is used for traversing and
displaying the information stored in the list from left to right.
The following steps are followed, to traverse a list from left to right:
Step 1: If list is empty then display ‗Empty List‘ message.
Step 2: If the list is not empty, follow the steps given below:
temp = start;
while(temp != NULL)
{
print temp -> data;
temp = temp -> right;
}
ROUTINE TO TRAVERSE THE LIST
void traverse()
{
node * temp;
temp=start;
printf(―\n the contents of list‖);
if (start == NULL)
printf(―\n empty list‖);
else
{
while(temp!=NULL)
{
printf(―\t%d‖,temp->data);
temp=temp->right;
}
}
}
ROUTINE TO COUNT THE NUMBER OF NODES:
if countnode(node * start)
{
if (start == NULL)
return 0;
else
return 1+countnode(start->right)
}
done while creating a list) before reading the data. The new node will contain empty
data field and empty next field. The data field of the new node is then stored with the
information read from the user. The next field of the new node is assigned to NULL.
The new node can then be inserted at three different places namely:
• Inserting a node at the beginning.
• Inserting a node at the end.
• Inserting a node at intermediate position.
Inserting a node at the beginning:
The following steps are to be followed to insert a new node at the beginning of the list:
• Get the new node using getnode(). newnode = getnode();
• If the list is empty then start = newnode.
• If the list is not empty, follow the steps given below:
newnode -> next = start;
start = newnode;
Figure 3.15 shows inserting a node into the single linked list at the beginning.
else
{ newnode->next = start;
start=newnode;
}
}
Inserting a node at the end:
The following steps are followed to insert a new node at the end of the list:
• Get the new node using getnode()
newnode = getnode();
• If the list is empty then start = newnode.
• If the list is not empty follow the steps given below:
temp = start;
while(temp -> next != NULL)
void delete_at_beg()
{
node *temp;
if(start = = NULL)
{
printf(―\n Node does not exist‖);
return;
}
else
{ temp=start;
start = temp - >next;
free(temp);
printf(―\n node deleted‖);
}}
prev=start;
while (temp->next !=NULL)
{
prev=temp;
temp=temp->next;
}
prev->next=NULL;
free(temp);
printf(―\n deleted‖);
}
}
Deleting a node at Intermediate position:
The following steps are followed, to delete a node from an intermediate position in the
list
(List must contain more than two node).
If list is empty then display ‗Empty List‘ message
If the list is not empty, follow the steps given below.
if(pos > 1 && pos < nodectr)
{
temp = prev = start;
ctr = 1;
while(ctr < pos)
{
prev = temp;
temp = temp -> next;
ctr++;
}
prev -> next = temp -> next;
free(temp);
if(start = = NULL)
{
printf(―\n Empty List‖);
return;
}
else
{
nodectr=countnode(start);
if(pos > nodectr)
{
printf(―\n The node does not exist‖);
}
if(pos> 1 && pos < nodectr)
{
temp=prev=start;
while(ctr < pos)
{
prev=temp;
temp=temp - > next;
ctr++;
}
prev->next = temp ->next;
free(temp);
printf(―\n Deleted‖);
}
else
{
printf(―\n Invalid position‖);
getch();
}
}
}
Traversal and displaying a list (Left to Right):
To display the information, you have to traverse (move) a linked list, node by node from
the first node, until the end of the list is reached. Traversing a list involves the following
steps:
• Assign the address of start pointer to a temp pointer.
• Display the information from the data field of each node.
The function traverse() is used for traversing and displaying the information stored in the
list from left to right.
void traverse()
{
node *temp;
temp = start;
printf("\n The contents of List (Left to Right): \n");
if(start == NULL )
printf(―\n Epty List‖);
else
{
while(temp!=NULL)
{
printf(―%d‖, temp ->data);
temp=temp->next;
}
}
}
Counting the Number of Nodes:
The following code will count the number of nodes exist in the list using recursion.
int countnode(node *st)
{
if (st == NULL)
return 0;
else
return(1+countnode(st->next));
}
Merging two sorted List:
SortedMerge() function that takes two lists, each of which is sorted in increasing order,
and merges the two together into one list which is in increasing order. SortedMerge()
should return the new list. The new list should be made by splicing together the nodes
of the first two lists.
For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20,
then SortedMerge() should return a pointer to the head node of the merged list 2->3->5-
>10->15-
>20
3. POLYNOMIAL MANIPULATION
(a) Explain the following: (8 + 8) Nov / Dec 2014
(i) Applications of lists.
(ii) Polynomial Manipulations - Addition (8) (Nov / Dec 2015)
(b) Write a C program to perform addition, subtraction and multiplication
operations on polynomial using linked list. (16) April / May 2015[CO3,L3]
Polynomials is represented as a list of pairs of coefficient and exponent. Each of these
pairs will constitute a structure, so a polynomial will be represented as a list of
structures. A linked list structure that represents polynomials 5x4 – 8x3 + 2x2 + 4x1 +
9x0 illustrates in
figure 3.10.1
Declaration of Linked list implementation of Polynomial:
struct poly{
{
int coeff;
int power;
struct poly *next;
} *list1, *list2, *list3;
Creation of Polynomial:
poly create(poly *head, poly *newnode)
{
poly*ptr;
if(head==NULL)
{
head=newnode;
return(head);
}
else
{
ptr=head;
while(ptr-> next!=NULL)
ptr=ptr->next;
ptr->next=newnode;
}
return(head);
}
Addition of Polynomials:
To add two polynomials we need to scan them once. If we find terms with the same
exponent in the two polynomials, then we add the coefficients; otherwise, we copy the
term of larger exponent into the sum and go on. When we reach at the end of one of the
polynomial, then remaining part of the other is copied into the sum.
To add two polynomials follow the following steps:
• Read two polynomials.
• Add them.
• Display the resultant polynomial.
Addition of Polynomials:
void add()
{
poly *ptr1, *ptr2, *newnode;
ptr1=list1;
ptr2=list2;
while(ptr1!=NULL && ptr2!= NULL)
{
newnode=malloc(sizeof(struct poly));
if(ptr1->power==ptr2->power)
{
newnode->coeff = ptr1->coeff + ptr2->coeff;
newnode->power=ptr1->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr1=ptr->next;
ptr2=ptr2->next;
}
else
{
if(ptr1->power > ptr2->power)
{
newnode->coeff = ptr1->coeff
newnode->power=ptr1->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr1=ptr1->next;
}
else
{
newnode->coeff = ptr2->coeff
newnode->power=ptr2->power;
newnode->next=NULL;
list3=create(list3,newnode);
ptr2=ptr2->next;
}
}
}
list3=create(list3,newnode);
ptr2=ptr2->next;
}
ptr2=list2;
ptr1=ptr1->next;
}
}
}
}
CREATING A NODE:
struct cslinklist
{
int data;
struct cslinklist *next;
};
typedef struct cslinklist node;
node *start = NULL;
int nodectr;
node* getnode()
{
node * newnode;
newnode = (node *) malloc(sizeof(node));
printf("\n Enter data: ");
scanf("%d", &newnode -> data);
newnode -> next = NULL;
return newnode;
}
The function createlist(), is used to create ‗n‘ number of nodes:
}
newnode->next = start;
}
Inserting a node at the beginning:
The following steps are to be followed to insert a new node at the beginning of the
circular list:
o Get the new node using getnode(). newnode = getnode();
o If the list is empty, assign new node as start.
start = newnode;
newnode -> next = start;
o If the list is not empty, follow the steps given below:
last = start;
while(last -> next != start)
last = last -> next;
newnode -> next = start;
start = newnode;
last -> next = start;
The function cll_insert_beg(), is used for inserting a node at the beginning.Figure shows
inserting a node into the circular single linked list at the beginning.
ROUTINE TO INSERT A NODE AT THE BEGINNING OF THE LIST
void cll_insert_beg() {
node *newnode, *last;
newnode = getnode();
if (start == NULL)
{
start =newnode;
newnode - > next = start;
}
else
{ last = start;
while(last -> next != start)
last = last - >next;
start=newnode;
last->next = start;
}
nodectr++;
}
prev = temp;
temp = temp -> next;
}
prev->next = start;
• After deleting the node, if the list is empty then start = NULL.
The function cll_delete_last(), is used for deleting the last node in the list.
Figure 3.6.5 shows deleting a node at the end of a circular single linked list.
do
{
printf("%d ", temp -> data);
temp = temp -> next;
} while(temp != start);
ROUTINE TO TRAVERSE THE LIST
void traverse()
{
node * temp;
temp=start;
If (start == NULL)
printf(―\n empty‖);
else
{
do
{
printf(―%d‖, temp->data);
temp=temp->next;
} while(temp!=start);
}
Arrays can be declared in various ways in different languages. For illustration, let's take
C array declaration.
As per above shown illustration, following are the important points to be considered.
Index starts with 0.
Array length is 8 which means it can store 8 elements.
Each element can be accessed via its index. For example, we can fetch element at
index 6 as 9.
Basic Operations
Following are the basic operations supported by an array.
Traverse − print all the array elements one by one.
Insertion − add an element at given index.
Deletion − delete an element at given index.
Search − search an element using given index or by value.
Update − update an element at given index.
Sorting – arrange the elements in ascending and descending order
Merging – combine the elements of the arrays
Insertion:
Inserting an element at the end of an array can be done easily if the memory space
allocated for the array is large. If we need to insert an element in the middle of the array,
then on an average, half of the elements must be moved downward to new locations to
accommodate the new element and keep the order of the other elements. (downward –
higher subscript)
Insertion of an element into an array:
(Inserting into a linear Array) INSERT (A, N , K , ITEM)
A is a linear array with N elements and K is a Positive integer such that K<=N. This
algorithm inserts an element ITEM into the Kth position in A
1. Initialise Counter. Set J=N
2. Repeat Steps 3 and 4 while J>=K
3. Move J th element downward. Set A[j+1] = A[j]
4. Decrease Counter. Set J= J – 1
End of Loop
5. Insert Element. Set A[K] = ITEM
6. Reset N. Set N := N+1;
7. Exit
scanf("%d",&a[i]);
}
}
void print(int a[], int n)
{
int i;
printf("\nThe elements of the array are!!");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
}
void insertatpos(int a[],int *n, int loc)
{
loc--;
int t=*n;
while(t>loc)
{
a[t]=a[t-1];
t--;
}
(*n)--;
printf("\nNow enter the element:");
scanf("%d",&t);
a[loc]=t;
}
void del(int a[],int *n, int loc)
{
loc--;
while(*n>loc)
{
a[loc]=a[loc+1];
loc++;
}
(*n)--;
}
void search(int a[],int n)
{
int i;
int t,flag=0;
printf("\nEnter the search element:");
scanf("%d",&t);
for(i=0;i<n;i++)
{
if(a[i]==t)
{
flag=1;
break;
}
}
if(flag==0)
printf("\nThe element not found!!!!");
else
printf("\nThe element found at location %d", i+1);
}
int main()
{
int a[100],n;
printf("\nEnter the array size:");
scanf("%d",&n);
int o,loc;
while(o!=0)
{
printf("\nENTER YOUR OPTION!!\n");
printf("\nEnter 1 for INSERTION");
printf("\nEnter 2 for DELETION");
printf("\nEnter 3 for ADDING ELEMENT");
printf("\nEnter 4 for PRINTING");
printf("\nEnter 5 for SEARCHING");
printf("\nEnter 0 for exit!!");
scanf("%d",&o);
switch(o){
case 1:{
insert(a,n);
break;
}
case 2:{
UNIT – IV
LINEAR DATA STRUCTURES – STACKS, QUEUES
PART A
1. Define Double ended Queue. May / June 2014
What is double ended Queue. Nov / Dec 2014
Define dequeue. May / June 2006[CO4,L1]
A double-ended queue is an abstract data type similar to an simple queue, it allows to
insert and delete from both sides ie., items can be added or deleted from the front or
rear end.
In double ended queue we can make use of both the front as well as rear ends for
insertion and deletion. That means it is possible to insert/delete elements by rear as well
as front end.
insertion by front end deletion by rear end
10 20 30 40
deletion by front end insertion by rear end
7. Give the various applications of stack and Queue. Nov / Dec 2014,Nov/ Dec
2009
List the applications of a Queue. May / June 2014
Write any four applications of Queues. Nov /Dec 2008, Nov/Dec 2007[CO4,L1]
Applications of Stack:
(i) Evaluating arithmetic operations
(ii)Balancing the symbols
(iii)Tower of Hanoi
(iv) Function calls
(v) 8 Queens Problem
Applications of Queue:
(i) Implementing priority queue
(ii)Batch processing in OS
(iii)Simulation
(iv)Queuing theory
(i) Description of the way in which components are related to each other.
(ii) Statements of operations that can be performed on that data type.
Since Queue is defined by a set of values and a set of operations (insert and delete)
and therefore it represents the Logical behavior of ADT.
A Queue is a linear data structure which follows First In First Out (FIFO) principle,
inwhich insertion is performed at rear end and deletion is performed at front end.
10. Given the prefix for an expression, write its postfix. Apr / May 2015[CO4,L3]
-*-+abc/ef–g/hi
postfix form: a b + c – e / f * g – h / i –
What are the postfix and prefix forms of the expression?
A+B*(C-D)/(P-R)
Postfix form: ABCD-*PR-/+
Prefix form: +A/*B-CD-PR
13. What are the different types of notations used to represent Arithmetic
Expression? [CO4,L1]
There are 3 different ways of representing the arithmetic expression.
INFIX NOTATION
POSTFIX NOTATION
PREFIX NOTATION
14. What is INFIX notation, POSTFIX notation and PREFIX notation? [CO4,L1]
In Infix notation, The arithmetic operator appears between the two operands to which it
is being applied. For example : - A / B + C
The arithmetic operator appears directly after the two operands to which it applies. Also
called reverse polish notation. ((A/B) + C) . For example : - AB / C +
The arithmetic operator is placed before the two operands to which it applies. Also
called as polish notation. ((A/B) + C) .For example : - +/ABC
PART B
1.STACK ADT-IMPLEMENTATION
Explain the array and linked list implementation of stack. (OR)
Explain STACK ADT in detail. (8) Nov/Dec 2014[CO4,L2]
STACK
A stack is a linear data structure which follows Last In First Out (LIFO) principle, in
which both insertion and deletion occur at only one end of the list called the Top.
Example: pile of coins.
top C
POP(S) STACK(S) PUSH(X,S) A
TOP(S) B
OPERATIONS ON STACK
The fundamental operations performed on a stack are : Push and Pop.
PUSH :
The process of inserting a new element to the top of the stack. For every push operation
the top is incremented by 1.
POP :
The process of deleting an element from the top of stack is called pop operation. After
every pop operation the top pointer is decremented by 1.
EXCEPTIONAL CONDITIONS
OverFlow
Attempt to insert an element when the stack is full is said to be overflow.
UnderFlow
Attempt to delete an element, when the stack is empty is said to be underflow.
IMPLEMENTATION OF STACK
Stack can be implemented in 2 ways.
1. Array Implementation
2. Linked List Implementation
ARRAY IMPLEMENTATION
In this implementation each stack is associated with a pop pointer, which is -1 for an
empty stack.
• To push an element X onto the stack, Top Pointer is incremented and set Stack [Top]
= X.
• To pop an element, the stack [Top] value is returned and the top pointer is
decremented.
ROUTINE TO PUSH AN ELEMENT ONTO A STACK
void push (int x, Stack S)
{
if (IsFull (S))
Error ("Full Stack");
}
else
{
Top = Top + 1;
S[Top] = x;
}
}
int IsFull (Stack S)
{
if (Top = = Arraysize)
return (1);
}
ROUTINE TO POP AN ELEMENT FROM THE STACK
void pop (Stack S)
{
if (IsEmpty (S))
Error ("Empty Stack");
else
{
x = S [Top];
Top = Top - 1;
}
}
int IsEmpty (Stack S)
{
if (S[Top] = = -1)
return (1);
}
ROUTINE TO RETURN TOP ELEMENT OF THE STACK
int TopElement (Stack S)
{
if (! IsEmpty (s))
return S[Top];
else
Error ("Empty Stack");
return 0;
}
{
if (S = = NULL)
Error (" Create Stack First");
else
while (! IsEmpty (s))
pop (s);
}
Tempcell=S→Next;
S→Next=S→Next→Next;
Free (Tempcell);
}
}
3. APPLICATIONS OF STACK
What are the applications of stack? Discuss in detail. (8) [Dec2014]
1. Stack is used by compilers to check for balancing of parentheses, brackets and
braces
2. Stack is used to evaluate a postfix expression.
Step 2 : - If the character is an operator, POP two values from the stack, apply the
operator to them and push the result onto the stack.
Infix Expression : A * B #
Read Character Stack Output
AA
**A
B*AB
#AB*
Example: Let us consider the symbols A,B, with values
Symbol Value
A4
B5
EVALUATION OF A B *
Read Character Stack
A4
-
5
B
4
* 20 result=20
2. Balancing the symbols
Read one character at a time until it encounters the delimiter. "#"
Step 1 : If the character is an opening symbol, push it on to the stack.
Step 2 : If the character is a closing symbol, and if the stack is empty, then report an
error as missing opening symbol.
Step 3 : If the character is a closing symbol and if it has a corresponding opening
symbol in the stack, then pop it from the stack. Otherwise report an error as
mismatched symbols.
Step 4 : At the end of file, if the stack is not empty, report an error as missing closing
symbol.
Otherwise report as balanced symbols.
Let us consider the expression (a+b)#
Read Character Stack
((
a(
+(
b(
)
# Balanced symbol. Stack is empty.
3. Towers of Hanoi
The problem is moving a collection of N disks of decreasing size from one pillar to
another
pillar. The movement of the disk is restricted by the following rules.
Rule 1: Only one disk could be moved at a time.
Rule 2: No larger disk could ever reside on a pillar on top of a smaller disk.
Rule 3: A 3rd pillar could be used as an intermediate to store one or more disks, while
they
werebeing moved from sourced to destination.
Recursive Solution
N - represents the number of disks.
Step 1. If N = 1, move the disk from A to C.
Step 2. If N = 2, move the 1st disk from A to B. Then move the 2nd disk from A to C,
Then move the 1st disk from B to C.
Step 3. If N = 3, Repeat the step (2) to more the first 2 disks from A to B using C as
intermediate.Then the 3rd disk is moved from A to C. Then repeat the step (2) to move
2 disks from B to C using A as intermediate.
In general, to move N disks. Apply the recursive technique to move N - 1 disks from
A to B using C as an intermediate. Then move the Nth disk from A to C. Then again
apply the recursive technique to move N - 1 disks from B to C using A as an
intermediate.
4.Function Calls
When a call is made to a new function all the variables local to the calling routine need
to be saved, otherwise the new function will overwrite the calling routine variables.
Similarly the current location address in the routine must be saved so that the new
function knows where to go after it is completed.
Main( ) Balance ( ) Push ( )
Call Balance ( ) Call Push ( )
Return Return
RECURSIVE FUNCTION TO FIND FACTORIAL: -
int fact (int n)
{
int s;
141
if (n = = 1)
return (1);
else
s = n * fact (n - 1);
return (s);
}
IMPLEMENTATION OF QUEUE
Queue can be implemented in 2 ways.
1. Array Implementation
2. Linked List Implementation
ARRAY IMPLEMENTATION
In order to create a queue we require a one dimensional array Q(1:n) and two variables
front and rear. The conventions we shall adopt for these two variables are that front is
always 1 less than the actual front of the queue and rear always points to the last
element in the queue.
Thus, front = rear if and only if there are no elements in the queue.
The initial condition is front = rear = -1.
The various queue operations to perform creation, deletion and display the elements in
a queue are as follows:
1. insertQ(): inserts an element at the end of queue Q.
2. deleteQ(): deletes the first element of Q.
3. displayQ(): displays the elements in the queue.
In this implementation queue Q is associated with two pointers namely rear pointer and
front pointer.
• To insert an element X onto the Queue Q, the rear pointer is incremented by 1 and
then set Queue [Rear] = X
• To delete an element, the Queue [Front] is returned and the Front Pointer is
incremented by 1.
ROUTINE TO ENQUEUE
void Enqueue (int X)
{
if (rear = = max _ Arraysize-1)
print (" Queue overflow");
else
{
rear = rear + 1;
Queue [rear] = X;
if(front==-1)
front=0;
}
}
newnode →data = X;
newnode →Next = NULL;
Front = newnode;
Rear = newnode;
}
else
{
newnode → data = X;
newnode → Next = NULL;
Rear →next = newnode;
Rear = newnode;
}
}
ROUTINE TO DEQUEUE AN ELEMENT FROM THE QUEUE
void Dequeue ( )
{
{
R = (R+1) %SIZE;
queue[R] = x;
}
}
/* To insert element in the front of Double ended queue*/
void insert_f(int x)
{
if(F == (R+1)%SIZE)
{
printf("\nQueue Overflow");
}
else if(R == -1)
{
F = 0;
R = 0;
queue[R] = x;
}
else
{
F = (F+SIZE-1) %SIZE;
queue[F] = x;
}
}
}
return x;
}
void main()
{
char choice;
int x;
while(1)
{
printf("1: Insert From Front\n");
printf("2: Insert From Rear\n");
printf("3: Delete From Front\n");
printf("4: Delete From Rear\n");
printf("5: Exit Program\n");
printf("Enter Your Choice:");
choice = getche();
switch(choice)
{
case '1':
printf("\nEnter Integer Data :");
scanf("%d",&x);
insert_f(x);
break;
case '2':
printf("\nEnter Integer Data :");
scanf("%d",&x);
insert_r(x);
break;
case '3':
printf("\nDeleted Data From Front End: %d",delete_f());
break;
case '4':
printf("\nDeleted Data From Back End: %d",delete_r());
break;
case '5':
exit(0);
break;
}
}}
UNIT-V
SORTING, SEARCHING AND HASH TECHNIQUES
PART A
1. What is meant by Sorting and searching?[CO5,L1]
Sorting and searching are fundamentals operations in computer science. Sorting refers
to the operation of arranging data in some given order, ascending or descending.
Searching refers to the operation of searching the particular record from the existing
information.
One essential condition for the binary search is that the array which is to be searched,
should be arranged in ascending order. It is efficient when compared to linear search
and useful in applications where the data is sorted.
Time complexity:O(logn)
The record with hash key value K is stored in bucket, where i=h(K).
Hash function is used to locate records for access, insertion as well as deletion.
Dynamic Hashing
Good for database that grows and shrinks in size
Allows the hash function to be modified dynamically
Extendable hashing – one form of dynamic hashing
PART B
1. SHELL SORT AND INSERTION SORT
Sort the given integers and show the intermediate results using shell sort
35,12,14,9,15,45,32,95,40,5
Write C code to sort an integer array using shell sort April/May 2015
Shell sort: [CO5,L3]
Shell sort, also known as the diminishing increment sort, is one of the oldest sorting
algorithms, named after its inventor Donald. L. Shell (1959).
• Shell sort works by comparing elements that are distant rather than adjacent elements
in an array or list.
• Shell sort uses a sequence h1, h2, …, ht called the increment sequence. It can
assume values from a set (1,3,5,19,41…). The increment sequence is chosen within the
following range. ht=N/2, hk=hk+1/2, h1=1
35 12 14 9 15 45 32 95 40 5
Given the input the array has to be sorted using shell sort
Steps:
1. Sort with increment 5
35 12 14 9 15 45 32 95 40 5
5 and 15 are swapped
2. Sort with increment 3
35 12 14 9 5 45 32 95 40 15
Result after sorting:
9 5 14 15 12 40 32 95 45 35
3. Sort with increment 1
9 5 14 15 12 40 32 95 45 35
Result after sorting:
5 9 12 14 15 32 35 40 45 95
Code:
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[30];
int i,j,k,tmp,num;
printf("Enter total no. of elements : ");
scanf("%d", &num);
for(k=0; k<num; k++)
{
scanf("%d",&arr[k]);
}
for(i=num/2; i>0; i=i/2)
{
for(j=i; j<num; j++)
{
tmp=arr[j];
for(k=j; k>=i; k=k-i)
{
if(tmp<arr[k- i])
{
arr[k]=arr[k-i];
}
else
{
break;
}
arr[k-i]=tmp;
}
}
}
printf("\t**** Shell Sorting ****\n");
for(k=0; k<num; k++)
printf("%d\t",arr[k]);
getch();
return 0;
}
b. Sort the given integers and show the intermediate results using insertion sort
35,12,14,9,15,45,32,95,40,5. Write C code to sort an integer array using insertion
sort[CO5,L3]
Insertion sort:
An insertion sort is one that sorts a set of records by inserting records into an existing
sorted file.
Based on the technique used by card players to arrange a hand of cards
– Player keeps the cards that have been picked up so far in sorted order
– When the player picks up a new card, he makes room for the new card and then
inserts it in its proper place
Given a list of numbers it divides the list into two parts- sorted part and unsorted part.
It picks up one element from the front of the unsorted part and then inserts it at its
proper position in the sorted part of the list
It requires two steps:
1. Scan the sorted part to find the place where the element from unsorted part can be
inserted.
While scanning shift the elements towards right to create space
2. Insert the element in the created space.
35 12 14 9 15 45 32 95 40 5
Given the input, the array has to be sorted using insertion sort
Steps:
1. Take 12 and check with the previous element and insert it in a sorted manner
12 35 14 9 15 45 32 95 40 5
2. Take 14 and place it in the correct position
12 14 35 9 15 45 32 95 40 5
3. Take 9 and place it in the correct position
9 12 14 35 15 45 32 95 40 5
4. Take 15 and place it in the correct position
9 12 14 15 35 45 32 95 40 5
5. Take 45 and 32 & place it in the correct position
9 12 14 15 32 35 45 95 40 5
6. Take 95 and 40 & place it in the correct position
9 12 14 15 32 35 40 45 95 5
7. Remaining elements are in their position except 5. Take 5 & place it in the correct
position
5 9 12 14 15 32 35 40 45 95
Finally array is sorted.
Code:
void main()
{
int n, arr[30], i, j, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i< n; i++) {
scanf("%d", &arr[i]);
}
for (j = 1 ; j < n; j++)
{
k=j ;
while ( k> 0 && arr[k] < arr[k-1])
{
t = arr[k];
arr[k] = arr[k-1];
arr[k-1] = t;
k--;
}
}
printf("Sorted list in ascending order:\n");
for (i= 0; i< n; i++) {
printf("%d\n", arr[i]);
}
getch();
}
Steps:
1. Find the minimum and swap with the first position 5 12 14 9 15 45 32 95 40 35
2. Find the next minimum and swap with the second position. Similarly the remaining
steps are proceeded.5 9 14 12 15 45 32 95 40 35 3.
5 9 12 14 15 45 32 95 40 35
4.
5 9 12 14 15 45 32 95 40 35
5.
5 9 12 14 15 45 32 95 40 35
6.
5 9 12 14 15 32 45 95 40 35
7.
5 9 12 14 15 32 35 95 40 45
8.
5 9 12 14 15 32 35 40 95 45
9.
5 9 12 14 15 32 35 40 45 95
Code:
void main()
{
int arr[30],n,i,j,t,small,pos;
}
t=arr[i];
arr[i]=arr[pos];
arr[pos]=t;
}
printf("The sorted list is…");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
}
b. Sort the given integers and show the intermediate results using bubble sort
35,12,14,9,15,45,32,95,40,5
Write C code to sort an integer array using bubble sort[CO5,L3]
Bubble sort:
Bubble sort is a simple sorting algorithm. The algorithm starts at the beginning of the
data set. It compares the first two elements, and if the first is greater than the second, it
swaps them.
It continues doing this for each pair of adjacent elements to the end of the data set. It
then starts again with the first two elements, repeating until no swaps have occurred on
the last pass.
Bubble sort can be used to sort a small number of items (where its inefficiency is
not a high penalty). Bubble sort may also be efficiently used on a list that is already
sorted except for a very small number of elements.
35 12 14 9 15 45 32 95 40 5
Given the input the array has to be sorted using bubble sort
Steps:
Pass 1:
Comparison 1:
First two elements are compared and swapped if not in order
12 35 14 9 15 45 32 95 40 5
Comparison 2:
Next two elements are compared and swapped if not in order. This proceeds for the
remaining elements
12 14 35 9 15 45 32 95 40 5
Comparison 3:
12 14 9 35 15 45 32 95 40 5
Comparison 4:
12 14 9 15 35 45 32 95 40 5
Comparison 5:
12 14 9 15 35 45 32 95 40 5
Comparison 6:
12 14 9 15 35 32 45 95 40 5
Comparison 7:
12 14 9 15 35 32 45 95 40 5
Comparison 8:
12 14 9 15 35 32 45 40 95 5
Comparison 8:
12 14 9 15 35 32 45 40 5 95
Similarly after 2nd pass the result is:
12 9 14 15 32 35 40 5 45 95
After 3rd pass:
9 12 14 15 32 35 5 40 45 95
After 4th pass:
9 12 14 15 32 5 35 40 45 95
After 5th pass:
9 12 14 15 5 32 35 40 45 95
After 6th pass:
9 12 14 5 15 32 35 40 45 95
After 7th pass:
9 12 5 14 15 32 35 40 45 95
After 8th pass:
9 5 12 14 15 32 35 40 45 95
After 9th pass:
5 9 12 14 15 32 35 40 45 95
Code:
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[100];
int i, j, temp, n ,flag=1;
printf("how many numbers you want to sort : \n");
scanf("%d",&n);
printf("Enter %d number values you want to sort\n", n);
if(a[j]>a[j+1])
{
flag=1;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <n ; i++ )
printf ( "%d\t", a[i] ) ;
getch();
}
32<44
44 32
Pivot i=4
j=4
32<44
32 44
Code:
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int left, int right);
int main()
{
int arr[30];
int i,n;
printf("Enter total no. of the elements : ");
scanf("%d",&n);
printf("Enter total %d elements : \n",size);
for(i=0; i<n; i++)
scanf("%d",&arr[i]);
qsort(arr,0,n-1);
printf("Quick sorted elements are as : \n");
for(i=0; i<n; i++)
printf("%d\t",arr[i]);
getch();
return 0;
}
void qsort(int arr[20], int left, int right)
{
int i,j,pivot,tmp;
if(left<right)
{
pivot=left;
i=left+1;
j=right;
while(i<j)
{
while(arr[i]<=arr[pivot] && i<right)
i++;
while(arr[j]>arr[pivot])
j--;
if(i<j)
{
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
}
tmp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=tmp;
qsort(arr,left,j-1);
qsort(arr,j+1,right);
}
}
b. Write an algorithm to sort a set of 'N' numbers using Merge sort. Trace the
algorithm for the following set of numbers.
88,11,22,44,66,99,32,67,54,10 Nov/Dec 2015[CO5,L3]
The Merge sort algorithm is based on divide and conquers strategy. First, the sequence
to be sorted is decomposed into two halves ( Divide ). Each half is sorted independently
( Conquer
). Then the two sorted halves are merged to a sorted sequence ( Combine ).
88 11 22 44 66 99 32 67 54 10
Given the input, the array has to be sorted using quick sort
Steps:
1. Divide Step
88 11 22 44 66
99 32 67 54 10
88 11 22 44 66 99 32 67 54 10
88 11 22 44 66 99 32 67 54 10
99 32
88 11
#include<conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int main()
{
int arr[30];
int i,size;
printf("\n\t------- Merge sorting method -------\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t------- Merge sorted elements -------\n\n");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
return 0;
}
void part(int arr[],int min,int max)
{
88 11 99 32
11 88 22 44 66 32 99 67 54 10
11 22 88 44 66 10 54 32 67 99
11 22 44 66 88 10 32 54 67 99
10 11 22 32 44 54 66 67 88 99
int mid;
if(min<max)
{
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
merge(arr,min,mid,max);
}
}
c. Write an algorithm to sort a set of 'N' numbers using Radix sort. Trace the
algorithm for the following set of numbers.
88,11,22,44,66,99,32,67,54,10[CO5,L3]
Radix sort is a non-comparative integer sorting algorithm that sorts data with integer
keys by grouping keys by the individual digits which share the same significant position
and value
Sort by the least significant digit first (counting sort)
Numbers with the same digit go to same bin
Reorder all the numbers: the numbers in bin 0 precede the numbers in bin 1, which
precede the numbers in bin 2, and so on
Sort by the next least significant digit
Continue this process until the numbers have been sorted on all k digits
88 11 22 44 66 99 32 67 54 10
Given the input the array has to be sorted using radix sort
Steps:
Code:
#include<stdio.h>
#include<conio.h>
radix_sort(int array[], int n);
void main()
{
int array[100],n,i;
clrscr();
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
printf("\nEnter the elements to be sorted: \n");
for(i = 0 ; i < n ; i++ )
{
printf("\tArray[%d] = ",i);
scanf("%d",&array[i]);
}
printf("\nArray Before Radix Sort:"); //Array Before Radix Sort
for(i = 0; i < n; i++)
{
printf("%d ", array[i]);
}
printf("\n");
radix_sort(array,n);
printf("\nArray After Radix Sort: "); //Array After Radix Sort
bucket[l][buck[l]++] = arr[i];
}
i=0;
for(k=0 ; k<10 ; k++)
{
for(j=0 ; j<buck[k] ; j++)// Rearrange the elements in the array
{
arr[i++] = bucket[k][j];
}
}
div*=10;
}
}
}
Sort by comparing and ordering the one‟s digits:
Digit Sub list
0 10
1 11
2 22 32
3
4 44 54
5
6 66
7 67
8 88
9 99
Combine the numbers in order
10 11 22 32 44 54 66 67 88 99.
It is already sorted. Therefore it is not necessary to go for the next significant
digit.
Hash Function:
The hash function will take any item in the collection and return an integer in the range
of slot names, between 0 and m-1. Assume that we have the set of integer items 54, 26,
93, 17,77, and 31. Our first hash function, sometimes referred to as the ―remainder
method,‖ simply takes an item and divides it by the table size, returning the remainder
as its hash value (h(item)=item%11) gives all of the hash values for our example items.
Note that this remainder method (modulo arithmetic) will typically be present in some
form in all hash functions, since the result must be in the range of slot names.
Item Hash Value
54 10
26 4
93 5
17 6
77 0
31 9
Methods of Hashing Function:
i) Mid Square Method
A key is multiplied by itself and the hash value is obtained by selecting an appropriate
number of digits from the middle of the square. The method works best if the table size
is a power of two. The same positions in the square must be used for all keys.
ii) Module Division (or) Division Remainder
Address = Key MOD Table size. While this algorithm works with any table size, a list
size that is a prime number produces fewer collisions than other list sizes.
iii) Folding Method
There are two folding methods that are used, fold shift and fold boundary. In fold shift,
the key value is divided into parts whose size matches the size of the required address.
Then the left and right parts are shifted and added with the middle part.
In fold boundary, the left and right numbers are folded on a fixed boundary between
them and the center number.
a. Fold Shift
Key: 123456789
123
456
789
---
1368 ( 1 is discarded)
b. Fold Boundary
Key: 123456789
2. Quadratic Probing
3. Double hashing
Linear probing (using neighboring slots):
Probing is the process of a placing in next available empty position in the hash table.
The Linear probing method searches for next suitable position in a linear manner(next
by next).Since this method searches for the empty position in a linear way, this method
is referred as linear probing. In linear probing for the ith probe, the position to be tried is,
(h(k) + i) mod Table_Size, where ‗f‘ is a linear function of i, F(i)=i. This amounts to
trying cells sequentially in search of an empty cell.
Algorithm for linear probing:
1. Apply hash function on the key value and get the address of the location.
2. If the location is free, then
i) Store the key value at this location, else
ii) Check the remaining locations of the table one after the other till an empty location is
reached. Wrap around on the table can be used. When we reach the end of the table,
start
looking again from the beginning.
iii) Store the key in this empty location.
3.End
Advantages of linear probing:
1. It does not require pointers.
2. It is very simpler to implement.
Disadvantages of linear probing:
1. It forms clusters, which degrades the performance of the hash table for sorting and
retrieving data. It is known as primary clustering meaning that any key that hashes into
the cluster will require several attempts to resolve the collision and then it will add to the
cluster.
2. If any collision occur when the hash table becomes half full, it is difficult to find an
empty location in the hash table and hence the insertion process takes a longer time.
As shown in the above figure, the elements are inserted in the next adjacent possible
position if not able to insert elements in the index calculated.
Quadratic probing:
Better behavior is usually obtained with quadratic probing, where the secondary hash
function depends on the re-hash index. In this technique, F(i) is a quadratic function of i.
That means, alternative locations are searched as a quadratic function. Thus F(i)=i2 or
hi(x)=(hash(x) + i2) % n
• Probe sequence:
h0(k) = h(k) mod TableSize
h1(k) = (h(k) + 1) mod TableSize
Double hashing:
To overcome the situation of secondary clustering of quadratic probing, Double hashing
is used. Double hashing uses the idea of applying a second hash function will be the
number of positions from the point of collision to insert.
F(i)=i*hash2(k)
Or
hi(k)= (hash(k) +i *hash2(k))%TableSize.
h0(k) = h(k) mod TableSize
h1(k) = (h(k) + 1*h2(k)) mod TableSize
h2(k) = (h(k) + 2*h2(k)) mod TableSize
h3(k) = (h(k) + 3*h2(k)) mod TableSize
hi(k) = (h(k) + i* h2(k)) mod TableSize
A popular second hash function is Hash2(X)=R-(X mod R) where R is a prime number
that is smaller than the size of the table.
To insert 18,89,21,58,68 using Double hashing the following steps are followed:
To insert 18, 18%10=8
To insert 89, 89%10=9
To insert 21, 21%10=1
To insert 58, 58%10=8
Collision occurs. Therefore (8+1*(7-58%7) )%10=3
Hash2(58)=7-58%7=5
To insert 68, 68%10=8
Collision occurs. Therefore (8+1*(7-68%7))%10=0
15
34
Enter the number to search
12
12 is present at location 3
20 32 12 15 34
01234
For searching 12 in the array, search begins from index 0 sequentially and as the
element is
found in index 2 search is completed successfully
b. Binary search April/May 2015
A dichotomizing search in which the set of items to be searched is divided at each step
into two equal, or nearly equal, parts, Also known as binary chop. The most efficient
method used for searching a sequential table is binary search. It doesn‘t need any
primary or secondary index.
A binary search or half-interval search algorithm finds the position of a specified
value (the input "key") within a sorted array. At each stage, the algorithm compares the
input key value with the key value of the middle element of the array.
If the keys match, then a matching element has been found so its index, or position, is
returned.
Otherwise, if the sought key is less than the middle element's key, then the algorithm
repeats its action on the sub-array to the left of the middle element or, if the input key is
greater, on the sub-array to the right. If the remaining array to be searched is reduced to
zero, then the key cannot be found in the array and a special "Not found" indication is
returned.
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the number to search: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is present in location %d\n.",mid+1);
getch();
}
Output:
Enter the size of an array
5
Enter the elements in ascending order
12
13
16
20
32
Enter the number to search
20
The number is present in location 4
The elements to be inserted in the table of size 7 are 13, 15, 24 and 6. They are
inserted by
applying h(k)= k mod 7 using linear probing as follows:
13%7=6
15%7=1
24%7=3
6%7=6(Using linear probing it is inserted in 0)
Now 23 is inserted into the table, as the table is more than half full, a new table is
created which is double the size. The new table size is 17 as it is the first prime which is
twice as large as the old table size. The elements are reinserted using the hash function
h(k)=k mod
17. 23 and 24 are inserted using linear probing.
06
1 15
2
3 24
4
5
6 13
1
2
3
4
5
66
7
23
8 24
9
10
11
12
13
13
14
15
15
16
Linear Probing is used Global depth(GD): Value associated with the root indicating the
number of bits to determine the leaf The directory is extended for the following reasons:
1. If the insertion of the new element is causing overflow situation in a bucket then
compare its local depth with the global depth
2. If the local depth is less than the global depth then add a new bucket, adjust the
pointers and redistribute the elements
3. If the local depth is equal to the global depth then expand the directory
GD:2
Insertion:
Assume that we want to insert the key 100100 into the table which is given in figure
above.
This would go into the third leaf, because the the first two bits are 10. But the third leaf
leaf is already full there is no room. We thus split this leaf into two leaves, the elements
that starts with 100 are placed into one block and 101 is placed into another block. Now
all the elements are determined by the first three bits. This requires increasing the
directory size to 3. These changes are reflected in the following figure.
GD: 3
00 01 10 11
000 001 010 011 100 101 110 111
LD:2
000100
001000
001010
001011
LD:2
010100
011000
LD:2
100000
101000
101100
101110
LD:2
111000
111001
LD:2
000100
001000
001010
001011
LD:3
101000
101100
101110
LD:3
100000
100100
LD:2
010100
011000
LD:2
111000
111001
If the key 000000 is now inserted then the first leaf is split generating two leaves. The
result
is as follows:
GD:3Advantages:
It provides quick access times for insert and find operations
There is possibility of duplicate keys
7. PROBLEM IN HASHING
Given input {4371, 1323, 6173, 4199, 4344, 9679, 1989} and a hash function h(x)=x
mod10. Show the result in: May/June 2012[CO5,H3]
1. Separate Chaining hash table:
2. Open addressing hash table using linear probing
3. Open addressing hash table using quadratic probing
4 Open addressing hash table with second hash function h2(x)=7-{x mod 7}
1. Separate Chaining hash table:
h(4371)=4371 mod 10=1
h(1323)=1323 mod 10=3
h(6173)=6173 mod 10=3
h(4199)=4199 mod 10=9
h(4344)=4344 mod 10=4
h(9679)=9679 mod 10=9
h(1989)=1989 mod 10=9
000 001 010 011 100 101 110 111
LD:3
000000
000100
LD:3
101000
101100
101110
LD:3
100000
100100
LD:2
010100
011000
LD:2
111000
111001
LD:3
001000
001010
001011
4. Open addressing hash table with second hash function h2(x)=7-{x mod 7}
h(4371)=4371 mod 10=1
h(1323)=1323 mod 10=3
h(6173)=6173 mod 10=3
Collision occurs and so h(6173)=(3+1*(7-(6173 mod 7))) mod 10=4
h(4199)=4199 mod 10=9
h(4344)=4344 mod 10=4
Collision occurs and so h(4344)=(4+1*(7-(4344 mod 7))) mod 10=7
h(9679)=9679 mod 10=9
Collision occurs and so h(9679)=(9+1*(7-(9679 mod 7))) mod 10=1. Again collision
occurs
and so h(9679) )=(9+2*(7-(9679 mod 7))) mod 10=3. Again collision occurs and so
h(9679)
)=(9+3*(7-(9679 mod 7))) mod 10=5.
h(1989)=1989 mod 10=9
Collision occurs and so h(1989)=(9+1*(7-(1989 mod 7))) mod 10=5. Again Collision
occurs
and so h(1989)=(9+2*(7-(1989 mod 7)))mod 10=1. Again collision occurs and so
h(1989)=(9+3*(7-(1989 mod 7)))mod 10=7.Again collision occurs and so
h(1989)=(9+4*(7-
(1989 mod 7)))mod 10=3. Again collision occurs and so h(1989)=(9+5*(7-(1989 mod
7)))mod 10=9. Again collision occurs and so h(1989)=(9+6*(7-(1989 mod 7)))mod 10=5.
Again collision occurs and so h(1989)=(9+7*(7-(1989 mod 7)))mod 10=5. The Cycle
continues. It cannot be assigned.
0
1 4371
2
3 1323
4 6173
5 9679