You are on page 1of 157

COMPUTER SCIENCE

MADE BY
Name: Jack
Class: XII
Board Enrolment No.: 1023

1
LEARNING OBJECTIVES
To develop logic for Problem Solving.

To develop problem solving skills and their implementation


using C++.

To understand and implement the concept of Object Oriented


Methodology.

To understand the concept of working with Relational


Database.

2
PRACTICAL SYLLABUS
Duration: 3 hours Total Marks: 30

1. Programming in C++ 12

One programming problem in C++ to be developed and tested


on computer during the examination.
Marks are allotted on the basis of following:

Logic : 7 Marks
Documentation/Indentation : 2 Marks
Output presentation : 3 Marks

Notes: The types of problem to be given will be of application


type from the following topics:
Arrays (One dimensional and two dimensional)
Class(es) and objects
Stack using arrays and or linked implementation
Queue using arrays (circular) and or linked implementation

3
Binary File operations (creation, displaying, searching and
modification)
Text File operations (creation, displaying and modification)

2. SQL Commands 05
Five Query based questions on a particular Table / Relation to be
tested practically on computer during the examination. The
command along with the result must be written in the answer
sheet.

3. A digital circuit diagram (after reduction using K-map) to be


given during the examination. The question must be written in
the answer sheet. 02

4. Project Work 05
The project has to be developed in C++ language with Object
Oriented Technology and also should have use of Data files. (The
project is required to be developed in a group of 2-4 students)
Presentation on the computer
Project report (Listing, Sample, Output, Documentation)
Viva

4
* 1 mark is for innovation while writing program.

Practical File 03+01*


Must have minimum 20 programs from the following topics:
Arrays (One dimensional and two dimensional, sorting,
searching, merging, deletion & insertion of elements)
Class(es) and objects
Stacks using arrays and linked implementation
Queue using arrays & linked implementation (circular also).
File (Binary and Text) operations (creation, updation, query)
Any computational based problems
15 SQL commands along with the output based on any
table/relation

6. Viva Voce 02
Viva will be asked from syllabus covered in class XII and the
project developed by student.

5
INDEX
1. Program to generate Fibonacci series recursively.
2. Implement concept of function overloading for calculating
area of circle, rectangle and triangle.
3. Define a class student with the following specifications
4. Write a program display lower half and upper half of a 2D
matrix
5. Program to implement Linear Search.
6. Program to implement Binary Search.
7. Program to create a base class Building that stores the
number of floors and the number of rooms
8. Show the use of virtual classes with the help of following
program
9. Program to implement Bubble Sort technique.
10. Program to implement Selection Sort technique.
11. Program to implement Insertion Sort technique.
12. Program to implement Merge Sort technique.
13. Program to find the length of a string and print the reversed
string using pointer.

6
14. Program to create count the number of characters, lines,
spaces and digits present in a text file data.txt.
15. Program create a binary file and write objects to it and
display them on screen after reading from the file.
16. Program to implement stack as an array.
17. Program to implement queue as an array.
18. Program to implement dynamic stack/stack as a linked list.
19. Program to implement dynamic queue as a linked list.
20. Program to implement linked list.
21. Program to implement circular queue.

SQL Queries:

1. Consider the following tables CARDEN and CUSTOMER and


answer (a) and (b) parts of this question
2. Consider the following tables ITEMS and TRADERS and
answer (a) and (b) parts of this question
3. Answer the questions (a) and (b) on the basis of the
following tables STORE and ITEM

7
4. Write SQL queries for (a) and write the outputs for the SQL
queries mentioned shown in (b) part on the basis of tables
PRODUCTS and SUPPLIERS.

5. Consider the following tables PRODUCT and CLIENT. Write


SQL commands for the (a) part of the questions and give
outputs for (b) part of SQL queries.

6. Viva Voce

8
Index^

9
Index^

1. Program to generate Fibonacci series recursively.

Solution:

#include<iostream.h>
#include<conio.h>

long fibo(int n)
{
if(n<=1)
return n;
else
return fibo(n-1)+fibo(n-2);
}
void main()
{clrscr();
int n;
long f;

cout<<"\nEnter range: ";


cin>>n;

cout<<"\nThe fibonacci series is:\n\n";


for(int i=0;i<=n;i++)
{
f=fibo(i);
cout<<f<<" , ";
}
getch();
}

10
Index^

OUTPUT

11
Index^

2. Implement concept of function overloading for calculating


area of circle, rectangle and triangle.

Solution:

#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define pi 3.14

void area(int); //circle


void area(int,int); //rectangle
void area(float ,int,int); //triangle

void area(int a)
{
cout<<"Area of Circle:"<<pi*a*a;
}

void area(int a,int b)


{
cout<<"Area of Rectangle:"<<a*b;
}

void area(float t,int a,int b)


{
cout<<"Area of Triangle:"<<t*a*b;
}

12
void main()
{ int ch;
int a,b,r;
clrscr();

cout<<"\n\t\tImplementing function overloading";


cout<<"\n1.Area of Circle\n2.Area of Rectangle\n3.Area of
Triangle\n4.Exit";
cout<<"\nEnter your Choice:";
cin>>ch;

switch(ch)
{
case 1: cout<<"\nEnter Radious of the Circle:";
cin>>r;
area(r);
break;
case 2: cout<<"\nEnter Sides of the Rectangle:";
cin>>a>>b;
area(a,b);
break;
case 3: cout<<"Enter Sides of the Triangle:";
cin>>a>>b;
area(0.5,a,b);
break;
case 4: exit(0);
}
getch();
}

13
Index^

OUTPUT

14
Index^

3. Define a class student with the following specifications:

Private members:

admno : integer

sname : array of characters

phy : integer

chem : integer

maths : integer

eng :integer

csc : integer

total : float

avg : total

grade : character

ctotal() : A function that return the value for total variable as sum
of the marks:

phy+chem+maths+eng +csc

Public members:

Grade() function to calculate avg and grade as per the given


criteria:

15
Avg grade

80-100 A

60-79 B

40-59 C

- D

Takedata() function to accept values for admno, sname, phy,


chem, maths and eng. This function will also invoke ctotal() and
Grade function to calculate tota, avg and grade.

Showdata() function to display all the data members on the screen.

Solution:

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class student
{
private:
int admno;
char sname[20];
float phy, chem,maths,eng,csc;

16
float total;
float avg;
char grade;

float ctotal()
{
return phy+chem+maths+eng+csc;
}

public:

void Takedata()
{
cout<<"Enter admission number: ";
cin>>admno;

cout<<endl<<"Enter student name: " ;


gets(sname);

cout<<"\nEnter marks in physics: ";


cin>>phy;

cout<<"\nEnter marks in chemistry: ";


cin>>chem;

cout<<"\nEnter marks in maths: ";


cin>>maths;

cout<<"\nEnter marks in english: ";


cin>>eng;

17
cout<<"\nEnter marks in computer science: ";
cin>>csc;

total=ctotal();
}

void Grade()
{
avg=total/5;

if(avg>=80 && avg<=100)


grade='A';

else if(avg>=60 && avg<=79)


grade='B';

else if(avg>=40 && avg<=59)


grade='C';

else
grade='D';

void Showdata()
{
cout<<endl<<"..........Student
information...."<<endl;
cout<<"Admission number "<<admno;
cout<<"\nStudent name "<<sname;

18
cout<<"\nPhysics "<<phy;
cout<<"\nChemistry "<<chem;
cout<<"\nMath "<<maths;
cout<<"\nEnglish "<<eng;
cout<<"\nComputer Science "<<csc;

cout<<"\nTotal "<<total;
cout<<"\nAverage "<<avg;
cout<<"\nGrade "<<grade;
}
};

int main()
{
clrscr();

student obj ;

obj.Takedata();
obj.Grade();
obj.Showdata();

getch();
return 0;
}

19
Index^

OUTPUT

20
Index^

4. Program to display lower half and upper half of a 2D matrix


For example-if matrix A is-

781
501
915

The output should be-

Lower half-
7
50
915

Upper half-
781
01
5
Solution:

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int i, j;
int a[3][3];

21
cout<<"\nEnter values for matrix: ";
for(i=0; i<3; i++)
{

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


cin>>a[i][j];
}

clrscr();
cout<<"\n";

cout<<" The entered matrix is..."<<'\n';


for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cout<<a[i][j]<<"\t";

cout<<"\n\n";

cout<<"\nThe lower half of the matrix is...\n";


for(i=0; i<3; i++)
{
for(j=0; j<=3; j++)
{
if(i>=j)
cout<<a[i][j]<<" ";
}
cout<<"\n\n";
}

22
cout<<"\nThe upper half of the matrix is...";

cout<<"\n";
for(i=0; i<3; i++)
{

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


{
if(i<=j)
cout<<a[i][j]<<" ";

else if(i>j)
cout<<" ";

}
cout<<"\n\n";
}
getch();
}

23
Index^

OUTPUT

24
Index^

5. Program to implement Linear Search technique.

Solution:

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

int a[10], n, ele;

int flag=1;

cout<<"\nEnter the range:";


cin>>n;

cout<<"\nEnter elements: ";


for(int i=0;i<n;i++)
cin>>a[i];

cout<<"\nThe array is: ";


for(i=0;i<n;i++)
cout<<"\n"<<a[i];

cout<<"\nEnter the element to be search for:";


cin>>ele;

25
int pos;

for(i=0;i<n;i++)
{
if(a[i]==ele)
{
pos=i+1;
flag=1;
break;
}
else
flag=1;
}
if(flag==1)
cout<<"\nElement found at position. "<<pos;
else
cout<<"\nElement not present. ";
getch();
}

26
Index^

OUTPUT

27
Index^

6. Program to implement Binary Search technique.

Solution:

#include<iostream.h>
#include<conio.h>

int bsearch(int AR[], int N, int VAL);

void main()
{
clrscr();

int AR[20],n,val;
int found;

cout<<"Enter range <20: ";


cin>>n;

cout<<"Enter element in ascending order\n";

for(int i=0;i<n;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>AR[i];
}

cout<<"\nEnter the number you want to search ";


cin>>val;

28
found=bsearch(AR,n,val);

if(found==1)
cout<<"\nItem found";
else
cout<<"\nItem not found";

getch();

int bsearch(int AR[], int N, int ele)


{
int Mid,Lbound=0,Ubound=N-1;

while(Lbound<=Ubound)
{
Mid=(Lbound+Ubound)/2;

if(ele>AR[Mid])
Lbound=Mid+1;

else if(ele<AR[Mid])
Ubound=Mid-1;
else
return 1;
}
return 0;
}

29
Index^

OUTPUT

30
Index^

7. Program to create a base class Building that stores the


number of floors and the number of rooms the building has.
From this, derive a class Flats that stores the number of
bathrooms and open terraces. From Building, derive another
class Offices that stores the number of Fire Exits.

Solution:

#include <iostream.h>
#include<conio.h>

class Building
{
int floors;
int rooms;

public :

void getd()
{
cout<<"\nNo. of Floors = ";
cin>>floors;
cout<<"\nNo. of Rooms = ";
cin>>rooms;
}

void dispd()
{
cout<<"\nNo. of Floors = "<<floors;

31
cout<<"\nNo. of Rooms = "<<rooms;
}

};

class Flats : public Building


{
int baths;
int terraces;

public :

void getdat()
{
getd();
cout<<"\nNo. of Bathrooms = ";
cin>>baths;
cout<<"\nNo. of Terraces = ";
cin>>terraces;
}

void dispdat()
{
dispd();
cout<<"\nNo. of Bathrooms = "<<baths;
cout<<"\nNo. of Terraces = "<<terraces;
}
};

class Offices : public Building


{ int firexits;

32
public:

void getdata()
{
getd();
cout<<"\nNo. of Fire Exits = ";
cin>>firexits;
}

void dispdata()
{
dispd();
cout<<"\nNo. of Fire Exits = "<<firexits;
}
};

void main()
{
clrscr();
Flats of;
Offices oo;

of.getdat();
of.dispdat();
oo.getdata();
oo.dispdata();

getch();
}

33
Index^

OUTPUT

34
Index^

8. Show the use of virtual classes with the help of following


program-

Imagine a publishing company that markets both books and


audio-cassette of its works. Create a class publication that
stores the item no and price of a publication. From these class
derive two classes named book and tape. The class book adds
the pages and class tape adds paying time. Define another
class record that adds price. In each of these classes define
appropriate methods to read and display the information.

Solution:

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class publication
{ int item_no;
char title[20];

public:
void input()
{
cout<<"\nEnter item no: ";
cin>>item_no;
cout<<"\nEnter title: ";
cin>>title;
}

35
void print()
{
cout<<"\nItem No: "<<item_no;
cout<<"\nItem title: "<<title;
}

};

class book: public virtual publication


{
int pages;
public:

void getbook()
{
cout<<"Enter number of pages: ";
cin>>pages;
}

void showbook()
{
cout<<"\nPages: "<<pages;
}
};

class tape:virtual public publication


{
int ptime;

public:

36
void gettape()
{
cout<<"\nEnter playng time: ";
cin>>ptime;
}

void showtape()
{
cout<<"\nPlaying time: "<<ptime;

};

class record:public book, public tape


{
int price;

public:
void getdata()
{
cout<<"\nEnter price: ";
cin>>price;
}
void display()
{
cout<<"\nPrice: "<<price;
}
};

37
void main()
{
clrscr();

record rec;

cout<<"\nEnter book information: ";


rec.input();
rec.getbook();
rec.getdata();

cout<<"\nThe book information is: ";


rec.print();
rec.showbook();
rec.display();

cout<<"\nEnter tape information: ";


rec.input();
rec.gettape();
rec.getdata();

cout<<"\nThe tape reocrd is: ";


rec.print();
rec.showtape();
rec.display();

getch();
}

38
Index^

OUTPUT

39
Index^

9. Program to implement Bubble Sort technique to arrange the


elements in ascending order.

Solution:

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();

int a[30],size,i,j,temp;

cout<<"\nEnter the size of the array: ";


cin>>size;

cout<<"\nEnter elements in to the array: ";

for(i=0;i<size;i++)
cin>>a[i];

for(i=0;i<size-1;i++)
{
for(j=i+1;j<size;j++)
{

if(a[i]>a[j])
{

40
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

cout<<"\n The sorted array is: \n\n";

for(i=0;i<size;i++)
cout<<a[i]<<",\t";

getch();
}

41
Index^

OUTPUT

42
Index^

10. Program to implement Selection Sort technique.

Solution:

#include<iostream.h>
#include<conio.h>

//Selection Sort
void selsort (int ar[], int size)
{
int min,temp,loc;

for (int i=0; i<size-1; ++i)


{

loc = i;

for (int j=i+1; j<size; ++j)


{
if (ar[j] < ar[loc])
{
//Found new minimum position, if present
loc = j;
}
}

temp=ar[i];
ar[i]=ar[loc];
ar[loc]=temp;

43
}
}

void main ()
{
clrscr();

int n,i,min;
int ar[20];

cout << "\nEnter range: ";


cin>>n;

cout<<"\nEnter elements: ";


for(i=0;i<n;i++)
cin>>ar[i];

selsort(ar,n);

cout << "Array after selection sort : ";


for (i=0;i<n;++i)
{
cout<<ar[i] <<" ";
}
getch();
}

44
Index^

OUTPUT

45
Index^

11. Program to implement Insertion sort technique.

Solution:

#include<iostream.h>
#include<conio.h>

//Insertion Sort

void InsertionSort(int ar[],int n)


{
int temp,min;

for(int i=1;i<n;i++)
{
temp = ar[i];

for(int j=i;j>0 && ar[j-1]>temp;j--)


{
ar[j] = ar[j-1];
}
ar[j] = temp;
}
}

void main ()
{
clrscr();

46
int n,i,min;
int ar[20];

cout << "\nEnter range: ";


cin>>n;

cout<<"\nEnter elements: ";


for(i=0;i<n;i++)
cin>>ar[i];

InsertionSort(ar,n);

cout <<"\nArray after insertion sort : ";


for (i=0;i<n;++i)
{
cout<<ar[i] <<" ";
}
getch();
}

47
Index^

OUTPUT

48
Index^

12. Program to implement Merge sort technique.

Solution:

#include<iostream.h>
#include<conio.h>

int a[20];

void merge(int,int,int);

void merge_sort(int low,int high)


{

int mid;

if(low<high)
{

mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}

void merge(int low,int mid,int high)


{
int h,i,j,b[20],k;

49
h=low;
i=low;
j=mid+1;

while((h<=mid)&&(j<=high))
{

if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}

if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{

50
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}

for(k=low;k<=high;k++)
a[k]=b[k];
}

void main()
{
clrscr();
int num,i;

cout<<"\nEnter range: ";


cin>>num;

cout<<"\nEnter array elements: ";


for(i=1;i<=num;i++)
cin>>a[i] ;

merge_sort(1,num);

cout<<"\nSorted elements using merge sort--> "<<endl;


for(i=1;i<=num;i++)
cout<<a[i]<<" , ";

getch();
}

51
Index^

OUTPUT

52
Index^

13. Program to find the length of a string and print the reversed
string using pointer.

Solution:

#include<iostream.h>
#include<stdio.h>
#include<conio.h>

int string_length(char*);
void reverse(char*);

void main()
{
clrscr();
char string[100];

cout<<"\nEnter a string: ";


gets(string);

reverse(string);

cout<<"\nReverse of entered string is: "<<string;

getch();
}

void reverse(char *string)


{

53
int length, c;
char *begin, *end, temp;

length = string_length(string);

begin = string;
end = string;

for ( c = 0 ; c < ( length - 1 ) ; c++ )


end++;

for ( c = 0 ; c < length/2 ; c++ )


{
temp = *end;
*end = *begin;
*begin = temp;

begin++;
end--;
}
}

int string_length(char *pointer)


{
int c = 0;

while( *(pointer+c) != '\0' )


c++;

return c;
}

54
Index^

OUTPUT

55
Index^

14. Program to count the number of characters, lines, spaces and


digits present in a text file data.txt.

Solution:

#include<fstream.h>
#include<conio.h>

void main()
{
clrscr();
ifstream fin("sam.txt");

char ch;

int i,line=0,chars=0,space=0,nos=0;

while(fin)
{
fin.get(ch);

i=ch;

if(i>63&&i<91||i>96&&i<123)
chars++;

else if(i>47&&i<58)
nos++;

56
else if(ch==' ')
space++;

else if(ch=='\n')
line++;

else
cout<<"No data found";

}
cout<<"\nNumber of alphabates:"<<chars;
cout<<"\nNumber of digits:"<<nos;
cout<<"\nNumber of Spaces:"<<space;
cout<<"\nNumber of lines: "<<line;
getch();
}

57
Index^

OUTPUT

58
Index^

15. Program to create a binary file and write objects to it and


display them on screen after reading from the file. Consider
class Employee with data members such as empcode,
empname and depart. Define necessary functions to accept
and display data. Write a program to accept data for different
employees and write to the file whose name is provided by
the user.

Solution:

#include<fstream.h>

#include<conio.h>

class Employee

int empcode;

char empname[20];

char depart[20];

public:

void getdat()

cout<<"\nEmployee Code : ";

59
cin>>empcode;

char c=cin.get();

cout<<"\nEmployee Name : ";

cin.getline(empname,20);

cout<<"\nDepartment : ";

cin.getline(depart,20);

void dispdat()

cout<<"\nEmployee Code : "<<empcode;

cout<<"\nEmployee Name : "<<empname;

cout<<"\nDepartment : "<<depart;

};

void main()

clrscr();

Employee e;

60
int num=0;

char fname[13];

cout<<"Enter file name ";

cin>>fname;

ofstream ofl;

ofl.open(fname, ios::app|ios::binary);

if(!ofl)

cout<<"Cannot open file "<<fname;

return;

cout<<"How many employees? ";

cin>>num;

for(int i=1;i<=num;i++)

e.getdat();

61
ofl.write((char*)&e,sizeof(Employee));

ofl.close();

ifstream ifl;

ifl.open(fname, ios::app|ios::binary);

if(!ofl)

{ cout<<"Cannot open file "<<fname;

return;

else

{ cout<<"\nThe information stored in a file are: ";

while(ifl.read((char*)&e,sizeof(Employee)))

{ e.dispdat();

getch();

62
Index^

OUTPUT

63
Index^

16. Program to implement stack as an array.

Solution:

#include<iostream.h>

#include<conio.h>

#include<process.h>

const int SIZE=10;

static int top=-1;

class stack

private:

int ar[SIZE];

public:

void push(int item);

void pop();

64
void display();

};

void stack::push(int item)

if(top==SIZE-1)

cout<<"\nStack is Full!!";

else

ar[++top]=item;

cout<<"\nElement inserted.";

void stack::pop()

if(top==-1)

cout<<"\nStack Underflow!!";

65
else

cout<<"\nElement "<<ar[top]<<" sucessfully popped


from the Stack.";

top--;

void stack::display()

if(top==-1)

cout<<"\nStack is Empty...";

else

cout<<"\nThe stack is: ";

for(int i=top;i>=0;i--)

cout<<ar[i]<<" ";

66
void main()

clrscr();

char choice;

int ch,num;

stack ob;

do

cout<<"\n\n1.Push";

cout<<"\n2.Pop";

cout<<"\n3.Display";

cout<<"\n4.EXIT";

cout<<"\n\nEnter your choice:";

cin>>ch;

67
switch(ch)

case 1: cout<<"\nEnter element :";

cin>>num;

ob.push(num);

break;

case 2: ob.pop();

break;

case 3: ob.display();

break;

case 4: exit(0);

default: cout<<"\nInvalid choice!!";

cout<<"\nDo you want to continue(y/n):";

cin>>choice;

}while(choice=='y' || choice=='Y');

getch();

68
Index^

OUTPUT

69
Index^

17. Program to implement queue as an array.

Solution:

#include<iostream.h>

#include<conio.h>

#include<process.h>

const int SIZE=20;

class queue

int a[SIZE];

int front;

int rear;

public:

queue();

~queue();

void insert();

void remove();

70
void display();

};

queue::queue()

front=-1;

rear=-1;

queue::~queue()

delete []a;

void queue::insert()

int i;

if(rear==SIZE-1)

cout<<"Queue is FULL !!";

else

71
cout<<"\nEnter element: ";

cin>>i;

rear++;

a[rear] = i;

cout<<"\nElement "<<i<<" inserted.";

if(front==-1)

front++;

void queue::remove()

if(front==-1)

cout<<"Queue Empty!!";

else

{ cout<<"\nElement "<<a[front]<<" removed.";

front++;

72
if(front==rear+1)

front=rear=-1;

void queue::display()

if(front==-1)

cout<<"\nNo elements.";

else

cout<<"\nQueue is: ";

for(int i=front;i<=rear;i++)

cout<<a[i]<<" ,";

void main()

clrscr();

queue q;

73
char choice;

int ch;

do

cout<<"\n1.Insert";

cout<<"\n2.Remove";

cout<<"\n3.Display";

cout<<"\n4.Exit";

cout<<"\nEnter your choice: ";

cin>>ch;

switch(ch)

case 1: q.insert();

break;

case 2: q.remove();

break;

case 3: q.display();

break;

case 4: exit(0);

74
default:cout<<"\nInvalid choice.";

cout<<"\nDo you want to continue...y/n:";

cin>>choice;

}while(choice=='y' || choice=='Y');

getch();

75
Index^

OUTPUT

76
Index^

18. Program to implement dynamic stack/stack as a linked list.

Solution:

#include<iostream.h>

#include<conio.h>

class stack

struct node

{ int data;

node *link;

}*top;

public:

stack()

{ top=NULL; }

void push();

void pop();

void display();

};

77
void stack::push()

node *temp;

int ele;

temp=new node;

if(temp==NULL)

cout<<"\nStack is Full";

else

{ cout<<"\nEnter element into the stack:";

cin>>ele;

temp->data=ele;

temp->link=top;

top=temp;

void stack::pop()

int ele;

node *temp;

78
if(top==NULL)

cout<<"\nStack is Empty";

else

temp=top;

ele=temp->data;

temp=temp->link;

top=temp;

cout<<"\nThe element deleted is: "<<ele;

void stack::display()

node *temp;

if(top==NULL)

cout<<"\nStack is Empty";

else

{ temp=top;

cout<<"\nThe stack is: ";

79
while(temp!=NULL)

{ cout<<"\n"<<temp->data;

temp=temp->link;

void main()

int ch;

clrscr();

stack st;

st.push();

st.push();

st.push();

st.display();

st.pop();

st.display();

getch();

80
Index^

OUTPUT

81
Index^

19. Program to implement dynamic queue/queue as a linked list.

Solution:

#include<iostream.h>

#include<conio.h>

#include<process.h>

class LQueue

struct node

int data;

node *next;

}*front,*rear,*temp;

public:

LQueue()

82
front=NULL;

rear=NULL;

void add();

void del();

void display();

};

void LQueue::add()

temp=new node();

cout<<"\nEnter the data \t";

cin>>temp->data;

if(front==NULL)

front=temp;

83
rear=temp;

else

temp->next=NULL;

rear->next=temp;

rear=temp;

void LQueue::del()

temp=new node();

temp=front;

if(front==NULL)

cout<<"\nNo data found";

else

cout<<"\nElement "<<front->data<<" deleted successfully";

front=front->next;

84
delete temp;

void LQueue::display()

temp=new node();

temp=front;

cout<<"\nQueue is: \n";

while(temp!=NULL)

cout<<temp->data<<" , ";

temp=temp->next;

void main()

clrscr();

85
LQueue d;

int ch;

char choice;

do

cout<<"\nOperations on Queue-";

cout<<"\n1.Insert\n2.Delete\n3.Display\n4.Exit\t";

cout<<"\nEnter your choice: ";

cin>>ch;

switch(ch)

case 1:d.add();

break;

case 2:d.del();

break;

86
case 3:d.display();

break;

case 4: exit(0);

default: cout<<"Incorrect Input";

cout<<"\nDo you want to continue?(y/n): ";

cin>>choice;

}while((choice=='y')||(choice=='Y'));

getch();

87
Index^

OUTPUT

88
Index^

20. Program to implement linked list.

Solution:

#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

class list

struct node

int data;

node *link;

}*p;

public:

void inslast(int);

void insbeg(int);

void insnext(int,int);

89
void delelement(int);

void disp();

list(){p=NULL;}

~list();

};

void list::inslast(int x)

node *q,*t;

if(p==NULL)

p=new node;

p->data=x;

p->link=NULL;

else

q=p;

while(q->link!=NULL)

90
q=q->link;

t=new node;

t->data=x;

t->link=NULL;

q->link=t;

cout<<"Inserted successfully at the end..";

void list:: insbeg(int x)

node *q;

q=p;

p=new node;

p->data=x;

p->link=q;

cout<<" Inserted successfully at the begining..";

91
}

void list::delelement(int x)

node *q,*r;

if(p==NULL)

cout<<"\nEmpty list.";

else

q=p;

if(q->data==x)

p=q->link;

delete q;

cout<<"\nElement deleted...";

92
return;

r=q;

while(q!=NULL)

if(q->data==x)

r->link=q->link;

delete q;

cout<<"\nElement deleted...";

return;

r=q;

q=q->link;

cout<<"\nElement "<<x<<" not found..";

93
list::~list()

node *q;

if(p==NULL) return;

while(p!=NULL)

q=p->link;

delete p;

p=q;

void list::disp()

node *q;

q=p;

if(q==NULL)

94
cout<<" No data is in the list.. ";

return;

cout<<" The items present in the list are :";

while(q!=NULL)

cout<<" "<<q->data;

q=q->link;

void list :: insnext(int value,int position)

node *temp,*temp1;

temp=p;

for(int i=0;i<position;i++)

if((temp==NULL)&&(position>1))

95
{

cout<<"\nThere are less number of nodes


then the position.";

break;

else

if((temp==NULL)&&(position==1))

temp1= new node;

temp1->data=value;

temp1->link=NULL;

p=temp1;

cout<<"\nNode inserted.";

return;

else if(i==(position-1))

96
{

temp1= new node;

temp1->data= value;

temp1->link=temp->link;

temp->link=temp1;

cout<<"\nNode inserted.";

return;

temp=temp->link;

cout<<"\nElement inserted at position "<<position;

void main()

list l;

char choice;

int ch,v,p;

97
clrscr();

do

cout<<"\nOperations on List..";

cout<<"\n1.Insert node at begining\n2.Insert node at


end";

cout<<"\n3.Insert node after a position";

cout<<"\n4.Delete a node\n5.Display the list\n6.Exit";

cout<<"\nEnter your choice:";

cin>>ch;

switch(ch)

case 1: cout<<"Enter the value to insert:";

cin>>v;

l.insbeg(v);

break;

98
case 2: cout<<"\nEnter the value to insert:";

cin>>v;

l.inslast(v);

break;

case 3: cout<<"\nEnter the value to insert:";

cin>>v;

cout<<"\nEnter the position to insert the value:";

cin>>p;

l.insnext(v,p);

break;

case 4: cout<<"\nEnter the element to delete : ";

cin>>v;

l.delelement(v);

break;

99
case 5: l.disp();

break;

case 6: exit(1);

default: cout<<"\nThe option is invalid...";

cout<<"\nDo you want to continue...";

cin>>choice;

}while(choice=='Y'||choice=='y');

getch();

100
Index^

OUTPUT

101
Index^

21. Program to implement circular queue.

Solution:

#include<iostream.h>

#include<conio.h>

#include<process.h>

const int MAX = 3;

class cqueue

int a[MAX],front,rear;

public :

cqueue()

front=rear=-1;

void insert(int);

void deletion();

102
void display();

};

void cqueue :: insert(int val)

if((front==0 && rear==MAX-1) || (rear+1==front))

cout<<"\nCircular queue is full ";

else

if(rear==MAX-1)

rear=0;

else

rear++;

a[rear]=val;

if(front==-1)

front=0;

void cqueue :: deletion()

103
{

if(front==-1)

cout<<"\nCircular queue is empty";

else

{ cout<<"\nElement "<<a[front]<<" deleted.";

if(front==rear)

front=rear=-1;

else

if(front==MAX-1)

front=0;

else

front++;

void cqueue :: display()

104
int i;

if(front==-1)

cout<<"\nCircular queue is empty";

else

if(rear < front)

for(i=front;i<=MAX-1;i++)

cout<<a[i]<<" ";

for(i=0;i<=rear;i++)

cout<<a[i]<<" ";

else

for(i=front;i<=rear;i++)

cout<<a[i]<<" ";

cout<<endl;

105
}

void main()

{ cqueue c1;

int ch,val;

char op;

clrscr();

do

cout<<"\n1.Insertion \n2.Deletion \n3.Display


\n4.Exit";

cout<<"\nEnter your choice: ";

cin>>ch;

switch(ch)

{ case 1 : cout<<"\nEnter element: ";

cin>>val;

c1.insert(val);

break;

106
case 2 : c1.deletion();

break;

case 3 : c1.display();

break;

case 4: exit(0);

default: cout<<"\nInvalid input.";

cout<<"\nDo you want to continue(y/n)?: ";

cin>>op;

}while(op=='Y' || op=='y');

getch();

107
Index^

OUTPUT

108
109
Index^

1. Consider the following tables CARDEN and CUSTOMER and


answer (a) and (b) parts of this question:

Table: CARDEN

Ccode CarName Make Color Capacity Charges

501 A-star Suzuki RED 3 14

503 Indigo Tata SILVER 3 12

502 Innova Toyota WHITE 7 15

509 SX4 Suzuki SILVER 4 14

510 C Class Mercedes RED 4 14

Table: CUSTOMER

CCode Cname Ccode


1001 Hemant Sahu 501

1002 Raj Lal 509

1003 Feroza Shah 503

1004 Ketan Dhal 502

110
(a) Write SQL commands for the following:

i. To display the names of all the silver colored Cars.


ii. To display the name of the car, make and capacity of cars in
descending order of their sitting capacity.
iii. To display the highest charges at which vehicle can be hired
from CARDEN.
iv. To display the customer name and the corresponding name
of the cars hired by them.

(b) Give the output of the following SQL queries:

i. SELECT COUNT(DISTINCT Make) FROM CARDEN;


ii. SELECT MAX(Charges),MIN(Charges) FROM CARDEN;
iii. SELECT COUNT(*), Make FROM CARDEN;
iv. SELECT CarName FROM CARDEN WHERE Capacity =4;

Ans (a)

i. SELECT CarName FROM CARDEN WHERE Color = SILVER;

111
ii. SELECT CarName, Make, Capacity FROM CARDEN ORDER BY
Capacity desc;
iii. SELECT MAX(Charges) AS Highest Charges FROM CARDEN
iv. SELECT CName, CarName FROM CUSTOMER, CARDEN
WHERE CUSTOMER.CCode = CARDEN.Ccode

(b)

112
113
Index^

2. Consider the following tables ITEMS and TRADERS and


answer (a) and (b) parts of this question:

Table: ITEMS

CODE INAME QTY PRICE COMPANY TCODE


COMPANY

1001 DIGITAL 120 11000 XENITA T01


PAD 12i

1006 LED 70 38000 SANTORA T02


SCREEN 40

1004 CAR GPS 50 21500 GEOKBOW T01


SYSTEM

1003 DIGITAL 160 8000 DIGICLICK T02


CAMERA
12X

1005 PEN DRIVE 600 1200 STOREHOME T03


32 GB

114
Table: TRADERS

TCODE TNAME CITY

T01 ELECTRONIC SALES MUMBAI

T03 BUSY STORE CORP DELHI

T02 DISP HOUSE INC CHENNAI

(a) Write SQL commands for the following:

i. To display the details of all the items in the ascending order


of the item names (i.e. INAME).
ii. To display the item name and price of all those items,
whose price is in the range of 10000 and 22000 (both
values inclusive).
iii. To display the number of items those are traded by each
trader. The expected output of this query should be:

T01 2

T02 2

115
T01 1

iv. To display the price, item name and quantity (i.e., qty) of
those items that have quantity more than 150.
v. To display the names of those traders, who are either from
DELHI or MUMBAI.
vi. To display the names of the companies and the names of
the items in the descending order of the company names.

(b) Obtain the outputs of the following SQL queries based


on the data given in the tables ITEMS and TRADERS
above.

i. SELECT MAX(PRICE), MIN(PRICE) FROM ITEMS;


ii. SELECT PRICE*QTY AMOUNT FROM ITEMS WHERE CODE-
1004;
iii. SELECT DISTINCT TCODE FROM ITEMS;
iv. SELECT INAME, TNAME FROM ITEMS I, TRADERS T
WHERE I.TCODE = T.TCODE AND QTY<100;

Ans 2. (a)

116
i. SELECT * FROM ITEMS ORDER BY INAME ASC;
ii. SELECT INAME, PRICE FROM ITEMS WHERE PRICE
BETWEEN 10000 AND 22000;
iii. SELECT ITEMS.TCODE, COUNT (TCODE) FROM ITEMS,
TRADERS GROUP BY ITEMS.TCODE HAVING
TEMS.TCODE=TRADER.TCODE;
iv. SELECT PRICE, INAME, QTY FROM ITEMS WHERE QTY>150;
v. SELECT INAME FROM ITEMS I, TRADERS T WHERE
I.TCODE=T.TCODE AND CITY IN (DELHI, MUMBAI);
vi. SELECT COMPANY, INAME FROM ITEMS ORDER BY
COMPANY DESC;

(b)

i.

MAX MIN(PRICE)
(PRICE)

38000 1200

ii.

AMOUNT

1075000

117
iii.

TCODE

T01

T02

T03

iv.

INAME TNAME

LED SCREEN 40 DISP HOUSE INC

CAR GPS SYSTEM ELECTRONICS


SALES

118
Index^

3. Answer the questions (a) and (b) on the basis of the


following tables STORE and ITEM:

Table: STORE

SNo SName Area

ABC GK II
S01 Computronics
ALL Infotech CP
S01 Media
Tech Shoppe Nehru Place
S02
Geeks Tecno Nehru Place
S04 Soft
Hitech Tech CP
S05 Store

Table: ITEM

INo IName Price SNo

Mother Board 12000 S01


T01
Hard Disk 5000 S01
T02
Keyboard 500 S02
T03
Mouse 300 S01
T04

119
Mother Board 400 S03
T05
Key Board 400 S03
T06
LCD 6000 S04
T07
LCD 5500 S05
T08
Mouse 350 S05
T09
Hard Disk 4500 S03
T10

a) Write the SQL queries(i to iv):


i. To display IName and Price of all the Items in ascending
order of their price.
ii. To display SNo and SName of all Stores located in CP.
iii. To display Minimum and Maximum Price of each IName
from the table Item.
iv. To display IName, Price of all items and their respective
SName where they are available.

b) Write the output of the following SQL commands:


i. SELECT DISTINCT INAME FROM ITEM WHERE
PRICE>=5000;
ii. SELECT AREA, COUNT(*) FROM STORE GROUP BY AREA;

120
iii. SELECT COUNT(DISTINCT AREA) FROM STORE;
iv. SELECT INAME, PRICE*0.05 DISCOUNT FROM ITEM WHERE
SNO IN (S02,S03);

Ans.(a)
i. Select IName, Price From Item Order By Price Asc;
ii. Select SNo, SName From Store Where Area=CP;
iii. Select IName, Max(Price), Min(Price) From Item;
iv. Select IName, Price From Store, Item Where
Store.SNo=Item.INo;

(b)
i.

IName

Hard Disk

LCD

Mother Board

121
ii.

Area Count
2
CP
1
GK II
2
Nehru Place

iii.
Count

iv.

IName Price

25
Keyboard
650
Motherbaord
20
Key Board
225
Hard Disk

122
Index^

4. Write SQL queries for (a) and write the outputs for the SQL
queries mentioned shown in (b) part on the basis of tables
PRODUCTS and SUPPLIERS.

Table: PRODUCTS

PID PNAME QTY PRICE COMPANY SUPCODE

DIGITAL
CAMERA 120 12000 RENIX S01
101
14X

DIGITAL S02
102 100 2200 DIGI POP
PAD 11i

PEN DRIVE S01


104 500 1100 STOREKING
16 GB

LED S02
106 70 28000 DISPEXPERTS
SCREEN 32

CAR GPS S03


105 60 12000 MOVEON
SYSTEM

123
Table: SUPPLIERS

SNAME CITY
SUPCODE
GET ALL INC KOLKATA
S01
EASY MARKET DELHI
S03 CORP
DIGI BUSY CHENNAI
S02 GROUP

i. To display the details of all the products in ascending order


of product names ( i.e. PNAME).
ii. To display product name and price of all those products,
whose price is in the range of 10000 and 15000 (both
values inclusive).
iii. To display the number of products, which are supplied by
each supplier i.e., the expected output should be:
S01 2
S02 2
S03 1

124
iv. To display the price, product name and quantity (i.e., qty)
of those products which have quantity more than 100.
v. To display the names of those suppliers, who are either
from DELHI or from CHENNAI.
vi. To display the names of the companies and the names of
the products in descending order of company names.

b) Obtain the outputs of the following SQL queries based


on the data given in tables PRODUCTS and SUPPLIERS
above.
i. SELECT DISTINCT SUPCODE FROM PRODUCTS;
ii. SELECT MAX(PRICE), MIN(PRICE) FROM PRODUCTS;
iii. SELECT PRICE*QTY AMOUNT FROM PRODUCTS WHERE
PID=104;
iv. SELECT PNAME, SNAME FROM PRODUCTS P, SUPPLIERS S
WHERE P.SUPCODE=S.SUPCODE AND QTY>100;

Ans (a).
i. SELECT * FROM PRODUCTS ORDER BY PNAME ASC;

125
ii. SELECT PNAME, PRICE FROM PRODUCTS WHERE PRICE
BETWEEN 10000 AND 15000;
iii. SELECT PRODUCTS.SUPCODE, COUNT (SUPCODE) FROM
PRODUCTS, SUPPLIERS GROUP BY PRODUCT.SUPCODE;
HAVING PRODUCTS.SUPCODE=SUPPLIERS.SUPCODE;
iv. SELECT PRICE, PNAME, QTY FROM PRODUCTS WHERE
QTY>100;
v. SELECT PNAMES FROM PRODUCTS P, SUPPLIERS S WHERE
P.SUPCODE=S.SUPCODE AND CITY IN (DELHI, CHENNAI);
vi. SELECT COMPANY, PNAME FROM PRODUCTS ORDER BY
COMPANY DESC;

(b)
i.

SUPCODE

S01

S02

126
S03

ii.

MAX(PRICE) MIN(PRICE)

28000 1100

iii.

AMOUNT

550000

iv.

PNAME SNAME

GET ALL INC


DIGITAL CAMERA
14X
GET ALL INC
PEN DRIVE 18 GB

127
Index^

5. Consider the following tables PRODUCT and CLIENT. Write


SQL commands for the (a) part of the questions and give
outputs for (b) part of SQL queries.

Table: PRODUCT

P_ID Product Name Manufacturer Price

LAK 40
TP01 TalcomPowder
ABC 45
FW05 Face Wash

ABC 55
BS01 Bath Soap

XYZ 120
SH06 Shampoo

XYZ 95
FW12 Face Wash

Table: CLIENT

C_ID Client Name City P_ID


Delhi FW05
01 TalcomPowder

128
Mumbai BS01
06 Face Wash
Delhi SH06
12 Bath Soap

Delhi FW12
15 Shampoo
Banglore TP01
16 Face Wash

(a) Write the SQL queries(i to iv):


i. To display the details of those Clients whose city is Delhi.
ii. To display the details of Products whose Price is in the range
of 50 to 100(Both values included).
iii. To display the ClientName, City from table Client, and
ProductName and Price from table Product, with their
corresponding matching P_ID.
iv. To increase the Price of all Products by 10.

(b) Write the output of the following SQL commands:


i. SELECT DISTINCT Address FROM Client;
ii. SELECT Manufacturer, MAX(Price), Min(Price), Count(*)
FROM Product GROUP BY Manufacturer;

129
iii. SELECT ClientName, ManufacturerName FROM Product,
Client WHERE Client.Prod_Id=Product.P_Id;
iv. SELECT ProductName, Price * 4 FROM Product;

Ans. (a)
i. Select all from Client where City=Delhi
ii. Select all from product where Price between 50 and 100
iii. Select ClientName,City,ProductName, Price from
Product,Client where Product.P_ID=Client.P_ID
iv. Update Product Set Price=Price +10

(b)

i.

City

Delhi

Mumbai

Bangalore

130
ii.

Manufacturer Max(Price) Min(Price) Count(*)


LAK 40 40 1

ABC 55 45 2
XYZ 120 95 2

iii.

ClientName ManufacturerName

Cosmetic Shop ABC

Total Health ABC


Live Life XYZ

Pretty Woman XYZ

Dreams LAK

131
iv.

ProductName Price*4
Talcom Poweder 160

Face ash 180

Bath Soap 220

Shampoo 480

Face Wash 380

132
Index^

VIVA VOCE

Q1. What are static data members?

Ans1: Static data members are class variables. Only one copy
of the static data member is maintained and this is shared by all
the objects. They are visible only within the class but their
lifetime is the entire program. They can be used in all member
function.

Q2. What are static member functions?

Ans2: A static member function is a member function that can


access only static data members. It is called using the class
name and not with the object as is the case with other member
functions.

Q3. How is struct different from class in C++?

133
Ans3: Members of a class are private by default while
members of a structure are public by default.

Q4. What are objects?

Ans4: An object is an instance of a class. For a class that has


been defined, objects can be created as variables of that class.
Each object will have a set of data members defined in the class.

Q5. What is the difference between private and protected


members of a class?

Ans5: The only difference is that private members cannot be


inherited while protected members can be.

Q6. What is nesting of member functions?

Ans6: When a member function of a class calls another member


function, it is known as nesting of member functions.

134
Q7. How are public members different from private
members of a class?

Ans7: Public members can be called in outside functions, using


the object. Private members can be called or used only by other
members of the class. Also, public members can be inherited
while private members cannot be.

Q8. What is inheritance?

Ans8: Inheritance is an important concept of Object Oriented


Programming. It is the capability of one class to inherit
properties from another class.

Q9. What is the advantage of inheritance?

Ans9: One of the main advantages is code reusability. Once a


class has been satisfactorily defined, it can be used in other
classes without making changes. It represents real world

135
entities very effectively Person can be inherited by Employee
as well as Student.

Q10. Name the different forms of Inheritance.

Ans10: The different forms of inheritance are Single, Multiple,


Hierarchical, Multilevel and Hybrid.

Q11. What do you understand by base class and derived


class?

Ans11: An existing class can be used to derive a new class.


The existing class, whose properties are inherited is the base
class and the class that inherits features is the derived class.

Q12. What do you understand by visibility modes?

Ans12: Visibility modes are used to specify how the features of


the base class are inherited into the derived class. The three
visibility modes are public, private and protected. The
inheritable base class members are placed under the access

136
specifiers in the derived class depending on the visibility mode
and its own access specifier.

Q13. A class inherits a function that has the same name


and arguments as one of its own member functions. The
object calls the function and there is no scope resolution
operator given. Which of these two functions will be
called?

Ans13: The member function of its own class will be called.

Q14. Can private members be inherited? If yes, how. If


no, how can they be accessed in the derived class?

Ans14: Private members cannot be inherited. However,


other member functions that access the private members can be
inherited. Thus, private members can be indirectly accessed
through inherited functions.

137
Q15. How are text files different from binary files?

Ans15: Text files are also called ASCII files. They stores
information in the form of ASCII characters. There are 128
different ASCII codes. Also, text files contain lines of text and
each of these has an end-of-line (EOL) marker automatically
appended whenever you indicate that you have reached the end
of a line. When a file is opened in text mode, various character
translations take place. In case of binary files, information is
stored in the same format in which it is stored in the memory.
No character translation takes place when a binary file is
opened, because of which binary files can be read and written
faster by the computer.

Q16. What is meant by stream?

Ans16: A stream is a sequence of bytes, or, flow of data. It


acts as an interface between the file and program.

Q17. Describe the streams used for input and output with
a file.

138
Ans17: There are 3 kinds of streams input, output and
input-output.

If we want to use the file for input i.e. reading, we must create
an input stream, using class ifstream. For example, ifstream ifl;

If we want to use the file for output i.e. writing, we must create
an output stream, using class ofstream. For example, ofstream
ofl; If we want to use the file for input as well as output, we
must create a stream performing both input and output, using
class fstream. For example, fstream iofl;

Q18. How is get() different from getline()?

Ans18: Both get() and getline() can read characters from the
input stream into an array till the specified number of characters
are entered or till the delimiting character is encountered( \n by
default). The difference is that, in case of getline() this
character is removed from the input stream but get() leaves it in
the input stream.

139
Q19. How is the file mode ios::ate different from ios::app?

Ans19: When a file is opened in the mode ios::ate or ios::app


, the file pointer is positioned at the end of the file. With
ios::app we can add data only at the end of the file, but with
ios::ate, we can write anywhere in the file.

Q20. When should the file mode ios::nocreate be used?

Ans20: Normally, in a program, when we give a file name to


be opened, it is available. If it is not there and the program is
going to output data to the file, it gets created by the given
name. At times, if the file is not there, we dont want it created
in situations like this we use ios :: nocreate.

Q21. Which classes are used for file input and output
operations?

Ans21: The classes used are ifstream, ofstream and fstream.

140
Q22. Name any two functions used in file input-output
error handling.

Ans22: int bad() and int fail() are used for error handling.

Q23. What are the two ways of opening a file?

Ans23: A file can be opened in two ways:

a) Using the constructor of the stream class this method is


useful when only one file is used in the stream.
Constructors of the stream classes ifstream, ofstream and
fstream are used to initialize the file stream object with the
file name.

For example, to open a file Names.Dat for reading i.e. input,


we create a stream object of class ifstream and pass on the
filename to it, as

ifstream read_file(Names.Dat);

141
b) Using the function open() - this method is useful when
we want to use different files in the stream. If two or more
files are to be processed simultaneously, separate streams
must be declared for each.

Q24. What kind of data structures are used to create


linked lists?

Ans24: Self-referential structures are used to create linked lists.


This type of structure has a member that refers to the structure
itself.

Example -

struct Emp{
int code;
char name[20];
Emp *next; // pointer to type Emp
};

142
Here, structure Emp is a self-referential structure. It has a
member, next, which stores the address of Emp type.

Q25. What is a linked list?

Ans25: A linked list is a series of nodes. Each node has two


parts one containing data and the other containing a pointer
that contains the address of the next node. Linked lists are used
when the number of elements to be stored is not known.
Memory is allocated at run time as the need arises.

Q26. What is an array?

Ans26: An array is a collection of elements of the same data


type - fundamental or user-defined. When an array is declared
we have to specify the size of the array and accordingly space is
allocated in memory. Subsequently, array elements are
accessed using the index number.

143
Q27. How a Singly linked list is different from a doubly
linked list?

Ans27: In a singly linked list, each node has one pointer


pointing to the next node while in a doubly linked list, each node
has two pointers, one pointing to the next and the other to the
previous node.

Q28. What is meant by Overflow and Underflow?

Ans28: Overflow is a situation that occurs when we try to put


in a value when there is no space. This situation is faced when
arrays are used as stacks or queues. Once the array is full, any
attempt to push or insert will give an Overflow Error.

Underflow occurs when we try to extract a value when there are


none. Underflow can occur in arrays if there is no data in it or in
linked lists if the first node has not been created yet. Any
attempt to extract from an empty list gives an Underflow Error.

Q29. What is a stack? What are the operations performed


on a stack?

144
Ans29: Stack is a LIFO (Last In First Out) structure. This
means that the element that comes in last is the first to go out.
It can be visualized as a stack of trays where a fresh tray is put
on top of the existing stack and the one picked up is the tray on
top. Thus, insert and delete are from the same side. This is
called the top of the stack. Inserting into a stack is called
push and deleting from a stack is called pop. A stack can be
implemented using an array or a linked list.

Q30. What is a queue? What are the operations


performed on a queue?

Ans30: Queue is a FIFO (First In First Out) structure. This


means that elements that enter the queue first, leave it first. All
insertions are at the rear and deletions are at the front end. The
value of front and rear are maintained to keep track of these
operations. A queue can be visualized as a queue of people
waiting to buy a ticket. New people coming stand at the end of
the queue and the people in front buy tickets and leave. A
queue can be implemented as an array or a linked list.

145
Q31. What is the difference between an array and a stack
implemented as an array?

Ans31: Elements of an array can be accessed and processed in


any order. In a stack, data can be inserted (push) and deleted
(pop) at one end, called the top. These are the only operations
possible on a stack. Stack is a LIFO structure meaning that the
element that has come in last must be sent out first.

Q32: Describe deque, mentioning its variations.

Ans32: Deque or double-ended queue, is a special kind of


queue in which elements can be inserted and deleted from either
end, but not in the middle. The deque can be of two types
input restricted deque and output restricted deque.

In the input restricted deque, insertions are allowed at one end


but deletions can be from both the ends.

146
In the output restricted deque, deletions are allowed at only one
end but insertions can be done from both the ends.

Q33. What is a constructor?

Ans33: A constructor is a member function of a class that is


invoked automatically when an object of that class is created. It
has the same name as the class and initializes the object with
legal initial values.

Q34. What purpose does a constructor serve?

Ans34: The constructor provides some valid initial values to


the object created.

Q35. What is a default constructor?

Ans35: A constructor that does not accept any argument is a


default constructor. Example: for a class called STUDENT, the
following is the default constructor-

STUDENT( )

147
{

rno=0;

Q36.How a constructor with default values works like the


default constructor.

Ans36: The default constructor takes no arguments. However,


the class can have a constructor with default arguments too. In
case values are not provided while creating the object, the
constructor with default values can provide values.

In the example below, we see how the constructor with default


arguments can work just like the default constructor-

class ABC

{ // constructor with default arguments.

ABC(int x=55, int y=88)

{ a=x; b=y; }

};

148
Q37. State the important characteristics of constructors?

Ans37: Constructors are special member functions. Their


characteristics are

They have the same name as the class.


They are invoked automatically when objects are created.
No return type is specified for constructors.
Constructors obey the access rules. Only functions that
have access to the constructor can create objects of that
class. So, if the constructor is private or protected, it is
available only to members or friends. If it is public, it can
be used in outside functions.
They cannot be static.
They cannot be inherited but the derived class can call the
base class constructor.
They can have default arguments.
It is not possible to take the address of a constructor.
An object cannot be member of a union if the class has a
constructor.
Member functions can be called from inside the constructor.

149
The compiler creates default constructor and copy
constructor wherever needed.
If the class has a constructor, the objects are initialized
before use.
Normally the constructor is called implicitly but it can be
called explicitly too.

Q38. Explain constructor overloading with the help of


examples.

Ans38: Overloaded function refer to the same function


performing different activities depending on the values passed to
it. Constructor too is a function, and it can be overloaded.
Multiple constructors can be defined and different number and
types of values can be sent for initialization.

Example:

class A{
:
A ( ) {a=0; b=0;} //default constructor

150
A( int x, int y){a=x;b=y;} //constructor with 2
arguments
A(int x){a=x; b=2*x;} //constructor with 1
arguments
};

Q39. What is a temporary instance?

Ans39: A temporary instance of a class is an unnamed object


which is short lived. It remains in memory as long as the
statement defining it is executed and then automatically
destroyed.

Q40. What is meant by the term copy initialization?

Ans40: Initializing objects through the copy constructor is


called copy initialization.

In the example, for a class ABC, the statement below creates


object ob2 initialized with the object ob.

ABC ob2(ob); // copy constructor called

151
Q41. What is meant by dynamic initialization of objects?

Ans41: Dynamic initialization means that initial values for the


object may be provided at runtime. In the example, values to
be passed as arguments are received at run time.

class ABC { int a;


int b;
public:
ABC( int x, int y) { a=x; b=y; }
..
};
void main( ){
int x, y;
cout<<Enter integer values for x and y ;
cin>>x>>y;
ABC ob ( x, y);

}

152
Q42. What are destructors?

Ans42: Destructors are special member functions that are


invoked automatically when an object is to be destroyed. The
name of the destructor is the same as the class, preceded by a
tilled (~) character.

Q43. Why are destructors needed?

Ans43: An object created in a program must be destroyed


when it is no more needed. This task is carried out by the
destructor. It deinitializes the object and deallocates all
allocated resources.

Q44. What are the main characteristics of destructors?

Ans44: Destructors too are special member functions. Their


characteristics are

153
They have the same name as the class, preceded by the ~
character (tilde).
They are invoked automatically when objects are
destroyed.
No return type is specified for destructors.
Destructors obey the access rules.
They cannot be static.
They cannot be inherited.
Arguments cannot be passed to a destructor.
It is not possible to take the address of a destructor.
An object cannot be member of a union if the class has a
destructor.
Member functions can be called from inside the destructor.
The compiler creates default destructors wherever needed.
If the class has a destructor, the objects are de-initialized
before they go out of scope.

Q45. Give two advantages and two disadvantages of


wireless communication.

154
Ans45: Wireless communication does not use a medium, like
cables, for transmission. There are advantages and
disadvantages of this mode.

Advantages

Wireless communication can be used where cable or wires


cannot be laid over mountains, sea etc.
It allows mobility, communication can generally be from
anywhere, anytime.

Disadvantages

Wireless communication is not secure as anyone with the


right receiver can catch the signals.
It is sensitive to atmospheric conditions, like rain, storm
etc.

Q46. What is Cybercrime?

Ans46: Cybercrime is criminal activity done using computers


and the Internet. This includes anything from illegally
downloading music files to stealing sensitive data.

155
Q47. What is Cyberlaw?

Ans47: Cyber law (or Cyberlaw) describes the legal issues


related to use of information technology. Some topics it covers
include intellectual property, privacy, freedom of expression, and
jurisdiction.

Q48. What is the difference between a web page and a


web site?

Ans48: Web pages are generally created using html. and a


collection of Web pages will form a website.

A website is a destination whereas a web portal acts as an entry


point to various services or resources. The portal will usually
including a search facility, directory of other sites, news, e-mail
etc. for example, Yahoo.

Q49. Explain use of a web portal.

Ans49: Generally, there is no need to login into a website, it


provides general information for any user who might visit. The

156
portal will have a login facility and will provide information based
on who you are.

Q50. Explain URL its purpose and components.

Ans50: URL, or Uniform Resource Locator, is the location of a


file on the Web. When we type the address of a Web page in the
browser, we give the URL.

The most common format of a URL is -


http://www.mytown.com/shopping/aasd1.html.

The URL has two parts the first part, http:// gives the protocol
used to locate the file on the Web.

Http represents the Hyper Text Transfer Protocol, which is used


to transfer Web pages across the Internet to Web browsers such
as Netscape Navigator, Internet Explorer, or Lynx. The protocol
is followed by a colon and two slashes (://).

157

You might also like