0% found this document useful (0 votes)
55 views173 pages

Final Sub FDSP 1941060

The document describes a lab manual for a programming lab on data structures. It contains instructions for students to write a C++ program to perform set operations like union, intersection, and difference on two input sets. The program is provided that implements these operations and tests them by running on sample input sets and displaying the output.

Uploaded by

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

Final Sub FDSP 1941060

The document describes a lab manual for a programming lab on data structures. It contains instructions for students to write a C++ program to perform set operations like union, intersection, and difference on two input sets. The program is provided that implements these operations and tests them by running on sample input sets and displaying the output.

Uploaded by

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

Government College of Engineering,

Jalgaon
(An Autonomous Institute of Govt of Maharashtra)
Department of Computer Engineering

Lab Manual
For
CO205 Fundamentals of Data Structure
Programming Lab
(Sem-III)
S. Y. B. Tech.(Computer)

Name of the student -: YASH PATIL

PRN -: 1941060

Course Teacher : RUCHA PATIL Course Coordinator :


Practical no. 01
Student Name :YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil

Aim:Write a program to perform Set operations - Union, Intersection, Difference etc.


Objective: - To accept two sets from users and perform set operations like Union,
Intersection and Difference

Theory:
Sets can be combined in a number of different ways to produce another set. Here four basic
operations are introduced and their properties are discussed.

Union:

The union of sets A and B, denoted by A B , is the set defined as

A B={x|x∈A x∈B}

Example 1: If A = {1, 2, 3} and B = {4, 5} , then A B = {1, 2, 3, 4, 5} .

Example 2: If A = {1, 2, 3} and B = {1, 2, 4, 5} , then A B = {1, 2, 3, 4, 5} .

Note that elements are not repeated in a set.

Intersection:

The intersection of sets A and B, denoted by A B , is the set defined as

A B={x|x∈A x∈B}

Example 1: If A = {1, 2, 3} and B = {1, 2, 4, 5} , then A B = {1, 2} .

Example 2: If A = {1, 2, 3} and B = {4, 5} , then A B=Ǿ.

Difference: The difference of sets A from B , denoted by A - B , is the set defined as

A-B={x|x∈A x∉B}

Example 5: If A = {1, 2, 3} and B = {1, 2, 4, 5} , then A - B = {3} .

Example 6: If A = {1, 2, 3} and B = {4, 5} , then A - B = {1, 2, 3} .

Note that in general (A - B ) is not equal to (B - A)


Difference:

1. Set A = {1, 2, 3} and B = {4, 5, 6}.

Find the difference between the two sets:

(i) A and B

(ii) B and A

Solution:

The two sets are disjoint as they do not have any elements in common. (i)

A - B = {1, 2, 3} = A

(ii) B - A = {4, 5, 6} = B

2. Let A = {a, b, c, d, e, f} and B = {b, d, f, g}.

Find the difference between the two sets:

(i) A and B

(ii) B and A

Solution:

(i) A - B = {a, c, e}

Therefore, the elements a, c, e belong to A but not to B

(ii) B - A = {g)

Therefore, the element g belongs to B but not A.


Implementation:
Header Files :
#include<stdio.h>
#include<stdlib.h>
#define max 20 // Macro

Function Declaration:

void accept(int a[max],int m);


void display(int a[max],int m);
void uni(int a[max],int b[max], int m,int n); void
diff(int a[max],int b[max],int m,int n); void
inter(int a[max],int b[max],int m,int n);

1. Accept:

void accept(int a[max],int m)


{
int i;
printf("\nEnter Set element : ");
for(i = 0; i < m; i + +)
scanf("%d",&a[i]);
}

2. Display
void display(int a[max],int m)
{
int i;
printf( "{ ");
for(i = 0; i < m; i + +)
printf("%d ",a[i]);
printf("}\n");
}
3. Union
void uni(int a[max],int b[max], int m,int n)
{ int c[10],i,j,k = 0, flag = 0;
for(i = 0; i < m; i + +)
{
c[k]=a[i]; k
+ +;
}
for(i = 0; i < n; i + +)
{ for(j = 0; j < m; j + +)
{
if(b[i] = = a[j])
flag = 1;
}
if(flag = = 0)
{
c[k]=b[i]; k
+ +;
}
flag = 0;
}
display(c,k);
}

4. Difference:

void diff(int a[max],int b[max],int m,int n)


{
int i,j,c[10],flag = 0, k = 0;
for(i = 0; i < m; i + +)
{ for(j = 0; j < n; j + +)
{
if(a[i] = = b[j])
flag = 1;
}
if(flag = = 0)
{ c[k]=a[i]; k
+ +;
}
flag = 0;
}
display(c,k);
}

5. Intersection:
void inter(int a[max],int b[max],int m,int n)
{
int c[10],i,j,k = 0; for(i =
0; i < m; i + +)
{
for(j = 0; j < n; j + +)
{
if(a[i] = = b[j])
{
c[k] = a[i]; k
+ +;
}
}
}
display(c,k);
}

Result and Conclusion:

Name and Sign of Course Teacher


PROGRAM -

#include <stdio.h>
#include <conio.h>
int main()
{
int a[5], b[5], c[5], fl = 0, ch;
char ans;
int i, j, n, m, k, x;
printf("Enter limit of set A \n ");
scanf("%d", &n);
printf("Enter value of set A \n ");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Enter limit of setB \n ");
scanf("%d", &m);
printf("Enter val of set B \n ");
for (j = 0; j < m; j++)
scanf("%d", &b[j]);
printf("Set A:{");
for (i = 0; i < n; i++)
printf("%d,", a[i]);
printf("}");
printf(" \n Set B:{");
for (j = 0; j < m; j++)
printf("%d,", b[j]);
printf("}");
do
{
printf(" \n 1.Intersection \n 2.Union \n 3.A-B \n 4.B-A \n
5.Symmetric Difference \n 6.Exit ");
printf(" \n Enter ur choice");
scanf("%d", &ch);
switch (ch)
{
case 1:
for (k = 0, i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
if (a[i] == b[j])
{
c[k] = a[i];
k++;
}
}
}
printf("Intersection of A nd B:{");
break;
case 2:
k = 0;
x = 0;
for (i = 0; i < n; i++)
{
c[x] = a[i];
x++;
}
k = x;
for (i = 0; i < m; i++)
{
fl = 0;
for (j = 0; j < n; j++)
{
if (a[j] == b[i])
{
fl = 0;
break;
}
else
fl = 1;
}
if (fl == 1)
{
c[k] = b[i];
k++;
}
}
printf("Union of A nd B:{");
break;
case 3:
k = 0;
for (i = 0; i < n; i++)
{
fl = 0;
for (j = 0; j < m; j++)
{
if (a[i] == b[j])
{
fl = 0;
break;
}
else
{
fl = 1;
}
}
if (fl == 1)
{
c[k] = a[i];
k++;
}
}
printf("Difference is A-B:{");
break;
case 4:
k = 0;
for (i = 0; i < m; i++)
{
fl = 0;
for (j = 0; j < n; j++)
{
if (b[i] == a[j])
{
fl = 0;
break;
}
else
fl = 1;
}
if (fl == 1)
{
c[k] = b[i];
k++;
}
}
printf("Difference is B-A:{");
break;
case 5:
k = 0;
for (i = 0; i < n; i++)
{
fl = 0;
for (j = 0; j < m; j++)
{
if (a[i] == b[j])
{
fl = 0;
break;
}
else
{
fl = 1;
}
}
if (fl == 1)
{
c[k] = a[i];
k++;
}
}
for (i = 0; i < m; i++)
{
fl = 0;
for (j = 0; j < n; j++)
{
if (b[i] == a[j])
{
fl = 0;
break;
}
else
fl = 1;
}
if (fl == 1)
{
c[k] = b[i];
k++;
}
}
printf("Symmetric Difference:{");
break;
}
for (i = 0; i < k; i++)
{
if (c[i] != c[i + 1])
printf(" %d,", c[i]);
}
printf("}");
printf("Wanna 2 continue.....(y/n)");
scanf("%c", &ans);
} while (ans == 'y' || ans == 'Y');
getch();
}

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
PS C:\Users\admin> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { gcc t.c -o t } ; if ($?) { .\t }
Enter limit of set A

3
Enter value of set A
1
4
3

Enter limit of setB


3
Enter value of set B
1

2
3
Set A:{1,4,3,}
Set B:{1,2,3,}

1.Intersection

2.Union
3.A-B

4.B-A
5.Symmetric Difference
6.Exit
Enter ur choice3
Difference is A-B:{ 4,}Wanna 2 continue.....(y/n)

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
PS C:\Users\admin> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { gcc t.c -o t } ; if ($?) { .\t }
Enter limit of set A
4
Enter value of set A
1

2
3
4
Enter limit of setB
4
Enter val of set B
3

4
5
6
Set A:{1,2,3,4,}

Set B:{3,4,5,6,}
1.Intersection
2.Union
3.A-B

4.B-A
5.Symmetric Difference
6.Exit
Enter ur choice1
Intersection of A nd B:{ 3, 4,}Wanna 2 continue.....(y/n)

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
PS C:\Users\admin> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { gcc t.c -o t } ; if ($?) { .\t }
Enter limit of set A

4
Enter value of set A

1
2
3
4
Enter limit of setB
4
Enter val of set B

3
4
5
6

Set A:{1,2,3,4,}
Set B:{3,4,5,6,}
1.Intersection
2.Union

3.A-B
4.B-A
5.Symmetric Difference
6.Exit
Enter ur choice2

Union of A nd B:{ 1, 2, 3, 4, 5, 6,}Wanna 2 continue.....(y/n)

Experiment No.2

Student Name : YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil


Aim:Write a program to perform various string operations such as Copy, Length,
Concatenation and Reversing etc without using library functions.
Objective: - Students has to accept two strings and perform the given operations using menu
driven program.

Theory:-
A string in C is merely an array of characters. The length of a string is determined by a
terminating null character: '\0'. So, a string with the contents, say, "abc" has four characters: 'a',
'b', 'c', and the terminating null character.
The terminating null character has the value zero.
In C, string constants (literals) are surrounded by double quotes ("), e.g. "Hello world!" and
are compiled to an array of the specified char values with an additional null terminating
character (0-valued) code to mark the end of the string. The type of a string constant is char [].

<string.h> is a standard header

Because programmers find raw strings cumbersome to deal with, they wrote the code in the
<string.h> library. It represents not a concerted design effort but rather the accretion of
contributions made by various authors over a span of years.
First, three types of functions exist in the string library:
● the mem functions manipulate sequences of arbitrary characters without regard to
the null character;
● the str functions manipulate null-terminated sequences of characters;
● the strn functions manipulate sequences of non-null characters.

The more commonly-used string functions


The nine most commonly used functions in the string library are:
● strcat - concatenate two strings
● strchr - string scanning operation
● strcmp - compare two strings
● strcpy - copy a string
● strlen - get string length
● strncat - concatenate one string with part of another
● strncmp - compare parts of two strings
● strncpy - copy part of a string
gets() and puts() functions:
We can read a string using the %s conversion specification in the scanf function. However, it has
a limitation that the strings entered cannot contain spaces and tabs. To overcome this problem, the
C standard library provides the gets function. It allows us to read a line of characters (including
spaces and tabs) until the newline character is entered, i. e., the Enter key is pressed. A call to this
function takes the following form:
gets(s);
where s is an array of char, i. e., a character string. The function reads characters entered from the
keyboard until newline is entered and stores them in the argument string s, The newline character
is read and converted to a null character (\O) before it is stored in s. The value returned by this
function, which is a pointer to the argument string s, can be ignored. The C standard library
provides another function named puts to print a string on the display. A typical call to this function
takes the following form:
puts(s);
where s is an array of char, i. e., a character string. This string is printed on the display followed
by a newline character.

Example: String I/O using the gets and puts function


Consider the code segment given below.
char str[81];
puts("Enter a line of text:\n");
gets (str);
puts("You entered:\n")
puts(str);

A line of text typically contains 80 characters. Thus, the array str has been declared to store 81
characters with a provision to store the null terminator. The output of this code segment is shown
below.
Output:
Enter a line of text:
Harish Gadade You
entered: Harish
Gadade
Implementation:

#define max 30

1. Function Declaration
void concat(char s1[max],char s2[max],char s3[max]);
void reverse(char s1[max],char s3[max]);
void copy(char s1[max],char s2[max]);

2. Function Calling
stringLength(s1);
concat(s1,s2,s3);
reverse(s1,s3);
copy(s1,s2);

3. String Length

void stringLength(char s1[max])


{
int i;
for(i=0;s1[i]!='\0';i++);
printf("\nString Length = %d ",i);
}

4. String Concat

void concat(char s1[max],char s2[max],char s3[max])


{
int i,k=0;
for(i=0;s1[i]!='\0';i++)
{
s3[k]=s1[i];
k++;
}
s3[k]='\0';
for(i=0;s2[i]!='\0';i++)
{
s3[k]=s2[i];
k++;
}
s3[k]='\0';
printf("\n Concatenation is : %s",s3);
}
5. String Reverse

void reverse(char s1[max],char s3[max])


{
int i=0,j,len,k=0;
len=strlen(s1);
j=len-1;
for(i=j;i>=0;i--)
{
s3[k]=s1[i];
k++;
}
s3[k]='\0';
printf("\n Reverse String is : %s",s3);
}

6. String Copy

void copy(char s1[max],char s2[max])


{
int i;
for(i=0;s2[i]!='\0';i++)
s1[i]=s2[i];
s2[i]='\0';
printf("\n Now First String is = %s",s1);
}

Lab Assignment:

Student has to accept full name in one sting and your branch name in second string.

e.g. s1=”Harish Gadade”

s2=”Computer Engineering”

Write a menu driven for string operation using above input string.

Name and Sign of Course Teacher


AIM : TO PERFORM VARIOUS STRING OPERATIONS SUCH AS
COPY,LENGTH,CONCATENATION AND REVERSING ETC WITHOUT USING LIBRARY
FUNCTIONS..
*/
#include<stdio.h>
#define max 30
void length(char[max]);
void concat(char[max],char[max],char[max]);
void reverse(char[max]);
void copy(char[max],char[max]);
void length(char s1[max])
{
int i,cnt=0;
for(i=0;s1[i]!='\0';i++)
{
cnt++;
}
printf("\n string length =%d",cnt);
}
void concat(char s1[max],char s2[max],char s3[max])
{
int i,k=0;
for(i=0;s1[i]!='\0';i++)
{
s3[k]=s1[i];
k++;
}
s3[k]='\0';
for(i=0;s2[i]!='\0';i++)
{
s3[k]=s2[i];
k++;
}
s3[k]='\0';
printf("\n concatenation is : %s",s3);
}
void reverse(char s1[max])
{
int i=0,j=0;
char rev[10];

while(s1[i]!='\0')
{
i++;
}
i--;
while(i>=0)
{
rev[j]=s1[i];
i--;
j++;
}
rev[j]='\0';
printf("reverse string is: %s\n",rev); }
void copy(char s1[max],char s2[max]) {
int i;
for(i=0;s2[i]!='\0';i++)
s1[i]=s2[i];
s2[i]='\0';
printf("\n copied string is=%s",s1); }
void main()
{
char s1[max],s2[max],s3[max]; int
ch;
printf("Enter the first string");
scanf("%s",s1);
printf("enter the second string");
scanf("%s",s2);
do
{
printf("\n 1.length");
printf("\n 2.concat");
printf("\n 3.reverse");
printf("\n 4.copy");
printf("\n 5.exit\n");
printf("enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1: length(s1);
break;
case 2: concat(s1,s2,s3);

Break;
case 3: reverse(s1);
break;
case 4: copy(s1,s2);
break;
case 5: printf("exit");
break;
}
}
while(ch<5);
}
OUTPUT :

PS C:\Users\admin\Desktop\C++1> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { gcc t.c -o t } ; if


($?) { .\t
}
Enter the first string
Yash
enter the second string
Patil

1.length
2.concat
3.reverse
4.copy
5.exit
enter your choice
1

string length =4
1.length
2.concat
3.reverse
4.copy
5.exit
enter your choice
2

concatenation is : YashPatil
1.length
2.concat
3.reverse
4.copy
5.exit
enter your choice
3
reverse string is: hsaY

1.length
2.concat
3.reverse
4.copy
5.exit
enter your choice
4

copied string is=Patil


1.length
2.concat
3.reverse
4.copy
5.exit
enter your choice
5
exit
PS C:\Users\admin\Desktop\C++1>

Experiment No. 3
Student Name : YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil

Aim: Write a program to perform operations on matrices like addition, multiplication, saddle
point & transpose etc using functions.

Objective: To accept two matrices from user and perform said matrix operation on these two
matrices. It is expected to use macro concept in your program.

Theory:
Followings are the matrix operation

● Matrix Addition:

Two matrices must have an equal number of rows and columns to be added.[1] The sum of two
matrices A and B will be a matrix which has the same number of rows and columns as do A and
B. The sum of A and B, denoted A + B, is computed by adding corresponding elements of A and
B

For example:
We can also subtract one matrix from another, as long as they have
the same dimensions. A − B is computed by subtracting elements of B
from corresponding elements of A, and has the same dimensions as A
and B. For example:
● Multiplication

If A is an n × m matrix and B is an m × p matrix,

the matrix product AB (denoted without multiplication signs or dots) is defined to be the n ×
p matrix

where each i, j entry is given by multiplying the entries Aik (across row i of A) by the entries
Bkj (down column j of B), for k = 1, 2, ..., m, and summing the results over k:

Thus the product AB is defined only if the number of columns in A is equal to the number of
rows in B, in this case m. Each entry may be computed one at a time. Sometimes, the
summation convention is used as it is understood to sum over the repeated index k.

● Transpose:

In linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal,
that is it switches the row and column indices of the matrix by producing another matrix denoted
as AT (also written A′, Atr, tA or At). It is achieved by any one of the following equivalent actions:

● reflect A over its main diagonal (which runs from top-left to bottom-right) to
obtain AT
● write the rows of A as the columns of AT
● write the columns of A as the rows of AT

Formally, the i th row, j th column element of AT is the j th row, i th column element of A:

If A is an m × n matrix then AT is an n × m matrix.


Examples:

● Saddle Point:

Given a matrix of n x n size, the task is to find saddle point of the matrix. A saddle point is an
element of the matrix such that it is the minimum element in its row and maximum in its column.

Examples:

Input: Mat[3][3] = { {1, 2, 3},


{4, 5, 6},
{7, 8, 9}}
Output: 7
7 is minimum in its row and maximum in its column.

Input: Mat[3][3] = {{1, 2, 3},


{4, 5, 6},
{10, 18, 4}}
Output: No saddle point
Implementation:
Header Files:
#include<stdio.h>
#include<stdlib.h>
#define max 20

Function Declarations:
void accept(int m[max][max],int row,int col); void
display(int m[max][max],int row,int col);
void add(int m1[max][max],int m2[max][max],int row,int col); void
mult(int m1[max][max],int m2[max][max],int row,int col); void
saddle(int m[max][max],int row,int col);
void transpose(int m[max][max],int row,int col);

1. Accept
void accept(int m[max][max],int row,int col)
{
int i,j;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&m[i][j]);
}

2. Display
void display(int m[max][max],int row,int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d ",m[i][j]);
}
printf("\n");
}
}

3. Matrix Addition
void add(int m1[max][max],int m2[max][max],int row,int col)
{
int m3[max][max],i,j;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
m3[i][j]=m1[i][j]+m2[i][j];

display(m3,row,col);
}
4. Matrix Multiplication
void mult(int m1[max][max],int m2[max][max],int row,int col)
{
int i,j,k,m3[max][max],sum=0;
for (i = 0; i < row; i++) // Rows of first matrix
{
for (j = 0; j < col; j++) //Columns of Second Matrix
{
for (k = 0; k < row; k++) // Rows of Second Matrix
{
sum = sum + m1[i][k]*m2[k][j];
}

m3[i][j] = sum;
sum = 0;
}
}
display(m3,row,col);
}

5. Matrix Transpose
void transpose(int m[max][max],int row,int col)
{
int t[max][max],i,j;
for(i=0; i<row; ++i)
{
for(j=0; j<col; ++j)
{
t[j][i] = m[i][j];
}
}
display(t,row,col);
}

6. Saddle Point
void saddle(int m[max][max],int row,int col)
{
int i,j,k,min,max1,pos[2][2];
/* find the saddle points in the given matrix */ for (i
= 0; i < row; i++)
{
min = m[i][0];
for (j = 0; j < col; j++)
{
if (min >= m[i][j])
{
min = m[i][j];
pos[0][0] = i;
pos[0][1] = j;
}
}

j = pos[0][1];
max1 = m[0][j];
for (k = 0; k < col; k++)
{
if (max1 <= m[k][j])
{
max1 = m[i][j];
pos[1][0] = k;
pos[1][1] = j;
}
}

/* saddle point - minimum of a row and maximum of the column */ if


(min == max1)
{
if (pos[0][0] == pos[1][0] && pos[0][1] == pos[1][1])
{
printf("Saddle point (%d, %d) : %d\n", pos[0][0], pos[0][1], max1);
}
}
}
}

Result and Conclusion:

Name and Sign of Course Teacher


AIM : TO PERFORM OPERATIONS ON MATRIX LIKE ADDITION, MULTIPLICATION,
TRANSPOSE
*/

#include<stdio.h> //header file


#include<stdlib.h> //header file
#define max 20
void accept(int matrix[max][max],int size); //function declaration void display(int
matrix1[max][max],int size);
void matrixadd(int matrix1[max][max],int matrix2[max][max],int add[max][max],int size1,int size2);
void matrixmult(int matrix1[max][max],int matrix2[max][max],int mult[max][max],int size1,int size2);
void matrixtranspose(int matrix[max][max],int trans[max][max],int size1);

int main()
{
int matrix1[max][max],matrix2[max][max],size1,size2,choice;
int trans[max][max],add[max][max],mult[max][max];

printf("\nProgram for arithmetic operations");


do //looping for display menu repeatedly
{
printf("\n---------------- MENU ----------------");
printf("\n1.Accept the matrices");
printf("\n2.Display");
printf("\n3.Addition");
printf("\n4.Multiplication");
printf("\n5.Transpose");
printf("\n0.Exit");
printf("\n--------------------------------------");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice) //perform operations on choice
{
case 1:
printf("\nEnter size of first matrix: ");
scanf("%d",&size1);
accept(matrix1,size1); //function calling
printf("\nEnter size of second matrix: ");
scanf("%d",&size2);
accept(matrix2,size2);
break;

case 2:
printf("\nFirst matrix is: ");
display(matrix1,size1); //function calling
printf("\nSecond` matrix is: ");
display(matrix2,size2);
break;

case 3:
printf("\nMatrix addition is: ");
matrixadd(matrix1,matrix2,add,size1,size2);
display(add,size1); //function calling break;

case 4:
printf("\nMatrix multiplication is: ");
matrixmult(matrix1,matrix2,mult,size1,size2);
display(mult,size1); //function calling
break;

case 5:
printf("\nTranspose of a matrix1 is: ");
matrixtranspose(matrix1,trans,size1);
display(trans,size1); //function calling
printf("\nTranspose of matrix2 is: ");
matrixtranspose(matrix2,trans,size2);
display(trans,size2);
break;

case 0:printf("\nGOOD BYE");


exit(0);
break;
default:
printf("\nEnter a valid choice");
break;
}
}while(choice!=0);
}

void accept(int matrix[max][max],int size) //function defination { int i,j;


printf("\nEnter matrix element: ");
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
scanf("%d",&matrix[i][j]);
}
}
}
void display(int matrix[max][max],int size) //function defination
{
int i,j;
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%d",matrix[i][j]);
printf("\t");
}
}
printf("\n");
}
void matrixadd(int matrix1[max][max],int matrix2[max][max],int mult[max][max],int size1,int size2)
//function defination
{
int i,j;
for(i=0;i<size1;i++)
{
for(j=0;j<size2;j++)
{
mult[i][j]=matrix1[i][j]+matrix2[i][j];
}
}
}
void matrixmult(int matrix1[max][max],int matrix2[max][max],int mult[max][max],int size1,int size2)
//function defination
{
int i,j,k,sum=0;
for(i=0;i<size1;i++)
{
for(j=0;j<size2;j++)
{
for(k=0;k<size1;k++)
{
sum=sum+matrix1[i][k]*matrix2[k][j];
}
mult[i][j]=sum;
sum=0;
}
}
}
void matrixtranspose(int matrix[max][max],int trans[max][max],int size) //function defination
{
int i,j;
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
trans[i][j]=matrix[j][i];
}
}
}

Output--

Program for arithmetic operations


---------------- MENU ----------------
1.Accept the matrices
2.Display
3.Addition
4.Multiplication
5.Transpose
0.Exit
--------------------------------------
Enter your choice: 1

Enter size of first matrix: 2

Enter matrix element: 1


2
3
4
Enter size of second matrix: 2

Enter matrix element: 1


2
3
4

---------------- MENU ---------------- 1.Accept


the matrices
2.Display
3.Addition
4.Multiplication
5.Transpose
0.Exit
-------------------------------------- Enter
your choice: 2

First matrix is: 1 2


34

12
34
---------------- MENU ---------------- 1.Accept
the matrices
2.Display
3.Addition
4.Multiplication
5.Transpose
0.Exit
-------------------------------------- Enter
your choice: 3

Matrix addition is: 2 4


68

---------------- MENU ---------------- 1.Accept


the matrices
2.Display
3.Addition
4.Multiplication
5.Transpose
0.Exit
-------------------------------------- Enter
your choice: 4

Matrix multiplication is: 7 10 15 22

---------------- MENU ---------------- 1.Accept


the matrices
2.Display
3.Addition
4.Multiplication
5.Transpose
0.Exit
-------------------------------------- Enter
your choice: 5

Transpose of a matrix1 is: 1 3 2 4

Transpose of matrix2 is: 1 3 2 4

---------------- MENU ---------------- 1.Accept


the matrices
2.Display
3.Addition
4.Multiplication
5.Transpose
0.Exit
-------------------------------------- Enter
your choice: 0

GOOD BYE
PS C:\Users\admin\Desktop\C++1>

Experiment No. 4
Student Name : YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil

Aim: Write a program to perform following operations on any database using structure:
Add,Delete, Modify, Display, Search & Sort etc

Objective: To accept student information from user and perform said operation on
students database. It is expected to use macro concept in your program.

Theory:

C Structure is a collection of different data types which are grouped together and each element
in a C structure is called member.

● If you want to access structure members in C, structure variable should be declared.


● Many structure variables can be declared for same structure and memory will be
allocated for each separately.
● It is a best practice to initialize a structure to null while declaring, if we don’t assign any
values to structure members.

Example program for C structure:


This program is used to store and access “id, name and percentage” for one student. We can also
store and access these data for many students using array of structures.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20]; float
percentage;
};

int main()
{
struct student record = {0}; //Initializing to null

record.id=1; strcpy(record.name,
"Vihaan"); record.percentage =
86.5;

printf(" Id is: %d \n", record.id);


printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

Output:
Id is: 1
Name is: Vihaan Percentage
is: 86.500000

Example program – Another way of declaring C structure:


In this program, structure variable “record” is declared while declaring structure itself. In above
structure example program, structure variable “struct student record” is declared inside main
function which is after declaring structure.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20]; float
percentage;
} record;

int main()
{
record.id=1; strcpy(record.name,
"Vihaan"); record.percentage =
86.5;

printf(" Id is: %d \n", record.id); printf("


Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

Output:
Id is: 1
Name is: Vihaan Percentage
is: 86.500000

C structure declaration in separate header file:


In above structure programs, C structure is declared in main source file. Instead of declaring C
structure in main source file, we can have this structure declaration in another file called “header
file” and we can include that header file in main source file as shown below.
Header file name – structure.h
Before compiling and executing below C program, create a file named “structure.h” and declare
the below structure.

struct student
{
int id;
char name[20]; float
percentage;
}record;

Main file name – structure.c:


In this program, above created header file is included in “structure.c” source file as #include
“Structure.h”. So, the structure declared in “structure.h” file can be used in “structure.c” source
file.

// File name - structure.c


#include <stdio.h> #include
<string.h>
#include "structure.h" /* header file where C structure is
declared */
int main()
{ record.id=1; strcpy(record.name,
"Vihaan"); record.percentage =
86.5;

printf(" Id is: %d \n", record.id); printf("


Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}
Output:
Id is: 1
Name is: Vihaan Percentage
is: 86.500000

Uses of structures in C:
1. C Structures can be used to store huge data. Structures act as a database.
2. C Structures can be used to send data to the printer.
3. C Structures can interact with keyboard and mouse to store the data.
4. C Structures can be used in drawing and floppy formatting.
5. C Structures can be used to clear output screen contents.
6. C Structures can be used to check computer’s memory size etc.
Array of Structures
As you know, C Structure is collection of different datatypes ( variables ) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This is also called as
structure array in C.

Example program for array of structures in C:


This program is used to store and access “id, name and percentage” for 3 students. Structure array
is used in this program to store and display records for many students. You can store “n” number
of students record by declaring structure variable as ‘struct student record[n]“, where n can be
1000 or 5000 etc.

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30]; float
percentage;
};
int main()
{ int i;
struct student record[2];

// 1st student's record record[0].id=1;


strcpy(record[0].name, "Vihaan");
record[0].percentage = 86.5;

// 2nd student's record record[1].id=2;


strcpy(record[1].name, "Priyanka");
record[1].percentage = 90.5;

// 3rd student's record record[2].id=3;


strcpy(record[2].name, "Rituja");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}
Output:
Records of STUDENT : 1 Id
is: 1
Name is: Vihaan Percentage
is: 86.500000 Records of
STUDENT : 2 Id is: 2
Name is: Priyanka Percentage
is: 90.500000 Records of
STUDENT : 3 Id is: 3
Name is: Rituja Percentage
is: 81.500000

Example program for declaring many structure variable in C:


In this program, two structure variables “record1″ and “record2″ are declared for same structure
and different values are assigned for both structure variables. Separate memory is allocated for
both structure variables to store the data.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[30]; float
percentage;
};

int main()
{
int i;
struct student record1 = {1, "Vihaan", 90.5};
struct student record2 = {2, "Rituja", 93.5};

printf("Records of STUDENT1: \n"); printf("


Id is: %d \n", record1.id); printf(" Name is:
%s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage);

printf("Records of STUDENT2: \n"); printf("


Id is: %d \n", record2.id); printf(" Name is:
%s \n", record2.name);
printf(" Percentage is: %f \n\n", record2.percentage);

return 0;
}
Output:
Records of STUDENT1:
Id is: 1
Name is: Vihaan Percentage
is: 90.500000 Records of
STUDENT2:
Id is: 2
Name is: Rituja Percentage
is: 93.500000

Passing struct to function


● A structure can be passed to any function from main function or from any sub function.
● Structure definition will be available within the function only.
● It won’t be available to other functions unless it is passed to those functions by value or by
address(reference).
● Else, we have to declare structure variable as global variable. That means, structure
variable should be declared outside the main function. So, this structure will be visible to
all the functions in a C program.

Passing structure to function in C:


It can be done in below 3 ways.

1. Passing structure to a function by value


2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global

Example program – passing structure to function in C by value:


In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can be
accessed from called function. This concept is very useful while writing very big programs in C.

#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,
"Vihaan"); 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: Vihaan Percentage
is: 86.500000

Example program – Passing structure to function in C by address:


In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to another
function with all members and their values. So, this structure can be accessed from called function
by its address.

#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, "Vihaan");
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: Vihaan Percentage
is: 86.500000

Example program to declare a structure variable as global in C:


Structure variables also can be declared as global variables as we declare other variables in C. So,
When a structure variable is declared as global, then it is visible to all the functions in a program.
In this scenario, we don’t need to pass the structure to any function separately.

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20]; float
percentage;
};
struct student record; // Global declaration of structure

void structure_demo(); int


main()
{
record.id=1; strcpy(record.name,
"Vihaan"); record.percentage =
86.5;

structure_demo();
return 0;
}
void structure_demo()
{
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: Vihaan Percentage
is: 86.500000
Structure using Pointer
C structure can be accessed in 2 ways in a C program. They are,

1. Using normal structure variable


2. Using pointer variable

Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to
access the data using pointer variable. You have learnt how to access structure data using normal
variable in C – Structure topic. So, we are showing here how to access structure data using pointer
variable in below C program.

Example program for C structure using pointer:


In this program, “record1” is normal structure variable and “ptr” is pointer structure variable. As
you know, Dot(.) operator is used to access the data using normal structure variable and arrow(->)
is used to access data using pointer variable.

#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30]; float
percentage;
};
int main()
{
int i;
struct student record1 = {1, "Vihaan", 90.5};
struct student *ptr;

ptr = &record1;

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", ptr->id); printf("
Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);

return 0;
}

Output:
Records of STUDENT1: Id
is: 1
Name is: Vihaan Percentage
is: 90.500000
Implementation:

Structure Declaration
struct student
{
int rollno;
char name[20];
float per;
};

Header Files:
#include<stdio.h>
#include<stdlib.h>
#define max 20

Function Declarations:
void create(struct student s[max],int n);
void display(struct student s[max],int n); int
insert(struct student s[max],int n);
int delet(struct student s[max],int n); void
search(struct student s[max],int n); void
sort(struct student s[max],int n); void
modify(struct student s[max],int n);

Calling Statements:
create(s,n);
display(s,n);
n=insert(s,n);
n=delet(s,n);
modify(s,n);
search(s,n);
sort(s,n);

1. Create Database
void create(struct student s[max],int n)
{
int i;
printf("\n Enter Records :\n\n");
for(i=0;i<n;i++)
{ printf("\nRoll No = ");
scanf("%d",&s[i].rollno);
printf("\nName = ");
scanf("%s",s[i].name);
printf("\nPercentage = ");
scanf("%f",&s[i].per);
}
}
2. Display
void display(struct student s[max],int n)
{
int i;
printf("\n \n");
printf("\nRoll No\t\tName\t\tPercentage\n");
printf("\n \n");
for(i=0;i<n;i++)
printf("%d\t\t%s\t\t%.2f\n",s[i].rollno,s[i].name,s[i].per);
printf("\n \n");
}

3. Insert New Record Into Database

int insert(struct student s[max],int n)


{
struct student s1; int
i,position;
printf("\nEnter New Record \n");
printf("\nRoll No = ");
scanf("%d",&s1.rollno);
printf("\nName = ");
scanf("%s",s1.name);
printf("\nPercentage = ");
scanf("%f",&s1.per);
printf("\nEnter Position : ");
scanf("%d",&position);
printf("%d\n",n);
for(i=n;i>=position;i--)
s[i+1]=s[i];
s[position]=s1;
return(n+1);
}

4. Delete Any Record from Database

int delet(struct student s[max],int n)


{
int i,key,location;
printf("\nEnter Roll Number to be deleted : ");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(s[i].rollno==key)
{
location=i;
}
}
for(i=location;i<=n;i++)
{
s[i]=s[i+1];
}
return(n-1);
}

5. Modify Any Record from Database


void modify(struct student s[max],int n)
{
int i,key;
printf("Enter Roll No. of Record to Modify : ");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(s[i].rollno==key)
{ printf("\nRoll No = ");
scanf("%d",&s[i].rollno);
printf("\nName = ");
scanf("%s",s[i].name);
printf("\nPercentage = ");
scanf("%f",&s[i].per);
}

}
display(s,n);
}

6. Search Any Record from Database

void search(struct student s[max],int n)


{
int i,key;
printf("Enter Roll No. to Search : ");
scanf("%d",&key);
for(i=0;i<n;i++)
{ if(s[i].rollno==key)
printf("\n%d\t\t%s\t\t%.2f\n",s[i].rollno,s[i].name,s[i].per);
}
if(i==n)
printf("\n No Record Found");
}
7. Sort all Records by Roll No.
void sort(struct student s[max],int n)
{
int i,j;
struct student temp;
for(i=0;i<n-1;i++)
{ for(j=i+1;j<n;j++)
{ if(s[i].rollno>s[j].rollno)
{ temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
display(s,n);
}

Result and Conclusion:

Name and Sign of Course Teacher


/* AIM : TO perform following operations on any database
using structure add,delete,modify,display,search and sort,etc..

*/

#include<stdio.h>
#include<stdlib.h>
#define max 30
typedef struct student
{
int prn;
double mob_no;
char name[30],branch[15];
float per;
}stu;
void create(stu obj[max],int n);
void disp(stu obj[max],int n);
int insert (stu obj[max],int n);
void search(stu obj[max],int n);
int delete(stu obj[max],int n);
void sort(stu obj[max],int n);
void modify(stu obj[max],int n);
int main()
{
stu obj[max];
int ch,n;
while(1)
{
printf("\n\n menu:-\n");
printf(" 1.create record\n");
printf(" 2.display record\n");
printf(" 3.insert record\n");
printf(" 4.search record\n");
printf(" 5.delete record\n");
printf(" 6.sort record\n");
printf(" 7.modify record\n");
printf(" 0.Exit\n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
/
printf("\n\nEnternumberofrecords :");
scanf("%d",&n);
create(obj,n);
break;
case 2:
disp(obj,n);
break;
case 3:
n=insert(obj,n);
break;
case 4:
search(obj,n);
break;
case 5:
n=delete(obj,n);
break;
case 6:
sort(obj,n);
break;
case 7:
modify(obj,n);
break;
case 0:
printf("\n\n Thank you...\n\n");
exit(0);
break;
default:
printf("\n\n invalid choice...");
}
}
}
voidcreate(stuobj[max],intn)
{
int i;
for(i=0;i<n;++i)
{
printf("\nEnterrecord%d ; \n",i+1);
printf("enter prn no : ");
scanf("%d",&obj[i].prn);
printf("enter mob_no: ");
scanf("%lf",&obj[i].mob_no);
printf("enter name : ");
scanf("%s",obj[i].name);
/
printf("enter branch : ");
scanf("%s",obj[i].branch);
printf("enter percentage : ");
scanf("%f",&obj[i].per);
}
printf("\n records created succesful..\n");
}
void disp(stu obj[max],int n)
{
int i;
printf("\nrecords\tPRN
NO.\tmob_no\t\t\tNAME\t\tbranch\t\tpercentage\n");
for(i=0;i<n;++i)
{
printf("%d\t%d\t",i+1,obj[i].prn);
printf("%lf\t",obj[i].mob_no);
printf("%s\t\t",obj[i].name);
printf("%s\t\t",obj[i].branch);
printf("%f\n",obj[i].per);
}
}
int insert (stu obj[max],int n)
{
if(n==30)
{
printf("\n\n record full...");
return n;
}
else
{
printf("\n\n enter the records to be inserted: ");
printf("enter prn no : ");
scanf("%d",&obj[n].prn);
printf("enter mob_no: ");
scanf("%lf",&obj[n].mob_no);
printf("enter name : ");
scanf("%s",obj[n].name);
printf("enter branch : ");
scanf("%s",obj[n].branch);
printf("enter percentage : ");
scanf("%f",&obj[n].per);
printf("\n records created succesful..\n");
return n+1;
}
/
}
voidsearch(stuobj[max],intn)
{
intp,i;
printf("\n\nenterprnno. oftherecords :");
scanf("%d",&p);
for(i=0;i<n;++i)
{
if(p==obj[i].prn)
{
printf("record found!!!");
printf("\n record %d :\n",i+1);
printf("\nprn no : %d",obj[i].prn);
printf("\n mob_no : %lf",obj[i].mob_no);
printf("\nname : %s",obj[i].name);
printf("\nbranch : %s",obj[i].branch);
printf("\n percentage: %f",obj[i].per);
break;
}
}
if(i==n)
printf("\n\nrecordsnotfound!!!");
}
int delete(stu obj[max],int n)
{
int p,i;
printf("\n\n enter prn no. of the records :");
scanf("%d",&p);
for(i=0;i<n;++i)
{
if(p==obj[i].prn)
{
printf("record to br deleted!!!");
printf("\n record %d :\n",i+1);
printf("\nprn no : %d",obj[i].prn);
printf("\n mob_no : %lf",obj[i].mob_no);
printf("\nname : %s",obj[i].name);
printf("\nbranch : %s",obj[i].branch);
printf("\n percentage: %f",obj[i].per);
break;
}
}
if(i==n)
/
{
printf("\n\nrecordsnotfound!!!");
return n;
}
else
{
for(;i<n-1;++i)
obj[i]=obj[i+1];
printf("\n records deleted succesfully..");
return n-1;
}
}
voidsort(stuobj[max],intn)
{
int i,j;
stu temp;
for(i=0;i<n;++i)
{
for(j=0;j<n;++j)
{
if(obj[i].prn>obj[j].prn)
{
temp=obj[i];
obj[i]=obj[j];
obj[j]=temp;
}
}
}
printf("\n\nrecordsorted..");
}
void modify(stu obj[max],int n)
{
int p,i;
printf("\n\n enter prn no. of therecords :");
scanf("%d",&p);
for(i=0;i<n;++i)
{
if(p==obj[i].prn)
{
printf("\n enter new prn no. : ");
scanf("%d",&obj[i].prn);
printf("\n enter new mobile no. : ");
scanf("%lf",&obj[i].mob_no);
/
printf("\n enter new name. : ");
scanf("%s",obj[i].name);
printf("\n enter new branch. : ");
scanf("%s",obj[i].branch);
printf("\n enter new percentage. : ");
scanf("%f",&obj[i].per);
break;
}
}
if(i==n)
{
printf("\n\n records not found!!!");
}
}

OUTPUT

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS C:\Users\admin> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { gcc t.c


-o t } ; if ($?) { .\t }

Menu:-
1.create record
2.display record
3.insert record
4.search record
5.delete record
6.sort record
7.modify record
0.Exit
Enter your choice:1

Enter number of records :3

/
Enter record 1 ;
enter prn no : 1941060
enter mob_no: 9763086367
enter name : Yash
enter branch : "S3”
enter percentage : 95

Enter record 2 ;
enter prn no : 1941048
enter mob_no: 88888888888
enter name : Sase
enter branch : "S3"
enter percentage : 99

Enter record 3 ;
enter prn no : 1941051
enter mob_no: 8080808080
enter name : Amit
enter branch : "S3"
enter percentage : 100

records created succesful..

Menu:-
1.create record
2.display record
3.insert record
4.search record
5.delete record
6.sort record
7.modify record
0.Exit
Enter your choice:2

records PRN NO. mob_no NAME branch percentage 1 1941060


9763086367.000000 Yash "S3" 95.000000 2 1941048 88888888888.000000
Sase "S3" 99.000000 3 1941051 8080808080.000000 Amit "S3"
100.000000

Menu:-
/
1.create record
2.display record
3.insert record
4.search record
5.delete record
6.sort record
7.modify record
0.Exit
Enter your choice:3

enter the records to be inserted: enter prn no :


1941070 enter mob_no: 9999999999
enter name : Raj
enter branch : "S4"
enter percentage : 100

records created succesful..

Menu:-
1.create record
2.display record
3.insert record
4.search record
5.delete record
6.sort record
7.modify record
0.Exit
Enter your choice:4

enter prn no. of the records :1941060


record found!!!
record 1 :

prn no : 1941060
mob_no : 9763086367.000000
name : Yash
branch : "S3”
percentage: 95.000000
/
Menu:-
1.createrecord
2.displayrecord
3.insertrecord
4.searchrecord
5.deleterecord
6.sortrecord
7.modifyrecord
0.Exit
Enteryourchoice:5

enterprnno.oftherecords:1941048
recordtobrdeleted!!!
record2:

prnno:1941048
mob_no:88888888888.0000
00 name:Sase
branch:"S3"
percentage:99.000000
recordsdeletedsuccesfully..

Menu:-
1.createrecord
2.displayrecord
3.insertrecord
4.searchrecord
5.deleterecord
6.sortrecord
7.modifyrecord
0.Exit
Enteryourchoice:6

recordsorted..

Menu:-
1.createrecord
2.displayrecord
3.insertrecord
4.searchrecord
/
5.delete record
6.sort record
7.modify record
0.Exit
Enter your choice:2

records PRN NO. mob_no NAME branch percentage 1 1941070


9999999999.000000 Raj "S4" 100.000000 2 1941051 8080808080.000000
Amit "S3" 100.000000 3 1941060 9763086367.000000 Yash "S3”
95.000000

Menu:-
1.create record
2.display record
3.insert record
4.search record
5.delete record
6.sort record
7.modify record
0.Exit
Enter your choice:7

enter prn no. of the records :1941060

enter new prn no. : 1941077

enter new mobile no. : 9999963667

enter new name. : Yash

enter new branch. : "S3”

enter new percentage. : 100

Menu:-
1.create record
2.display record
3.insert record
4.search record
/
5.delete record
6.sort record
7.modify record
0.Exit
Enter your choice:2

records PRN NO. mob_no NAME branch percentage 1 1941070


9999999999.000000 Raj "S4" 100.000000 2 1941051 8080808080.000000
Amit "S3" 100.000000 3 1941077 9999963667.000000 Yash "S3"
100.000000

Menu:-
1.create record
2.display record
3.insert record
4.search record
5.delete record
6.sort record
7.modify record
0.Exit
Enter your choice:0

Thank you...

PS C:\Users\admin\Desktop\C++1>

Practical no - 5
Student Name : YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil

Aim: Accept Employee information (e.g. employeeNo, Name, salary etc.).


a. Display the data in descending order of Percentage (Bubble Sort).
b. Display data for Employee No specified by user (Linear Search).
c. Display the number of passes and comparisons for different test cases
(Worst, Average, Best case).

Objective: To accept employee record from user and sort these records using bubble sort
and search using linear search.

Theory:
● Bubble Sort
Bubble sort algorithm starts by comparing the first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first
element is greater than second then, you need to swap the elements but, if the first element is
smaller than second, you mustn't swap the element. Then, again second and third elements are
compared and swapped if it is necessary and this process go on until last and second last
element is compared and swapped. This completes the first step of bubble sort.
If there are n elements to be sorted then, the process mentioned above should be repeated n-1
times to get required result. But, for better performance, in second step, last and second last
elements are not compared becuase, the proper element is automatically placed at last after first
step. Similarly, in third step, last and second last and second last and third last elements are not
compared and so on.

We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it
short and precise.
● Linear Search
Linear search is used on a collections of items. It relies on the technique of traversing a list
from start to end by exploring properties of all the elements that are found on the way.
For example, consider an array of integers of size N
. You should find and print the position of all the elements with value x. Here, the linear search
is based on the idea of matching each element from the beginning of the list to the end of the list
with the integer x, and then printing the position of the element if the condition is
`True'.
The pseudo code for this example is as follows :
for(start to end of array)
{
if (current_element equals to 5)
{
print (current_index);
}
}

Example:

f you want to determine the positions of the occurrence of the number 7 in this array. To
determine the positions, every element in the array from start to end, i.e., from index 1 to index
10 will be compared with number 7, to check which element matches the number 7.

Time Complexity:
The time complexity of the linear search is O(n)
because each element in an array is compared only once.
Implementation

Structure Declaration :

typedef struct employee


{
int empNo; char
name[20]; float
salary;
}employee;

Function Declaration:

void create(employee e[max],int n);


void display(employee e[max],int n);
void linearSearch(employee e[max],int n);
void bubbleSort(employee e[max],int n);

Calling Statements:
create(e,n);
display(e,n);
linearSearch(e,n);
bubbleSort(e,n);

1. Accept Employee Records

void create(employee e[max],int n)


{
int i;
printf("\nEnter EMployee Information :\n");
for(i=0;i<n;i++)
{
printf("\nEmployee Number : ");
scanf("%d",&e[i].empNo);
printf("\nName : ");
scanf("%s",e[i].name);
printf("\nSalary : ");
scanf("%f",&e[i].salary);
}
}
2. Display Employee Records

void display(employee e[max],int n)


{
int i;
printf("\n \n");
printf("\nEmployee No.\t\tName\t\tSalary\n");
printf("\n \n");
for(i=0;i<n;i++)
{
printf("%d\t\t",e[i].empNo);
printf("%s\t\t",e[i].name);
printf("%f\n",e[i].salary);
}
printf("\n \n");
}

3. Sorting Employee Records Using Bubble Sort

void bubbleSort(employee e[max],int n)


{
employee temp; int
i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(e[j].empNo > e[j+1].empNo)
{
temp=e[j];
e[j]=e[j+1];
e[j+1]=temp;
}
}
}
display(e,n);
}
4. Search Records Using Linear Search

void linearSearch(employee e[max],int n)


{
int empNo,i;
printf("\nEnter Employee Number to Search : ");
scanf("%d",&empNo);
for(i=0;i<n;i++)
{
if(empNo==e[i].empNo)
{
printf("\n \n");
printf("\nEmployee No.\t\tName\t\tSalary\n");
printf("\n \n");
printf("%d\t\t",e[i].empNo);
printf("%s\t\t",e[i].name);
printf("%f\n",e[i].salary);
printf("\n \n");
break;
}
}
if(empNo==n)
{
printf("\nSorry!! Record Not Found");
}
}

Result and Conclusion:


Name and Sign of Course Teacher

/*Aim 5 : To prepare a program for employee database with linear search and bubble
sorting */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 30
typedef struct employee
{
int empNo;
char name[20];
float salary;
}employee;
void create(employee e[max],int n);
void display(employee e[max],int n);
void linearSearch(employee e[max],int n);
void bubbleSort(employee e[max],int n);
int main()
{
employee e[max];
int choice, n;
while(1)
{

printf("\n***********************MENU****************************");
printf("\n 1.create \n 2.display \n 3.liner serch \n 4.Bubble sort \n
0.exit"); printf("\n enter your choice ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n enter number of employee");
scanf("%d",&n);
create(e,n);
break;
case 2:
display(e,n);
break;
case 3:
linearSearch(e,n);
break;
case 4:
bubbleSort(e,n);
break;
/
case 0:
exit(0);
break;
default:
printf("\n enter valid choice");
}
}
}
void create(employee e[max],int n)
{
int i;
printf("\n enter employee information:\n");
for(i=0;i<n;i++)
{ printf("\n employee number:");
scanf("%d",&e[i].empNo);
printf("\n Name:");
scanf("%s",e[i].name);
printf("\n Salary:");
scanf("%f",&e[i].salary);

}
}
void display(employee e[max],int n)
{
int i;

printf("\n==================================================================
==========================================\n");
printf("\n employeeNo\tName\tSalary\n");

printf("\n==================================================================
===========================================\n");
for(i=0;i<n;i++)
{
printf("%d\t\t",e[i].empNo);
printf("%s\t",e[i].name);
printf("%f\t\n",e[i].salary);
}

printf("\n==================================================================
==================================\n");
}
void linearSearch(employee e[max],int n)
/
{
int empNo,i;
printf("\nEnter number to search:");
scanf("%d",&empNo);
for(i=0;i<n;i++)
{
if(empNo==e[i].empNo)
{
printf("\nEmployeeNo\t\tName\t\tSalary\n");

printf("\n==================================================================
===============\n");
printf("%d\t\t",e[i].empNo);
printf("%s\t\t",e[i].name);
printf("%f\n",e[i].salary);

printf("\n==================================================================
===========\n");
break;
}
}
if(i==n)
{
printf("\n sorry***Record Not Found");
}
}
void bubbleSort(employee e[max],int n)
{
employee temp;
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(e[i].empNo>e[j].empNo)
{
temp=e[i];
e[i]=e[j];
e[j]=temp;
}
}
}
display(e,n)
/
}

OUTPUT :

//Output using linear search of no:

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS C:\Users\admin> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { gcc t.c -o t } ; if ($?) { .\t }

***********************MENU****************************
1.create
2.display
3.liner serch
4.Bubble sort
0.exit
enter your choice 1

enter number of employee :2

enter employee information:

employee number:123

Name:Ashish

Salary:2000

employee number:1234

Name:Rajesh

Salary:3000

***********************MENU****************************
1.create
2.display
3.liner serch

/
4.Bubble sort
0.exit
enter your choice 2

==================================================================
==========================================

employeeNo Name Salary

==================================================================
===========================================
123 Ashish 2000.000000
1234 Rajesh 3000.000000

==================================================================
==================================

***********************MENU****************************
1.create
2.display
3.liner serch
4.Bubble sort
0.exit
enter your choice 3

Enter number to search:123

EmployeeNo Name Salary

==================================================================
===============
123 Ashish 2000.000000

==================================================================
===========

***********************MENU****************************
1.create
2.display
3.liner serch
4.Bubble sort
0.exit
enter your choice 4

/
==================================================================
==========================================

employeeNo Name Salary

==================================================================
===========================================
123 Ashish 2000.000000
1234 Rajesh 3000.000000

==================================================================
==================================

***********************MENU****************************
1.create
2.display
3.liner search
4.Bubble sort
0.exit
enter your choice 0
PS C:\Users\admin\Desktop\C++1>

/*Aim 5 : To prepare a program for employee database with linear


search and bubble sorting */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 30
typedef struct employee
{
int empNo ;
char name [ 20 ];
float salary ;
} employee ;
void create ( employee e [ max ], int n );
void display ( employee e [ max ], int n );
void linearSearch ( employee e [ max ], int n );
void bubbleSort ( employee e [ max ], int n );
/
int main ()
{
employee e [ max ];
int choice , n ;
while ( 1 )
{

printf ( " \n ***********************MENU****************************" );


printf ( " \n 1.create \n 2.display \n 3.liner serch \n 4.Bubble sort \n
0.exit" );
printf ( " \n enter your choice " );
scanf ( "%d" , & choice );
switch ( choice )
{
case 1 :
printf ( " \n enter number of employee :" );
scanf ( "%d" , & n );
create ( e , n );
break ;
case 2 :
display ( e , n );
break ;
case 3 :
linearSearch ( e , n );
break ;
case 4 :
bubbleSort ( e , n );
break ;
case 0 :
exit ( 0 );
break ;
default :
printf ( " \n enter valid choice" );
}
/
}
}
void create ( employee e [ max ], int n )
{
int i ;
printf ( " \n enter employee information: \n " );
for ( i = 0 ; i < n ; i ++)
{
printf ( " \n employee number:" );
scanf ( "%d" , & e [ i ]. empNo );
printf ( " \n Name:" );
scanf ( "%s" , & e [ i ]. name );
printf ( " \n Salary:" );
scanf ( "%f" , & e [ i ]. salary );
}
}
void display ( employee e [ max ], int n )
{
int i ;

printf ( " \n
================================================================ ==
========================================== \n " );
printf ( " \n employeeNo \t Name \t Salary \n " );

printf ( " \n
================================================================ ==
=========================================== \n " );
for ( i = 0 ; i < n ; i ++)
{
printf ( "%d \t\t " , e [ i ]. empNo );
printf ( "%s \t " , e [ i ]. name );
printf ( "%f \t\n " , e [ i ]. salary );
}

printf ( " \n ================================================================


/
== ================================== \n " );
}
void linearSearch ( employee e [ max ], int n )
{
char name ;
int i ;
printf ( " \n Enter name to search:" );
scanf ( "%s" , & name );
for ( i = 0 ; i < n ; i ++)
{
if ( name == * e [ i ]. name )
{
printf ( " \n EmployeeNo \t\t Name \t\t Salary \n " );

printf ( " \n
================================================================ ==
=============== \n " );
printf ( "%d \t\t " , e [ i ]. empNo );
printf ( "%s \t\t " , e [ i ]. name );
printf ( "%f \n " , e [ i ]. salary );

printf ( " \n
================================================================ ==
=========== \n " );
break ;
}
}
if ( i == n )
{
printf ( " \n sorry***Record Not Found" );
}
}
void bubbleSort ( employee e [ max ], int n )
{
employee temp ;
int i , j ;
/
for ( i = 0 ; i < n ; i ++)
{
for ( j = i + 1 ; j < n ; j ++)
{
if ( e [ i ]. empNo > e [ j ]. empNo )
{
temp = e [ i ];
e [ i ] = e [ j ];
e [ j ] = temp ;
}
}
}
display ( e , n );
}

***************OUTPUT***********

//Output using linear search of name:

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS C:\Users\admin> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { gcc t.c -o t } ; if ($?) { .\t }

***********************MENU****************************
1.create
2.display
3.liner search
4.Bubble sort
0.exit
enter your choice 1

enter number of employee :2

enter employee information:


/
employee number:123

Name:Rajesh

Salary:2000

employee number:1234

Name:Raj

Salary:3000

***********************MENU****************************
1.create
2.display
3.liner search
4.Bubble sort
0.exit
enter your choice 2

==================================================================
==========================================

employeeNo Name Salary

==================================================================
===========================================
123 Rajesh 2000.000000
1234 Raj 3000.000000

==================================================================
==================================

***********************MENU****************************
1.create
2.display
3.liner search
4.Bubble sort
0.exit
enter your choice 3

Enter name to search:Rajesh


/
EmployeeNo Name Salary

==================================================================
===============
123 Rajesh 2000.000000

==================================================================
===========

***********************MENU****************************
1.create
2.display
3.liner search
4.Bubble sort
0.exit
enter your choice 4

==================================================================
==========================================

employeeNo Name Salary

==================================================================
===========================================
123 Rajesh 2000.000000
1234 Raj 3000.000000

==================================================================
==================================

***********************MENU****************************
1.create
2.display
3.liner search
4.Bubble sort
0.exit
enter your choice 0
PS C:\Users\admin\Desktop\C++1> Windows PowerShell

CO205 Fundamentals of Data Structure Programming Lab


Government College of Engineering,
Jalgaon
(An Autonomous Institute of Govt of Maharashtra) Department of
Computer Engineering

Lab Manual For


CO205 Fundamentals of Data Structure Programming
Lab
(Sem-III)
S. Y. B. Tech.(Computer)

Course Teacher Course Coordinator

Experiment No - 06
Student Name : YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil

Aim: Accept Mobile user information (e.g. MobileNo, Name, BillAmount etc.).
a. Display the data in Ascending order of MobileNo. (insertion Sort)
b. Display the data in Descending order of MobileNo (Selection Sort)
c. Display details for Mobileno specified by user (Binary Search)
d. Display the number of passes and comparisons for different test cases
(Worst, Average, Best case)

Objective: To accept students record from user and sort these records using insertion and selection
sort and also search using binary search.

Theory:
● Insertion Sort
Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.

Algorithm
// Sort an arr[] of size n
insertionSort(arr, n) Loop
from i = 1 to n-1.
……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]
Example:

Another Example:
12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 5 (Size of input array) i =
1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13 11,
12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position
ahead of their current position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead
of their current position.
5, 6, 11, 12, 13

Function
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i]; j =
i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j]; j =
j-1;
}
arr[j+1] = key;
}
}

Time Complexity: O(n*n)


Auxiliary Space: O(1)
Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse
order. And it takes minimum time (Order of n) when elements are already sorted.

● Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm
maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray.

Following example explains the above steps:

arr[] = 64 25 12 22 11

// Find the minimum element in arr[0...4]


// and place it at beginning 11
25 12 22 64

// Find the minimum element in arr[1...4]


// and place it at beginning of arr[1...4] 11
12 25 22 64

// Find the minimum element in arr[2...4]


// and place it at beginning of arr[2...4] 11
12 22 25 64

// Find the minimum element in arr[3...4]


// and place it at beginning of arr[3...4] 11
12 22 25 64

Function
void selectionSort(int arr[], int n)
{
int i, j, min_idx;

// One by one move boundary of unsorted subarray for


(i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

Time Complexity: O(n2) as there are two nested loops.


Auxiliary Space: O(1)
The good thing about selection sort is it never makes more than O(n) swaps and can be useful
when memory write is a costly operation.

● Binary Search
Given a sorted array arr[] of n elements, write a function to search a given element x in arr[]. A
simple approach is to do linear search.The time complexity of above algorithm is O(n). Another
approach to perform the same task is using Binary Search.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with
an interval covering the whole array. If the value of the search key is less than the item in the
middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half.
Repeatedly check until the value is found or the interval is empty.
Example:

The idea of binary search is to use the information that the array is sorted and reduce the time
complexity to O(Logn).

We basically ignore half of the elements just after one comparison.


1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray after
the mid element. So we recur for right half.
4. Else (x is smaller) recur for the left half.

Implementation

Structure Declaration :

typedef struct bill

{
long int mobile_no;
char name[20]; float
bill_amount;
}bill;

Function Declaration:

void accept(bill b[max],int n);


void display(bill b[max],int n);
void insertion_sort(bill b[max],int n);
void selection_sort(bill b[max],int n);
void binary_search(bill b[max],int n);
Calling Statements:
accept(b, n);
display(b, n);
insertion_sort(b, n);
selection_sort(b, n);
binary_search(b, n);

1. Accept Customer's Records


void accept(bill b[max],int n)
{
int i; float
x;
for(i=0;i<n;i++)
{
printf("\nMobile No : ");
scanf("%ld",&b[i].mobile_no);
printf("\nName : ");
scanf("%s",b[i].name); printf("\n
Bill Amount: "); scanf("%f",&x);
b[i].bill_amount=x;
}
}

2. Display Customer’s Information


void display(bill b[max],int n)
{
int i;
printf("\nCustomer Details : \n\n");
printf("\n \n");
printf("\nMobile No.\t\tName\t\tBill Amount\n");
printf("\n \n\n");
for(i=0;i<n;i++)
{
printf("%ld\t\t%s\t\t%f\n",b[i].mobile_no,b[i].name,b[i].bill_amount);
printf("\n");
}
printf("\n \n");
}
3. Insertion Sort by Mobile No.
void insertion_sort(bill b[max],int n)
{
int i,j; bill
temp;
for(i=1;i<=n-1;i++)
{
temp=b[i];
j=i-1;

while((j>=0) && (b[j].mobile_no>temp.mobile_no))


{
b[j+1]=b[j];
j=j-1;
}
b[j+1]=temp;
}
display(b,n);
}

4. Selection Sort by Mobile No.


void selection_sort(bill b[max],int n)
{
int i,j,min;
bill temp;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(b[j].mobile_no>b[min].mobile_no)
min=j;
}
temp=b[i];
b[i]=b[min];
b[min]=temp;
}
display(b,n);
}
5. Binary Search
void binary_search(bill b[max],int n)
{
int first,last,mid,i;
long int key;
insertion_sort(b,n);
printf("Enter a number to find :");
scanf("%ld", &key);
first = 0; last
= n-1;
mid = (first+last)/2;
while (first <= last)
{ if(b[mid].mobile_no < key)
{
first = mid + 1;
}
else if(b[mid].mobile_no == key)
{ printf("\n\n\n");

printf("%ld\t\t%s\t\t%f\n\n",b[mid].mobile_no,b[mid].name,b[mid].bill_amount);
printf("%ld found at location %d\n\n", key, mid+1);
break;
}
else
{
last = mid - 1;
}

mid = (first + last)/2;


}
if(first > last)
{
printf("Not found! %ld is not present in the list.",key);
}
}
Result and Conclusion:
Name and Sign of Course Teacher

AIM 6 : MENU DATABASE PROGRAM FOR MOBILE BILL.


*/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
typedef struct bill
{
long int mob_no;
char name[20];
float bill_amt;
}bill;
int i;
void create(bill b[MAX],int n);
void display(bill b[MAX],int n);
void insertionsort(bill b[MAX],int n);
void selectionsort(bill b[MAX],int n);
void binarysearch(bill b[MAX],int n);
int main()
{
bill b[MAX];
int n,ch;
while(1)
{
printf("***********************************************************************\n");
printf("\t\t\t\tMENU\n");
printf("***********************************************************************\n");
printf("1.Accept Data\n2.Display Data\n3.Descending Order of Mobile
No.(Insertion sorting)\n4.Asending order of Name(Selection sort)\n5.Search the record(Binary
Search)\n6.Exit\n");
printf("-----------------------------------------------------------------------\n");
printf("Enter your choice: ");
scanf("%d",&ch);

switch(ch)
{
case 1:printf("Enter the Total no. of records: ");
scanf("%d",&n);
create(b,n);
break;
case 2:display(b,n);
break;
case 3: insertionsort(b,n);
break;
case 4:selectionsort(b,n);
break;
case 5: binarysearch(b,n);
break;
case 6:exit(0);
break;
default:
printf("INVALID choice!!!!!!!!!!!!");
}
}
}
void create(bill b[MAX],int n)
{
for(i=0;i<n;i++)
{
printf("Enter NAME: ");
scanf("%s",b[i].name);
printf("Enter MOBILE NO.: ");
scanf("%ld",&b[i].mob_no);
printf("Enter the BILL AMOUNT: ");
scanf("%f",&b[i].bill_amt);
printf("\n---------------------------------------------------------------------------\n");
}
}
void display(bill b[MAX],int n)
{

printf("\n==================================================================
======\n");
printf("NAME\t\t\tMOBNILE NO.\t\t\tBILL");

printf("\n==================================================================
======\n");
for(i=0;i<n;i++)
{
printf("%s\t\t\t%ld\t\t\t%f",b[i].name,b[i].mob_no,b[i].bill_amt);
printf("\n");
}

printf("\n==================================================================
========\n");
}
void insertionsort(bill b[MAX],int n)
{
int j,k;
bill temp;
for(i=1;i<=n-1;i++)
{
temp=b[i];
j=i-1;

while( (j>=0) && (b[j].mob_no < temp.mob_no) ) {


b[j+1]=b[j];
j=j-1;
}
b[j+1]=temp;
}
display(b,n);
}
void selectionsort(bill b[MAX],int n)
{
int j;
bill temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if((strcmp(b[i].name,b[j].name))>0)
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
}
}
}
display(b,n);
}
void binarysearch(bill b[MAX],int n)
{
int first,last,mid,i;
long int key;
printf("\nEnter a number to find : ");
scanf("%ld", &key);
first = 0;
last = n-1;
mid = (first+last)/2;
while (first <= last)
{
if(b[mid].mob_no == key)
{
printf("\n\n");
printf("-----------------------------------------------------------------------\n");
printf("\nMobile Number\t\tName\t\tBill Amount\n");
printf("\n----------------------------------------------------------------------\n\n");
printf("%ld\t\t%s\t\t%f\n\n",b[mid].mob_no,b[mid].name,b[mid].bill_amt);
printf("\n----------------------------------------------------------------------\n\n");
printf("%ldfound at location %d\n\n",key,mid+1);
break;
}
else if(b[mid].mob_no < key)
{
first = mid + 1;

}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if(first > last)
{
printf("\nNot found!! %ld is not present in the list.\n\n",key);
}

.
}

OUTPUT :-

PS C:\Users\admin\Desktop\C++1> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { g++


t2.cpp -o t2 } ; if ($?) { .\t2 }
***********************************************************************
MENU
***********************************************************************
1.Accept Data
2.Display Data
3.Descending Order of Mobile No.(Insertion sorting)
4.Asending order of Name(Selection sort)
5.Search the record(Binary Search)
6.Exit
-----------------------------------------------------------------------
Enter your choice: 1
Enter the Total no. of records: 2
Enter NAME: Yash
Enter MOBILE NO.: 9763086367
Enter the BILL AMOUNT: 5000

---------------------------------------------------------------------------
Enter NAME: Rajesh
Enter MOBILE NO.: 545546464
Enter the BILL AMOUNT: 4500

---------------------------------------------------------------------------
***********************************************************************
MENU
***********************************************************************
1.Accept Data
2.Display Data
3.Descending Order of Mobile No.(Insertion sorting)
4.Asending order of Name(Selection sort)
5.Search the record(Binary Search)
6.Exit
-----------------------------------------------------------------------
Enter your choice: 2

================================================================== ====== NAME


MOBNILE NO. BILL
================================================================== ======
Yash 1173151775 5000.000000
Rajesh 545546464 4500.000000

==================================================================
========
***********************************************************************
MENU
***********************************************************************
1.Accept Data
2.Display Data
3.Descending Order of Mobile No.(Insertion sorting)
4.Asending order of Name(Selection sort)
5.Search the record(Binary Search)
6.Exit
-----------------------------------------------------------------------
Enter your choice: 3

================================================================== ====== NAME


MOBNILE NO. BILL
================================================================== ======
Yash 1173151775 5000.000000
Rajesh 545546464 4500.000000

==================================================================
========
***********************************************************************
MENU
***********************************************************************
1.Accept Data
2.Display Data
3.Descending Order of Mobile No.(Insertion sorting)
4.Asending order of Name(Selection sort)
5.Search the record(Binary Search)
6.Exit
-----------------------------------------------------------------------
Enter your choice: 4

================================================================== ====== NAME


MOBNILE NO. BILL
================================================================== ======
Rajesh 545546464 4500.000000
Yash 1173151775 5000.000000

==================================================================
========
***********************************************************************
MENU
***********************************************************************
1.Accept Data
2.Display Data
3.Descending Order of Mobile No.(Insertion sorting)
4.Asending order of Name(Selection sort)
5.Search the record(Binary Search)
6.Exit
-----------------------------------------------------------------------
Enter your choice: 5

Enter a number to find : 9763086367

-----------------------------------------------------------------------

Mobile Number Name Bill Amount ----------------------------

------------------------------------------ 1173151775 Yash

5000.000000

----------------------------------------------------------------------

1173151775found at location 2

***********************************************************************
MENU
***********************************************************************
1.Accept Data
2.Display Data
3.Descending Order of Mobile No.(Insertion sorting)
4.Asending order of Name(Selection sort)
5.Search the record(Binary Search)
6.Exit
-----------------------------------------------------------------------
Enter your choice: 6
PS C:\Users\admin\Desktop\C++1>
Experiment No. 7
Student Name : YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil

Aim: Implement Sorting Methods using recursion - Quicksort and Merge Sort.

Objective: To accept random numbers from user and sort these records using merge and quicksort..

Theory:
● Merge Sort
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the
two halves and then merges the two sorted halves. The merge() function is used for merging two
halves. The merge(a low, mid, high) is key process that assumes that a[low....m] and arr[mid+1..high]
are sorted and merges the two sorted sub-arrays into one. See following C implementation for details.

MergeSort(a[], low, high)


If high > low
1. Find the middle point to divide the array into two halves:
middle mid = (low+high)/2
2. Call mergeSort for first half: Call
mergeSort(a, low, mid)
3. Call mergeSort for second half: Call
mergeSort(a, mid+1, high)
4. Merge the two halves sorted in step 2 and 3: Call
merge(a, low, mid, high)

Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and
time complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) + O(n)
The above recurrence can be solved either using Recurrence Tree method or Master method. It falls
in case II of Master Method and solution of the recurrence is O(nlogn).
Time complexity of Merge Sort is O(nlogn) in all 3 cases (worst, average and best) as merge sort
always divides the array in two halves and take linear time to merge two halves.
● Quick Sort:
Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and
partitions the given array around the picked pivot. There are many different versions of quickSort
that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot.
3. Pick a random element as pivot.
4. Pick median as pivot.
The key process in quickSort is partition(). Target of partitions is, given an array and an element
x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller
than x) before x, and put all greater elements (greater than x) after x. All this should be done in
linear time.

Time Complexity:
Complexity The worst case time complexity of this algorithm is O(n 2) , but as this is randomized
algorithm, its time complexity fluctuates between O(n2) and O(nlogn) and mostly it comes out to
be O(nlogn)
Implementation

Function Declaration:

void accept(int a[max],int n);


void display(int a[max],int n);
void mergesort(int a[max],int low,int high);
void combine(int a[max],int low,int mid,int high);
void quicksort(int a[max],int low, int high);
int partition(int a[max],int low,int high);

Calling Statements:
accept(a n);
display(a, n);
mergesort(a, low, high);
combine(a, low, mid, high);
quicksort(a, low, high);
m=partition(a, low, high);

Initially the values of low and high are


low = 0
high = n-1

1. Accept Elements
void accept(int a[max],int n)
{
int i;
printf("\n Enter the elements \n" );;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}

2. Display Elements
void display(int a[max],int n)
{
int i;
printf("\nArray elements are displaying... \n" );;
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
3. Merge Sort
void mergesort(int a[max],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
combine(a,low,mid,high);
}
}

void combine(int a[max],int low,int mid,int high)


{
int i,j,k;
int temp[max];
i=low; j=mid+1;
k=low;
while((i<=mid)&&(j<=high))
{
if(a[i]<a[j])
{ temp[k]=a[i];
i++;
k++;
}
else
{ temp[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{ temp[k]=a[i];
i++;
k++;
}
while(j<=high)
{ temp[k]=a[i];
j++;
k++;
}
for(k=low;k<=high;k++)
a[k]=temp[k];
}
4. Quick Sort
void quicksort(int a[max],int low, int high)
{
int m,i;
if(low<high)
{ m=partition(a,low,high);
quicksort(a,low,m-1);
quicksort(a,m+1,high);
}
}

int partition(int a[max],int low,int high)


{
int pivot=a[low],i=low,j=high,temp;
while(i<j)
{ while(a[i]<=pivot)
i++;
while(a[j]>pivot) j--
;
if(i<j)
{ temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return(j);
}

Result and Conclusion:


Name and Sign of Course Teacher

/*AIM 7 : TO PERFORM MERGE SORT AND QUICKSORT.

*/

#include<stdio.h>
#include<stdlib.h>
#define M 10
void accept(int a[M],int n);
void display(int a[M],int n);
void mergesort(int a[M],int low,int high);
void combine(int a[M],int low,int mid,int high);
void quicksort(int a[M],int low,int high);
int partition(int a[M],int low,int high);
void main()
{
int a[M],choice,n,low,high;
char ch;
while(1)
{
printf("\n\t\t::menu::\n");
printf("\n*******MENU*******");
printf("\n 1.Accept array \n 2.Display array \n 3.Merge sort \n 4.Quick sort \n 0.Exit"); printf("\n
Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter size of array: ");
scanf("%d",&n);
accept(a,n);
break;
case 2:
display(a,n);
break;
case 3:
low=0;
high=n-1;
mergesort(a,low,high);
display(a,high+1);
break;
case 4:
low=0;
high=n-1;
quicksort(a,low,high);
display(a,high+1);
break;
case 0:
printf("Thank you");
exit(0);
break;
default:
printf("\n!!!Enter valid choice\n!!!");
}
}
}
void accept(int a[M],int n)
{
int i;
printf("\n Enter the array elements: \n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
}
void display(int a[M],int n)
{
int i;
printf("\n Array elements are displayng
..\n"); for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
}
void mergesort(int a[M],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
combine(a,low,mid,high);
}
}
void combine(int a[M],int low,int mid,int high)
{
int i,j,k;
int temp[M];
i=low;
j=mid+1;
k=low;
while((i<=mid)&&(j<=high))
{
if(a[i]<=a[j])
{
temp[k]=a[i];
i++;
k++;
}
else
{
temp[k]=a[j];
j++;
k++;
}
}
while(i<=mid)
{
temp[k]=a[i];
i++;
k++;
}
while(j<=high)
{
temp[k]=a[j];
j++;
k++;
}
for(k=low;k<=high;k++)
{
a[k]=temp[k];
}
}
void quicksort(int a[M],int low,int high) {
int m,j;
if(low<high)
{
m=partition(a,low,high);
quicksort(a,low,m-1);
quicksort(a,m+1,high);
}
}
int partition(int a[M],int low,int high)
{
int pivot=a[low],i=low,j=high,temp;
while(i<j)
{
while(a[i]<=pivot)
{
i++;
}
while(a[j]>pivot)
{
j--;
}
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[low];
a[low]=a[j];
a[j]=temp;
return (j);
}

Output -

PS C:\Users\admin\Desktop\C++1> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { g++ t.cpp -o t }


; if ($?) { .\t }

::menu::

*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 6

!!!Enter valid choice


!!!
::menu::

*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 1

Enter size of array: 6

Enter the array elements: 3


8
6
5
13
9

::menu::

*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 2

Array elements are displayng .. 3 8 6 5


13 9
::menu::

*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 3

Array elements are displayng .. 3 5 6 8


9 13

::menu::

*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 4
Array elements are displayng .. 3 5 6 8
9 13

::menu::

*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 0
Thank you
PS C:\Users\admin\Desktop\C++1>

Experiment No. 8
Student Name : YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil

Aim: Represent polynomial using structures or array and write a program to perform Addition
and Evaluation given polynomial

Objective: To accept two polynomials from user and perform addition and evaluation of two
polynomials. It is expected to use macro concept in your program.

Theory:

A polynomial is a mathematical expression consisting of variables, coefficients, and the


operations of addition, subtraction, multiplication, and non-negative integer exponents.

Below are some examples of polynomials:

P1(X) = X2 + 2X + 5

P2(X) = 3X3 + 2X2 + 4X + 10

P3(X) = X4 + 8
Polynomials are an important part of the "language" of mathematics and algebra. They are used in
nearly every field of mathematics to express numbers as a result of mathematical operations.
Polynomials are also "building blocks" in other types of mathematical expressions, such as rational
expressions.
Many mathematical processes that are done in everyday life can be interpreted as polynomials.
Summing the cost of items on a grocery bill can be interpreted as a polynomial. Calculating the
distance traveled of a vehicle or object can be interpreted as a polynomial. Calculating perimeter,
area, and volume of geometric figures can be interpreted as polynomials. These are just some of
the many applications of polynomials.

Operations on polynomials can be performed using array and structure. When we use array as a
data structure for polynomial operations, it waste memory while using structure, we can minimize
wastage of memory.
Using Array:
Following examples can be represented using structure and array is as follows

P1(X) = X2 + 2X + 5

P2(X) = 3X3 + 2X2 + 4X + 10

P3(X) = X4 + 8

P1[0] P1[1] P1[2]


5 2 1

P2[0] P2[1] P2[2] P2[3]


10 4 2 3

P3[0] P3[1] P3[2] P3[3] P3[4]


8 0 0 0 1

Using Structure:
Following examples can be represented using structure and array is as follows

P1(X) = X2 + 2X + 5

P2(X) = 3X3 + 2X2 + 4X + 10

P3(X) = X4 + 8

p1[0].coeff p1[0].exp p1[1].coeff p1[1].exp p1[2].coeff p1[2].exp


1 2 2 1 5 0

p2[0].coeff p2[0].exp p2[1].coeff p2[1].exp p2[2].coeff p2[2].exp p2[3].coeff p2[3].exp


3 3 2 2 4 1 10 0

p3[0].coeff p3[0].exp p3[1].coeff p3[1].exp


1 4 8 0
Implementation:

Structure Declaration:
struct node
{
i
n
}; t
c
Header Files: #include<stdio.h> o
#include<stdlib.h> #define max 10 e
f
f
;
i
n
t
e
x
p
;

Function Declarations:
void accept(struct node p[max],int m);
void display(struct node p[max],int m);
void add(struct node p1[max],struct node p2[max],int m,int n);
void eval(struct node p[],int);
int power(int base,int exp);

1. Accept

void accept(struct node p[max],int n)


{
int i,exp,coeff;
for(i=0;i<n;i++)
{
printf("\n\nenter ceofficient and exponents ");
scanf("%d%d",&p[i].coeff,&p[i].exp);
}
}

2. Display

void display(struct node p[max],int n)


{
int i;
for(i=0;i<n;i++)
{
if(p[i].exp!=0)
printf(" %d X^ %d + ",p[i].coeff,p[i].exp);
else
printf("%d",p[i].coeff);

}
}
3. Addition of Two Polynomials

void add(struct node p1[max],struct node p2[max],int m,int n)


{
struct node p3[max]; int
i=0,j=0,k=0; while(i<m
&& j<n)
{
if(p1[i].exp==p2[j].exp)
{
p3[k].coeff=p1[i].coeff+p2[j].coeff;
p3[k].exp=p1[i].exp;
i++;j++;k++;
}
if(p1[i].exp>p2[i].exp)
{
p3[k].coeff=p1[i].coeff;
p3[k].exp=p1[i].exp;
i++;k++;
}
if(p1[i].exp<p2[i].exp)
{
p
3
[
} k
]
} .
while(i<m) c
{ o
e
f
f
=
p
2
[
j
]
.
c
o
e
f
f
;
p ]
3 .
[ e
k x
] p
. ;
e j
x +
p +
= ;
p k
2 +
[ +
j ;
p3[k].coeff=p1[i].coeff;
p3[k].exp=p1[i].exp;
i++;k++;
}
while(j<n)
{
p3[k].coeff=p2[j].coeff;
p3[k].exp=p2[j].exp;
j++;k++;
}
display(p3,k);
}
4. Evaluation

void eval(struct node p[max],int m)


{
int i,ans=0,x; printf("enter
value of x");
scanf("%d",&x);

for(i=0;i<m;i++)
ans=ans+p[i].coeff*(power(x,p[i].exp));
printf("ans=%d",ans);
}

5. Power Calculation

int power(int base,int exp)


{
int result=1;
while(exp!=0)
{
result=result* base;
exp--;
}
return(result);
}

Result and Conclusion:


Name and Sign of Course Teacher

/* 8. Polynomial */

#include<stdio.h>
#include<stdlib.h>
#define max 30
struct poly
{
int c,e;
};
void accept(struct poly p[max],int n);
void disp(struct poly p[max],int n);
void add(struct poly p1[max],struct poly p2[max],int n1,int n2);
void eval(struct poly p[max],int n,int x);
int main()
{
int ch,n1,n2,x;
struct poly p1[max],p2[max];
while(1)
{
printf("\n!!!!!MENU!!!!!\n");
printf("\n 1.ACCEPT \n");
printf("\n 2.DISPLAY \n");
printf("\n 3.ADDITION \n");
printf("\n 4.EVALUATE \n");
printf("\n 0.EXIT \n");
printf("\n Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n Enter number of terms of first polynomial : ");
scanf("%d",&n1);
accept(p1,n1);
printf("\n Enter number of terms of second polynomial : ");
scanf("%d",&n2);
accept(p2,n2);
break;
case 2: printf("\n 1st polynomial : ");
disp(p1,n1);
printf("\n 2nd polynomial : ");
disp(p2,n2);
break;
case 3: add (p1,p2,n1,n2);
break;
/
case 4: printf("\n Enter value of x for 1st polynomial : ");
scanf("%d",&x);
eval(p1,n1,x);
printf("\n Enter value of x for 2nd polynomial : ");
scanf("%d",&x);
eval(p2,n2,x);
break;
case 0: printf("\n\n Good bye...\n\n");
exit (0);
default:
printf("\n\n Invalid choice...");
}
}
}
void accept(struct poly p[max],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("\n Enter coefficient : ");
scanf("%d",&p[i].c);
printf("\n Enter exponent : ");
scanf("%d",&p[i].e);
}
}
void disp(struct poly p[max],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%d",p[i].c);
if(p[i].e!=0 && p[i].c!=0)
printf("x^%d",p[i].e);
if(i<n-1)
printf("+");
}
}
void add(struct poly p1[max],struct poly p2[max],int n1,int
n2) {
int i,j,k=0,flag;
struct poly p3[max];
for(i=0;i<n1;++i)
{
/
flag=0;
for(j=0;j<n2;++j)
{
if(p1[i].e==p2[j].e)
{
p3[k].c=p1[i].c+p2[j].c;
p3[k].e=p1[i].e;
++k;
flag=1;
}
}
if(flag==0)
{
p3[k].c=p1[i].c;
p3[k].e=p1[i].e;
++k;
}
}
for(i=0;i<n2;++i)
{
flag=0;
for(j=0;j<n1;++j)
{
if(p2[i].e==p1[j].e)
flag=1;
}
if(flag==0)
{
p3[k].c=p2[i].c;
p3[k].e=p2[i].e;
++k;
}
}
printf("\n\nADDITION : ");
disp(p3,k);
}
void eval(struct poly p[max],int n,intx)
{
inte=0,i,j,t;
for(i=0;i<n;++i)
{
for(j=0,t=1;j<p[i].e;++j)
t*=x;
/
e+=p[i].c*t;
}
printf("\n EVALUATION RESULT :%d",e);
}

OUTPUT -

Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.

PS C:\Users\admin\Desktop\C++1> cd "c:\Users\admin\Desktop\C++1\" ; if
($?) { gcc t.c -o t } ; if ($?) { .\t }

!!!!!MENU!!!!!

1.ACCEPT

2.DISPLAY

3.ADDITION

4.EVALUATE

0.EXIT

Enter your choice : 1

Enter number of terms of first polynomial : 3

Enter coefficient : 1

Enter exponent : 2

Enter coefficient : 3

Enter exponent : 1

Enter coefficient : 7

Enter exponent : 0
/
Enter number of terms of second

polynomial : 3 Enter coefficient : 7

Enter exponent : 2

Enter coefficient : 3

Enter exponent : 1

Enter coefficient : 6

Enter exponent : 0

!!!!!MENU!!!!!

1.ACCEPT

2.DISPLAY

3.ADDITION

4.EVALUATE

0.EXIT

Enter your choice : 2

1st polynomial : 1x^2+3x^1+7


2nd polynomial : 7x^2+3x^1+6
!!!!!MENU!!!!!

1.ACCEPT

2.DISPLAY

3.ADDITION

4.EVALUATE

0.EXIT

Enter your choice : 3

ADDITION : 8x^2+6x^1+13
/
!!!!!MENU!!!!!

1.ACCEPT

2.DISPLAY

3.ADDITION

4.EVALUATE

0.EXIT

Enter your choice : 4

Enter value of x for 1st polynomial : -3

EVALUATION RESULT :7
Enter value of x for 2nd polynomial : 2

EVALUATION RESULT :40


!!!!!MENU!!!!!

1.ACCEPT

2.DISPLAY

3.ADDITION

4.EVALUATE

0.EXIT

Enter your choice : 0

Good bye...

PS C:\Users\admin\Desktop\C++1>

Experiment No. 9
Student Name : YASH PATIL PRN : 1941060

Course Teacher : Rucha Patil

Aim: Represent Sparse Matrix using array/Structure and perform Matrix Addition & Simple
Transpose.

Objective: To accept two sparse matrices from user, represent these two sparse matrices and
perform addition and transpose of these sparse matrices.

Theory:
If there is a matrix of very large size and many of its elements are zero, then such matrix is called
Sparse Matrix.

To represent this type of matrix by using a 2D array, will waste a lot of memory. Hence there is a
need to find other better methods to represent sparse matrix in which only non-zero values should
be stored.

In numerical analysis and computer science, a sparse matrix or sparse array is a matrix in which
most of the elements are zero. By contrast, if most of the elements are nonzero, then the matrix is
considered dense.

A matrix is a two-dimensional data object made of m rows and n columns, therefore having total
m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix.

Why to use Sparse Matrix instead of simple matrix ?


● Storage: There are lesser non-zero elements than zeros and thus lesser memory can be
used to store only those elements.
● Computing time: Computing time can be saved by logically designing a data structure
traversing only non-zero elements..
Example:
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the
matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements,
we only store non-zero elements. This means storing non-zero elements with triples- (Row,
Column, value).
Sparse Matrix Representations can be done in many ways following are two common
representations:
1. Array Representation
2. Structure Representation
3. Linked List Representation

1. Representation of Sparse Matrix Using Array:


2D array is used to represent a sparse matrix in which there are three rows named as
● Row: Index of row, where non-zero element is located
● Column: Index of column, where non-zero element is located
● Value: Value of the non zero element located at index – (row,column)

We will store only non-zero elements of the sparse matrix. Each element is uniquely identified
by its row and column position, say i , j. we store a matrix as a list of 3 tuples
(i , j , value) OR (Row, Column, Non Zero Values) In

representation of sparse matrix

A[0,0] & A[0,1] - Contains the number of rows and columns of matrix.
A[0,2] - Contains the number of nonzero terms.

Example
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0

Sparse Representation of above matrix is

Sr. Row Column Value


No.

0 4 5 5

1 0 2 3

2 0 4 4

3 0 2 5

4 0 3 7

5 3 1 2
6 3 2 6
2. Representation of Sparse Matrix using Structure:
We will store only non-zero elements of the sparse matrix. Each element is uniquely
identified by its row and column position, say i , j. we store a matrix as a list of 3 tuples

(i , j , value) OR (Row, Column, Non Zero Values)

In representation of sparse matrix,


A[0].row & A[0].Column - Contains the number of rows and columns of matrix.
A[0].Value - Contains the number of nonzero terms.

Addition of Two Sparse Matrices:

When we want to add two sparse matrices, what we should know is,

i. The order of two matrices are same.


ii. If there is an element, at ( i1 , j1 ) in one matrix and also an element at the same position in
other matrix, then add these two elements and store the sum in the resultant matrix. Otherwise,
copy both the elements in the resulting matrix.

Example:
First Matrix is
0 0 0 5
0 3 0 0
0 0 0 0
0 0 2 0

Second Matrix is
2 0 0 0
0 1 0 2
0 0 1 0
0 1 0 1

Representation of First Matrix is

Sr. Row (0) Column Value (2)


No. (1)

0 4 4 3

1 0 3 5

2 1 1 3

3 3 2 2
Representation of Second Matrix is

Sr. Row (0) Column Value (2)


No. (1)

0 4 4 5

1 0 0 2

2 1 1 1

3 1 3 2

4 2 2 1

5 3 1 1

6 3 3 1

Addition of Two Sparse Matrices is

Sr. Row (0) Column Value (2)


No. (1)

0 4 4 8

1 0 0 2

2 0 3 5

3 1 1 4

4 1 3 2

5 2 2 1

6 3 1 1

7 3 2 2

8 3 3 3
Transpose of Sparse Matrix:
To transpose a matrix, we just need to swap the elements at (i, j) with the elements at (j, i).
Example,

Transpose of First Sparse Matrix is

Sr. Row (0) Column Value (2)


No. (1)

0 4 4 3

1 3 0 5

2 1 1 3

3 2 3 2

Implementation

Structure Declaration :

typedef struct sparse

{
int rno; int
cno; int
val;
}sp;

Function Declaration:

void accept(sp s[max],int,int,int);


void display(sp s[max],int);
void transpose(sp s[max],sp tr[max],int nz);
void add(sp s1[max],sp s2[max],sp s3[max],int nz1,int nz2);

Calling Statements:
accept(s1,m1,n1,nz1);
accept(s2,m2,n2,nz2);
display(s1,nz1);
display(s2,nz2);
add(s1,s2,nz1,nz2);
transpose(s1,nz1);
1. Accept Sparse Matrices

void accept(sp s[max],int m,int n,int nz)


{
int i;
s[0].rno=m;
s[0].cno=n;
s[0].val=nz; printf("\nEnter
Tuples : ");
for(i=1;i<=nz;i++)
{
scanf("%d%d%d",&s[i].rno,&s[i].cno,&s[i].val);
}
}

2. Display Sparse Matrices

void display(sp s[max],int nz)


{
int i;
printf("\n=====================================\n");
printf("\nSr. No.\tRow No.\tCol No\tValue\n");
printf("\n=====================================\n");
for(i=0;i<=nz;i++)
{
printf("%d\t%d\t%d\t%d\n",i,s[i].rno,s[i].cno,s[i].val);
}
printf("\n \n");
printf("\n\n");

3. Addition of Two Sparse Matrices

void add(sp s1[max],sp s2[max],int nz1,int nz2)


{
sp s3[max];
int i=1,j=1,k=1;
if((s1[0].rno==s2[0].rno)&&(s1[0].cno==s2[0].cno))
{
s3[0].rno=s1[0].rno;
s3[0].cno=s1[0].cno;
while(i<=nz1 && j<=nz2)
{
if(s1[i].rno==s2[j].rno)
{
if(s1[i].cno==s2[j].cno)
{
s3[k].rno=s1[i].rno;
s3[k].cno=s1[i].cno;
s3[k].val=s1[i].val+s2[j].val;
i++;j++;k++;
}
else if(s1[i].cno<s2[j].cno)
{
s3[k].rno=s1[i].rno;
s3[k].cno=s1[i].cno;
s
3
[
} k
else ].
{ v
a
l
=
s
1
} [i
}//End of 0 if ].
v
a
l;
i
+
+
;
k++;

s3[k].rno=s2[j].rno;
s3[k].cno=s2[j].cno;
s
3
[
k
].
v
a
l
=
s
2
[j j
]. +
v +
a ;
l; k++;
else if(s1[i].rno<s2[j].rno)
{
s3[k].rno=s1[i].rno;
s3[k].cno=s1[i].cno;
s
3
[
} k
else ]
{ .
v
a
l
=
s
} 1
}//End while [
i
]
.
v
a
l
;
i
+
+
;
k++;

s3[k].rno=s2[j].rno;
s3[k].cno=s2[j].cno;
s
3
[
k
]
.
v
a v
l a
= l
s ;
2 j
[ +
j +
] ;
. k++;

//Copy Remaining terms


while(i<=nz1)
{ s3[k].rno=s1[i].rno;
s3[k].cno=s1[i].cno;
s3[k].val=s1[i].val;
i++;
k++;
}
while(j<=nz2)
{
s3[k].rno=s2[j].rno;
s3[k].cno=s2[j].cno;
s3[k].val=s2[j].val;
j++;
k++;
}
s3[0].val=k-1;
}
else
printf("\nAddition is not possible");

display(s3,s3[0].val);
}

4. Transpose of Sparse Matrices

void transpose(sp s[max],int nz)


{
sp tr[max]; int
i,k=0;
for(i=0;i<=nz;i++)
{
tr[k].rno=s[i].cno;
tr[k].cno=s[i].rno;
tr[k].val=s[i].val;
k++;
}
display(tr,nz);
}

Result and Conclusion:


Name and Sign of Course Teacher

#include<stdio.h>
#include<stdlib.h>

#define max 10
struct sparse
{
int r;

int c;
int val;
};

void accept(struct sparse a[max]);


void display(struct sparse a[max]);
void add(struct sparse a[max],struct sparse b[max],struct sparse c[max]);
void transpose(struct sparse a[max],struct sparse tr[max]);
void main()

{
struct sparse a[max],b[max],c[max],tr[max]={0};
int choice;
while(1)

{
printf("\n1. Accept Sparse Matrix");
printf("\n2. Display Sparse Matrix");
printf("\n3. Addition of Two Sparse Matrices ");
printf("\n4. Transpose of Sparse Matrix");
printf("\n0. Exit");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)

{
case 1:
printf("Enter First Sparse : \n");
accept(a);

printf("Enter Second Sparse : \n");


accept(b);
break;
case 2:

printf("Firse Sparse Matrix is :\n");


display(a);
printf("Second Sparse Matrix is : \n");
display(b);

break;
case 3:
add(a,b,c); // a : the first sparse matrix
display(c); // b : the second sparse matrix
break; // c : the addition of two sparses matrices
case 4:
transpose(a,tr); // tr : the transpose matrix
display(tr);

break;
case 0:
exit(0);
break;
default:
printf("\nWrong choice");

break;
}
}
}

void accept(struct sparse a[max])


{

int m,n,nz,i;
printf("\nEnter number of rows, column and non zero Values : ");
scanf("%d%d%d",&m,&n,&nz);
a[0].r=m; // m : number of rows
a[0].c=n; // n : number of columns

a[0].val=nz; // nz : is number of non-zero terms


printf("\nEnter Triplet( row,column, value): ");
for(i=1;i<=nz;i++)
scanf("%d%d%d",&a[i].r,&a[i].c,&a[i].val);

void display(struct sparse a[max])

{
int i,nz;
nz=a[0].val;
printf("\n======================\n");
printf("Row\tColunm\tValue");
printf("\n======================\n");
for(i=0;i<=nz;i++)

printf("%d\t%d\t%d\n",a[i].r,a[i].c,a[i].val);
printf("\n======================\n");

/* algo for ADD


1.START

2.ADD IF ROW AND COLUMN ARE SAME


3. IF CL OF 1 ARE LESS ASSIGN TO FIRST ELSE SECOND
4.CHECK FOR ROW IF LESS ASSIGN TO K VALUES OF FIRST ELSE SECOND
5.ADD REAMINGI OF A
6.ADD REMAINGING OF B

*/
void add(struct sparse a[max],struct sparse b[max],struct sparse c[max])
{
int i=0,j=0,k=0,nz1,nz2;
nz1=a[0].val;//no of terms in first matrix
nz2=b[0].val;// no of terms in second matrix

while(i<=nz1 && j<=nz2)// run the loop untill the terms are remaining in any of the matrix
{
if(a[i].r==b[j].r) // if row's are same then check column
{
if(a[i].c==b[j].c) // if column's also same, add nonzero values
{
c[k].r=a[i].r;// m of resultant matrix

c[k].c=a[i].c;// n for resultant matrix


c[k].val=a[i].val+b[j].val;// nz value for resultant matrix
i++;
j++;

k++;
}
else if(a[i].c<b[j].c) // if first sparse column is smaller than
{ // second, then assign values first sparse to

c[k].r=a[i].r; // resultant sparse matrix


c[k].c=a[i].c;
c[k].val=a[i].val;
k++;
i++;

}
else // otherwise assign second sparse matrix to
{ // resultant sparse matrix
c[k].r=b[j].r;
c[k].c=b[j].c;
c[k].val=b[j].val;
k++;
j++;

}
}
else if(a[i].r < b[j].r) // if row number of first sparse is smaller than
{ // second sparse, then assign first sparse values to
c[k].r=a[i].r; // resultant sparse matrix
c[k].c=a[i].c;
c[k].val=a[i].val;

i++;
k++;
}
else // otherwise assign first sparse matrix values to

{ // resultant sparse matrix


c[k].r=b[j].r;
c[k].c=b[j].c;
c[k].val=b[j].val;

k++;
j++;
}
}
while(i<=nz1) // assign remaining values of first sparse matrix to resultant

{ // sparse matrix.
c[k].r=a[i].r;
c[k].c=a[i].c;
c[k].val=a[i].val;
k++;
i++;
}
while(j<=nz2) // assign remaining values of second sparse matrix to resultant

{ // sparse matrix
c[k].r=b[j].r;
c[k].c=b[j].c;
c[k].val=b[j].val;
k++;
j++;
}

c[0].val=k-1;// we have done here this because k++ executed before i++ as last itreation of i++
while loop condtion false k++ value is incremented so that's why we have done k-1
}

void transpose(struct sparse a[max],struct sparse tr[max])


{
int i,j,k,n;

tr[0].r=a[0].c;
tr[0].c=a[0].r;
tr[0].val=a[0].val;

k=1;

n=a[0].val;
for(i=1;i<=a[0].c;i++)
{
for(j=1;j<=n;j++)
{
//if a column number of current triple==i then insert the current triple in b2
if(i==a[j].c)
{

tr[k].r=i;
tr[k].c=a[j].r;
tr[k].val=a[j].val;
k++;
}
}
}

O/P:-

1. Accept Sparse Matrix

2. Display Sparse Matrix


3. Addition of Two Sparse Matrices
4. Transpose of Sparse Matrix
0. Exit
Enter your choice : 1

Enter First Sparse :

Enter number of rows, column and non zero Values : 3


3
2

Enter Triplet( row,column, value): 1


3

7
3
2
2
Enter Second Sparse :

Enter number of rows, column and non zero Values : 3

3
3

Enter Triplet( row,column, value): 1

3
5
2
2

1
3
3
1

1. Accept Sparse Matrix


2. Display Sparse Matrix
3. Addition of Two Sparse Matrices
4. Transpose of Sparse Matrix
0. Exit
Enter your choice : 2
Firse Sparse Matrix is :

======================
Row Column Value
======================
3 3 2
1 3 7
3 2 2

======================
Second Sparse Matrix is :

======================

Row Column Value


======================
3 3 3
1 3 5

2 2 1
3 3 1

======================

1. Accept Sparse Matrix


2. Display Sparse Matrix
3. Addition of Two Sparse Matrices
4. Transpose of Sparse Matrix
0. Exit
Enter your choice : 3

======================

Row Column Value


======================
3 3 4
1 3 12
2 2 1
3 2 2
3 3 1

======================

1. Accept Sparse Matrix

2. Display Sparse Matrix


3. Addition of Two Sparse Matrices
4. Transpose of Sparse Matrix
0. Exit

Enter your choice : 4

======================
Row Column Value
======================

3 3 2
2 3 2
3 1 7

======================

1. Accept Sparse Matrix


2. Display Sparse Matrix

3. Addition of Two Sparse Matrices


4. Transpose of Sparse Matrix
0. Exit
Enter your choice : 0
Experiment No. 10
Student Name : YASH PATIL PRN : 1941060
Course Teacher : Rucha Patil

Aim : - Represent Circular Queue using Array and write a program to


perform operations like Insert, Delete, and Display front and rear element.

Objective: - To represent circular queue using array and perform operations like
enqueue(rear element), dequeue(front element) and display the queue when required.

Theory:
Queue:

A queue is another special kind of list, where items are inserted at one end called the rear
and deleted at the other end called the front. Another name for a queue is a “FIFO” or “First-
in-first-out” list.

The operations for a queue are analogues to those for a stack, the difference is that the
insertions go at the end of the list, rather than the beginning. We shall use the following
operations on queues:

• enqueue: which inserts an element at the end of the queue.


• dequeue: which deletes an element at the start of the queue.

Representation of Queue:

Let us consider a queue, which can hold maximum of five elements. Initially the queue is
empty.

0 1 2 3 4

Queue Empty FRONT =


REAR = 0

FR

Now, insert 11 to the queue. Then queue status will be:


0 1 2 3 4

11
REAR = REAR + 1 = 1
FRONT = 0
F R

Next, insert 22 to the queue. Then the queue status is:

0 1 2 3 4

22
11
REAR = REAR + 1 = 2
FRONT = 0

F R

Again insert another element 33 to the queue. The status of the queue is:
0 1 2 3 4

22 33
11

F R
REAR = REAR + 1 = 3
FRONT = 0
Now, delete an element. The element deleted is the element at the front of the queue. So
the status of the queue is:

0 1 2 3 4
REAR = 3
Before, FRONT Now, FRONT =0

=FRONT + 1 = 1

F R

Again, delete an element. The element to be deleted is always pointed to by the FRONT
pointer. So, 22 is deleted. The queue status is as follows:
0 1 2 3 4
REAR = 3 FRONT =
F
R
O
N
T
+
1
=
2

F R

Now, insert new elements 44 and 55 into the queue. The queue status is:

0 1 2 3 4
REAR = 5
FRONT = 2

Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the
rear crossed the maximum size of the queue (i.e., 5). There will be queue full signal. The
queue status is as follows:

0 1 2 3 4
REAR = 5
FRONT = 2

Now it is not possible to insert an element 66 even though there are two
vacant positions in the linear queue. To over come this problem the elements of the queue
are to be shifted towards the beginning of the queue so that it creates vacant position at the
rear end. Then the FRONT and REAR are to be adjusted properly. The element 66 can be
inserted at the rear end. After this operation, the queue status is as follows:
0 1 2 3 4
REAR = 4
FRONT = 0
33

F R

This difficulty can overcome if we treat queue position with index 0 as a position that comes
after position with index 4 i.e., we treat the queue as a circular queue.

Applications of Queue:

1. It is used to schedule the jobs to be processed by the CPU.

2. When multiple users send print jobs to a printer, each printing job is kept in the
printing queue. Then the printer prints those jobs according to first in first out
(FIFO) basis.

3. Breadth first search uses a queue data structure to find an element from a graph.

Circular Queue:

A more efficient queue representation is obtained by regarding the array Q[MAX] as circular.
Any number of items could be placed on the queue. This implementation of a queue is called
a circular queue because it uses its storage array as if it were a circle instead of a linear list.

There are two problems associated with linear queue. They are:

• Time consuming: linear time to be spent in shifting the elements to the beginning
of the queue.

• Signaling queue full: even if the queue is having vacant position.

For example, let us consider a linear queue status as follows:

0 1 2 3 4
REAR = 5
FRONT = 2

Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the
rear crossed the maximum size of the queue (i.e., 5). There will be queue full signal. The
queue status is as follows:

0 1 2 3 4
REAR = 5
FRONT = 2

33 44 55

F R

This difficulty can be overcome if we treat queue position with index zero as a position that
comes after position with index four then we treat the queue as a circular queue.

In circular queue if we reach the end for inserting elements to it, it is possible to insert new
elements if the slots at the beginning of the circular queue are empty.

Representation of Circular Queue:

Let us consider a circular queue, which can hold maximum (MAX) of six elements. Initially the
queue is empty.

FR

Queue 4 Empty
1
5 0
MAX = 6
FRONT = REAR = 0
COUNT =0

Circular Queue

3 2

Now, insert 11 to the circular queue. Then circular queue status will be:

R 5 0

FRONT = 0
1
4
REAR = (REAR + 1) % 6 = 1
COUNT = 1

3 2
Circular Queue
Insert new elements 22, 33, 44 and 55 into the circular queue. The circular queue status is:

FRONT REAR = 4 F
R
0
5
1

5 2

4 3

3 2
=
0
1 (REAR + 1) %
6=5
COUNT =5

Circular Queue

Now, delete an element. The element deleted is the element at the front of the circular
queue. So, 11 is deleted. The circular queue status is as follows:
R

0
F 5

FRONT = COUNT = (FRONT + 1) % 6 = 1


4
22 REAR = 5
5
COUNT - 1 = 4

4 3

Circular
3 Queue 2

Again, delete an element. The element to be deleted is always pointed to by the FRONT
pointer. So, 22 is deleted. The circular queue status is as follows:

R
0
FRONT = 5 (FRONT + 1) % 6 = 2
4
REAR = 5
COUNT = COUNT - 1 = 3

5 1

4 3 Circular Queue

3 2
Again, insert another element 66 to the circular queue. The status of the circular queue is:

0
5
6

5 1
4
FRONT = 2
REAR = (REAR + 1) % 6 = 0
COUNT = COUNT + 1 = 4
4 3

3 2
F

Circular Queue

Now, insert new elements 77 and 88 into the circular queue. The circular queue status is:

5 0
66 77

55 88 4
1 FRONT = 2, REAR = 2 REAR = REAR % 6
=2
COUNT = 44 33
6

2
3 F R

Circular Queue

Now, if we insert an element to the circular queue, as COUNT = MAX we cannot add the
element to circular queue. So, the circular queue is full.
Implementation:
Header Files :
#include<stdio.h>
#include<stdlib.h>
#define max 20 // Macro Function
int front = 0; int
rear = 0;
int count = 0; //Global Variables

Declaration:
void insertCQ(int CQ[MAX]);
void deleteCQ(int CQ[MAX]);
void displayCQ(int CQ[MAX]);
Calling:
insertCQ(CQ);

deleteCQ (CQ);

displayCQ(CQ);

1. Insert

void insertCQ(int CQ[MAX])


{
int data;
if(count == MAX)
{
printf("\n Circular Queue is Full");
}
else
{
p
r
i
n
t
f
} (
}
"
\
n a
E t
n a
t ;
e r
r e
d a
a r
t =
a (
: r
" e
) a
; r
s +
c 1
a )
n %
f M
( A
" X
% ;
d c
" o
, u
& n
d t
a +
t +
a ;
) printf("\n Data Inserted in the Circular Queue
");
;
C
Q
[
r
e
a
r
]
=
d
CO205 Fundamentals of Data Structure Programming Lab

2. Delete:
void deleteCQ(int CQ[MAX])
{
if(count == 0)
{
printf("\n\nCircular Queue is Empty..");
}
else
{
printf("\n Deleted element from
Circular Queue is %d ",
CQ[front]); front = (front + 1)
} % MAX;
} count --;

3. Display:
void displayCQ(int CQ[MAX])
{
int i, j;
if(count == 0)
{
printf("\n\n\t Circular Queue is Empty ");
}
else
{
prin
tf("\
n
Ele
men
ts in
Circ
ular
Que
ue
are:
"); j
=
cou
nt;
for(i = front; j != 0; j--)
{
printf("%d\t", CQ[i]);
i = (i + 1) % MAX;
}
}
}

Result and Conclusion:


Name and Sign of Course Teacher

/*AIM 10: WRITE A C PROGRAM REPRESENT CIRCULAR QUEUE USING ARRAY AND WRITE A
PROGRAM TO PERFORM OPERATIONS INSERT, DELETE,AND DISPLAY FROM THE FRONT
AND REAR ELEMENTS.
************************************************************************************************************* **/
#include <stdio.h>
#include<stdlib.h>
#define MAX 20
void insert();

void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
int main()
{

int choice;

while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
break; default:
printf("Wrong choice \n");
} /*End of switch*/
} /*End of while*/
return 0;
} /*End of main()*/

void insert()
{
int item;
int i,n;
printf("\n enter the number of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
if (rear == MAX - 1)
printf("Queue Over ow \n");
else
{
if (front == - 1) /*If queue is initially empty */
front = 0;
// printf("Inset the element in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue_array[rear] = item;
}
}
} /*End of insert()*/

void delete()
{
if (front == - 1 || front > rear)
printf("Queue Under ow \n");
else
{
printf("Element deleted from queue is : %d\n",
queue_array[front]); front = front + 1;
}
} /*End of delete() */void display()
{
int i;
if (front == - 1 || front>rear)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /*End of display() */

OUTPUT :-

//Name : YASH PATIL


//Batch : S3
//PRN : 1941060

PS C:\Users\admin\Desktop\C++1> cd "c:\Users\admin\Desktop\C++1\" ; if ($?) { gcc t.c -o t } ; if


($?) { .\t
}
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1

enter the number of elements :5


1
2
3
4
5
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 2
Element deleted from queue is : 1
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is :
2345
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 4
PS C:\Users\admin\Desktop\C++1>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy