You are on page 1of 29

1 Program to implement the Constructor and Destructor in C++

#include <iostream.h>
class Rectangle
{
public:
float length, breadth;
public:
Rectangle() {
cout << "\n\n****** Inside the Constructor ******* \n\n";
length = 8;
breadth = 6;
}

public:
~Rectangle()
{
cout << "\n\n****** Inside the Destructor ******* \n\n";
}
};

main()
{
cout << " Program to demonstrate the concept of Constructor and Destructor in CPP \n\n";
cout << "\nCalling the default Constructor of the Rectangle class to initialize the object.\n\n";
Rectangle rect;
cout << "\nThe Length of the Rectangle set by the Constructor is = " << rect.length << "\n\n";
cout << "\nThe Breadth of the Rectangle set by the Constructor is = " << rect.breadth << "\n\n";
}

Output

Program to demonstrate the concept of Constructor and Destructor in CPP


Calling the default Constructor of the Rectangle class to initialize the object.

****** Inside the Constructor *******

The Length of the Rectangle set by the Constructor is = 8

The Breadth of the Rectangle set by the Constructor is = 6

****** Inside the Destructor *******


2 Program to implement the Copy Constructor in C++

#include<iostream.h>
class SCC
{
private:
int x, y;

public:
SCC(int x1, int y1)
{
x = x1;
y = y1;
}

/* Copy constructor */
SCC (const SCC &sam)
{
x = sam.x;
y = sam.y;
}

void display()
{
cout<<x<<" "<<y<<endl;
}
};

main()
{
SCC obj1(100, 50); // Normal constructor
SCC obj2 = obj1; // Copy constructor
cout<<"Normal constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
}

Output
Normal constructor : 100 50
Copy constructor : 100 50
3 Program to implement the Friend Class and Friend Function in C++

#include <iostream.h>

class ClassB;
class ClassA
{
public:
// constructor to initialize numA to 120
ClassA() : numA(120) {}
private:
int numA;
// friend function declaration
friend int add(ClassA, ClassB);
};

class ClassB
{
public:
// constructor to initialize numB to 10
ClassB() : numB(10) {}
private:
int numB;
// friend function declaration
friend int add(ClassA, ClassB);
};

// access members of both classes


int add(ClassA objectA, ClassB objectB)
{
return (objectA.numA + objectB.numB);
}

main()
{
ClassA objectA;
ClassB objectB;
cout << "Sum: " << add(objectA, objectB);
}
Output

Sum: 130
4 Program to implement the Multilevel Inheritance in C++

#include <iostream.h>
class base //single base class
{ public:
int x;
void getdata()
{
cout << "Enter value of x= "; cin >> x;
}
};
class derive1 : public base // derived class from base class
{ public:
int y;
void readdata()
{ cout << "\nEnter value of y= "; cin >> y;
}
};
class derive2 : public derive1 // derived from class derive1
{ private:
int z;
public:
void indata()
{ cout << "\nEnter value of z= "; cin >> z;
}
void product()
{ cout << "\nProduct= " << x * y * z;
}
};
main()
{
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
a.product();
}

Output

Enter value of x= 5
Enter value of y= 6
Enter value of z= 3
Product= 90
5 Program to implement the Multiple Inheritance in C++

#include<iostream.h>
class A
{
public:
int x;
void getx()
{
cout << "Enter value of x: "; cin >> x;
}
};
class B
{
public:
int y;
void gety()
{
cout << "Enter value of y: "; cin >> y;
}
};
class C : public A, public B //C is derived from class A and class B
{
public:
void sum()
{
cout << "Sum = " << x + y;
}
};

main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
}

Output

Enter value of x: 10
Enter value of y: 20
Sum = 30
6 Program to implement the Function Overloading in C++

#include <iostream.h>

// Function with 2 int parameters


int sum(int num1, int num2)
{
return num1 + num2;
}

// Function with 2 double parameters


double sum(double num1, double num2)
{
return num1 + num2;
}

// Function with 3 int parameters


int sum(int num1, int num2, int num3)
{
return num1 + num2 + num3;
}

main()
{
// Call function with 2 int parameters
cout << "Sum 1 = " << sum(15, 12) << endl;

// Call function with 2 double parameters


cout << "Sum 2 = " << sum(15.5, 12.6) << endl;

// Call function with 3 int parameters


cout << "Sum 3 = " << sum(15, 16, 17) << endl;
}

Output

Sum 1 = 27
Sum 2 = 28.1
Sum 3 = 48
7 Program to implement the Function Overriding in C++

#include <iostream.h>

class Base
{
public:
void print()
{
cout << "Base Function" << endl;
}
};

class Derived : public Base


{
public:
void print()
{
cout << "Derived Function" << endl;
}
};

main()
{
Base base1;
base1.print();

// Call print() function of Derived class


Derived derived1;
derived1.print();
}

Output

Base Function
Derived Function
8 Program to implement the Virtual Function in C++

#include<iostream.h>
class base
{
public:
virtual void print()
{
cout << "print base class\n";
}
void show()
{
cout << "show base class\n";
}
};

class derived : public base


{
public:
void print()
{
cout << "print derived class\n";
}

void show()
{
cout << "show derived class\n";
}
};

main()
{
base *bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();
}

Output
print derived class
show base class
9 Program to implement the Function Overloading in C++

#include <iostream.h>

class Count
{
private:
int value;
public:
// Constructor to initialize count to 5
Count() : value(5) {}

// Overload ++ when used as prefix


void operator ++()
{
value = value - 1;
}

void display()
{
cout << "Count: " << value << endl;
}
};

main()
{
Count count1;

// Call the "void operator ++()" function


++count1;

count1.display();
}

Output

Count: 4
10 Program to handle the Exception in C++

#include <iostream.h>
double div(int x, int y)
{
if (y == 0)
{
throw "Division by Zero!";
}
return (x / y);
}

main()
{
int a = 11;
int b = 0;
double c = 0;

try
{
c = div(a, b);
cout << c << endl;
}
catch (const char* message)
{
cerr << message << endl;
}
}

Output

Division by Zero!
11. Program to implement Stack operations using Array

#include <iostream.h>

int stack[100], n=100, top=-1;


void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}

void pop()
{
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else
{
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}

void display()
{
if(top>=0)
{
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}

main()
{
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do
{
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch)
{
case 1:
{
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
cout<<"Exit"<<endl;
break;
}
default:
{
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
}

1) Push in stack
2) Pop from stack
3) Display stack
4) Exit
Enter choice:
1
Enter value to be pushed:
10
Enter choice:
1
Enter value to be pushed:
20
Enter choice:
1
Enter value to be pushed:
30
Enter choice:
1
Enter value to be pushed:
40
Enter choice:
3
Stack elements are:40 30 20 10
Enter choice:
2
The popped element is 40
Enter choice:
3
Stack elements are:30 20 10
Enter choice:
2
The popped element is 30
Enter choice:
3
Stack elements are:20 10
Enter choice:
4
Exit
12. Program to implement Queue operations using Array

#include <iostream.h>
int queue[100], n = 100, front = - 1, rear = - 1;
void Insert()
{
int val;
if (rear == n - 1)
cout<<"Queue Overflow"<<endl;
else
{
if (front == - 1)
front = 0;
cout<<"Insert the element in queue : "<<endl;
cin>>val;
rear++;
queue[rear] = val;
}
}

void Delete()
{
if (front == - 1 || front > rear)
{
cout<<"Queue Underflow ";
return ;
}
else
{
cout<<"Element deleted from queue is : "<< queue[front] <<endl;
front++;;
}
}

void Display()
{
if (front == - 1)
cout<<"Queue is empty"<<endl;
else
{
cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)
cout<<queue[i]<<" ";
cout<<endl;
}
}
main()
{
int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do
{
cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}
} while(ch!=4);
}

Output

1) Insert element to queue


2) Delete element from queue
3) Display all the elements of queue
4) Exit
Enter your choice : 1
Insert the element in queue : 4
Enter your choice : 1
Insert the element in queue : 3
Enter your choice : 1
Insert the element in queue : 5
Enter your choice : 2
Element deleted from queue is : 4
Enter your choice : 3
Queue elements are : 3 5
Enter your choice : 7
Invalid choice
Enter your choice : 4
Exit
13 Program to convert Infix to Postfix

#include<iostream.h>
#include<stack.h>
#include<locale.h> //for function isalnum()

int preced(char ch)


{
if(ch == '+' || ch == '-') {
return 1; //Pr
ecedence of + or - is 1
}
else if(ch == '*' || ch == '/')
{
return 2; //Precedence of * or / is 2
}
else if(ch == '^')
{
return 3; //Precedence of ^ is 3
}
else
{
return 0;
}
}

string inToPost(string infix )


{
stack<char> stk;
stk.push('#'); //add some extra character to avoid underflow
string postfix = ""; //initially the postfix string is empty
string::iterator it;

for(it = infix.begin(); it!=infix.end(); it++)


{
if(isalnum(char(*it)))
postfix += *it; //add to postfix when character is letter or number
else if(*it == '(')
stk.push('(');
else if(*it == '^')
stk.push('^');
else if(*it == ')')
{
while(stk.top() != '#' && stk.top() != '(')
{
postfix += stk.top(); //store and pop until ( has found
stk.pop();
}
stk.pop(); //remove the '(' from stack
}
else
{
if(preced(*it) > preced(stk.top()))
stk.push(*it); //push if precedence is high
else {
while(stk.top() != '#' && preced(*it) <= preced(stk.top())) {
postfix += stk.top(); //store and pop until higher precedence is found
stk.pop();
}
stk.push(*it);
}
}
}

while(stk.top() != '#')
{
postfix += stk.top(); //store and pop until stack is not empty.
stk.pop();
}

return postfix;
}

main()
{
string infix = "(a+b)*(c-d)/e";
cout << "Postfix Form Is: " << inToPost(infix) << endl;
}

Output

Postfix Form Is: ab+cd-*e/


14 Program for Polynomial addition using Linked List
#include<iostream.h>
struct Node
{
int coeff;
int pow;
struct Node *next;
};

void create_node(int x, int y, struct Node **temp)


{
struct Node *r, *z;
z = *temp;
if(z == NULL)
{
r =(struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
else
{
r->coeff = x;
r->pow = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}

void polyadd(struct Node *p1, struct Node *p2, struct Node *result)
{
while(p1->next && p2->next)
{
if(p1->pow > p2->pow){
result->pow = p1->pow;
result->coeff = p1->coeff;
p1 = p1->next;
}
else if(p1->pow < p2->pow)
{
result->pow = p2->pow;
result->coeff = p2->coeff;
p2 = p2->next;
}
else
{
result->pow = p1->pow;
result->coeff = p1->coeff+p2->coeff;
p1 = p1->next;
p2 = p2->next;
}
result->next = (struct Node *)malloc(sizeof(struct Node));
result = result->next;
result->next = NULL;
}
while(p1->next || p2->next)
{
if(p1->next){
result->pow = p1->pow;
result->coeff = p1->coeff;
p1 = p1->next;
}
if(p2->next)
{
result->pow = p2->pow;
result->coeff = p2->coeff;
p2 = p2->next;
}
result->next = (struct Node *)malloc(sizeof(struct Node));
result = result->next;
result->next = NULL;
}
}

void printpoly(struct Node *node)


{
while(node->next != NULL){
printf("%dx^%d", node->coeff, node->pow);
node = node->next;
if(node->next != NULL)
printf(" + ");
}
}
main()
{
struct Node *p1 = NULL, *p2 = NULL, *result = NULL;
create_node(41,7,&p1);
create_node(12,5,&p1);
create_node(65,0,&p1);
create_node(21,5,&p2);
create_node(15,2,&p2);
printf("polynomial 1: ");
printpoly(p1);
printf("\npolynomial 2: ");
printpoly(p2);
result = (struct Node *)malloc(sizeof(struct Node));
polyadd(p1, p2, result);
printf("\npolynomial after adding p1 and p2 : ");
printpoly(result);
}

Output

polynomial 1: 41x^7 + 12x^5 + 65x^0


polynomial 2: 21x^5 + 15x^2
polynomial after adding p1 and p2 : 41x^7 + 33x^5 + 15x^2 + 65x^0

15 Program to Traverse a Binary Tree


#include <iostream.h>

struct Node
{
int data;
struct Node *left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};

// Preorder traversal
void preorderTraversal(struct Node* node)
{
if (node == NULL)
return;

cout << node->data << "->";


preorderTraversal(node->left);
preorderTraversal(node->right);
}

// Postorder traversal
void postorderTraversal(struct Node* node)
{
if (node == NULL)
return;

postorderTraversal(node->left);
postorderTraversal(node->right);
cout << node->data << "->";
}

// Inorder traversal
void inorderTraversal(struct Node* node)
{
if (node == NULL)
return;
inorderTraversal(node->left);
cout << node->data << "->";
inorderTraversal(node->right);
}
main()
{
struct Node* root = new Node(1);
root->left = new Node(12);
root->right = new Node(9);
root->left->left = new Node(5);
root->left->right = new Node(6);

cout << "Inorder traversal ";


inorderTraversal(root);

cout << "\nPreorder traversal ";


preorderTraversal(root);

cout << "\nPostorder traversal ";


postorderTraversal(root);
}

Output

Inorder traversal 5->12->6->1->9->

Preorder traversal 1->12->5->6->9->

Postorder traversal 5->6->12->9->1->


16 Program for Linear Search

#include <iostream.h>

int search(int arr[], int N, int x)


{
int i;
for (i = 0; i < N; i++)
if (arr[i] == x)
return i;
return -1;
}

// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);

// Function call
int result = search(arr, N, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}

Output

Element is present at index 3


17 Program for binary search
#include<iostream.h>

int binarySearch(int arr[], int l, int r, int x)


{
if (r >= l)
{
int mid = l + (r - l) / 2;

// If the element is present at the middle itself


if (arr[mid] == x)
return mid;

// If element is smaller than mid, then it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);

// Else the element can only be present in right subarray


return binarySearch(arr, mid + 1, r, x);
}

// We reach here when element is not present in array


return -1;
}

// Driver code
main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "Element is not present in array" :
cout << "Element is present at index " << result;
}

Output
Element is present at index 3
18 Program to sort using Bubble sort

#include<iostream.h>

main ()
{
int i, j,temp,pass=0;
int a[10] = {10,2,0,14,43,25,18,1,5,45};
cout <<"Input list ...\n";
for(i = 0; i<10; i++)
{
cout <<a[i]<<"\t";
}
cout<<endl;
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
pass++;
}
cout <<"Sorted Element List ...\n";
for(i = 0; i<10; i++)
{
cout <<a[i]<<"\t";
}
cout<<"\nNumber of passes taken to sort the list:"<<pass<<endl;
}

Input list ...


10 2 0 14 43 25 18 1 5 45
Sorted Element List ...
0 1 2 5 10 14 18 25 43 45
Number of passes taken to sort the list:10
19 Program to sort using Merge Sort

#include <iostream.h>

// Merge two subarrays L and M into arr


void merge(int arr[], int p, int q, int r)
{
// Create L ← A[p..q] and M ← A[q+1..r]
int n1 = q - p + 1;
int n2 = r - q;

int L[n1], M[n2];

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


L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];

// Maintain current index of sub-arrays and main array


int i, j, k;
i = 0;
j = 0;
k = p;
// Until we reach either end of either L or M, pick larger among
// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2)
{if (L[i] <= M[j])
{
arr[k] = L[i];
i++;
} else
{
arr[k] = M[j];
j++;
}
k++;
}

// When we run out of elements in either L or M,


// pick up the remaining elements and put in A[p..r]
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = M[j];
j++;
k++;
}
}

// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r)
{
// m is the point where the array is divided into two subarrays
int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted subarrays


merge(arr, l, m, r);
}
}

// Print the array


void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

// Driver program
main()
{
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);

mergeSort(arr, 0, size - 1);

cout << "Sorted array: \n";


printArray(arr, size);
}
Output
Sorted array:
1 5 6 9 10 12
20 Program to implement Dijikstra’s Shortest Path Algorithm

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int shortest(int ,int);
int cost[10][10],dist[20],i,j,n,k,m,S[20],v,totcost,path[20],p;
main()
{
int c;
cout <<"enter no of vertices";
cin >> n;
cout <<"enter no of edges";
cin >>m;
cout <<"\nenter\nEDGE Cost\n";
for(k=1;k<=m;k++)
{
cin >> i >> j >>c;
cost[i][j]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
cout <<"enter initial vertex";
cin >>v;
cout << v<<"\n";
shortest(v,n);
}

int shortest(int v,int n)


{
int min;
for(i=1;i<=n;i++)
{
S[i]=0;
dist[i]=cost[v][i];
}
path[++p]=v;
S[v]=1;
dist[v]=0;
for(i=2;i<=n-1;i++)
{
k=-1;
min=31999;
for(j=1;j<=n;j++)
{
if(dist[j]<min && S[j]!=1)
{
min=dist[j];
k=j;
}
}
if(cost[v][k]<=dist[k])
p=1;
path[++p]=k;
for(j=1;j<=p;j++)
cout<<path[j];
cout <<"\n";
//cout <<k;
S[k]=1;
for(j=1;j<=n;j++)
if(cost[k][j]!=31999 && dist[j]>=dist[k]+cost[k][j] && S[j]!=1)
dist[j]=dist[k]+cost[k][j];
}
}

INPUT
enter no of vertices 6
enter no of edges 11

enter
EDGE Cost
1 2 50
1 3 45
1 4 10
2 3 10
2 4 15
3 5 30
4 1 10
4 5 15
5 2 20
5 3 35
653
enter initial vertex 1
OUTPUT
1
14
145
1452
13

You might also like