Final Sub FDSP 1941060
Final Sub FDSP 1941060
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)
PRN -: 1941060
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:
A B={x|x∈A x∈B}
Intersection:
A B={x|x∈A x∈B}
A-B={x|x∈A x∉B}
(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
(i) A and B
(ii) B and A
Solution:
(i) A - B = {a, c, e}
(ii) B - A = {g)
Function Declaration:
1. Accept:
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:
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);
}
#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
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
Experiment No.2
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 [].
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.
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
4. String Concat
6. String Copy
Lab Assignment:
Student has to accept full name in one sting and your branch name in second string.
s2=”Computer Engineering”
Write a menu driven for string operation using above input string.
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 :
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
Experiment No. 3
Student Name : YASH PATIL PRN : 1941060
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
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
● 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:
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;
}
}
int main()
{
int matrix1[max][max],matrix2[max][max],size1,size2,choice;
int trans[max][max],add[max][max],mult[max][max];
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;
Output--
12
34
---------------- MENU ---------------- 1.Accept
the matrices
2.Display
3.Addition
4.Multiplication
5.Transpose
0.Exit
-------------------------------------- Enter
your choice: 3
GOOD BYE
PS C:\Users\admin\Desktop\C++1>
Experiment No. 4
Student Name : YASH PATIL PRN : 1941060
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.
#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;
Output:
Id is: 1
Name is: Vihaan Percentage
is: 86.500000
#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;
Output:
Id is: 1
Name is: Vihaan Percentage
is: 86.500000
struct student
{
int id;
char name[20]; float
percentage;
}record;
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.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30]; float
percentage;
};
int main()
{ int i;
struct student record[2];
#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};
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
#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;
}
Output:
Id is: 1
Name is: Vihaan Percentage
is: 86.500000
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20]; float
percentage;
};
void func(struct student *record); int
main()
{ struct student record; record.id=1;
strcpy(record.name, "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
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20]; float
percentage;
};
struct student record; // Global declaration of structure
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,
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.
#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;
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");
}
}
display(s,n);
}
*/
#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.
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 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
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
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
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
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
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
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
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
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 :
Function Declaration:
Calling Statements:
create(e,n);
display(e,n);
linearSearch(e,n);
bubbleSort(e,n);
/*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 :
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
***********************MENU****************************
1.create
2.display
3.liner serch
4.Bubble sort
0.exit
enter your choice 1
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
==================================================================
==========================================
==================================================================
===========================================
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
==================================================================
===============
123 Ashish 2000.000000
==================================================================
===========
***********************MENU****************************
1.create
2.display
3.liner serch
4.Bubble sort
0.exit
enter your choice 4
/
==================================================================
==========================================
==================================================================
===========================================
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>
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 " );
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***********
Windows PowerShell
Copyright (C) 2016 Microsoft Corporation. All rights reserved.
***********************MENU****************************
1.create
2.display
3.liner search
4.Bubble sort
0.exit
enter your choice 1
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
==================================================================
==========================================
==================================================================
===========================================
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
==================================================================
===============
123 Rajesh 2000.000000
==================================================================
===========
***********************MENU****************************
1.create
2.display
3.liner search
4.Bubble sort
0.exit
enter your choice 4
==================================================================
==========================================
==================================================================
===========================================
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
Experiment No - 06
Student Name : YASH PATIL PRN : 1941060
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;
}
}
● 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.
arr[] = 64 25 12 22 11
Function
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
● 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).
Implementation
Structure Declaration :
{
long int mobile_no;
char name[20]; float
bill_amount;
}bill;
Function Declaration:
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;
}
#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;
}
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 :-
---------------------------------------------------------------------------
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
==================================================================
========
***********************************************************************
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
==================================================================
========
***********************************************************************
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
==================================================================
========
***********************************************************************
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
-----------------------------------------------------------------------
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
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.
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:
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);
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);
}
}
*/
#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 -
::menu::
*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 6
*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 1
::menu::
*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 2
*******MENU*******
1.Accept array
2.Display array
3.Merge sort
4.Quick sort
0.Exit
Enter your choice : 3
::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
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:
P1(X) = X2 + 2X + 5
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
P3(X) = X4 + 8
Using Structure:
Following examples can be represented using structure and array is as follows
P1(X) = X2 + 2X + 5
P3(X) = X4 + 8
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
2. Display
}
}
3. Addition of Two Polynomials
for(i=0;i<m;i++)
ans=ans+p[i].coeff*(power(x,p[i].exp));
printf("ans=%d",ans);
}
5. Power Calculation
/* 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 coefficient : 1
Enter exponent : 2
Enter coefficient : 3
Enter exponent : 1
Enter coefficient : 7
Enter exponent : 0
/
Enter number of terms of second
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
1.ACCEPT
2.DISPLAY
3.ADDITION
4.EVALUATE
0.EXIT
ADDITION : 8x^2+6x^1+13
/
!!!!!MENU!!!!!
1.ACCEPT
2.DISPLAY
3.ADDITION
4.EVALUATE
0.EXIT
EVALUATION RESULT :7
Enter value of x for 2nd polynomial : 2
1.ACCEPT
2.DISPLAY
3.ADDITION
4.EVALUATE
0.EXIT
Good bye...
PS C:\Users\admin\Desktop\C++1>
Experiment No. 9
Student Name : YASH PATIL PRN : 1941060
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.
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
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
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
When we want to add two sparse matrices, what we should know is,
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
0 4 4 3
1 0 3 5
2 1 1 3
3 3 2 2
Representation of Second Matrix is
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
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,
0 4 4 3
1 3 0 5
2 1 1 3
3 2 3 2
Implementation
Structure Declaration :
{
int rno; int
cno; int
val;
}sp;
Function Declaration:
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
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++;
display(s3,s3[0].val);
}
#include<stdio.h>
#include<stdlib.h>
#define max 10
struct sparse
{
int r;
int c;
int val;
};
{
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);
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;
}
}
}
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
{
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");
*/
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
k++;
}
else if(a[i].c<b[j].c) // if first sparse column is smaller than
{ // second, then assign values first sparse to
}
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
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
}
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:-
7
3
2
2
Enter Second Sparse :
3
3
3
5
2
2
1
3
3
1
======================
Row Column Value
======================
3 3 2
1 3 7
3 2 2
======================
Second Sparse Matrix is :
======================
2 2 1
3 3 1
======================
======================
======================
======================
Row Column Value
======================
3 3 2
2 3 2
3 1 7
======================
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:
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
FR
11
REAR = REAR + 1 = 1
FRONT = 0
F R
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:
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.
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.
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
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
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;
}
}
}
/*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 :-