Вы находитесь на странице: 1из 110

C++

PROGRAMMING

PROGRAM NO: 1
DATE: 13/05/2014
STUDENT SURVEY
Students in a college were surveyed about how many days a week they eat fast-food. Write
a program to help analyze the result of the survey. Initially the program prompts how many input
values there are, it then reads in the specified number of values, and counts how many answers are
0 day a week, 1 day a week, etc. Finally the result is displayed in a table, each row showing the
number of days, the number of students that eat fast-food that many days a week, and what
percentage they constitute of the total number of students surveyed. An example running session
might look like follows (you dont have to align the table columns):
How many input values are there: 5
Enter number of days: 2
Enter number of days: 0
Enter number of days: 3
Enter number of days: 3
Enter number of days: 7
Days Students Percentage(%)
0 1 20
100
2 1 20
3 2 40
400
500
600
7 1 20

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class survey
{
private:
int n,count[8];
public:
survey()
{
n=0;
for(int i=0;i<8;i++)
{
count[i]=0;
}
}
void find()
{
int i=0,ch;
cout<<"\nEnter the total number of students to be surveyed: \n";
cin>>n;
while(i<n)
{
cout<<"\nSurvey for student "<<i+1;
cout<<"\nEnter the number of days(eat fast food):";
cin>>ch;
switch(ch)
{
case 0: count[0]++;
break;
case 1:count[1]++;
break;

case 2: count[2]++;
break;
case 3: count[3]++;
break;
case 4: count[4]++;
break;
case 5: count[5]++;
break;
case 6: count[6]++;
break;
case 7: count[7]++;
break;
default: cout<<"Invalid choice\n";
break;
}
i++;
}
}
void display()
{
cout<<"\nDAYS\tSTUDENTS\tPERCENTAGE";
for(int i=0;i<8;i++)
{
float t;
t=((count[i]/float(n))*100.0);
cout<<"\n"<<i<<"\t"<<count[i]<<"\t\t"<<t;
}
cout<<"\n";
}
};
int main()
{
survey s1;

s1.find();
s1.display();
return 0;
}

OUTPUT

PROGRAM NO: 2
DATE: 13/05/2014
PASSING ARRAY OF OBJECTS
Create a class student with rollno, name and marks of 3 subjects. Read the student details,
find total and percentage and display the details

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class student
{
private:
int m1,m2,m3,roll,total;
char name[20];
float per;
public:
void read()
{
cout<<"\nEnter the roll no: ";
cin>>roll;
cout<<"\nEnter the name: ";
cin>>name;
6

cout<<"\nEnter mark1,mark2 and mark3: ";


cin>>m1>>m2>>m3;
total=m1+m2+m3;
}
void display()
{
cout<<"\nName: "<<name;
cout<<"\nTotal: "<<total;
cout<<"\nPercentage: "<<per<<"\n";
}
int percentage(student s[],int n)
{
int sid;
float max;
for(int i=0;i<n;i++)
{
float avg=0;
avg=s[i].m1+s[i].m2+s[i].m3;
s[i].per=float((avg/300)*100);
if(i==0)
{
max=s[i].per;
sid=i;
}
else
{
if(max<s[i].per)
{
max=s[i].per;
sid=i;
}
}
}

return sid;
}
};
int main()
{
student S1[10];
int n,r;
cout<<"\nEnter the no:of students: ";
cin>>n;
for(int i=0;i<n;i++)
{
S1[i].read();
}
student S2,P;
r=S2.percentage(S1,n);
for(int j=0;j<n;j++)
{
S1[j].display();
}
return 0;
}

OUTPUT

PROGRAM NO: 3
DATE: 13/05/2014
INLINE FUNCTION
Create a inline function to find the sum of first n odd numbers

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<math.h>
using namespace std;
class sum
{
private:
int n;
public:
void getdata()
{
cout<<"Enter the limit: ";
cin>>n;
}
inline int oddsum()
{
int s;
s=pow(n,2);
cout<<"SUM= "<<s;
cout<<"\n";
}
10

};
int main()
{
sum s1;
s1.getdata();
s1.oddsum();
return 0;
}

OUTPUT

11

PROGRAM NO: 4
DATE: 20/05/2014
CONSTRUCTOR
Using constructor find sum of 2 integers (use default, parameterized constructor)

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class constructor
{
int a,b,sum;
public:
constructor()
{
a=0;
b=0;
cout<<"Value of a: "<<a<<"\n";
cout<<"Value of b: "<<b;
sum=0;
}
constructor(int i,int j)
{
a=i;
b=j;
cout<<"Value of a: "<<a<<"\n";
cout<<"Value of b: "<<b;
12

}
int add()
{
return a+b;
}
};
int main()
{
cout<<"\nDefault constructor called\n";
constructor c1;
cout<<"\nSum: "<<c1.add();
cout<<"\n\nParameterised constructor called\n";
constructor c2(5,5);
cout<<"\nSum: "<<c2.add()<<"\n";
return 0;
}

OUTPUT

13

PROGRAM NO: 5
DATE: 20/05/2014
TOLL BOOTH
Implement the toll booth . When a car is a paycar, increment count by one and increment
money by 10. If car is not a paycar,increment count by one. Count will represent number of cars
passed by.

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class tollbooth
{
int tot_car;
int amt;
public:
tollbooth():tot_car(0),amt(0)
{}
void display()
{
cout<<"\nTotal car passed: "<<tot_car;
cout<<"\nTotal Amount :"<<amt<<"\n";
}
void payingcar()
{
tot_car=tot_car+1;

14

amt=amt+10;
}
void nopayingcar()
{
tot_car=tot_car+1;
}
};
int main()
{
int n,ch=1;
tollbooth t;
while(ch==1)
{
cout<<"\nOptions\n1.Paying car\n2.Not paying car\n3.Display\nEnter your choice:
";
cin>>n;
switch(n)
{
case 1:
t.payingcar();
t.display();
break;
case 2:
t.nopayingcar();
t.display();
break;
case 3:
t.display();
break;
default:
cout<<"Invalid choice\n";
}
cout<<"\nDo you want to continue? Press 1 for yes else press 0: ";

15

cin>>ch;
}
return 0;
}

OUTPUT

16

PROGRAM NO: 6
DATE: 20/05/2014
STATIC VARIABLES AND FUNCTIONS
To count no of vowels,consonants in a string using static variables and functions.

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class count
{
static char str[10];
static int vowel_count,consonant_count;
public:
void getdata()
{
cout<<"\nEnter the string : ";
cin>>str;
}
static void putdata()
{
int i;
for(i=0;str[i]!='\0';i++)
{
if(str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u')
vowel_count++;

17

else
consonant_count++;
}
cout<<"\nNo of Vowels : "<<vowel_count;
cout<<"\nNo of Consonants : "<<consonant_count<<"\n";
}
};
char count::str[10];
int count::vowel_count=0;
int count::consonant_count=0;
int main()
{
count c;
c.getdata();
count::putdata();
return 0;
}

OUTPUT

18

PROGRAM NO: 7
DATE: 03/06/2014
BANK ACCOUNT
Define a class bankAccount. Include the following members. Write a program in C++ to
test Data
MEMBERS:
i. Name of depositor
ii. Account number
iii. Balance amount in the account
MEMBER FUNCTIONS:
i. To assign initial values
ii. To deposit an amount
iii.To withdraw an amount after checking the balance
iv.To display name and balance
v. Transfer amount from one Bank Account to another Bank Account

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
class bankaccount
{
19

private:
string name;
int accno;
unsigned long int bal;
public:
bankaccount()
{
cout<<"\nEnter the name: ";
cin>>name;
cout<<"Enter the account number: ";
cin>>accno;
bal=0;
}
int get()
{
return accno;
}
void display()
{
cout<<"\nName: "<<name<<"\n";
cout<<"Balance: "<<bal<<"\n";
}
void deposit()
{
int amt;
cout<<"\nEnter amount to deposit: ";
cin>>amt;
bal=bal+amt;
cout<<"Amount deposited!!!\n";
}
void withdraw()
{
int amt;

20

cout<<"\nEnter the amount to be withdrawn: ";


cin>>amt;
if(bal<=0 || bal<amt)
cout<<"\nNo sufficient balance!!!\nWithdrawing not possible\n";
else
{
bal=bal-amt;
cout<<"Amount withdrawn!!!\n";
}
}
bankaccount transfer(bankaccount b1)
{
int amt;
cout<<"\nEnter the amount you want to transfer: ";
cin>>amt;
if(amt>b1.bal)
cout<<"No sufficient amount to transfer\n";
else
{
bal=bal+amt;
b1.bal=b1.bal-amt;
cout<<"Amount successfully transferred!!!\n";
}
return b1;
}
};
int main()
{
bankaccount b1,b2;
int a=1,ch,ac1,ac2;
while(a==1)
{
cout<<"\nOptions\n1.Deposit\n2.Withdraw\n3.Transfer\n4.Display\nEnter the

21

choice: ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter the account number: ";
cin>>ac1;
if(b1.get()==ac1)
b1.deposit();
else if(b2.get()==ac1)
b2.deposit();
else
cout<<"\nAccount doesn't exist\n";
break;
case 2:
cout<<"Enter the account number:";
cin>>ac1;
if(b1.get()==ac1)
b1.withdraw();
else if(b2.get()==ac1)
b2.withdraw();
else
cout<<"\nAccount doesn't exist\n";
break;
case 3:
cout<<"Enter the account number from which you want to transfer: ";
cin>>ac1;
cout<<"Enter the account number to which u want to deposit: ";
cin>>ac2;
if(b1.get()==ac1 && b2.get()==ac2)
b1=b2.transfer(b1);
else if(b2.get()==ac1 && b1.get()==ac2)
b2=b1.transfer(b2);

22

else
cout<<"\nAccount doesn't exist\n";
break;
case 4:b1.display();
b2.display();
break;
case 5: exit(0);
break;
default: cout<<"\nInvalid choice\n";
}
cout<<"Press 1 to continue else press 0: ";
cin>>a;
}
return 0;
}

OUTPUT

23

24

25

PROGRAM NO: 8
DATE: 03/06/2014
COMPLEX NUMBER ADDITION
Complex number addition using friend function

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class complex
{
float real,image;
public:
void get()
{
cout<<"Enter real and imaginary part: ";
cin>>real>>image;
}
void display()
{
cout<<real<<"+i"<<image<<"\n";
}
friend complex sum(complex,complex);
};
complex sum(complex c1,complex c2)
{
complex c3;
26

c3.real=c1.real+c2.real;
c3.image=c1.image+c2.image;
return c3;
}
int main()
{
complex a,b,c;
cout<<"\nFirst complex number\n";
a.get();
cout<<"\nSecond complex number\n";
b.get();
c=sum(a,b);
cout<<"Sum of complex numbers:";
c.display();
return 0;
}

OUTPUT

27

PROGRAM NO: 9
DATE: 10/06/2014
TRANSLATE THE GIVEN SENTENCE TO PIG LATIN
Write an interactive program that prompts the user to input a valid sentence containing at
least two letters and ending in a period. Use getline(cin,sentence); to read the sentence. Use string
functions. Translate the given sentence to Pig Latin and display it.
NOTE: Use functions to make your code as efficient and as organized as possible. Correctness is
the most important element, however, points will be given for the quality of your code.
The Pig Latin system works as follows:
Words that start with a vowel (A, E, I, O, U) simply have "WAY" appended to the end of the
word.
Words that start with a consonant have the first consonant letter moved to the end of the word and
"AY" is appended.
Incorporate the following features and special case functionality:
Correct upper case and lower case formatting.
Assume Words consist of alphabetic characters only (A-Z and a-z).
All punctuation, numerals, symbols and whitespace should not be modified.
For example:
Input:
Output:
These awful french fries are getting cold.
Hesetay awfulway renchfay riesfay areway ettinggay oldcay.

CLASS DIAGRAM

28

PROGRAM
#include <string.h>
#include <iostream>
using namespace std;
class convert
{
int wordLen;
char low_case,ch;
string word,first,newWord;
public:
bool isVowels(char x)
{
low_case = tolower (x);
if (low_case == 'a' )
return true;
else if (low_case == 'e' )
return true;
else if ( low_case== 'i' )
return true;
else if (low_case == 'o' )
return true;
else if (low_case == 'u' )
return true;
else
return false;
}
void changeLine (string line)
{
while (line.length() !=0)
{
wordLen = line.find(' ');
if (wordLen >0)
29

{
word = line.substr(0,wordLen);
first=word.substr(0,1);
ch = first[0];
string notFirst(word,1);
if (isVowels (ch))
{
Vowel(word);
}
else
{
nonVowel(ch,notFirst);
}
line = line.substr(wordLen+1);
}
else
{
word = line;
ch = line[0];
string notFirst(word,1);
if (isVowels (ch))
Vowel(word);
else
nonVowel(ch, notFirst);
line="";
}
}
}
void Vowel(string changed)
{
newWord=changed+"way";
cout<<newWord<<" ";
}

30

void nonVowel(char begin, string end)


{
newWord=end+begin+"ay";
cout<<newWord<<" ";
}
};
int main()
{
convert c;
char ch;
string word, first, line;
cout <<endl;
cout << "Enter a string or, blank to exit.\n";
cout << "This program will output the words in Pig Latin.\n";
cout <<endl;
getline(cin,line);
cout <<endl;
while (line.length()!= 0)
{
c.changeLine(line);
cout<<endl;
cout<<endl;
cout << "Enter a string or, blank to exit.\n";
cout << "This program will output the words in Pig Latin.\n\n";
cout <<endl;
getline(cin,line);
}
return 0;
}

31

OUTPUT

32

PROGRAM NO: 10
DATE: 10/06/2014
ALLOCATING MEMORY DYNAMICALLY
Allocate memory for students dynamically and search for a particular student using rollno.

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<stdlib.h>
using namespace std;
class student
{
int rolno;
char name[20];
char grade;
public:
void read()
{
cout<<"\nEnter roll number: ";
cin>>rolno;
cout<<"Enter name: ";
cin>>name;
cout<<"Enter Grade: ";
cin>>grade;
}
void display()
{
33

cout<<"\nROLL No : "<<rolno;
cout<<"\nNAME : "<<name;
cout<<"\nGRADE : "<<grade;
}
int search(int r)
{
if(rolno==r)
return 1;
else
return 0;
}
};
main()
{
int r,f,n,ch=1;
cout<<"Enter number of students";
cin>>n;
student *s[n];
do
{
cout<<"\nOptions\n1.READ\n2.SEARCH\n3.DISPLAY \n4.EXIT\nEnter your
choice: ";
cin>>ch;
switch(ch)
{
case 1:for(int i=0;i<n;i++)
{
s[i]=new student;
cout<<"Enter the details of Student "<<i+1;
s[i]->read();
}
break;
case 2:cout<<"\nEnter rollno to search: ";

34

cin>>r;
f=0;
for(int i=0;i<n;i++)
{
f=s[i]->search(r);
if(f==1)
{
cout<<"\n ROLL NO FOUND";
cout<<"Details of student\n";
s[i]->display();
break;
}
}
if(f==0)
{
cout<<"\n ROLL NO NOT FOUND";
}
break;
case 3:for(int i=0;i<n;i++)
{
cout<<"\nDetails of Student "<<(i+1);
s[i]->display();
}
break;
case 4:
exit(0);
}
cout<<"\nPress 1 to continue else press 0\n";
cin>>ch;
}
while(ch!=0);
}

35

OUTPUT

36

37

PROGRAM NO: 11
DATE: 17/06/2014
OPERATOR OVERLOADING-STRING
Create a class string class which contains 2 strings as its data members .Overload '+', '= =',
'<', '>'

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<string.h>
using namespace std;
class string1
{
char s1[10],s2[10];
public:
void getdata()
{
cout<<"\nEnter first string: ";
cin>>s1;
cout<<"Enter the second string: ";
cin>>s2;
}
void operator==(int a)
{
if(strcmp(s1,s2)==0)
38

cout<<"\nStrings are equal\n";


else
cout<<"\nStrings are not equal\n";
}
void operator+(int a)
{
char str[25];
strcpy(str,s1);
strcat(str,s2);
cout<<"\nStrings after concatination: "<<str;
}
void operator<(int a)
{
if(strcmp(s1,s2)<0)
cout<<"\nFirst string is smaller\n";
else
cout<<"\nSecond string is smaller\n";
}
void operator>(int a)
{
if(strcmp(s1,s2)>0)
cout<<"\nFirst string is greater\n";
else
cout<<"\nSecond string is greater\n";
}
};
int main()
{
string1 ob;
int n=1;
ob.getdata();
ob==n;
ob+n;

39

ob<n;
ob>n;
cout<<"\n";
return 0;
}

OUTPUT

40

PROGRAM NO: 12
DATE: 17/06/2014
OPERATOR OVERLOADING - DISTANCE
Create a class Distance with feet and inches as data members. Overload '+', '==' , ','

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class Distance
{
private:
float feet,inches;
public:
Distance():feet(0),inches(0)
{}
Distance(float f,float i):feet(f),inches(i)
{}
void display()
{
cout<<feet<<" feet and "<<inches<<" inches\n";
}
Distance operator+(Distance d1)
{
41

Distance temp;
temp.inches=inches+d1.inches;
temp.feet=feet+d1.feet;
if(temp.inches>=12)
{
temp.feet=temp.feet+1;
temp.inches=temp.inches-12;
}
return temp;
}
bool operator==(Distance d1)
{
float f1=feet+(inches/12);
float f2=d1.feet+(d1.inches/12);
if(f1==f2)
return true;
else
return false;
}
void operator+=(Distance d1)
{
inches=inches+d1.inches;
feet=feet+d1.feet;
if(inches>=12)
{
feet=feet+1;
inches=inches-12;
}
}
void operator()(float f,float i)
{
feet=f;

42

inches=i;
}
Distance operator,(Distance d1)
{
Distance temp;
temp.feet=d1.feet;
temp.inches=d1.inches;
return temp;
}
};
main()
{
float f,i;
cout<<"\nEnter first distance: ";
cin>>f>>i;
Distance d1(f,i);
cout<<"Enter second distance: ";
cin>>f>>i;
Distance d2(f,i);
Distance d3=d1+d2;
cout<<"First distance: ";
d1.display();
cout<<"\nSecond distance: ";
d2.display();
cout<<"\nd1+d2= ";
d3.display();
if(d1==d2)
cout<<"\nd1 is equal to d2";
else
cout<<"\nd1 is not equal to d2";
d1+=d2;
cout<<"\nd1+=d2 = ";
d1.display();

43

d1(10,20);
cout<<"\nd1(10,20)= ";
d1.display();
d3=(d1,d2);
cout<<endl<<"d3=(d1,d2) : ";
d3.display();
}

OUTPUT

44

PROGRAM NO: 13
DATE: 01/07/2014
INHERITANCE
Create a class counter with a count variable initialized to zero and a function to increment
the counter and another function to display it.create another class which inherits class counter and
it contains a function which decrements the count. When an employee enters into office, count is
incremented and when employee goes out, count is decremented. Write a program to implement
this functionality.

CLASS DIAGRAM

PROGRAM
#include<stdlib.h>
#include<iostream>
using namespace std;
class base
{
protected:
int count;
public:
base():count(0)
{}
void increment()

45

{
count++;
}
void display()
{
cout<<"\nValue of count : "<<count;
}
};
class derived:public base
{
public:
void dercement()
{
count--;
}
};
int main()
{
derived d1;
int ch=1,c;
do
{
cout<<"\nOptions\n1.Employee enters office\n2.Employee leaves
office\n3.Exit\nEnter your choice: ";
cin>>c;
switch(c)
{
case 1:
d1.increment();
d1.display();
break;
case 2:
d1.dercement();

46

d1.display();
break;
case 3:
exit(0);
}
cout<<"\nPress 1 to continue else press 0: ";
cin>>ch;
}
while(ch!=0);
return 0;
}

OUTPUT

47

PROGRAM NO: 14
DATE: 01/07/2014
VIRTUAL FUNCTIONS- SHAPE CLASS
Create a base class shape. Take two data members of double types to compute the area of
different shapes. Derive two classes triangle and rectangle from the base shape. Include
constructors in every class to initialize the objects. Include one pure virtual function
compute_area() to compute area. Using these classes, write a c++ program to compute the area of
triangle and rectangle. Use base class pointer to implement the virtual function.

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class shape
{
protected:
double x,y;
public:
shape()
{
x=0;
48

y=0;
}
shape(double a,double b)
{
x=a;
y=b;
}
virtual double compute_area()=0;
};
class triangle:public shape
{
public:
triangle(double a,double b):shape(a,b){}
double compute_area()
{
return ((x*y)/2);
}
};
class rectangle:public shape
{
public:
rectangle(double a,double b):shape(a,b){}
double compute_area()
{
return x*y;
}
};
int main()
{
int op,ch=1;
double a,b;
shape *s;
cout<<"\nEnter base and height of a triangle: ";

49

cin>>a;
cin>>b;
triangle t(a,b);
s=&t;
cout<<"\nArea of triangle: "<<s->compute_area()<<"\n";
cout<<"\nEnter length and breadth of rectangle: ";
cin>>a;
cin>>b;
rectangle r(a,b);
s=&r;
cout<<"\nArea of rectangle: "<<s->compute_area()<<"\n";
return 0;
}

OUTPUT

50

PROGRAM NO: 15
DATE: 08/07/2014
TRY-CATCH
Write a program that will read the denominator and numerator and if denominator is zero
throw an exception with message denominator cannot be zero

CLASS DIAGRAM

PROGRAM
#include<iostream>
using namespace std;
class Exception
{
float a,b,c;
public:
void read()
{
cout<<"Enter two numbers: ";
cin>>a>>b;
}
void divide()
{
try
{
if(b==0)
throw(b);
else
{
51

c=a/b;
cout<<"Result: "<<c<<"\n";
}
}
catch(float)
{
cout<<"Denominator cannot be zero!!!\n";
}
}
};
int main()
{
Exception e;
e.read();
e.divide();
return 0;
}

OUTPUT

52

PROGRAM NO: 16
DATE: 08/07/2014
BUBBLE SORT USING FUNCTION TEMPLATE
Implement bubble sort using function template

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
template <class t>
class bubble
{
t a[25];
public:
void get(int);
void sort(int);
void display(int);
};
template <class t>
void bubble <t>::get(int n)
{
int i;
cout<<"Enter the array elements:";
53

for(i=0; i<n;i++)
cin>>a[i];
}
template <class t>
void bubble <t>::display(int n)
{
int i;
cout<<"\nThe sorted array is\n";
for(i=0;i<n;i++)
cout<<a[i]<<"\t";
}
template <class t>
void bubble <t>::sort(int n)
{
int i,j;
t temp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
int main()
{
int n,ch;
while(1)

54

{
cout<<"\nBubble sort\n";
cout<<"\nOptions\n1.Integer\n2.Floating Point\n3.Character\n4.Exit\nEnter your
choice: ";
cin>>ch;
switch(ch)
{
case 1:
{
cout<<"\nInteger Sort\n";
bubble<int> b1;
cout<<"Enter the size of array: ";
cin>>n;
b1.get(n);
b1.sort(n);
b1.display(n);
break;
};
case 2:
{
cout<<"\nFloating Point Sort\n";
bubble<float> b2;
cout<<"Enter the size of array: ";
cin>>n;
b2.get(n);
b2.sort(n);
b2.display(n);
break;
};
case 3:
{
cout<<"\nCharacter Sort\n";
bubble<char> b3;

55

cout<<"Enter the size of array: ";


cin>>n;
b3.get(n);
b3.sort(n);
b3.display(n);
break;
};
case 4:
exit(0);
default:
cout<<"Invalid Choice\n";
return 0;
}
}
}

56

OUTPUT

57

PROGRAM NO: 17
DATE: 14/07/2014
CLASS TEMPLATE
Write a class template to represent a generic array. Include member functions to perform
the following tasks:
1. To initialize the array
2. To modify the value at a given position in the array.
3. To multiply by an element in a given location with a scalar value
4. To display the elements in the array.

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<stdlib.h>
using namespace std;
template<class T>class myarray
{
T arr[20];
int n,pos;
public:
void read()
{
cout<<"\nEnter the size of array: ";
cin>>n;
cout<<"\nEnter the elements: ";
58

for(int i=0;i<n;i++)
cin>>arr[i];
}
void modify()
{
cout<<"\nEnter the position: ";
cin>>pos;
if(pos>n)
cout<<"\nNo such position\n";
else
{
T b;
cout<<"\nEnter the element: ";
cin>>b;
arr[pos-1]=b;
cout<<"\nModified Array";
}
}
void multiply()
{
cout<<"\nEnter the position: ";
cin>>pos;
if(pos>n)
cout<<"\nNo such position\n";
else
{
int b;
cout<<"\nEnter the element to be multiplied: ";
cin>>b;
arr[pos-1]=b*arr[pos-1];
cout<<"\nMultiplication done\n";
}
}

59

void display()
{
for(int i=0;i<n;i++)
cout<<arr[i]<<"\t";
}
};
int main()
{
int ch,c,a;
myarray<int>m1;
myarray<double>m2;
do
{
cout<<"\nOptions\n1.Integer\n2.Double\n3.Exit\nEnter your choice: ";
cin>>c;
switch(c)
{
case 1:
do
{
cout<<"\nInteger\n";
cout<<"\nOptions\n1.Initialize\n2.Modify\n3.Multiply with a
value\n4.Display\n5.Exit\nEnter your choice: ";
cin>>ch;
switch(ch)
{
case 1:m1.read();
break;
case 2:m1.modify();
break;
case 3:m1.multiply();
break;
case 4:m1.display();

60

break;
}
}
while(ch!=5);
break;
case 2:
cout<<"\nDouble\n";
do
{
cout<<"\nOptions\n1.Initialize\n2.Modify\n3.Multiply with a
value\n4.Display\n5.Exit\nEnter your choice: ";
cin>>ch;
switch(ch)
{
case 1:m2.read();
break;
case 2:m2.modify();
break;
case 3:m2.multiply();
break;
case 4:m2.display();
break;
}
}
while(ch!=5);
break;
case 3: exit(0);
}
cout<<"Press 1 to continue else press 0: ";
cin>>c;
}
while(c!=0);
}

61

OUTPUT

62

63

64

65

PROGRAM NO: 18
DATE: 14/07/2014
FILE PROGRAM
C++ Program to Count no. of alphabets , digits and spaces present in a file STORY.TXT

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<fstream>
using namespace std;
class count
{
int a,b,c;
public:
void find()
{
a=b=c=0;
char ch;
ifstream fp;
fp.open("story.txt",ios::app);
while(fp)
{
fp.get(ch);
if(isalpha(ch))
a++;
if(isdigit(ch))
b++;
66

if(ch==' ')
c++;
}
cout<<"\n Number of Alphabets: "<<a;
cout<<"\n Number of Digits: "<<b;
cout<<"\n Number of Spaces: "<<c;
fp.close();
}
};
int main()
{
count c1;
c1.find();
cout<<"\n";
}

OUTPUT

67

PROGRAM NO: 19
DATE: 15/07/2014
EMPLOYEE DB
Implement Employee db. The db should hold details of Emplyee(ID,name,address,phno).
1. Add a Employee
2. Update a employee records.
3. Search a employee.
4. Delete a employee.

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
class employee
{
int id;
char phnno[20];
char name[20];
char addr[20];
public:
void add();
68

void display();
void update();
void del();
void search();
int menu();
};
main()
{
int n;
employee e;
n=e.menu();
switch(n)
{
case 1 : e.add(); break;
case 2 : e.del(); break;
case 3 : e.update(); break;
case 4 : e.display(); break;
default: cout<<"Thankyou\n";
}
}
int employee::menu()
{
int a;
cout<<"\nMain Menu\n";
cout<<"\n1.Add\n2.Delete\n3.Update\n4.Display\n5.EXIT\n";
cout<<"Enter your choice: ";
cin>>a;
return(a);
}
void employee::add()
{
ofstream f;
employee t;

69

int x=1;
f.open("empdb",ios::app|ios::binary);
while(x==1)
{
cout<<"Enter the id: ";
cin>>t.id;
cout<<"Enter the name: ";
cin>>t.name;
cout<<"Enter the phone number: ";
cin>>t.phnno;
cout<<"Enter the address: ";
cin>>t.addr;
f.write((char *)&t,sizeof(t));
cout<<"\nRecord Successfully Added !!";
f.close();
cout<<"\nPress 1 to add more record: ";
cin>>x;
}
main();
}
void employee::del()
{
int x=1,flag=0,eid;
employee t;
ofstream f1;
ifstream f2;
while(x==1)
{
flag=0;
cout<<"Enter the id to be deleted: ";
cin>>eid;
f1.open("temp",ios::app|ios::binary);

70

f2.open("empdb",ios::app|ios::binary);
while(f2.read((char *)&t,sizeof(t)))
{
if(eid!=t.id)
f1.write((char *)&t,sizeof(t));
else
flag=1;
}
f1.close();
f2.close();
remove("empdb");
rename("temp","empdb");
if(flag==1)
cout<<"Record is successfully deleted\n";
else
cout<<"Record not found\n";
cout<<"\nPress 1 to delete another record else Press 0: ";
cin>>x;
}
main();
}
void employee::update()
{
int x=1,eid;
int flag=0;
ofstream f1;
ifstream f2;
employee t;
while(x==1)
{
flag=0;
f1.open("temp",ios::app|ios::binary);
f2.open("empdb",ios::in|ios::binary);

71

cout<<"Enter the id to be modified: ";


cin>>eid;
while(f2.read((char *)&t,sizeof(t)))
{
if(eid!=t.id)
f1.write((char *)&t,sizeof(t));
else
{
cout<<"Enter the new name: ";
cin>>t.name;
cout<<"Enter the new place: ";
cin>>t.addr;
cout<<"Enter the new phone no: ";
cin>>t.phnno;
f1.write((char *)&t,sizeof(t));
flag=1;
}
}
f1.close();
f2.close();
remove("empdb");
rename("temp","empdb");
if(flag==1)
cout<<"Record is successfully updated\n";
else
cout<<"Record is not found\n";
cout<<"Press 1 to update another record Else press 0: ";
cin>>x;
}
main();
}
void employee::search()
{

72

ifstream f;
int flag=0,s;
employee t;
cout<<"\nEnter id : ";
cin>>s;
f.open("empdb",ios::in|ios::binary);
f.seekg(0);
while(f.read((char *)&t,sizeof(t)))
{
if(s==t.id)
{
flag=1;
t.display();
break;
}
}
if(flag==0)
cout<<"Entry Not Found !!!\n";
f.close();
}
void employee::display()
{
ifstream f;
int flag=0;
employee t;
cout<<"DETAILS ARE!!!\n";
f.open("empdb",ios::in|ios::binary);
f.seekg(0);
while(f.read((char *)&t,sizeof(t)))
{
flag=1;
cout<<"\n------------------------------\n";
cout<<"Id :"<<t.id;

73

cout<<"\nName :"<<t.name;
cout<<"\nPhone number :"<<t.phnno;
cout<<"\nAddress :"<<t.addr<<"\n";
73
}
if(flag==0)
cout<<"\n FILE IS EMPTY\n";
f.close();
main();
}

74

OUTPUT

75

76

PROGRAM NO: 20
DATE: 15/07/2014
PASSING FILE NAME AS ARGUMENTS
Passing file name as arguments, put even numbers in one file and odd numbers in another
file.

CLASS DIAGRAM

PROGRAM
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class evenodd
{
public:
void find(char *fn1,char*fn2)
{
int i,n,a[20];
char ch;
cout<<"\nEnter the limit: ";
cin>>n;
cout<<"\nEnter the elements: ";
for(i=0;i<n;i++)
cin>>a[i];
fstream f1,f2;
f1.open(fn1,ios::out);
f2.open(fn2,ios::out);
77

for(i=0;i<n;i++)
{
if(a[i]%2==0)
f1<<a[i]<<" ";
else
f2<<a[i]<<" ";
}
f1.close();
f2.close();
f1.open(fn1,ios::in);
f2.open(fn2,ios::in);
f1.close();
f2.close();
}
};
int main(int argc,char *argv[])
{
evenodd ev;
ev.find(argv[1],argv[2]);
cout<<"\n";
return 0;
}

OUTPUT

78

DATABASE MANAGEMENT
SYSTEM

79

QUESTION 1
DATE: 13/05/2014
Create the following table in a database called sea, and answer the
following queries?

80

E-R DIAGRAM

CREATING DATABASE
database1=> create database sea;
CREATE DATABASE
database1=> \c sea
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
You are now connected to database "sea" as user "user1".

TABLE DESCRIPTION
Boat:

81

sea=> select * from boat;

Sailors:

sea=> select * from sailors;

82

Reserves:

sea=> select * from reserves;

QUERIES
1. List sid, sname of all Sailors
sea=> select sid,sname from sailors;

83

2.List sailors whose rating is less than 5


sea=> select sname from sailors where(rating<5);

3. List the details of sailors whose age is between 25 and 40


sea=> select * from sailors where(age BETWEEN '25' and '40');

4. List the name of sailors who reserve boats


sea=> select distinct sname from sailors s,reserves r where s.sid=r.sid;

5. List the name of sailors whose boat id is 104


sea=> select distinct sname from sailors s,reserves r where r.bid=104 and
s.sid=r.sid;

84

6. List the name of sailors who reserve a red boat


sea=> select distinct sname from sailors s,reserves r,boat b where s.sid=r.sid and
b.color='red';

7. List the name of sailors with their boat color


sea=> select sname,color from sailors s,reserves r,boat b where s.sid=r.sid and
b.bid=r.bid;

8. Create a function to display total number of sailors


sea=> create or replace function totalsailors() returns integer as ' declare r int;
sea'> begin
sea'> select into r(count(*)) from sailors;
sea'> return r;
sea'> end
sea'> 'language 'plpgsql';
CREATE FUNCTION
sea=> select totalsailors();

85

QUESTION 2
DATE: 20/05/2014
A college admission database has the following tables:
Course(name, id, duration, no of seats , no of students, Fee/Sem, department)
Department(No, Name, no of course)
Student(id , name, course, Semester, Address)
Hostel(course, no of rooms, occupied, Fee/month)
FeeRemit(stud_id, course, semester, date)

E-R DIAGRAM

86

CREATING DATEBASE
database1=> create database college;
CREATE DATABASE
database1=> \c college
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
You are now connected to database "college" as user "user1".

TABLE DESCRIPTION
College:

college=> select * from course;

87

Department:

college=> select * from department;

Student:

college=> select * from student;

88

Hostel:

college=> select * from hostel;

FeeRemit:

college=> select * from feeRemit;

89

QUERIES
1. Find the course with id 200.
college=> select name from course where id=200;

2. Display the courses with name, duration and Fee/Sem for the courses with semester fee
less than 50000.
college=> select name,duration,fee_sem from course where fee_sem<'50000';

3. Find out the students with course name and semester who had remitted the fee after
15-09-05
college=> select s.name,s.course,s.semester from student s,feeRemit f where
s.id=stud_id and f.date>'2005-09-15';

4. Find out the courses with seats filled fully.


college=> select name from course where no_of_seats=no_of_students;

90

5. Write a function that accepts the course name and displays the no of seats available.
college=> create or replace function seat(CHARACTER) returns integer as'
college'> declare
college'> r int;
college'> begin
college'> select into r (no_of_seats-no_of_students) from course where
name=$1;return r;
college'> end
college'> 'language 'plpgsql'
college-> ;
CREATE FUNCTION
college=> select seat('MCA');

6. Find out the no of rooms available in the hostel for the students of the given course.
college=> create or replace function room(CHARACTER) returns integer as '
college'> declare
college'> r int;
college'> begin
college'> select into r(no_of_rooms) from hostel where course=$1;
college'> return r;
college'> end
college'> 'language 'plpgsql'
college-> ;
CREATE FUNCTION
college=> select room('MCA');

91

7. Create a trigger to restrict the entry to the hostel if rooms are all filled.
college=> create or replace function hostelentry() returns opaque as'
college'> declare
college'> c course.name%type;
college'> s int;
college'> begin
college'> c:=old.course;
college'> select into s (no_of_rooms-occupied) from hostel where course=c;
college'> if s<=0 then
college'> raise exception ''ROOM FULL'';
college'> end if;
college'> return new;
college'> end;
college'> 'language 'plpgsql';
CREATE FUNCTION
college=> create trigger trig_entry before update on hostel for each row execute
procedure hostelentry();
WARNING:

changing return type of function hostelentry from "opaque" to

"trigger"
CREATE TRIGGER
college=> update hostel set occupied=25 where course='MBA';
ERROR: ROOM FULL

92

QUESTION 3
DATE: 03/02/2014
Movie ( mID, title, year, director ) - The movie with id mID has a title, a release year and
a director
Reviewer ( rID, name ) - The reviewer with id rID has a name
Rating ( rID, mID, stars, ratingDate ) - The reviewer rID gave the movie mID a number
of stars rating (1-5) on a certain ratingDate.

E-R DIAGRAM

CREATING DATABASE
database1=> create database movies;
CREATE DATABASE
database1=> \c movies
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
You are now connected to database "movies" as user "user1".
93

TABLE DESCRIPTION
Movies:

movies=> select * from movie;

Reviewer:

94

movies=> select * from reviewer;

Rating:

movies=> select * from rating;

95

QUERIES
1. Display director name and the title of the movies directed by them.
movies=> select director,title from movie;

2. Find the titles of all movies that have no ratings.


movies=> select distinct title from movie,rating where movie.mid not in(select
mid from rating);

3. Find all movies that received a rating of 4 or 5 in the year 2000.


movies=> select distinct title from rating,movie where movie.mid=rating.mid and
(rating.stars='4' or rating.stars='5') and (EXTRACT(year from rating_date))=2000;

4. Write a query to display reviewer name, movie title, stars, and ratingDate. Also, sort the
results
movies=> select re.name as reviewer_name,title as movie_title,stars,rating_date
from movie m,rating ra,reviewer re where m.mid=ra.mid and re.rid order by
re.name;
96

5. Find the reviewer name, movie title, and number of stars for all movies
movies=> select name as reviewer_name,title as movie_title,stars as no_of_stars
from movie,rating,reviewer where movie.mid=rating.mid and rating.rid=reviewer.rid;

6. Display all movie released in each year.


movies=> select title as movie_title,year from movie group by year,title;

97

7. Write a trigger which will display error message when you are deleting a row from
movie table.
movies=> create or replace function deletetrigfun() returns opaque as '
movies'> begin
movies'> raise exception ' 'YOU ARE GOING TO DELETE ROW FROM
TABLE MOVIE!!!' ';
movies'> end;
movies'> 'language 'plpgsql';
CREATE FUNCTION
movies=> create trigger deletetrigger before delete on movie for each row
execute procedure deletetrigfun();
WARNING: changing return type of function deletetrigfun from "opaque" to
"trigger"
CREATE TRIGGER
movies=> delete from movie where mid=104;
ERROR: YOU ARE GOING TO DELETE ROW FROM TABLE MOVIE!!!

98

QUESTION 4
DATE: 10/06/2014
Suppliers(sid: integer, sname: string, address: string)
Parts(pid: integer, pname: string, color: string)
Catalog(sid: integer, pid: integer, cost: real)
E-R DIAGRAM

CREATING DATABASE
database1=> create database shop;
CREATE DATABASE
database1=> \c shop
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
You are now connected to database "shop" as user "user1".

99

TABLE DESCRIPTION
Suppliers:

shop=> select * from suppilers;

Parts:

100

shop=> select * from parts;

Catalog:

shop=> select * from catalog;

101

QUERIES
1. Find the names of suppliers who supply some red part.
shop=> select sname from suppilers,parts,catalog where catalog.sid=suppilers.sid and
parts.pid=catalog.pid and color='red';

2. Find the sids of suppliers who supply some red or green part.
shop=>

select

distinct

suppilers.sid

from

suppilers,parts,catalog

where

catalog.sid=suppilers.sid and parts.pid=catalog.pid and parts.color='red' or color='green';

3. Find the sids of suppliers who supply some red part and some green part.
shop=>

select

distinct

suppilers.sid

from

suppilers,parts,catalog

where

catalog.sid=suppilers.sid and parts.pid=catalog.pid and parts.color='red' and color='green';

4. Find the pids of the most expensive parts supplied by suppliers


shop=>

select

distinct

parts.pid

from

parts,suppilers,catalog

where

catalog.pid=parts.pid and catalog.sid=suppilers.sid and cost=(select max(cost) from catalog);

102

5. Find the pids of parts supplied by every supplier at less than $200
shop=>

select

distinct

parts.pid

from

parts,catalog,suppilers

where

parts.pid=catalog.pid and suppilers.sid=catalog.sid and cost<200;

6. Create a function to count the number of parts.


shop=> create or replace function countpart() returns integer as'
shop'> declare
shop'> c int;
shop'> begin
shop'> select into c count(pid) from parts;
shop'> return c;
shop'> end;
shop'> 'language 'plpgsql';
CREATE FUNCTION
shop=> select countpart();

7. Create trigger which will display warning message whenever yo are inserting a part with color
red
shop=> create or replace function x() returns trigger as '
shop'> begin
shop'> if new.color="red" then
shop'> raise warning ''You are inserting a part having color red'';
shop'> end if;
shop'> return new;
103

shop'> end;
shop'> 'language 'plpgsql';
CREATE FUNCTION
shop=> create trigger trig before insert or update on parts for each row execute
procedure x();
CREATE TRIGGER

104

QUESTION 5
DATE: 17/06/2014
Flights(flno: integer, from: string, to: string, distance: integer, departs:
time, arrives: time)
Aircraft(aid: integer, aname: string, cruisingrange: integer)
Certified(eid: integer, aid: integer)
Employees(eid: integer, ename: string, salary: integer)
(The maximum distance from a base that the fuel capacity of a ship or aircraft
will allow it to travel and then return safely at cruising speed: a fuel capacity of 2200
gallons should give a cruising range of around 2000 miles)
E-R DIAGRAM

105

CREATING DATABASE
database1=> create database airport;
CREATE DATABASE
database1=> \c airport
SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)
You are now connected to database "airport" as user "user1".

TABLE DECRIPTION
Flights:

airport=> select * from flights;

106

Aircrafts:

airport=> select * from aircraft;

Employees:

airport=> select * from employees;

107

Certified:

airport=> select * from certified;

QUERIES:
1. Find the eids of pilots certified for some Boeing aircraft.
airport=>

select

employees.eid

from

employees,certified,aircraft

where

certified.eid=employees.eid and certified.aid=aircraft.aid and aname='boeing';

2. Find the names of pilots certified for some Boeing aircraft.


airport=>

select

ename

from

employees,certified,aircraft

certified.eid=employees.eid and certified.aid=aircraft.aid and aname='boeing';

108

where

3. Find the details of all the aircraft.


airport=> select * from aircraft;

4. Identify the flights that can be piloted by every pilot whose salary is more than $100,000. (Hint:
The pilot must be certified for at least one plane with a sufficiently large cruising range.)
airport=> select distinct a.aname from certified c,aircraft a,employees e where
e.eid=c.eid and e.salary>100000 and a.aid=c.aid;

5. Create a function to Find the names of pilots who can operate some plane with a range greater
than 3,000 miles.
airport=> create type mtype as(n character(20));
CREATE TYPE
airport=> create or replace function func() returns setof mtype as'
airport'> declare mytype mtype;
airport'> begin
airport'> for mytype in select distinct e.ename from employees e,certified c,aircraft a
where e.eid=c.eid and c.aid in(select a.aid from certified c,aircraft a where a.aid=c.aid
and a.cruisingrange>3000) loop return next mytype;
airport'> end loop;
airport'> end;
airport'> 'language 'plpgsql';
CREATE FUNCTION
109

airport=> select func();

6. Find the eids of employees who make the highest salary.


airport=> select eid from employees where salary=(select max(salary)from
employees);

7. Create a trigger to display the warning message when you are deleting a raw in Certified table
airport=> create or replace function delcertified() returns opaque as'
airport'> begin
airport'> raise exception ''you are going to delete row from table certified!!!'';
airport'> end;
airport'> 'language 'plpgsql';
CREATE FUNCTION
airport=> create trigger deletetrigger before delete on certified for each row execute
procedure delcertified();
WARNING:

changing return type of function delcertified from "opaque" to

"trigger"
CREATE TRIGGER
airport=> delete from certified where eid=10;
ERROR: you are going to delete row from table certified!!!

110

Вам также может понравиться