You are on page 1of 61

COMPUTER

SCIENCE
PRACTICAL FILE

XII
1

Index
S.No
1.

Program
Function overloading

2.
3.
4.
5.
6.
7.
8.

Class using private function


Class using constructor
Single inheritance
Multiple inheritance
Multilevel inheritance
Writing in text file
Program to use multiple files in succession.

9.
10.

Reading and writing in file with class bjects.


Program to use multiple files in succession.

11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

Linear search
Binary search
Selection sort
Bubble sort
Insertion sort
Merging of two arrays
Sum of rows of a 2-D array
Sum of columns of a 2-D array
Sum of Diagonal element of a 2-D array
Insertion,Deletionand traversal in array
queue
Insertion,Deletion and traversal in linked
queue

21.

Teachers Sign.

22.
23.
24.
25.

Insertion,Deletion and traversal in array


stack
Insertion,Deletion and traversal in linked
stack
Insertion and deletion in circular queue

Program to illustrate function overloading


#include<iostream.h >
#include<conio.h>
#include<stdlib.h >
int divide(int a,int b)
{
if(b == 0)
return -1 ;
if((a%b)==0)
return 1;
else
return 0;
}
int divide(int a)
{
int j=a/2;
int flag= 1;
for(int i=2;(i<=j)&&(flag);i++)
{ if(a%i == 0)
flag = 0;
}
return flag;
}
int main( )
{
//system (" cls ") ;
3

int ch, res, a, b;


do
{ cout << "1. Check for divisibility \n";
cout << "2. Check for Prime \n";
cout << "3. Exit \n";
cout << "Enter your choice (1-3) :";
cin >> ch;
cout << "\n";
switch(ch)
{
case 1 : cout << "Enter the Numerator and Dennominator \n";
cin >> a >> b;
res = divide(a,b);
cout << ((res) ? "It is" : "It is not") << "\n";
break;
case 2 : cout <<"Enterthenumber\n";
cin >> a;
res = 0;
res = divide(a);
cout << ((res)?"It is " : "It is not")<< "\n";
break;
case 3 : break;
default : cout << "Wrong choice !\n";
}//end switch
}while(ch>0&&ch<3);
getch ();
return 0;
} //end of main ( )

OUTPUT

Write a program to display record of a topper student or specific student


depending upon the user choice.
#include<iostream.h>
#include<conio.h>
#include<stdio.h> // for gets( )

#include<stdlib.h>
class Student { private:
int rollno;
char name[25] ;
float marks ;
char grade ;
public:
5

void readStudent( )
{
cout << " \n Enter rollno : " ;cin>>rollno;
cout << " \n Enter name : " ;cin>>name;
cout << " \n Enter marks : " ;cin>>marks;
}
void dispStudent( )
// accessor
{ calcGrade( ) ;
//invokefunction to determine grade
cout << " Roll no. : " << rollno << endl ;
cout << " Name : " << name << endl ;
cout <<"Marks : " << marks << endl ;
cout << " Grade : " << grade << endl ;
getch();
}
int getRollno( )
{ return rollno;
}
float getMarks( )
{ return marks ;
}
void calcGrade( )
{ if ( marks >= 75)
grade ='O' ;
else if ( marks >= 60)
grade ='A' ;
else if ( marks >= 50)
grade ='B' ;
else if ( marks >= 40)
grade ='C';
else
grade ='F' ;
}
};
int main( )
{int i;
Student XIIa[10] ;
for( i= 0; i< 5; ++i)
{
cout<< " \nEnter details of Student " << i+1 << " : " ;
XIIa[i].readStudent( ) ;
}
int choice, rno, pos = -1;
float highmarks = 0 ;
do
{
system (" cls ") ;
cout << " \n\n Main Menu\n " ;
6

cout << " 1. SPecific student \n " ;


cout << " 2. ToPPer\n " ;
cout << " 3. Exit\n " ;
cout << " \n Enter your choice (1-3) : " ;
cin >> choice;
switch(choice)
{
case 1 : cout << " \n Enter roll no of student whose details U want to see: " ;
cin >> rno ;
for( i=0;i<5;++i)
{ if (XIIa[i].getRollno( ) == rno)
{XIIa[i].dispStudent( ) ;
break ;
}
}
if (i == 5)
cout << " \nINVALID ROLLNO !!!\n " ;
break ;
case 2 : for(i = 0 ; i < 5 ; ++i)
{ if (XIIa[i].getMarks( ) > highmarks)
{pos=i;
highmarks = XIIa[i].getMarks( ) ;
}
}
XIIa[pos].dispStudent( ) ;
break ;
case 3 : break;
default : cout << " \n Wrong Choice !!\n " ;
}
} while (choice >=1 && choice < 3) ;
getch();
return 0 ;}

OUTPUT

Class With Constructor


#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class GARMENTS
{
char gcode[25];
char gtype[25];
int gsize;
char gfabric[25];
float gprice;
void assign()
{
if((strcmp(gfabric,"cotton")==0))
{
if((strcmp(gtype,"trouser")==0))
gprice=1300;
else
gprice=1100;
}
else
{ if((strcmp(gtype,"trouser")==0))
gprice=1300-130;
else
gprice=1100-110;
}
}
public: GARMENTS()
{ strcpy(gcode,"NOT ALLOTTED");
strcpy(gtype,"NOT ALLOTTED");
strcpy(gfabric,"NOT ALLOTTED");
gsize=0;
gprice=0;
}
void input()
{ cout<<"enter the code";
gets(gcode);
cout<<"enter the type";
gets(gtype);
cout<<"enter the size";
cin>>gsize;
cout<<"enter the fabric";
gets(gfabric);
assign();
}
9

void display()
{ cout<<"size is"<<gsize;
cout<<"type is";
puts(gtype);
cout<<"fabric is";
puts(gfabric);
cout<<"code is";
puts(gcode);
cout<<"price is"<<gprice;
}

;
int main()
{ GARMENTS G;
G.input();
G.display();
getch();
}

OUTPUT

10

Write a program to implement single inheritance.


#include <iostream.h>
#include <conio.h>
// Demonstrating the class inheritance
class base
{
private:
int counter; // Represents private class data
public:
base()
{
counter = 0;
}
void newset(int n)
{
counter = n;
}
void factorial(void);
};
class derived: public base
{
public:
derived(): base()
{
};
void changecounter(int n)
{
newset(n);
factorial();
}
};
void base::factorial(void)
{
int i;
long double fact = 1.0;
for (i = 1; i<= counter; i++)
fact = fact * i;
cout << "The factorial value is : " << fact;
}
int main()
{
//
clrscr();
int num;
derived tderived;
cout << "Enter the value for factorial ";
11

cin >> num;


tderived.changecounter(num);
getch();
return 0;
}

OUTPUT

12

Write a program to demonstrate the hierarichal inheritance


#include <iostream.h>
#include <conio.h>
class CPolygon
{
protected:
int width, height;
public:
void set_values (int a, int b)
{
width = a; height = b;
}
};
class CRectangle: public CPolygon
{
public:
int area()
{
return (width * height);
}
};
class CTriangle: public CPolygon
{
public:
int area()
{
return (width * height / 2);
}
};
int main ()
{
//clrscr();
CRectangle rect;
CTriangle trgl;
rect.set_values (4, 5);
trgl.set_values (4, 5);
cout << "The area of rectangle : " << rect.area() << endl;
cout << "The area of triangle : " << trgl.area() << endl;
getch();
return 0;
}
13

OUTPUT

14

Write a program to illustrate multilevel inheritance


#include <iostream.h>
#include <conio.h>
#include <stdio.h>
class Employee // Base class or super class of employee
{
private:
int empcode;
char empname[25];
char empdesig[15];
float empsalary;
public:
void empinput_data(void);
void empdisplay(void);
};
// derived class of base class
class Customer : public Employee
{
private:
int custcode;
char custname[25];
char custdesig[15];
double balance;
public:
void custinput_data(void);
void custdisplay(void);
};
// derived class of derived class
class Emp_Cust : private Customer
{
public:
void get_data();
void show_data();
};
void Emp_Cust::get_data(void)
{
empinput_data();
15

custinput_data();
}
void Emp_Cust::show_data()
{
empdisplay();
custdisplay();
}
void Employee::empinput_data(void)
{
cout << "\Enter employee information : \n";
cout << "Enter code : ";
cin >> empcode;
cout << "Enter name : ";
cin>>empname;
cout << "Enter designation : ";
cin>>empdesig;
cout << "Enter salary : ";
cin >> empsalary;
}
void Customer::custinput_data(void)
{
cout << "\nEnter customer information : \n";
cout << "Enter code : ";
cin >> custcode;
cout << "Enter name : ";
cin>>custname;
cout << "Enter designation : ";
cin>>custdesig;
cout << "Enter balance : ";
cin >> balance;
}
void Employee::empdisplay(void)
{
cout << "\nHere is the employee information : \n";
for (int i=0; i<=35; i++)
cout << "=";
cout << "\nCode : " << empcode;
cout << "\nName : " << empname;
cout << "\nDesignation : " << empdesig;
cout << "\nSalary : " << empsalary;
}
void Customer::custdisplay(void)
{
cout << "\nHere is the customer information : \n";
for (int i=0; i<=35; i++)
cout << "=";
cout << "\nCode : " << custcode;
16

cout << "\nName : " << custname;


cout << "\nDesignation : " << custdesig;
cout << "\nBalance : " << balance;
}
int main()
{
//
clrscr();
Emp_Cust empcust; // Declares Object of type Employee and Customer
empcust.get_data();
empcust.show_data();
getch();
return 0;
}

17

Write a program to implement multiple inheritance


#include <iostream.h>
#include <conio.h>
#include <stdio.h>
class Employee // Base class or super class of Employee
{
private:
int empcode;
char empname[25];
char empdesig[15];
float empsalary;
public:
void empinput_data(void);
void empdisplay(void);
};
// Base class or super class of Customer
class Customer
{
private:
int custcode;
char custname[25];
char custdesig[15];
double balance;
public:
void custinput_data(void);
void custdisplay(void);
};
// Derived class for multiple inheritance
class Emp_Cust : public Employee, public Customer
{
public:
void get_data();
void show_data();
};
void Emp_Cust::get_data(void)
{
empinput_data();
custinput_data();
18

}
void Emp_Cust::show_data()
{
empdisplay();
custdisplay();
}
void Employee::empinput_data(void)
{
cout << "\Enter employee information : \n";
cout << "Enter code : ";
cin >> empcode;
cout << "Enter name : ";
cin>>empname;
cout << "Enter designation : ";
cin>>empdesig;
cout << "Enter salary : ";
cin >> empsalary;
}
void Customer::custinput_data(void)
{
cout << "\nEnter customer information : \n";
cout << "Enter code : ";
cin >> custcode;
cout << "Enter name : ";
cin>>custname;
cout << "Enter designation : ";
cin>>custdesig;
cout << "Enter balance : ";
cin >> balance;
}
void Employee::empdisplay(void)
{
cout << "\nHere is the employee information : \n";
for (int i=0; i<=35; i++)
cout << "=";
cout << "\nCode : " << empcode;
cout << "\nName : " << empname;
cout << "\nDesignation : " << empdesig;
cout << "\nSalary : " << empsalary;
}
void Customer::custdisplay(void)
{
cout << "\nHere is the customer information : \n";
for (int i=0; i<=35; i++)
cout << "=";
cout << "\nCode : " << custcode;
cout << "\nName : " << custname;
cout << "\nDesignation : " << custdesig;
cout << "\nBalance : " << balance;
}
int main()
{
clrscr();
19

Emp_Cust empcust; // Declares Object of type Employee and Customer


empcust.get_data();
empcust.show_data();
getch();
return 0;
}

OUTPUT

20

Write a program get roll numbers and marks of the students of a class and
store these details into a file called Marks.dat
#include<iostream.h>
#include<fstream.h>
int main()
{ ofstream fileout;
// stream decided and declared-steps 1 & 2
fileout.open("marks.dat",ios::out|ios::app);
// file linked-step 3
char ans ='y';
//process as required-step 4 begins
int rollno; float marks;
while(ans=='y' ans=='y')
{ cout<<"\n Enter Rollno.:";
cin>>rollno;
cout<<"\n Enter Marks:";
cin>>marks;
fileout<<rollno<<'\n'<<marks<<'\n';
cout<<"\n Want to enter more records?(y/n)...";
cin>>ans;
}
fileout.close();
//delink the file-step 5
return 0;
}

OUTPUT

21

Write a program for reading and writing class objects.


#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
class student { Char name[40];
char grade;
float marks;
public:
void getdata(void);
void display(void); }
void student::getdata(void)
{ char ch;
cin.get(ch);
cout<<"Enter name:";
cin.getline(name,40);
cout<<"Enter grade:";
cin>>grade;
22

cout<<"Enter marks;";
cout<<"\n";

cin>>marks;

}
void student::display(void)
{ cout<<"Name:"<<name<<"\t"
<<"Grade:"<<grade<<"\t"
<<"Marks:"<<marks<<"\t" <<"\n";
}
int main()
{ system("cls");
students arts[3];
//declare array of 3 objects
fstream filin;
//input and output file
filin.open("stu.dat",ios::in ios::out);
if(!filin)
{ cout<<"cannot open file!!\n";
return 1;
}
cout<<"enter details for 3 students \n";
for(inti=0;i<3;i++)
{ arts[i].getdata();
fillin.write((char*)&arts[i],sizeof(arts[i]));
}
fill.seekg(0);
//seekg(0)resets the file to start,so that the file can be
//accessed from the beginning.
cout<<"The contents of stu.dat are shown below.\n";
for(i=0;i<3;i++)
{ filln.read((char*) & arts[i],sizeof(arts[i]));
arts[i].display();
}
fillin.close();
return 0;
}

OUTPUT

23

Write a program to search in a file having records maintained through classes.


#include<iostream.h>
#include<fstream.h>
class stu { int rollno;
24

char name[25];
char Class[4];
float marks;
char grade;
public:
void getdata()
{ cout << "Rollno:"; cin >> rollno;
cout << "Name:";
cin >> name;
cout << "Class:";
cin >> class;
cout << "Marks:";
cin >> marks;
if(marks >= 75)
grade = 'A';
else if(marks >= 60) grade = 'B';
else if(marks >= 50) grade = 'C';
else if(marks >= 40) grade = 'D';
else grade='F';
}
void putdata()
{ cout << name << ", rollno" << "has" << marks
<<" % marks and " << grade << "grate." << endl;
}
int getrno() //accessor function
{ return rollno;
}
}s1;
int main()
{
int rn; char found='n';
ifstream fi("stu.dat",ios::in);
//stu.dat must exist on disk
cout << "Enter rollno to be searched for:";
cin >> rn;
while(!fi.eof())
{ fi.read((char*)&s1, sizeof(s1);
if(s1.getrno() == rn)
{ s1.putdata();
found='y';
break;
}
}
if(found == 'n')
cout <<"Rollno not found in file!!"<<endl;
fi.close();
return 0;
}

OUTPUT
25

Write a program to insert data in a sorted file.


#include<iostream.h>
#include<fstream.h>
26

#include<stdio.h>
// for rename() and remove()
class stu{ int rollno;
char name[25];
char Class[4];
float marks;
char grade;
public:
void getdata()
{ cout << "Rollno:"; cin >> rollno;
cout << "Name:";
cin >> name;
cout << "Class:";
cin >> class;
cout << "Marks:";
cin >> marks;
if(marks >= 75)
grade = 'A';
else if(marks >= 60) grade = 'B';
else if(marks >= 50) grade = 'C';
else if(marks >= 40) grade = 'D';
else grade='F';
}
void putdata()
{ cout << "Rollno" << rollno << "\tName:" << name
<<" \n Marks:" << marks << "\tGrade:" << grate << endl;
}
int getrno() //accessor function
{ return rollno; }
}s1, stud;
int main()
{ ifstream fi("stu.dat",ios::in);
//stu.dat must exist on disk
ofstream fo("temp.dat",ios::out);
char last="y";
cout << "Enter details of student whose record is to be inserted\n";
s1.getdata();
while(!fi.eof())
{ fi.read((char*)&stud,sizeof(stud)); // s1 is new record, stud is record from file
if (s1.getrno() <=stud.getrno())
{ fo.write((char*) &s1, sizeof(s1));
last ='n';
break;
}
else
fo.write((char*)&stud, sizeof(stud));
}
if(last == 'y'
fo.write(char*)&s1, sizeof(s1));
else if(!fi.eof())
{ while(!fi.eof())
27

fi.read((char*)&stud,sizeof(stud));
fo.write((char*)&stud,sizeof(stud));

}
}
fi.close();
fo.close();
remove("stu.dat");
rename("temp.dat"),"stu.dat");
fi.open("stu.dat",ios::in);
cout<<"File now contains\n";
while(!fi.eof())
{ fi.read((char*)&stud,sizeof(stud));
if(fi.eof()) break;
stud.putdata();
}
fi.close();
return 0;
}

28

Write a program to delete a record from a file.


#include<iostream.h>
#include<fstream.h>
#include<stdio.h>
// for rename() and remove()
#include<string.h>
class stu{ int rollno;
char name[25];
char Class[4];
float marks;
char grade;
public:
void getdata()
{
cout << "Rollno:"; cin >> rollno;
cout << "Name:";
cin >> name;
cout << "Class:";
cin >> class;
cout << "Marks:";
cin >> marks;
if(marks >= 75)
grade = 'A';
else if(marks >= 60) grade = 'B';
else if(marks >= 50) grade = 'C';
else if(marks >= 40) grade = 'D';
else grade='F';
}
void putdata()
{ cout << "Rollno" << rollno << "\tName:" << name
<<" \n Marks:" << marks << "\tGrade:" << grate << endl;
}
int getrno() //accessor function
{ return rollno; }
}s1,stud ;
int main()
{ ifstream fiO("stu.dat",ios::in); //stu.dat must exist on disk
ofstream file("temp.dat",ios::out);
int rno; char found='f', confirm='n';
cout << "Enter rollno of student whose record is to be deleted\n";
cin>>rno;
while(!fio.eof())
{ fio.read((char*)&s1,sizeof(s1)); // s1 is new record, stud is record from file
if(s1.getrno() == rno)
{ s1.putdata();
found='t'
cout<<"Are you sure, you want to delete this record?(y/n..)";
cin>>confirm;
if(confirm == 'n')
file.write((char*)&s1, sizeof(s1));
}
29

else
file.write((char*)&s1, sizeof(stud));
}
if(found == 'f')
cout<<"Record not found!!\n";
fio.close();
file.close();
remove("stu.dat");
rename("temp.dat"),"stu.dat");
fio.open("stu.dat",ios::in);
cout<<"Now the file contains\n";
while(!fio.eof())
{
fio.read((char*)&stud,sizeof(stud));
if(fio.eof())break;
stud.putdata();
}
fio.close();
return 0;
}

OUTPUT

30

Write a program to search a element using Linear search


#include<iostream.h>
int Lsearch(int[],int,int);
int main()
{ int AR[50],ITEM,N,index;
cout<<":enter the desired array size(max 50)...";
cin>>N;
cout<<"\n enter the array elements\n";
for(int i=0;i<N;i++)
{ cin>>AR[i];}
cout<<"\n enter element to be searched for ...";
cin>>ITEM;
index=Lsearch(AR,N,ITEM);
if(index==-1)
cout<<"\n sorry!!given element could not be found.\n";
else
cout<<"\n element found at index:"<<index<<", position:"<<index+1<<endl;
return 0;
}
int Lsearch(int AR[],int size, int item)
{ for(int i=0;i<size;i++)
{ if(AR[i]==item) return i;
}
return -1;
}

OUTPUT
enter the desired array size(max 50)...10
enter the array elements(in asc order)
23
45
56
57
60
65
67
78
89
93
enter element to be searched for ...65
31

element found at index:5, position:6

Write a program to search a element using Binary search


#include <iostream.h>
#include <conio.h>
void clr_screen(void);
void main()
{
int range[50], T, i, j, NUM;
int first = 0, last, mid = 0, find = 0, search;
clr_screen();
gotoxy(0, 0);
cout << "Enter the total numbers in array : " ;
cin >> NUM;
for (i = 0; i < NUM; i++)
{
cout << "Value " << i + 1 << " . ";
cin >> range[i];
}
// Sorting procedures before binary search
for (i = 0; i < NUM - 1; i++)
{
for (j = i + 1; j < NUM; j++)
{
if (range[i] > range[j])
{
T = range[i];
range[i] = range[j];
range[j] = T;
}
}
}
cout << "Sorted elements are : \n" ;
for (i = 0; i < NUM; i++)
{
cout << "\nValue " << i + 1 << " . " << range[i];
}
first = 0;
find = 0;
last = NUM - 1;
// Binary search procedure
cout << "\nEnter the element to search in the above list ";
32

cin >> search;


while ((first <= last) && (find == 0))
{
mid = (first + last) / 2;
if (range[mid] == search)
find = mid;
else
if (range[mid] < search)
first = mid + 1;
else
last = mid - 1;
}
if (find > 0)
cout << "\nThe position of the element is : " << ++find;
else
cout << "\nSearch not perfect";
getch();
// To make auto break.
}
// Function for clear screen
void clr_screen(void)
{
int x = 0;
while (x <= 25)
{
cout << "\n";
x++;
}
}

OUTPUT
Enter the total numbers in array : 5
Value 1 . 445
Value 2 . 67
Value 3 . 76
Value 4 . 89
Value 5 . 45
Sorted elements are :
Value 1 . 45
Value 2 . 67
Value 3 . 76
Value 4 . 89
Value 5 . 445
Enter the element to search in the above list 76
33

The position of the element is : 3

Insertion in an array at particular location


#include <iostream.h>
#include <conio.h>
void main()
{
int range[100], N, num, loc, prev, i;
clrscr();
cout << "Enter the length of your array : ";
cin >> N;
cout << "Enter the array values \n";
for (i = 0; i < N; i++)
{
cout << "Value " << i + 1 << ". ";
cin >> range[i];
}
cout << "Enter the inserted value : ";
cin >> num;
cout << "Enter the location to insert in array : ";
cin >> loc;
cout << "\n";
if (loc <= N)
{
prev = N;
while (prev >= loc)
{
range[prev] = range[prev-1];
prev = prev - 1;
}
range[prev] = num;
N = N + 1;
cout << "The resulted output is :\n";
for (i = 0; i < N; i++)
cout << range[i] << endl;
}
else
cout << "Your location is not in the array range";
}
34

OUTPUT
Enter the length of your array : 6
Enter the array values
Value 1. 23
Value 2. 12
Value 3. 32
Value 4. 43
Value 5. 23
Value 6. 45
Enter the inserted value : 65
Enter the location to insert in array : 3
The resulted output is :
23
12
65
32
43
23
45

35

Write a program to deleted from an array range at loc place


#include <iostream.h>
#include <conio.h>
void main()
{
int range[100], N, loc, prev, i, num;
clrscr();
cout << "Enter the length of your array : ";
cin >> N;
cout << "Enter the array values \n";
for (i = 0; i < N; i++)
{
cout << "Value " << i + 1 << ". ";
cin >> range[i];
}
cout << "Enter the location to delete from the array : ";
cin >> loc;
cout << "\n";
loc = loc - 1;
if (loc < N)
{
num = range[loc];
prev = loc;
while (prev < N)
{
range[prev] = range[prev + 1];
prev = prev + 1;
}
N = N - 1; // Decrease the length of array by 1.
cout << "The resulted output is :\n";
for (i = 0; i < N; i++)
cout << range[i] << endl;
cout << "\nThe deleted value is : " << num;
}
36

else
cout << "Your location is not in the array range to delete";
}

OUTPUT
Enter the length of your array : 5
Enter the array values
Value 1. 76
Value 2. 56
Value 3. 23
Value 4. 32
Value 5. 43
Enter the location to delete from the array : 2
The resulted output is :
76
23
32
43
The deleted value is : 56

37

Demonstration of the program for selection sort


#include <iostream.h>
#include <conio.h>
main()
{
int range[100], loc, lowest, T, N, i, j, x;
clrscr();
cout << "Enter the number of elements in your array : ";
cin >> N;
cout << "Enter the array elements : \n";
for (i = 0; i < N; i++)
{
cout << "Location " << i + 1 << ". Value : ";
cin >> range[i];
}
for (i = 0; i < N - 1; i++)
{
lowest = range[i];
loc = i;
for (j = i + 1; j < N; j++)
{
if (lowest > range[j])
{
loc = j;
lowest = range[j];
}
}
T = range[i];
range[i] = range[loc];
38

range[loc] = T;
}
cout << "\nThe sorted list is ... \n";
for (i = 0; i < N; i++)
cout << range[i] << endl;
return 0;
}

OUTPUT
Enter the number of elements in your array : 6
Enter the array elements :
Location 1. Value : 19
Location 2. Value : 21
Location 3. Value : 31
Location 4. Value : 23
Location 5. Value : 45
Location 6. Value : 43
The sorted list is ...
19
21
23
31
43
45

39

Demonstration of the program for Bubble sort


#include <iostream.h>
#include <conio.h>
#include <stdio.h>
int array[8] = {25, 57, 48, 37, 12, 92, 86, 33};
void bubble(int a[], int N);
int main(void)
{
int i;
putchar('\n');
cout << "Unsorted elements...\n";
for (i = 0; i < 8; i++)
cout << array[i] << ' ';
bubble(array, 8);
putchar('\n');
cout << "Sorted elements...\n";
for (i = 0; i < 8; i++)
cout << array[i] << '\t';
return 0;
}
void bubble(int a[], int N)
{
int i, j, temp;
for (i = 0; i < N; i++)
for (j = 0 ; j < N-1; j++)
if (a[j] > a[j+1])
{
40

temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}

OUTPUT
Enter the array elements : 25
57
48
37
12
92
86
33
Unsorted elements...
25 57 48 37 12 92 86 33
Sorted elements...
12 25 33 37 48

57

86

92

41

Demonstration of program insertion sort


#include <iostream.h>
#include <conio.h>
void main()
{
int range[100], i, j, N, T, x;
clrscr();
cout << "Enter your total number of elements : ";
cin >> N;
cout << "Enter the array elements : \n";
for (i = 0; i < N; i++)
{
cout << "Location " << i + 1 << ". Value : ";
cin >> range[i];
}
for (i = 1; i < N; i++)
{
T = range[i]; // Extracts the first element of the unsorted part
j = i - 1;
while ((T < range[j]) && (j >= 0))
{
range[j + 1] = range[j];
j = j - 1;
}
42

range[j + 1] = T;
for (x = 0; x < N; x++) // Displays the output after every insertion
cout << range[x] << " ";
cout << "\n";
}
cout << "\nThe sorted list is ... \n";
for (i = 0; i < N; i++)
cout << range[i] << endl;
}

OUTPUT
Enter the array elements : 6
4
7
3
7
9
4
7
2
5
4 6 7 3 7 9 4 7 2 5
4 6 7 3 7 9 4 7 2 5
3 4 6 7 7 9 4 7 2 5
3 4 6 7 7 9 4 7 2 5
3 4 6 7 7 9 4 7 2 5
3 4 4 6 7 7 9 7 2 5
3 4 4 6 7 7 7 9 2 5
2 3 4 4 6 7 7 7 9 5
2 3 4 4 5 6 7 7 7 9
The sorted list is ...
2
3
43

4
4
5
6
7
7
7
9

Write a program to calculate the sum of rows


#include <iostream.h>
#include <conio.h>
void Row_sum(int M[5][6])
{
int sum, i, j;
for (i=0; i<5; i++)
{
sum = 0;
for (j = 0; j<6; j++)
sum = sum + M[i][j];
cout << "Sum of Rows : " << i+1 << " is : " << sum << endl;
}
}
void main()
{
clrscr();
int ar[5][6];
int i, j;
for (i=0; i<5; i++)
for (j = 0; j<6; j++)
cin >> ar[i][j];
Row_sum(ar);
44

OUTPUT
enter elements of array1
2
3
4
5
6
array is
1
2
3
4
5
6
Sum of Rows : 1 is : 3
Sum of Rows : 2 is : 7
Sum of Rows : 3 is : 11

Demonstration for MERGE sort operation by using two sorted arrays.


#include <iostream.h>
#include <conio.h>
void main()
{
int rang1[100], rang2[100], rang3[100];
int M, N, i, j, k, T;
clrscr();
cout << "Enter your first array length : ";
cin >> M;
cout << "Enter your second array length : ";
cin >> N;
cout << "Enter sorted elements of rang1 : \n";
for (i = 0; i < M; i++)
cin >> rang1[i];
cout << "Enter sorted elements of rang2: \n ";
for (j = 0; j < N; j++)
cin >> rang2[j];
i = 0; // Assign to start from 0th position in array
j = 0;
k = 0;
45

while ((i < M) && (j < N))


{
if (rang1[i] < rang2[j])
{
rang3[k] = rang1[i];
k = k + 1;
i = i + 1;
}
else
{
rang3[k] = rang2[j];
k = k + 1;
j = j + 1;
}
}
while (i <= M)
{
rang3[k] = rang1[i];
k = k + 1;
i = i + 1;
}
while (j <= N)
{
rang3[k] = rang2[j];
k = k + 1;
j = j + 1;
}
cout << "The resulted output is as :\n" ;
T = M + N;
for (k = 0; k < T; k++)
cout << rang3[k] << endl;
}

OUTPUT
first array is 1
Second array is 2

7
4

The merged arrays are :


1
2
46

4
4
6
7
8

Write a program to display the sum of both the diagonal elements of a two
dimensional array
#include <iostream.h>
#include <conio.h>
const M = 6;
const N = 6;
void sum()
{
clrscr();
int MATRIX[M][N], i, j, s1 = 0, s2 = 0;
cout << "Input steps";
cout << "\nEnter the element in the array\n";
for(i=0; i<M; i++)
for(j=0; j<N; j++)
{
cin >> MATRIX[i][j];
}
// Display the array elements
for(i=0; i<M; i++)
{
47

for(j=0; j<N; j++)


{
cout << MATRIX[i][j] << "\t";
}
cout << "\n";
}
// Find the diagonal sum in s1 from left index to right
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
{
s1 = s1 + MATRIX[i][j];
i++;
}
}
// Finding the diagonal sum s2 from right index to left
j = N - 1;
for(i=0; i<=M; i++)
{
s2 = s2 + MATRIX[i][j];
j = j - 1;
}
// The resulted sum of diagonals
cout << s2 << "
" << s1;
getch();
}
void main()
{
clrscr();
sum();
}

OUTPUT
Input steps
Enter the element in the array
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
48

7
8
9
sum of main diagonal is 15
sum of other diagonal is
15

Write a program illustrates the basic operations add, delete and display in array
queue .
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100 // Shows maximum array length
int queue[MAX]; // Declares array global variable
int front, rear;
// Declares integer front and read
// Function prototypes of add queue, delete queue, and show queue in array implementation
void add_Q(int queue[], int val, int &rear); // Add queue
int del_Q(int queue[], int &front, int rear); // Delete queue
void show_Q(int queue[], int front, int rear); // Show queue
void main()
{
int choice, val;
char opt = 'Y';
// To continue the do loop in case
rear = -1;
// Initialization of Queue
front = -1;
clrscr();
49

do
{
cout << "\n\t\t Main Menu";
cout << "\n\t1. Addition of Queue";
cout << "\n\t2. Deletion from Queue";
cout << "\n\t3. Traverse of Queue";
cout << "\n\t4. Exit from Menu";
cout << "\n\nEnter your choice from above ";
cin >> choice;
switch (choice)
{
case 1:
do
{
cout << "Enter the value to be added in the queue ";
cin >> val;
add_Q(queue, val, rear);
cout << "Do you want to add more elements <Y/N> ? ";
cin >> opt;
} while (toupper(opt) == 'Y');
break;
case 2:
opt = 'Y'; // Initialize for the second loop
do
{
val = del_Q(queue, front, rear);
if (val != -1)
cout << "Value deleted from Queue is " << val;
cout << "\nDo you want to delete more elements <Y/N> ?
";
cin >> opt;
} while (toupper(opt) == 'Y');
break;
case 3:
show_Q(queue, front, rear);
break;
case 4:
exit(0);
}
}
while (choice != 4);
}
// Function body for add queue with array
void add_Q(int queue[], int val, int &rear)
{
if (rear == MAX)
{
50

cout << "Queue Full ";


}
else
{
rear = rear + 1;
queue[rear] = val;
}
}
// Function body for delete queue with array
int del_Q(int queue[], int &front, int rear)
{
int value;
if (front == rear)
{
cout << "Queue Empty ";
value = -1;
}
else
{
front = front + 1;
value = queue[front];
}
return (value);
}
// Function body for show queue with array
void show_Q(int queue[], int front, int rear)
{
clrscr();
if (front == rear)
{
cout << "Queue Empty";
return;
}
cout << "The values are ";
do
{
front = front + 1;
cout << "\n" << queue[front];
}while (front != rear);
}

OUTPUT
Main Menu
1. Addition of Queue
51

2. Deletion from Queue


3. Traverse of Queue
4. Exit from Menu
Enter your choice from above 1
Enter the value to be added in the queue 23
Do you want to add more elements <Y/N> ? y
Enter the value to be added in the queue 56
Do you want to add more elements <Y/N> ? y
Enter the value to be added in the queue 65
Do you want to add more elements <Y/N> ? n
Main Menu
1. Addition of Queue
2. Deletion from Queue
3. Traverse of Queue
4. Exit from Menu
Enter your choice from above 2
Value deleted from Queue is 23
Do you want to delete more elements <Y/N> ? n
Main Menu
1. Addition of Queue
2. Deletion from Queue
3. Traverse of Queue
4. Exit from Menu
Enter your choice from above 3
The values are
56
65
Main Menu
1. Addition of Queue
2. Deletion from Queue
3. Traverse of Queue
4. Exit from Menu
Enter your choice from above

52

Write a program to illustrates the basic operation add , delete and display in
linked queue .
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
// Declares a queue structure
struct node
{
int data;
node *link;
53

};
// Functions prototype for add queue, delete queue, and show queue
node *add_Q(node *rear, int val); // Add queue
node *del_Q(node *front, int &val); // Delete queue
void show_Q(node *front); // Show queue
// Main programming logic
void main()
{
node *front, *rear;
int val, choice;
char opt = 'Y';
// To continue the do loop in case
front = rear = NULL; // Initialization of Queue
clrscr();
do
{
cout << "\n\t\t Main Menu";
cout << "\n\t1. Addition of Queue";
cout << "\n\t2. Deletion from Queue";
cout << "\n\t3. Traverse of Queue";
cout << "\n\t4. Exit from Menu";
cout << "\n\nEnter your choice from above ";
cin >> choice;
switch (choice)
{
case 1:
do
{
cout << "Enter the value to be added in the queue ";
cin >> val;
rear = add_Q(rear, val);
if (front == NULL)
front = rear;
cout << "\nDo you want to add more elements <Y/N> ? ";
cin >> opt;
} while (toupper(opt) == 'Y');
break;
case 2:
opt = 'Y'; // Initialize for the second loop
do
{
front = del_Q(front, val);
if (front == NULL)
rear = front;
if (val != -1)
cout << "Value deleted from Queue is " << val;
cout << "\nDo you want to delete more elements <Y/N> ? ";
cin >> opt;
54

} while (toupper(opt) == 'Y');


break;
case 3:
show_Q(front);
break;
case 4:
exit(0);
}
}
while (choice != 4);
}
// Function body for add queue elements
node *add_Q(node *rear, int val)
{
node *temp;
temp = new node;
temp->data = val;
temp->link = NULL;
rear->link = temp;
rear = temp;
return (rear);
}
// Function body for delete queue elements
node *del_Q(node *front, int &val)
{
node *temp;
clrscr();
if (front == NULL)
{
cout << "Queue Empty ";
val = -1;
}
else
{
temp = front;
front = front->link;
val = temp->data;
temp->link = NULL;
delete temp;
}
return (front);
}
// Function body for show queue elements
void show_Q(node *front)
{
node *temp;
temp = front;
55

clrscr();
cout << "The Queue values are";
while (temp != NULL)
{
cout <<"\n"<< temp->data;
temp = temp->link;
}
}

OUTPUT
Main Menu
1. Addition of Queue
2. Deletion from Queue
3. Traverse of Queue
4. Exit from Menu
Enter your choice from above 1
Enter the value to be added in the queue 56
Do you want to add more elements <Y/N> ? y
Enter the value to be added in the queue 78
Do you want to add more elements <Y/N> ? y90
Enter the value to be added in the queue
Do you want to add more elements <Y/N> ? n

Main Menu
1. Addition of Queue
2. Deletion from Queue
3. Traverse of Queue
4. Exit from Menu
Enter your choice from above 1
Enter the value to be added in the queue 56
Do you want to add more elements <Y/N> ? y
Enter the value to be added in the queue 78
Do you want to add more elements <Y/N> ? y
Enter the value to be added in the queue 90
Do you want to add more elements <Y/N> ? n
56

Main Menu
1. Addition of Queue
2. Deletion from Queue
3. Traverse of Queue
4. Exit from Menu
Enter your choice from above
Value deleted from Queue is 56
Do you want to delete more elements <Y/N> ? n
Main Menu
1. Addition of Queue
2. Deletion from Queue
3. Traverse of Queue
4. Exit from Menu
Enter your choice from above 3
The Queue values are
78
90
Main Menu
1. Addition of Queue
2. Deletion from Queue
3. Traverse of Queue
4. Exit from Menu
Enter your choice from above 4

1. Write a program to implement array-stack


#include<iostream.h>
#include<process.h>
int pop(int[],int&);
int push(int[],int&,int);
void display (int [],int);
const int size= 50;
int main()
{ int stack[size],item,top=-1,res;
57

char ch='y';
while(ch=='y'||ch=='Y')
{cout<<"enter the item for insertion";
cin>>item;
res=push(stack,top,item);
if(res==-1)
{cout<<"overflow;
exit(1);
}
cout<<"the stack now is";
display(stack,top);
cout<<"want to insert more elements?(y/n)";
cin>>ch;
}
cout<<"now deletion of elements begins...\n";
ch='y';
while(ch=='y'||ch=='Y')
{res=pop(stack,top);
if(res==-1)
{cout<<"underflow";
exit(1);
}
else{cout<<"elements deleted is"<<res<<endl;
cout<<"the stack now is";
display(stack,top);
}
cout<<"want to delete more elements ?(y/n)";
cin>>ch;
}
return 0;
}
int push(int stack[],int &top,int ele)
{if(top==size-1)
return -1;
else{top++;
stack[top]=ele;
}
return 0;}
int pop(int stack[],int &top)
{
int ret;
if(top==-1)
return -1;
else{ret=stack[top];
58

top--;
}
return ret;}
void display(int stack[],int top)
{ if(top==-1)
return;
cout<<stack[top]<<"<--"<<endl;
for(int i=top-1;i>=0;i--)
cout<<stack[i]<<endl;
}

OUTPUT

59

Write a program to implement Linked-Stack.


#include<iostream.h>
#include<conio.h>
#include<process.h>
struct Node { int info;
Node * next;
} *top, *newptr, *save, *ptr;
Node * Create_New_Node( int );
void Push( Node* );
void Display( Node* );
void main( )
{ int inf;
char ch = y;
top = NULL; clrscr( );
while ( ch == y || ch == Y )
{
cout << \n Enter INFOrmation for the new node;
cin >> inf;
newptr = Create_New_Node( inf );
if ( newptr == NULL )
{ cout << \nCannot create new node!!! Aborting!!\n; exit(1); }
Push( newptr );
cout << \nNow the linked-stack is :\n;
Display( top );
cout << \n Press Y to enter more nodes, N to exit;
cin >> ch;
}
}
Node * Create_New_Node( int n )
{
ptr = new Node;
ptr -> info = n;
ptr -> next = NULL;
return ptr;
}
void Push( Node* np)
{ if ( top == NULL )
top = np;
else
{
save = top;
top = np;
np -> next = save;
}
}
void Display( Node* np )
{ while ( np != NULL )
{
cout << np -> info << ->;
60

np = np -> next;
}
cout << !!!\n;
}

OUTPUT
Enter INFOrmation for the new node5
Now the linked-stack is :
5 -> !!!
Press Y to enter more nodes, N to exity
Enter INFOrmation for the new node8
Now the linked-stack is :
8 -> 5 -> !!!
Press Y to enter more nodes, N to exity
Enter INFOrmation for the new node15
Now the linked-stack is :
15 -> 8 -> 5 -> !!!
Press Y to enter more nodes, N to exit.

61

You might also like