C
C
C
# include<iostream>
int main()
{
int (*p1)(int);
int (*p2)(int,int);
p1=area;
p2=area;
cout<<"Address of area(int)="<<p1<<endl;
cout<<"Address of area(int,int)="<<p2<<endl;
cout<<"\n";
return 0;
}
Output
Address of area(int)=4199220
Address of area(int,int)=4199232
class point
{
int x,y,z;
public:
point()
{
x=y=z=0;
}
point(point &a)
{
x=a.x;
y=a.y;
z=a.z;
}
void negate()
{
x=-x;
y=-y;
z=-z;
}
void print()
{
cout<<"("<<x<<","<<y<<","<<z<<")\n";
}
int norm()
{
return(sqrt(x*x+y*y+z*z));
}
};
int main()
{
point p(2,3,4),p1(p);
p.negate();
p.print();
return 0;
}
Output
The point has the coordinates
(2,3,4)
The point coordinates after negation
(-2,-3,-4)
Normal Distance of the point from (0,0,0) is
5
The coordinates of the point p1 after copy constructor is
(2,3,4)
Class Example
#include<iostream>
class programming
{
private:
int variable;
public:
void input_value()
{
cout << "In function input_value, Enter an integer\n";
cin >> variable;
}
void output_value()
{
cout << "Variable entered is ";
cout << variable << "\n";
}
};
int main()
{
programming object;
object.input_value();
object.output_value();
return 0;
}
Output
function input_value, Enter an integer 5 Variable entered is 5
Minus Operator Overloading
#include<iostream>
class MinusOperatorOverloading
{
int x,y,z;
public:
void get_data(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
void display()
{
cout<<"\nx: "<<x;
cout<<"\ny: "<<y;
cout<<"\nz: "<<z;
}
};
int main()
{
MinusOperatorOverloading oo;
oo.get_data(53,73,93);
cout<<"Before overloading:";
oo.display();
-oo;
cout<<"\n\n";
cout<<"After overloading:";
oo.display();
return 0;
}
Output
Before overloading:
x: 53
y: 73
z: 93
After overloading:
x: 43
y: 63
z: 83
Function Overloading (Polymorphism)
#include<iostream>
class Add
{
public:
void add(int a,int b)
{
int c;
c=(a+b);
cout<<a<<" + "<<b<<" = "<<c<<endl;
}
int main()
{
Add a;
a.add(5,6);
a.add(7,8,9);
a.add(8.0f,9.0f);
return 0;
}
Output
5 + 6 = 11
7 + 8 + 9 = 24
8 + 9 = 17
Hierarchical Inheritance Example
#include<iostream>
public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};
int main ()
{
Rectangle rect;
Triangle tri;
rect.set_data (5,3);
tri.set_data (2,5);
return 0;
}
Output
Area of Rectangle : 15
Area of Triangle : 5
Multiple Inheritance Example
#include <iostream>
class Perimeter
{
public:
float peri_calc(float l,float b)
{
return 2*(l+b);
}
};
public:
Rectangle() : length(0.0), breadth(0.0) { }
void get_data( )
{
cout<<"Enter length: ";
cin>>length;
float area_calc()
{
//Calls area_calc() of class Area and returns it.
return Area::area_calc(length,breadth);
}
float peri_calc()
{
//Calls peri_calc() function of class Perimeter and returns it.
return Perimeter::peri_calc(length,breadth);
}
};
int main()
{
Rectangle r;
r.get_data();
cout<<"\n\n";
cout<<"Area = "<<r.area_calc();
cout<<"\nPerimeter = "<<r.peri_calc();
return 0;
}
OUTPUT
Enter length: 3
Enter breadth: 2
Area = 6
Perimeter = 10
Single Inheritance Example
#include <iostream>
class Value
{
protected:
int val;
public:
void set_values (int a)
{
val=a;
}
};
int main()
{
Cube cub;
cub.set_values (5);
return 0;
}
Output
The Cube of 5 is : 125
Multilevel Inheritance Example
#include<iostream>
#include<string.h>
class student
{
private:
int rl;
char nm[20];
public:
void read();
void display();
};
public:
void getmarks();
void putmarks();
};
public:
void process();
void printresult();
};
void student::read()
{
cout<<"Enter Roll no. : ";
cin>>rl;
cout<<"\n";
}
void result::process()
{
t= s1+s2+s3;
p = t/3.0;
p>=60?strcpy(div,"First"):p>=50?strcpy(div, "Second"):
strcpy(div,"Third");
}
void result::printresult()
{
cout<<"Total = "<<t<<endl;
cout<<"\n";
cout<<"Percentage = "<<p<<endl;
cout<<"Division = "<<div<<endl;
}
int main()
{
result x;
x.read();
x.getmarks();
x.process();
x.display();
x.putmarks();
x.printresult();
return 0;
}
Output
Enter Roll no. : 1
Enter Name : Yogesh
Enter marks for 3 subjects :
87
98
76
Roll no. : 1
Name : Yogesh
Subject 1 :87
Subject 2 : 98
Subject 3 : 76
Total = 261
Percentage = 87
Division = First
Hybrid Inheritance Example
#include<iostream>
class A
{
public:
int l;
void len()
{
cout<<"Lenght : ";
cin>>l;
}
};
class B : public A
{
public:
int b,c;
void l_into_b()
{
len();
cout<<"Breadth : ";
cin>>b;
c=b*l;
}
};
class C
{
public:
int h;
void height()
{
cout<<"Height : ";
cin>>h;
}
};
//Hybrid Inheritance Level
class D : public B , public C
{
public:
int res;
void result()
{
l_into_b();
height();
res=h*c;
cout<<"\n";
cout<<endl<<"Result (l*b*h) : "<<res;
}
};
int main()
{
D dObj;
dObj.result();
return 0;
}
OUTPUT
Lenght : 5
Breadth : 6
Height : 7
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
OUTPUT
Volume of Box1 : 210 Volume of Box2 : 1560 Volume of Box3 : 5400
Friend Function Example
/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
class Distance
{
private:
int meter;
public:
Distance(): meter(0){ }
//friend function
friend int func(Distance);
};
//function definition
int func(Distance d)
{
//accessing private data from non-member function
d.meter = 10;
return d.meter;
int main()
{
Distance D;
//using friend function
cout<<"Distace: "<<func(D)<<"\n";
return 0;
}
Output
Distace: 10
Pure Virtual Function Example
#include<iostream>
using namespace std;
int main()
{
Base *b;
Derived d;
b = &d;
b->show();
}
Output
Implementation of Virtual Function in Derived class
Merge Singly linked list
#include <iostream>
#include <cstdlib>
Linked_list *t = *head;
l->data = d;
l->next = NULL;
if(*head == NULL)
{
*head = l;
return 1;
}
while(t->next != NULL)
{
t = t->next;
}
t->next = l;
return 1;
}
if(l1 == NULL)
{
return l2;
}
if(l2 == NULL)
{
return l1;
}
if(l1->next != NULL)
{
r->next = l1;
}
if(l2->next != NULL)
{
r->next = l2;
}
return h;
}
print_list(h);
del_list(h);
return 0;
}
Output
0 3 6 9 12 15 18 21 24 27
0 7 14 21 28 35 42 49 56 63
0 0 3 6 7 9 12 14 15 18 21 21 24 28 35 42 49 56 63
Prime number using Constructor
#include<iostream>
#include<conio.h>
using namespace std;
class prime
{
int num,k,i;
void check()
{
k=1;
{
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
k=0;
break;
}
else
{
k=1;
}
}
}
}
void show()
{
if(k==1)
{
cout<<"\n"<<num<<" is a prime number.";
}
else
{
cout<<"\n"<<num<<" is Not a prime number.";
}
}
};
int a;
cout<<"Enter the Number : ";
cin>>a;
prime obj(a); //calling constructor
obj.check();
obj.show();
}
Output
Enter the Number : 7 7 is a prime number.
setprecision Manipulator
//using setprecision manipulator
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
float num1,num2,result;
num1=20;
num2=3;
result=num1/num2;
}
Output
7 6.7 6.67 6.667
Using ws manipulator
#include <iostream>
#include <iomanip>
using namespace std;
int main ( )
{
char empname [100];
cout<<"Enter a employee name : ";
//define class
class operations
{
//member variables
public:
int num1,num2;
void sub()
{
cout<<"enter two number for subtraction : ";
cin>>num1>>num2;
cout<<"addition = "<<num1-num2;
cout<<"\n";
}
void mul()
{
cout<<"enter two number for multiplication : ";
cin>>num1>>num2;
cout<<"addition = "<<num1*num2;
cout<<"\n";
}
void div()
{
cout<<"enter two number for division : ";
cin>>num1>>num2;
cout<<"addition = "<<(float)num1/num2;
cout<<"\n";
}
};
int main()
{
//creation of object
operations op1;
op1.add();
op1.sub();
op1.mul();
op1.div();
return 0;
}
OUTPUT
//class creation
class CubeDemo
{
//member variable and member function declaration
public:
int side;
//constructor declaration
CubeDemo()
{
side=8;
}
//destructor declaration
~CubeDemo()
{
cout<<"\nDestructor called...";
}
};
//declaration of main method
int main()
{
//object creation
CubeDemo cdemoobj;
cout<<"";
cout << cdemoobj.side;
}
Output
8 Destructor called...
Method Overloading Example
//program to show how method overloading works
# include<iostream>
int main()
{
int (*para1)(int);
int (*para2)(int,int);
para1=area;
para2=area;
#include<iostream>
using namespace std;
//function definition
void swap(int x, int y)
{
int z;
z = x;
x = y;
y = z;
cout<<"Swapped value of a is : "<< x<<endl;
cout<<"Swapped value of b is : "<<y<<endl;
}
//function declaration
int add(int num);
//main method
int main()
{
//variable declaration
int num;
//method definition
int add(int num)
{
if(num!=0)
{
return num+add(num-1);
}
}
Output
Enter a positive integer : 2 Sum of n integer is : 3
Constructor overloading
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
// Constructor without argument
Area(): length(5), breadth(2)
{
}
// Constructor with two argument
Area(int l, int b): length(l), breadth(b)
{ }
void GetLength()
{
cout<<"Enter length and breadth : ";
cin>>length>>breadth;
}
int AreaCalculation()
{
return (length*breadth);
}
void DisplayArea(int temp)
{
cout<<"Area is : "<<temp<<endl;
}
};
int main()
{
Area objarea1,objarea2(24,2);
int temp;
objarea1.GetLength();
cout<<"Area when default constructor is called."<<endl;
temp=objarea1.AreaCalculation();
objarea1.DisplayArea(temp);
cout<<"Area when (parameterized constructor is called."<<endl;
temp=objarea2.AreaCalculation();
objarea2.DisplayArea(temp);
return 0;
}
Output
Enter length and breadth : 5 7 Area when default constructor is called. Area is : 35 Area
when (parameterized constructor is called. Area is : 48
Copy constructor
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1; y = y1;
}
// Copy constructor
Point(const Point &p2)
{
x = p2.x;
y = p2.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// simple constructor is called
Point objpoint1(53, 13);
// Copy constructor is called
Point objpoint2 = objpoint1;
cout << "objpoint1.x : " << objpoint1.getX() << ", objpoint1.y : "
<< objpoint1.getY();
cout << "\nobjpoint2.x : " << objpoint2.getX() << ", objpoint2.y : "
<< objpoint2.getY();
return 0;
}
Output
objpoint1.x : 53, objpoint1.y : 13 objpoint2.x : 53, objpoint2.y : 13
Read Char using cin example
#include <iostream>
#include <stdlib.h>
int main()
{
char mychar[100];
int i = 0;
//while the character is not a new line
while((mychar[i] = cin.get()) != '\n')
i++;
mychar[i] = NULL;
//display characters
cout<<mychar<<endl;
return 0;
}
Output
Hello
Hello
Print Time in 24 hrs and Standard format
#include<iostream>
#include<conio.h>
int main()
{
int hours,mins,seconds,x;
cout<<"Enter hours=";
cin>>hours;
cout<<"\nEnter minutes=";
cin>>mins;
cout<<"\nEnter seconds=";
cin>>seconds;
if(hours > 24)
cout<<"Invalid Entery";
else
hours=hours-12;
else
} // end of main
Output
Enter hours=4
Enter minutes=44
Enter seconds=33
24 Hours Format
Hours : Mins : Seconds
4 : 44 : 33
12 Hours Format
Hours : Mins : Seconds
4: 44 : 33
Hello World Example
#include<iostream>
int main()
{
cout << "Hello World\n";
return 0;
}
OUTPUT
Hello World
Hello World using Class
#include<iostream>
// Creating class
class Message
{
public:
void display() {
cout << "Hello World\n";
}
};
int main()
{
Message c; // Creating object
c.display(); // Calling function
return 0;
}
Output
Hello World
Multiplication Table
#include<iostream>
for(int a=1;a<=10;a++)
cout<<num<<" * "<<a<<" = "<<num*a<<endl;
return 0;
}
Output
Enter number to find multiplication table : 19
19 * 1 = 19
19 * 2 = 38
19 * 3 = 57
19 * 4 = 76
19 * 5 = 95
19 * 6 = 114
19 * 7 = 133
19 * 8 = 152
19 * 9 = 171
19 * 10 = 190
Check vowel using switch statement
#include<iostream>
using namespace std;
int main()
{
char ch;
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
cout<<ch<<" is a vowel.";
break;
default:
cout<<ch<<" is not a vowel.";
}
return 0;
}
Output
Input a character : u
u is a vowel.
Basic Calculator
# include <iostream>
using namespace std;
int main()
{
char operation;
float num1,num2;
cout << "Enter operator either + or - or * or /: ";
cin >> operation;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(operation) {
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
/* If operator is other than +, -, * or /, error message is
shown */
cout << "Error! operator is not correct";
break;
}
return 0;
}
Output
Enter operator either + or - or * or /: +
Enter two operands: 4 2
6
FizzBuzz Program
#include<iostream>
using namespace std;
int main()
{
for(int i=1;i<=100;i++)
{
if(i%15==0)
{
cout<<"FizzBuzz"<<endl;
}
else if(i%3==0)
{
cout<<"Fizz"<<endl;
}
else if(i%5==0)
{
cout<<"Buzz"<<endl;
}
else
{
cout<<i<<endl;
}
}
return 0;
}
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
Symbol Table
//Request No.16635
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>#define NULL 0
int size=0;
void Insert();
void Display();
void Delete();
int Search(char lab[]);
void Modify();
struct SymbTab
{
char label[10],symbol[10];
int addr;
struct SymbTab *next;};
struct SymbTab *first,*last;
void main()
{
int op,y;
char la[10];
do
{
printf("\n\tSYMBOL TABLE IMPLEMENTATION\n");
printf("\n\t1.INSERT\n\t2.DISPLAY\n\t3.DELETE\n\t4.SEARCH\n\t5.MODIFY\n\
t6.END\n");
switch(op)
{
case 1:
Insert();
break;
case 2:
Display();
break;
case 3:
Delete();
break;
case 4:
printf("\n\tEnter the label to be searched : ");
scanf("%s",la);
y=Search(la);
printf("\n\tSearch Result:");
if(y==1)
printf("\n\tThe label is present in the symbol table\n");
else
printf("\n\tThe label is not present in the symbol table\n");
break;
case 5:
Modify();
break;
case 6:
exit(0);
}
}
while(op<6);
getch();
}
void Insert()
{
int n;
char l[10];
n=Search(l);
if(n==1)
{
printf("\n\tThe label exists already in the symbol table\n\tDuplicate can't be inserted");
}
else
{
struct SymbTab *p;
p=malloc(sizeof(struct SymbTab));
strcpy(p->label,l);
printf("\n\tEnter the symbol : ");
scanf("%s",p->symbol);
printf("\n\tEnter the address : ");
scanf("%d",&p->addr);
p->next=NULL;
if(size==0)
{
first=p;
last=p;
}
else
{
last->next=p;
last=p;
}
size++;
}
printf("\n\tLabel inserted\n");
}
void Display()
{
int i;
struct SymbTab *p;
p=first;
printf("\n\tLABEL\t\tSYMBOL\t\tADDRESS\n");
for(i=0;i<size;i++)
{
printf("\t%s\t\t%s\t\t%d\n",p->label,p->symbol,p->addr);
p=p->next;
}
}
for(i=0;i<size;i++)
{
if(strcmp(p->label,lab)==0)
flag=1;
p=p->next;
}
return flag;
}
void Modify()
{
char l[10],nl[10];
int add,choice,i,s;
struct SymbTab *p;
p=first;
printf("\n\tWhat do you want to modify?\n");
printf("\n\t1.Only the label\n\t2.Only the address\n\t3.Both the label and address\n");
printf("\tEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n\tEnter the old label : ");
scanf("%s",l);
s=Search(l);
if(s==0)
{
printf("\n\tLabel not found\n");
}
else
{
if(strcmp(p->label,l)==0)
{
strcpy(p->label,nl);
p=p->next;
}
printf("\n\tAfter Modification:\n");
Display();
}
break;
case 2:
printf("\n\tEnter the label where the address is to be modified : ");
scanf("%s",l);
s=Search(l);
if(s==0)
{
printf("\n\tLabel not found\n");
}
else
{
printf("\n\tEnter the new address : ");
scanf("%d",&add);
for(i=0;i<size;i++)
{
if(strcmp(p->label,l)==0)
{
p->addr=add;
p=p->next;
}
}
printf("\n\tAfter Modification:\n");
Display();
}
break;
case 3:
printf("\n\tEnter the old label : ");
scanf("%s",l);
s=Search(l);
if(s==0)
{
printf("\n\tLabel not found\n");
}
else
{
printf("\n\tEnter the new label : ");
scanf("%s",nl);
for(i=0;i<size;i++)
{
if(strcmp(p->label,l)==0)
{
strcpy(p->label,nl);
p->addr=add;
}
p=p->next;
}
printf("\n\tAfter Modification:\n");
Display();
}
break;
}
}
void Delete()
{
int a;
char l[10];
struct SymbTab *p,*q;
p=first;
if(a==0)
{
printf("\n\tLabel not found\n");
}
else
{
if(strcmp(first->label,l)==0)
{
first=first->next;
}
else if(strcmp(last->label,l)==0)
{
q=p->next;
while(strcmp(q->label,l)!=0)
{
p=p->next;
q=q->next;
}
p->next=NULL;
last=p;
}
else
{
q=p->next;
while(strcmp(q->label,l)!=0)
{
p=p->next;
q=q->next;
}
p->next=q->next;
}
size--;
printf("\n\tAfter Deletion:\n");
Display();
}
}
OUTPUT
SYMBOL TABLE IMPLEMENTATION 1.INSERT 2.DISPLAY 3.DELETE 4.SEARCH
5.MODIFY 6.END
Absolute value of a number
#include<iostream>
using namespace std;
int main()
{
float num;
cout<<"Enter any number:";
cin>>num;
if(num>0)
{
cout<<"The absolute value of number is:"<<num;
}
else
{
cout<<"The absolute value of number is:"<<-(num);
}
return 0;
}
Output
Enter any number:-9 The absolute value of number is:9
Largest and Smallest number in an vector
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i,num;
int vec[num],large,small;
for(i=0;i<num;i++)
{
cin>>vec[i];
}
large=vec[1];
small=vec[1];
for(i=0;i<num;i++)
{
if(vec[i]>large)
{
large=vec[i];
}
else
{
if(vec[i]<small)
{
small=vec[i];
}
int main()
{
//declare variable
int year;
else
cout<<"This is not a leap year"<<endl;
return 0;
}
Output
Enter year : 2016 This is a leap year
Display System Date and Time
#include <iostream>
#include <ctime>
int main( )
{
// current date/time based on your system
time_t nowuptime = time(0);
}
Output
The localhost date and time is: Fri Jan 22 13:11:30 2016
Count Vowels Consonants Numbers and Blank spaces in a sentance
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
//variable declaration
char str[150];
int i,vowel,cons,ch,digit,space,o;
o=vowel=cons=ch=digit=space=0;
else if(str[i]>='0'&&cons<='9')
{
++digit;
}
else if (str[i]==' ')
{
++space;
}
//display output
cout << "\nNumbers of Vowels : " << vowel << endl;
cout << "Numbers of Consonants : " << cons << endl;
cout << "Numbers of Digits : " << digit << endl;
cout << "Numbers of White Spaces : " << space << endl;
return 0;
}
Output
Enter a string : i love programming very much Numbers of Vowels : 8 Numbers of
Consonants : 16 Numbers of Digits : 0 Numbers of White Spaces : 4
Date Format
// Display the current date in the formats of "2007-11-10"
// and "Sunday, November 10, 2007".
#include <vector>
#include <string>
#include <iostream>
#include <ctime>
class Date
{
struct tm ltime;
public:
int main()
{
Date d;
std::cout << d.getISODate() << std::endl;
std::cout << d.getTextDate() << std::endl;
return 0;
}
Output
2016-03-16
Wednesday, March 16, 2016
Calendar
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class Calendar
{
private:
int month;
int year;
int firstday;
public:
Calendar(int =03, int =2016);
void setFirstDay();
void print();
};
switch (month)
{
case 1:
cout<<setw(21)<<"January "<<year;
NumberOfDaysInMonth = 31;
break;
case 2:
cout<<setw(21)<<"February "<<year;
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
NumberOfDaysInMonth = 29;
else
NumberOfDaysInMonth = 28;
break;
case 3:
cout<<setw(21)<<"March "<<year;
NumberOfDaysInMonth = 31;
break;
case 4:
cout<<setw(21)<<"April "<<year;
NumberOfDaysInMonth = 30;
break;
case 5:
cout<<setw(21)<<"May "<<year;
NumberOfDaysInMonth = 31;
break;
case 6:
cout<<setw(21)<<"June "<<year;
NumberOfDaysInMonth = 30;
break;
case 7:
cout<<setw(21)<<"July "<<year;
NumberOfDaysInMonth = 31;
break;
case 8:
cout<<setw(21)<<"August "<<year;
NumberOfDaysInMonth = 31;
break;
case 9:
cout<<setw(21)<<"September "<<year;
NumberOfDaysInMonth = 30;
break;
case 10:
cout<<setw(21)<<"October "<<year;
NumberOfDaysInMonth = 31;
break;
case 11:
cout<<setw(21)<<"November "<<year;
NumberOfDaysInMonth = 30;
break;
case 12:
cout<<setw(21)<<"December "<<year;
NumberOfDaysInMonth = 31;
break;
cout<<setw(14);
}
int tempfirstday=firstday;
DateCounter = 1;
DayOfWeekCounter = tempfirstday;
//This loop represents the date display and will continue to run until
//the number of days in that month have been reached
tempfirstday = DayOfWeekCounter + 1;
}
int main()
{
Calendar c;
c.setFirstDay();
c.print();
return 0;
}
Output
March 2016 Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27 28 29 30 31
Balanced Brackets
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
bool balanced(const string &str, char left = '[', char right = ']')
{
int count = 0;
for (string::const_iterator it = str.begin(); it != str.end(); ++it)
{
if (*it == left)
count++;
else if (*it == right)
if (--count < 0) return false;
}
return count == 0;
}
int main()
{
srand(time(NULL)); // seed rng
for (int i = 0; i < 9; ++i)
{
string s(generate(i));
cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n";
}
}
Output
ok: ok: [] ok: [[]] bad: ][[]][ bad: [][[]]][ ok: [][[][][]] bad: []]][[[][[]] ok: [[[][][]][]][]
bad: ][]]][[[[[][]]][
Huffman coding
#include <iostream>
#include <queue>
#include <map>
// for CHAR_BIT
#include <climits>
#include <iterator>
#include <algorithm>
virtual ~INode() {}
protected:
INode(int f) : f(f) {}
};
struct NodeCmp
{
bool operator()(const INode* lhs, const INode* rhs) const { return
lhs->f > rhs->f; }
};
int main()
{
// Build frequency table
int frequencies[UniqueSymbols] = {0};
const char* ptr = SampleString;
while (*ptr != '\0')
++frequencies[*ptr++];
HuffCodeMap codes;
GenerateCodes(root, HuffCode(), codes);
delete root;
int main()
{
int min,max,i,range,r,x;
unsigned first = time(NULL);
range=max-min+1;
for(i=0;i<x;i++)
{
r=rand()/100%range+min;
cout<<r<<" ";
}
getch();
}
Output
FIRST = 1408222966
ENTER THE MINIMUM NUMBER :33
ENTER THE MAXIMUM NUMBER :55
ENTER THE NO.OF TERMS YOU WANT :4
35 44 36 37
Perfect Number example
#include<iostream>
#include<conio.h>
while(u<=500)
{ //start of second loop.
if(u<i)
{
if(i%u==0 )
sum=sum+u;
} //End of if statement
u++;
} //End of second loop
if(sum==i)
{
cout<<i<<" is a perfect number."<<"\n";
}
i++;
u=1; sum=0;
} //End of First loop
getch();
}
Output
6 is a perfect number.
28 is a perfect number.
496 is a perfect number.
Greatest of three numbers
#include<iostream>
using namespace std;
int main()
{
int num1,num2,num3;
cout<<" Enter value for first number ";
cin>>num1;
int main()
int num,factorial=1;
cin>>num;
for(int a=1;a<=num;a++)
factorial=factorial*a;
return 0;
}
Output
Enter Number To Find Its Factorial: 5
Factorial of Given Number is = 120
Swap two numbers
#include<iostream>
int main()
cin>>var1;
cin>>var2;
swap=var1;
var1=var2;
var2=swap;
return 0;
}
Output
Enter value for first integer: 4
Enter value for second integer: 5
First Integer =4
Second Interger =5
First Integer =5
Second Interger =4
Print Fibonacci Series
#include<iostream>
using namespace std;
int main()
{
int range, first = 0, second = 1, fibonicci=0;
cout << "Enter Range for Terms of Fibonacci Sequence: ";
cin >> range;
cout << "Fibonicci Series upto " << range << " Terms "<< endl;
for ( int c = 0 ; c < range ; c++ )
{
if ( c <= 1 )
fibonicci = c;
else
{
fibonicci = first + second;
first = second;
second = fibonicci;
}
cout << fibonicci <<" ";
}
return 0;
}
Output
Enter Range for Terms of Fibonacci Sequence: 5
Fibonicci Series upto 5 Terms
0 1 1 2 3
Quotient and Remainder
#include<iostream>
for(int a=1;a<=number;a++)
if(number%a==0)
count++;
if(count==2)
cout<<"Its Prime Number \n";
else
cout<<"Its not a Prime Number\n";
return 0;
}
Output
Enter number to check its Prime or Not : 13
Its Prime Number
Average of Positive Numbers using Recursion
#include <iostream>
void recurse (float sum, int i ) // Each call gets its own count
{
int num = 0;
cout<<"ERROR\n";
recurse (sum, i ); //First function call, so it starts at one
}
else if(num == 0){
if(sum == 0){
cout<<"NO AVERAGE";
}
else {
cout<<"\nThe Average of Positive Integers is
"<<(sum/i)<<"\n";
}
}
else {
int main()
{
float num;
float sum = 0;
int i = 0;
cout<<"ERROR\n";
recurse (sum, i ); //First function call, so it starts at one
}
else if(num == 0){
cout<<"NO AVERAGE";
}
else {
return(0);
}
Output
Enter a positive integer: -1
ERROR
Enter another positive integer: 2
Enter another positive integer: 3
Enter another positive integer: 0
Sum of n Numbers
#include<iostream>
using namespace std;
int main()
{
int times, Inp, sum,i;
times=Inp=sum=i=0;
cout<<"The sum of your " << times << " numbers is "<< sum;
cout<< "." << endl;
return 0;
}
Output
Input the number of integers you want to add:5
Enter a number:7
Enter a number:1
Enter a number:3
Enter a number:9
Enter a number:5
The sum of your 5 numbers is 25.
Sum of n Squares
#include<iostream>
using namespace std;
int main()
{
int times, Inp, sum,i;
times=Inp=sum=i=0;
cout << "Input the number of integers you want to square and add :
";
cin >> times;
cout<<"The sum of squares of " << times << " numbers is "<< sum;
cout<< "." << endl;
return 0;
}
Output
Input the number of integers you want to square and add : 3
Enter a number:4
Enter a number:3
Enter a number:5
The sum of squares of 3 numbers is 50.
Average of Numbers
#include<iostream>
using namespace std;
int main()
{
int n;
double average(0);
cout<<"Enter the number of values : ";
cin >> n;
for(int i = 0; i < n; ++i)
{
int value;
cin >> value;
average += value;
}
average /= n;
cout<<"Average is "<<average;
return 0;
}
Output
Enter the number of values : 5
12
35
20
45
95
Average is 41.4
Armstrong Number
#include <iostream>
using namespace std;
int main()
{
int n, n1, rem, num=0;
while(n1!=0)
{
rem=n1%10;
num+=rem*rem*rem;
n1/=10;
}
if(num==n)
{
cout << n << " is an Armstrong number.";
}
else
{
cout << n << " is not an Armstrong number.";
}
return 0;
}
Output
Enter a positive integer: 153
153 is an Armstrong number.
Binary to Decimal
#include<iostream>
using namespace std;
int main()
{
long bin, dec = 0, rem, num, base = 1;
if (num <= 1)
{
cout << num;
return;
}
rem = num % 2;
binary(num / 2);
cout << rem;
}
int main()
{
int dec, bin;
cout << "Enter the number : ";
cin >> dec;
if (dec < 0)
cout << dec << " is not a positive integer." << endl;
else
{
cout << "The binary form of " << dec << " is ";
binary(dec);
cout << endl;
}
return 0;
}
Output
Enter the number : 64
The binary form of 64 is 1000000
Check whether two numbers are Amicable Numbers
#include<iostream>
using namespace std;
if(s==b)
{
s=0;
for(i=1;i<b;i++)
{
if(b%i==0)
{
s=s+i;
}
}
if(s==a)
return 1;
else
return 0;
}
return 0;
}
int main()
{
int a,b;
if(check(a,b))
{
cout<<a<<" and "<<b<<" are Amicable Number";
}
else
{
cout<<a<<" and "<<b<<" are not Amicable Number";
}
}
Output
Example 1
Example 2
class Sample
{
private:
int x,y;
public:
void setdata(int a,int b)
{
x=a;
y=b;
}
void showdata()
{
cout<<"x="<<x<<"\ny="<<y;
}
int main()
{
Sample s;
int x,y;
cout<<"Enter x = ";
cin>>x;
cout<<"Enter y = ";
cin>>y;
s.setdata(x,y);
cout<<"\nBefore Swapping\n";
s.showdata();
cout<<"\nAfter Swapping\n";
swap(s);
s.showdata();
return 0;
}
Output
Enter x = 15
Enter y = 5
Before Swapping
x=15
y=5
After Swapping
x=5
y=15
Reverse of Number
#include <iostream>
using namespace std;
int main()
{
int number, reverse = 0;
cout<<"Input a Number to Reverse and press Enter: ";
// Taking Input Number in variable number
cin>> number;
while(number!= 0)
{
reverse = reverse * 10;
reverse = reverse + number%10;
number = number/10;
}
cout<<"New Reversed Number is: "<<reverse;
return 0;
}
Output
Input a Number to Reverse and press Enter: 123
New Reversed Number is: 321
Find all Prime Factor of the Number
# include <iostream>
# include <math.h>
void primeFactors(int n)
{
while (n%2 == 0)
{
cout<<"2 ";
n = n/2;
}
if (n > 2)
{
cout<<n;
}
}
int main()
{
int n;
cout<<"Enter number to find all prime factor : ";
cin>>n;
cout<<"Prime factors are : ";
primeFactors(n);
return 0;
}
Output
Enter number to find all prime factor : 55
Prime factors are : 5 11
Find Primorial(P#) of a number
#include<iostream>
int main()
{
int num,i,j,flag,res = 1;
cout<<"Enter number : ";
cin>>num;
for(i=2;i<=num;i++)
{
flag=0;
for(j=2;j<i;j++)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag!=1)
{
res *= i;
}
}
cout<<num<<"# = "<<res;
return 0;
}
Output
Enter number : 13
13# = 30030
Count Number of Digits
#include <iostream>
int main()
{
int n,count=0;
cout<<"Enter an integer: ";
cin>>n;
while(n!=0)
{
n/=10;
++count;
}
cout<<"Number of digits : "<<count;
}
Output
Enter an integer: 1234567
Number of digits : 7
Number is Palindrome or Not
#include<iostream>
int main()
{
int i,temp,d,revrs=0;
}
if(revrs==i)
cout<<i<<" is Palindrome";
else
cout<<i<<" is not Palindrome";
}
Output
Enter the number : 121
121 is Palindrome
Arithmetic Operation of a Complex number using Structure
#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
struct complex
{
float rel;
float img;
}s1,s2;
int main()
{
float a,b;
cout<<"Enter real and imaginary part of 1st complex number:";
cin>>s1.rel>>s1.img;
cout<<"Enter real and imaginary part of 2nd complex number:";
cin>>s2.rel>>s2.img;
//Addition
a=(s1.rel)+(s2.rel);
b=(s1.img)+(s2.img);
cout<<"\nAddition: "<<"("<<a<<")"<<"+"<<"("<<b<<")"<<"i";
//Subtraction
a=(s1.rel)-(s2.rel);
b=(s1.img)-(s2.img);
cout<<"\nSubtraction: "<<"("<<a<<")"<<"+"<<"("<<b<<")"<<"i";
//Multiplication
a=((s1.rel)*(s2.rel))-((s1.img)*(s2.img));
b=((s1.rel)*(s2.img))+((s2.rel)*(s1.img));
cout<<"\nMultiplication: "<<"("<<a<<")"<<"+"<<"("<<b<<")"<<"i";
//Division
a=(((s1.rel)*(s2.rel))+((s1.img)*(s2.img)))/
(pow(s2.rel,2)+pow(s2.img,2));
b=(((s2.rel)*(s1.img))-((s1.rel)*(s2.img)))/
(pow(s2.rel,2)+pow(s2.img,2));
cout<<"\nDivision: "<<"("<<a<<")"<<"+"<<"("<<b<<")"<<"i";
return 0;
}
Output
Enter real and imaginary part of 1st complex number:4 2
Enter real and imaginary part of 2nd complex number:3 -1
Addition: (7)+(1)i
Subtraction: (1)+(3)i
Multiplication: (14)+(2)i
Division: (1)+(1)i
Find Even or Odd
#include <iostream>
int main()
{
int n;
cout<<"Enter an integer : ";
cin>>n;
if(n % 2 == 0)
{
cout<<n<<" is even.";
}
else
{
cout << n << " is odd.";
}
return 0;
}
Output
Enter an integer : 7
7 is odd.
Find prime number in given range
#include<iostream>
using namespace std;
int main()
{
int startNum,endNum;
int found=0,count=0,i,j;
bool b[1000];
for(i=2;i<endNum;i++)
{
b[i]=true;
}
for(i=startNum;i<endNum;i++)
{
if(b[i])
{
cout<<i<<" ";
for(j=i*2;j<endNum;j+=i)
{
b[j]=false;
}
}
}
return 0;
}
Output
Enter number START of range : 1
Enter number END of range : 30
Prime number from 1 to 30 :
2 3 5 7 11 13 17 19 23 29
Perfect Square Number
#include <stdio.h>
#include <math.h>
#include<iostream>
using namespace std;
int main()
{
int num, tempnum;
tempnum = sqrt(num);
if(tempnum*tempnum==num)
{
cout<<"YES,its perfect square";
}
else
{
cout<<"NO,its not perfect square";
}
return 0;
}
Output
Enter a number: 9 YES,its perfect square
Largest and Smallest number
#include<iostream>
using namespace std;
int main()
{
//declaration of variables
int num1, num2, num3;
int smallest, largest;
//
int main( )
{
int size;
int num[10][10];
if (size % 2 == 0)
{
cout<<"Magic square works for an odd numbered size\n";
}
else
{
magicsquare(size, num);
}
return 0;
}
if (k % size == 0)
{
i += 2;
--j;
}
else
{
if (j == size)
{
j -= size;
}
else if (i < 0)
{
i += size;
}
}
}
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
cout<<"\n";
}
Output
enter size but number should be odd number : 3 8 1 6 3 5 7 4 9 2
Integer to Roman
//C++ Program to Convert Integer to Roman Numeral
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
//variable declaration
int Number,j,m,d,c,l,x,ix,v,iv,i;
m = Number / 1000;
Number = Number % 1000;
d = Number / 500;
Number = Number % 500;
c = Number / 100;
Number = Number % 100;
l = Number / 50;
Number = Number % 50;
x = Number / 10;
Number = Number % 10;
ix = Number / 9;
Number = Number % 9;
v = Number / 5;
Number = Number % 5;
iv = Number / 4;
Number = Number % 4;
i = Number;
s=n*n;
c=0;
p=1;
t=n;
while(n!=0)
{
c++;
n=n/10;
}
for(i=1;i<=c;i++)
{
p=p*10;
}
if(s%p==t)
{
cout<<"Number is automorphic.";
}
else
{
cout<<"Number is not automorphic.";
}
}
Output
Enter a number : 25 Number is automorphic.
Decimal to Octal
//program to convert decimal to octal or vise versa
#include <iostream>
#include <cmath>
using namespace std;
//method declaration
int decimal_octal(int n);
int octal_decimal(int n);
int main()
{
//variable declaration
int n;
char c;
if (c =='o' || c == 'O')
{
cout << "Enter a decimal number : ";
cin >> n;
cout << n << " in decimal : " << decimal_octal(n) << " in
octal";
}
return 0;
}
return octal;
}
"eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","
sixteen","seventeen",
"eighteen","nineteen"};
if(value<0)
{
cout<<"minus ";
convetTo(-value);
}
else if(value>=1000)
{
convetTo(value/1000);
cout<<" thousand";
if(value % 1000)
{
if(value % 1000 < 100)
{
cout << " and";
}
cout << " " ;
convetTo(value % 1000);
}
}
if(value % 100)
{
cout << " and ";
convetTo (value % 100);
}
}
else
{
cout<<ones[value];
}
return;
}
OUTPUT
Enter a number : 112
one hundred and twelve
Niven number
#include<iostream>
int main(void)
{
int n,d,a,sum = 0; // Initializing the variable
a = n;
return 0;
}
Output
Enter the number : 54 The number is Niven Number
Rotation of a String
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char name[40],bubble,temp[40];
int loop,size,count;
printf("Enter the word ");
scanf("%s",name);
printf("");
for(loop=0;loop<strlen(name);loop++)
{
temp[loop]=name[loop];
printf("%c",temp[loop]);
}
for(count=1;count<strlen(name);count++)
{
for(loop=0;loop<(strlen(name));loop++)
{
if(loop==0)
bubble=temp[0];
temp[loop]=temp[loop+1];
temp[strlen(name)]=bubble;
}
printf(" ");
for(loop=0;loop<(strlen(name));loop++)
printf("%c",temp[loop]);
}
getch();
}
Output
Enter the word Hello
Hello elloH lloHe loHel oHell
Strings Sorting
#include <iostream>
#include <set>
#include <algorithm>
int main()
{
set<string> sortedItems;
int size;
cout<< "How many names you want to sort : ";
cin>>size;
for(int i = 1; i <= size; ++i)
{
string name;
cout << i << ". ";
cin >> name;
sortedItems.insert(name);
}
cout<< "Sorted String -> ";
for_each(sortedItems.begin(), sortedItems.end(), &print);
return 0;
}
Output
How many names you want to sort : 5
1. Mark
2. Larry
3. Bill
4. Harry
5. John
Sorted String ->
Bill
Harry
John
Larry
Mark
Concat Strings
#include <iostream>
#include <string>
int main ()
{
string str1 = "Programming";
string str2 = "Hub";
string str3;
int len ;
return 0;
}
Output
str3 : Programming
str1 + str2 : ProgrammingHub
str3.size() : 14
Length of String without inbuilt method
#include<iostream>
#include<stdio.h>
int main( )
{
char str[80];
int i = 0;
cout<<"Enter a string : ";
gets(str);
for(i=0;str[i]!='\0';i++);
int main( )
{
char str[80];
int temp,l,i,j;
cout<<"Enter string : ";
gets(str);
for(i=0,j=l-1;i<l/2;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
return 0;
}
Output
Enter string : programs
Reverse of String : smargorp
Convert String to Lowercase
#include<iostream>
#include<stdio.h>
int main( )
{
char str[80];
cout<<"Enter a string : ";
gets(str);
for(int i=0;str[i]!='\0';i++)
str[i] = (str[i]>='A' && str[i]<='Z')?(str[i]+32):str[i];
cout<<str;
return 0;
}
Output
Enter a string : HelLo
hello
Convert String to Uppercase
#include<iostream>
#include<stdio.h>
int main( )
{
char str[80];
cout<<"Enter a string : ";
gets(str);
for(int i=0;str[i]!='\0';i++)
str[i] = (str[i]>='a' && str[i]<='z')?(str[i]-32):str[i];
cout<<str;
return 0;
}
Output
Enter a string : heLlo
HELLO
String is Palindrome or Not
#include<iostream>
#include<stdio.h>
#include<string.h>
int main()
{
char a[100], b[100];
strcpy(b,a);
strrev(b);
if( strcmp(a,b) == 0 )
printf("Entered string is a palindrome.\n");
else
printf("Entered string is not a palindrome.\n");
return 0;
}
Output
Enter the string to check if it is a palindrome : madam
Entered string is a palindrome.
Convert String to Char Array
#include <iostream>
#include <stdio.h>
#include <string.h>
int main()
{
string tmp = "C Plus Plus";
cout<<"String : "<<tmp<<endl;
char charArray[1024];
strncpy(charArray, tmp.c_str(), sizeof(charArray));
charArray[sizeof(charArray) - 1] = 0;
for(int i = 0;charArray[i]!=0;i++)
{
cout<<endl<<"charArray["<<i<<"] :\t"<<charArray[i];
}
return 0;
}
Output
String : C Plus Plus
Converting string to char array :
charArray[0] : C
charArray[1] :
charArray[2] : P
charArray[3] : l
charArray[4] : u
charArray[5] : s
charArray[6] :
charArray[7] : P
charArray[8] : l
charArray[9] : u
charArray[10] : s
Find Area and Perimeter of Rectangle
#include<iostream>
int main()
int width,height,area,perimeter;
cin>>width;
cin>>height;
area=height*width;
perimeter=2*(height+width);
return 0;
}
Output
Enter Width of Rectangle = 4
Enter Height of Rectangle = 5
Area of Rectangle = 20
Perimeter of rectangle are = 18
Area of Circle
#include <iostream>
using namespace std;
int main()
{
float r,a;
a=3.14*r*r;
return 0;
}
Output
Enter Radius : 3
Area of Circle : 28.26
Calculate Area and Circumference of a Circle
// to calculate the circumference and area of circle
#include <iostream>
using namespace std;
int main(void)
{
// circumference = 2*PI*radius
circumference = TWO * PI * radius;
// circle circumference
cout<<"\nCircumference = "<<circumference<<" meter";
// circle area
cout<<"\nCircle area = "<<area<<" square meter"<<endl;
return 0;
}
Output
Enter a radius of the circle in meter: 2
int main()
{
}
Output
Day in Julian Calendar is 2456988
int main()
{
float fahrenheit, celsius;
int main()
{
float a, b, c, x1, x2, determinant, realPart, imaginaryPart;
cout << "Enter coefficients a, b and c: ";
cin >> a >> b >> c;
determinant = b*b - 4*a*c;
if(a==0)
{
cout<<" 'a'can not be zero";
}
else
{
if (determinant > 0)
{
x1 = (-b + sqrt(determinant)) / (2*a);
x2 = (-b - sqrt(determinant)) / (2*a);
cout << "Roots are real and different." << endl;
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else if (determinant == 0)
{
cout << "Roots are real and same." << endl;
x1 = (-b + sqrt(determinant)) / (2*a);
cout << "x1 = x2 =" << x1 << endl;
}
else
{
realPart = -b/(2*a);
imaginaryPart =sqrt(-determinant)/(2*a);
cout << "Roots are complex and different." << endl;
cout << "x1 = " << realPart << "+" << imaginaryPart << "i"
<< endl;
cout << "x2 = " << realPart << "-" << imaginaryPart << "i"
<< endl;
}
return 0;
}
}
Output
Enter coefficients a, b and c: 4 2 3
Roots are complex and different.
x1 = -0.25+0.829156i
x2 = -0.25-0.829156i
Area of Triangle
#include<iostream>
#include<math.h>
int main()
{
float base,height;
float area;
class Mathematics
{
int a, b;
public:
void input()
{
cout << "Input a:\n";
cin >> a;
cout << "Input b:\n\n";
cin >> b;
}
void add()
{
cout << "(a+b)^2 = " << ((a*a)+(2*a*b)+(b*b));
}
};
int main()
{
Mathematics m; // Creating object of class
m.input();
m.add();
return 0;
}
Output
Input a:8 Input b:10 (a+b)^2 = 324
Body Mass Intake (BMI)
#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
int main()
{
float weight;
float height;
float bmi;
char response;
do
{
cout<<"Please enter your weight (pounds): ";
cin>>weight;
cout<<"Please enter your height (inches): ";
cin>>height;
bmi = (weight / pow(height, 2)) * 703;
cout<<"\n";
cout<<fixed<<showpoint<<setprecision(2);
cout<<"Your BMI is "<<bmi<<endl;
cin.get();
cout<<endl;
return 0;
}
OUTPUT
Please enter your weight (pounds):100 Please enter your height (inches):67 Your BMI is
15.66 You are underweight! Eat more!! Would you like to enter the information again?
Find Radius of a Circle using Area
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int area;
cout<<"enter area of circle : ";
cin>>area;
cout<<"\n";
double radius=sqrt(area/3.14);
int main()
{
int num, tempnum;
tempnum = sqrt(num);
if(tempnum*tempnum==num)
{
cout<<"YES,its perfect square of : "<<sqrt(num);
}
else
{
cout<<"NO,its not perfect square";
}
return 0;
}
Output
Enter a number: 9
YES,its perfect square of : 3
Compound Interest
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float PA,R,Time,CI;
cout<<"Enter Principal amount : ";
cin>>PA;
cout<<"\n";
cout<<"enter rate : ";
cin>>R;
cout<<"\n";
cout<<"enter time(in year) : ";
cin>>Time;
cout<<"\n";
return 0;
}
Output
Enter Principal amount : 400 enter rate : 7 enter time(in year) : 1 Compound Interest is :
28
Simple Interest
#include<iostream>
using namespace std;
int main()
{
float p,r,t,i;
return 0;
}
Output
Enter Principle : 400 Enter Rate : 7 Enter Time(in years) : 2 Simple interest is : 56
(a-b)^2
#include <iostream>
class Mathematics
{
int a, b;
public:
void input()
{
cout << "Input a:\n";
cin >> a;
cout << "Input b:\n\n";
cin >> b;
}
void add()
{
cout << "(a-b)^2 = " << ((a*a)-(2*a*b)+(b*b));
}
};
int main()
{
Mathematics m; // Creating object of class
m.input();
m.add();
return 0;
}
Output
Input a: 50 Input b: 10 (a-b)^2 = 1600
Convert Hexadecimal to Decimal
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int num;
return 0;
}
Output
Enter Hexadecimal Number : fffh Decimal number for given hexadecimal number is :
4095
GCD and LCM
#include<iostream>
int main()
{
//variable declaration
int num1, num2, gcd = 1;
int main()
{
//variable declaration
float meter, cmeter, kmeter;
//user input
cout << "\nEnter length in centimeters : ";
cin >> cmeter;
return 0;
}
Output
Length in Meter : 1
Length in Kilometer : 0.001
Square and Cube Root
#include <iostream>
#include <cmath>
int main()
{
//variable declaration
int number;
return 0;
}
Output
Enter number : 27 square root of 27 is 5.19615 cube root of 27 is 3
Volume of box
#include <iostream>
int main()
{
double length;
double width;
double height;
double volume;
return 0;
}
Output
Please Enter a Length for your box:2
int main()
{
int i, j, rows;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
cout << "* ";
}
cout << "\n";
}
return 0;
}
Output
Enter the number of rows: 6
*
* *
* * *
* * * *
* * * * *
* * * * * *
Half Pyramid with Numbers
#include <iostream>
int main()
{
int i, j, rows;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
cout << j << " ";
}
cout << "\n";
}
return 0;
}
Output
Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Half Pyramid with Characters
#include <iostream>
using namespace std;
int main()
{
int i, j;
char input, temp = 'A';
cout << "Enter uppercase character you want in triange at last row:
";
cin >> input;
for (i = 1; i <= (input - 'A' + 1); ++i)
{
for (j = 1; j <= i; ++j)
cout << temp << " ";
++temp;
cout << endl;
}
return 0;
}
Output
Enter uppercase character you want in triange at last row: E
A
B B
C C C
D D D D
E E E E E
Pyramid of Digits
#include <iostream>
int main()
{
int i, space, rows, k = 0, count = 0, count1 = 0;
cout << "Enter the number of rows: ";
cin >> rows;
for (i = 1; i <= rows; ++i)
{
for (space = 1; space <= rows - i; ++space)
{
cout << " ";
++count;
}
while (k != 2 * i - 1)
{
if (count <= rows - 1)
{
cout << i + k << " ";
++count;
}
else
{
++count1;
cout << i + k - 2 * count1 << " ";
}
++k;
}
count1 = count = k = 0;
cout << "\n";
}
return 0;
}
Output
Enter the number of rows: 5
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
Floyd's Triangle
#include <iostream>
int main()
{
int rows, i, j, k = 0;
cout << "Enter number of rows: ";
cin >> rows;
for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; ++j)
cout << k + j << " ";
++k;
cout << endl;
}
return 0;
}
OUTPUT
Enter number of rows: 5
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
Pascal's triangle
#include <iostream>
#include <string>
void PascalsTriangle(int);
int main()
{
int n;
cout << "Enter the number of rows you would like to print for
Pascal's Triangle: ";
cin >> n;
cout << endl;
PascalsTriangle(n);
return 0;
}
int numdigits(int x)
{
int count = 0;
while (x != 0)
{
x = x / 10;
++count;
}
return count;
}
void PascalsTriangle(int n)
{
int i, j, x, y, maxlen;
string len;
for (i = 0; i < n; i++)
{
x = 1;
len = string((n - i - 1) * (n / 2), ' ');
cout << len;
for (j = 0; j <= i; j++)
{
y = x;
x = x * (i - j) / (j + 1);
maxlen = numdigits(x) - 1;
if (n % 2 == 0)
cout << y << string(n - 1 - maxlen, ' ');
else
{
cout << y << string(n - 2 - maxlen, ' ');
}
}
cout << endl;
}
}
OUTPUT
Enter the number of rows you would like to print for Pascal's Triangle:
5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Triangle with only Border
#include <iostream>
int main()
{
int length = 12;
drawTriangle('*', ' ', length);
return 0;
}
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* * * * * * * * * * * *
Diamond Pattern
#include <iostream>
using namespace std;
int main()
{
int i, j, k, n;
cout << "Enter the number of lines to be printed: ";
cin >> n;
int main()
{
int i, n, j;
int main()
{
//variable declaration
int i, j, rows;
int main()
{
//variable declaration
int x, y, n;
char ch;
cout << "Number of rows : ";
cin >> n;
Number of rows : 9
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
Number Pattern 2
#include<stdio.h>
#include<iostream>
int main()
{
//variable declaration
int i, j, k, rows;
k = 1;
int main()
{
if (n == p)
{
cout << "\nEnter first matrix:\n";
for (i = 0; i < m; ++i)
for (j = 0; j < n; ++j)
cin >> a[i][j];
return 0;
}
Output
Enter rows and columns of first matrix: 2
3
Enter rows and columns of second matrix: 3
2
2
3
4
5
6
int main()
{
// an array with 5 rows and 2 columns.
int a[5][2] = {{0, 0},
{1, 2},
{2, 4},
{3, 6},
{4, 8}};
return 0;
}
Output
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
Array Initialization
int main()
{
//If the size is omitted, the compiler uses the number of values
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// No intitialization.
float p1[1000];
//To initialize an array to all zeros, initialize only the first
value.
// All 1000 values initialized to zero.
float p2[1000] = {0.0};
return 0;
}
Output
Matrix Addition
#include<iostream>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
cout << "Enter the number of rows and columns of matrix : ";
cin >> m >> n;
cout << "Enter the elements of first matrix : \n";
return 0;
}
Output
Enter the number of rows and columns of matrix : 2 2
Enter the elements of first matrix :
8 1
2 3
Enter the elements of second matrix :
4 9
5 2
Sum of entered matrices:-
12 10
7 5
Matrix Subtraction
#include<iostream>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sub[10][10];
cout << "Enter the number of rows and columns of matrix : ";
cin >> m >> n;
cout << "Enter the elements of first matrix : \n";
class Demo
{
int x;
public:
void setX(int i)
{
x = i;
}
int getX()
{
return x;
}
};
int main()
{
Demo obj[4];
int i;
int main()
{
int i, j, k, n;
float a[10][10] = {0}, d;
return 0;
}
Output
Enter the order of matrix : 3
Enter the elements :
4
2
7
5
1
8
9
4
7
Augmented :
9 4 7 0 0 1
4 2 7 1 0 0
5 1 8 0 1 0
Inverse Matrix :
-0.490196 0.27451 0.176471
0.72549 -0.686274 0.0588236
0.215686 0.0392157 -0.117647
Stack using Array
#include <stdio.h>
#include<iostream>
if (top == -1)
{
cout << "empty";
}
else
{
for (i = top; i >= 0; --i)
cout << stack[i] << "\t";
}
cout << "\n";
}
// main method
int main()
{
int stack[MAX], item;
int ch;
top = -1;
do
{
do
{
cout << "\n\nEnter your choice : ";
cin >> ch;
switch (ch)
{
case 1:
cout << "enter element you want to push :";
cin >> item;
cout << item;
push(stack, item);
if (state)
{
cout << "\n after push operation";
showstack(stack);
else
cout << "stack overflow";
break;
case 2:
item = pop(stack);
if (state)
{
cout << "poped item is :" << item << "\n after pop operation";
showstack(stack);
}
else
cout << "stack underflow";
break;
default:
cout << "Exit... ";
return 0;
}
OUTPUT
Select one choice from following Menu :
int main()
{
int numarr[100],evenarr[100],i,j=0,k=0,num;
for(i=0; i<num;i++)
{
if(numarr[i]%2==0)
{
evenarr[j]=numarr[i];
j++;
}
}
int main()
{
#define SIZE 10
using namespace std;
int main()
{
cout << "array values :" << " 132, 520, 210, 510, 140 ,
125,52,96,55,85" << "\n";
//input array values
int array[SIZE] = {132, 520, 210, 510, 140, 125, 52, 96, 55, 85};
int main()
{
i = 1, j = 1;
if (i > n)
{
goto b;
}
}
else
{
resultarr[k] = arr2[j];
j++;
if (j > m)
{
goto a;
}
}
}
a:
// Copy the Remaining Elements of Array A to C
for (s = i; s <= n; s++)
{
k++;
resultarr[k] = arr1[s];
}
b:
// Copy the Remaining Elements of Array B to C
for (s = j; s <= m; s++)
{
k++;
resultarr[k] = arr2[s];
}
Enter Elements :
7
5
8
6
Enter No. of Elements in Second Array : 4
//method declaration
void lower_halfmatrix(int mat[10][10], int row);
return 0;
}
//method definition
void lower_halfmatrix(int mat[10][10], int row)
{
int i, j;
cout << "\n";
//method declaration
void upper_halfofmatrix(int mat[10][10], int col, int r);
int main()
{
//variable declaration
int mat[10][10], row, col, i, j;
//input for row and column
cout << "enter how many numbers of row and column you want : ";
cin >> row >> col;
//enter element into matrix
cout << "enter elements: \n";
return 0;
}
//method definition
void upper_halfofmatrix(int mat[10][10], int col, int row)
{
int i, j;
else
cout << " ";
}
int main()
{
int size;
cout << "enter size of array : ";
cin >> size;
int arra[size];
return 0;
}
Output
enter size of array : 10 enter array elements : 12 43 64 97 36 54 23 98 65 46 The biggest
number is 98 The smallest number is 12
Array Element Swapping
#include<iostream>
int main()
{
//variable declaration
int arr[100], i, temp, size;
return 0;
}
Output
enter array size : 4 enter elements in to array : 1 2 3 4 array before swaping elements : 1 2
3 4 array after swapping elements : 2 1 4 3
Identity Matrix
#include<iostream>
int main()
{
int mat[5][5], order, i, j, flag = 0;
return 0;
}
OUTPUT
Enter size of matrix : 3 Enter matrix element : 1 0 0 0 1 0 0 0 1 The given matrix is an
identity matrix.
Symmetric Matrix
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
int main()
{
int arr[10][10], i, j, size;
exit(0);
}
}
}
cout << "\n\nMatrix is symmetric";
return 0;
}
Output
Enter size of matrix : 3 Enter values in matrix : 5 6 7 6 3 2 7 2 1 Matrix is symmetric
Skew Symmetric matrix
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int arr[10][10], i, j, size;
return 0;
}
Output
int main()
{
int size;
cout << "Enter How Many Elements You Want To Insert in Array : ";
cin >> size;
int arr[size];
int c, searchelement;
int flag = 0;
return 0;
}
Output
Enter How Many Elements You Want To Insert in Array : 6 Enter array element : 1 2 3 4
5 6 Enter the number to search : 3 Element is present at location : 3
Remove Duplicates from Array
#include<stdio.h>
#include<iostream>
int main()
{
//variable declaration
int a[20], i, j, k, n;
//display new array elements and remove duplicate numbers from array
cout << "\nNew array Element are : ";
return 0;
}
Output
Enter array size : 5 Enter array 5 element : 9 7 3 6 9 Original array Elements are : 9 7 3 6
9 New array Element are : 9 7 3 6
Simple Array
#include<iostream>
int main()
{
//variable declaration
int size;
int num[size];
return 0;
}
Output
Enter how many elements you want to insert in array : 4 Enter Array elements : 1 2 3 4
Elements in array : 1 2 3 4
Spiral Matrix
#include <vector>
// for auto_ptr
#include <memory>
// for the ceil and log10 and floor functions
#include <cmath>
#include <iostream>
// for the setw function
#include <iomanip>
using namespace std;
int j;
int sideLen = dimension;
int currNum = 0;
// do right side
for (j = 1; j < sideLen; j++)
(*spiralArrayPtr)[i + j][dimension - 1 - i] = currNum++;
// do bottom side
for (j = sideLen - 2; j > -1; j--)
(*spiralArrayPtr)[dimension - 1 - i][i + j] = currNum++;
// do left side
for (j = sideLen - 2; j > 0; j--)
(*spiralArrayPtr)[i + j][i] = currNum++;
sideLen -= 2;
}
return spiralArrayPtr;
}
size_t col;
for (size_t row = 0; row < dimension; row++)
{
for (col = 0; col < dimension; col++)
cout << setw(fieldWidth) << (*spiralArrayPtr)[row][col];
cout << endl;
}
}
int main()
{
printSpiralArray(getSpiralArray(5));
return 0;
}
Output
0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 20 7 12 11 10 9 8
Matrix transpose
#include <iostream>
int main()
{
int a[10][10], trans[10][10], r, c, i, j;
cout << "Enter rows and columns of matrix: ";
cin >> r >> c;
return 0;
}
OUTPUT
Enter rows and columns of matrix: 2 3
Enter elements of matrix:
Enter elements a11 :1
Enter elements a12 :2
Enter elements a13 :3
Enter elements a21 :4
Enter elements a22 :5
Enter elements a23 :6
Entered Matrix:
1 2 3
4 5 6
Transpose of Matrix:
1 4
2 5
3 6
Array Sum and Average
#include <iostream>
int main()
{
int n, i;
float sum = 0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
float num[n];
for (i = 0; i < n; ++i)
{
cout << endl << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
cout << endl << "Sum = " << sum;
average = sum / n;
cout << endl << "Average = " << average;
return 0;
}
Output
Enter the numbers of data: 4
1. Enter number: 5
2. Enter number: 2
3. Enter number: 9
4. Enter number: 3
Sum = 19
Average = 4.75
Sum of the array elements
#include<iostream>
int main()
{
int i, Num_arr[50], sum, num;
//Computation of total
sum = 0;
for (i = 0; i < num; i++)
{
sum = sum + Num_arr[i];
}
//Printing of total
cout << "\nSum of array element is : " << sum;
return 0;
}
Output
Enter size of array : 5
struct node
{
int info;
struct node *next;
}*start;
class single_llist
{
public:
node* create_node(int);
void insert_begin();
void insert_pos();
void insert_last();
void delete_pos();
void sort();
void search();
void update();
void reverse();
void display();
single_llist()
{
start = NULL;
}
};
main()
{
int choice, nodes, element, position, i;
single_llist sl;
start = NULL;
while (1)
{
cout<<endl<<"---------------------------------"<<endl;
cout<<endl<<"Operations on singly linked list"<<endl;
cout<<endl<<"---------------------------------"<<endl;
cout<<"1.Insert Node at beginning"<<endl;
cout<<"2.Insert node at last"<<endl;
cout<<"3.Insert node at position"<<endl;
cout<<"4.Sort Link List"<<endl;
cout<<"5.Delete a Particular Node"<<endl;
cout<<"6.Update Node Value"<<endl;
cout<<"7.Search Element"<<endl;
cout<<"8.Display Linked List"<<endl;
cout<<"9.Reverse Linked List "<<endl;
cout<<"10.Exit "<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Inserting Node at Beginning: "<<endl;
sl.insert_begin();
cout<<endl;
break;
case 2:
cout<<"Inserting Node at Last: "<<endl;
sl.insert_last();
cout<<endl;
break;
case 3:
cout<<"Inserting Node at a given position:"<<endl;
sl.insert_pos();
cout<<endl;
break;
case 4:
cout<<"Sort Link List: "<<endl;
sl.sort();
cout<<endl;
break;
case 5:
cout<<"Delete a particular node: "<<endl;
sl.delete_pos();
break;
case 6:
cout<<"Update Node Value:"<<endl;
sl.update();
cout<<endl;
break;
case 7:
cout<<"Search element in Link List: "<<endl;
sl.search();
cout<<endl;
break;
case 8:
cout<<"Display elements of link list"<<endl;
sl.display();
cout<<endl;
break;
case 9:
cout<<"Reverse elements of Link List"<<endl;
sl.reverse();
cout<<endl;
break;
case 10:
cout<<"Exiting..."<<endl;
exit(1);
break;
default:
cout<<"Wrong choice"<<endl;
}
}
}
{
struct node *temp, *s;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
}
else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}
void single_llist::insert_begin()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *p;
temp = create_node(value);
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
p = start;
start = temp;
start->next = p;
}
cout<<"Element Inserted at beginning"<<endl;
}
void single_llist::insert_last()
{
int value;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s;
temp = create_node(value);
s = start;
while (s->next != NULL)
{
s = s->next;
}
temp->next = NULL;
s->next = temp;
cout<<"Element Inserted at last"<<endl;
}
void single_llist::insert_pos()
{
int value, pos, counter = 0;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s, *ptr;
temp = create_node(value);
cout<<"Enter the postion at which node to be inserted: ";
cin>>pos;
int i;
s = start;
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos == 1)
{
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
}
else if (pos > 1 && pos <= counter)
{
s = start;
for (i = 1; i < pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
else
{
cout<<"Positon out of range"<<endl;
}
}
void single_llist::sort()
{
struct node *ptr, *s;
int value;
if (start == NULL)
{
cout<<"The List is empty"<<endl;
return;
}
ptr = start;
while (ptr != NULL)
{
for (s = ptr->next;s !=NULL;s = s->next)
{
if (ptr->info > s->info)
{
value = ptr->info;
ptr->info = s->info;
s->info = value;
}
}
ptr = ptr->next;
}
}
void single_llist::delete_pos()
{
int pos, i, counter = 0;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the position of value to be deleted: ";
cin>>pos;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{
while (s != NULL)
{
s = s->next;
counter++;
}
if (pos > 0 && pos <= counter)
{
s = start;
for (i = 1;i < pos;i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
else
{
cout<<"Position out of range"<<endl;
}
free(s);
cout<<"Element Deleted"<<endl;
}
}
void single_llist::update()
{
int value, pos, i;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the node postion to be updated: ";
cin>>pos;
cout<<"Enter the new value: ";
cin>>value;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start->info = value;
}
else
{
for (i = 0;i < pos - 1;i++)
{
if (s == NULL)
{
cout<<"There are less than "<<pos<<" elements";
return;
}
s = s->next;
}
s->info = value;
}
cout<<"Node Updated"<<endl;
void single_llist::search()
{
int value, pos = 0;
bool flag = false;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the value to be searched: ";
cin>>value;
struct node *s;
s = start;
while (s != NULL)
{
pos++;
if (s->info == value)
{
flag = true;
cout<<"Element "<<value<<" is found at position "<<pos<<endl;
}
s = s->next;
}
if (!flag)
cout<<"Element "<<value<<" not found in the list"<<endl;
}
void single_llist::reverse()
{
struct node *ptr1, *ptr2, *ptr3;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
if (start->next == NULL)
{
return;
}
ptr1 = start;
ptr2 = ptr1->next;
ptr3 = ptr2->next;
ptr1->next = NULL;
ptr2->next = ptr1;
while (ptr3 != NULL)
{
ptr1 = ptr2;
ptr2 = ptr3;
ptr3 = ptr3->next;
ptr2->next = ptr1;
}
start = ptr2;
}
void single_llist::display()
{
struct node *temp;
if (start == NULL)
{
cout<<"The List is Empty"<<endl;
return;
}
temp = start;
cout<<"Elements of list are: "<<endl;
while (temp != NULL)
{
cout<<temp->info<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
Output
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
The List is Empty.
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 5
Delete a particular node:
List is empty
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 6
Update Node Value:
List is empty
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 7
Search element in Link List:
List is empty
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 3
Inserting Node at a given position:
Enter the value to be inserted: 1010
Enter the postion at which node to be inserted: 5
Positon out of range
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 1
Inserting Node at Beginning:
Enter the value to be inserted: 100
Element Inserted at beginning
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 1
Inserting Node at Beginning:
Enter the value to be inserted: 200
Element Inserted at beginning
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
200->100->NULL
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 2
Inserting node at last:
Enter the value to be inserted: 50
Element Inserted at last
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 2
Inserting node at last:
Enter the value to be inserted: 150
Element Inserted at last
---------------------------------
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 3
Inserting node at a given position:
Enter the value to be inserted: 1111
Enter the position at which node to be inserted: 4
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
200->100->50->1111->150->NULL
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 3
Inserting node at a given position:
Enter the value to be inserted: 1010
Enter the position at which node to be inserted: 100
Position out of range
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
200->100->50->1111->150->NULL
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 5
Delete a Particular node:
Enter the position of value to be deleted: 1
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
100->50->1111->150->NULL
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 6
Update Node Value:
Enter the node position to be updated: 1
Enter the new value: 1010
Node Updated
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
1010->50->1111->150->NULL
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 7
Search element in Link List:
Enter the value to be searched: 50
Element 50 is found at position 2
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 9
Reverse elements of Link List
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
150->1111->50->1010->NULL
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 4
Sort Link List:
---------------------------------
---------------------------------
1.Insert Node at beginning
2.Insert node at last
3.Insert node at position
4.Sort Link List
5.Delete a Particular Node
6.Update Node Value
7.Search Element
8.Display Linked List
9.Reverse Linked List
10.Exit
Enter your choice : 8
Display elements of link list
Elements of list are:
50->150->1010->1111->NULL
---------------------------------
// Node Declaration
struct node
{
int info;
struct node *next;
struct node *prev;
}*start;
class double_llist
{
public:
void create_list(int value);
void add_begin(int value);
void add_after(int value, int position);
void delete_element(int value);
void search_element(int value);
void display_dlist();
void count();
void reverse();
double_llist()
{
start = NULL;
}
};
int main()
{
int choice, element, position;
double_llist dl;
void double_llist::display_dlist()
{
struct node *q;
if (start == NULL)
{
cout<<"List empty,nothing to display"<<endl;
return;
}
q = start;
cout<<"The Doubly Link List is :"<<endl;
while (q != NULL)
{
cout<<q->info<<" <-> ";
q = q->next;
}
cout<<"NULL"<<endl;
}
void double_llist::count()
{
struct node *q = start;
int cnt = 0;
while (q != NULL)
{
q = q->next;
cnt++;
}
cout<<"Number of elements are: "<<cnt<<endl;
}
void double_llist::reverse()
{
struct node *p1, *p2;
p1 = start;
p2 = p1->next;
p1->next = NULL;
p1->prev = p2;
while (p2 != NULL)
{
p2->prev = p2->next;
p2->next = p1;
p1 = p2;
p2 = p2->prev;
}
start = p1;
cout<<"List Reversed"<<endl;
}
Output
Operations on Doubly linked list 1.Create Node 2.Add at begining 3.Add after position
4.Delete 5.Display 6.Count 7.Reverse 8.Quit Enter your choice : 1 Enter the element: 5
Enter your choice : 5 The Doubly Link List is : 5 <-> NULL Enter your choice : 1 Enter
the element: 8 Enter your choice : 5 The Doubly Link List is : 5 <-> 8 <-> NULL Enter
your choice : 1 Enter the element: 9 Enter your choice : 5 The Doubly Link List is : 5 <->
8 <-> 9 <-> NULL Enter your choice : 2 Enter the element: 5 Element Inserted Enter
your choice : 5 The Doubly Link List is : 5 <-> 5 <-> 8 <-> 9 <-> NULL Enter your
choice : 3 Enter the element: 4 Insert Element after postion: 2 Element Inserted Enter
your choice : 5 The Doubly Link List is : 5 <-> 5 <-> 4 <-> 8 <-> 9 <-> NULL Enter
your choice : 4 Enter the element for deletion: 8 Element Deleted Enter your choice : 5
The Doubly Link List is : 5 <-> 5 <-> 4 <-> 9 <-> NULL Enter your choice : 6 Number
of elements are: 4 Enter your choice : 7 List Reversed Enter your choice : 5 The Doubly
Link List is : 9 <-> 4 <-> 5 <-> 5 <-> NULL Enter your choice : 8
template<class T>
class Queue
{
private:
int front, rear;
T *queue;
int maxsize;
public:
Queue(int maxqueuesize)
{
front = 0;
rear = -1;
maxsize = maxqueuesize;
queue = new T[maxsize];
}
~Queue()
{
delete[] queue;
}
int isempty();
int isfull();
void insert();
void deletion();
void atfront();
void atrear();
void display();
};
template<class T>
int Queue<T>::isempty()
{
if (front == 0 && rear == -1 || front == rear)
return 1;
else
return 0;
}
template<class T>
int Queue<T>::isfull()
{
if (rear == maxsize - 1)
return 1;
else
return 0;
}
template<class T>
void Queue<T>::atfront()
{
if (isempty())
cout << "\nSorry the queue is empty!";
else
cout << "\nFront element of the queue is : " << queue[front];
}
template<class T>
void Queue<T>::atrear()
{
if (isempty())
cout << "\nSorry the queue is empty!";
else
cout << "\nRear element of the queue is : " << queue[rear];
}
template<class T>
void Queue<T>::insert()
{
T ele;
if (isfull())
cout << "\nSorry the queue is full!";
else
{
cout << "\nEnter the element to insert : ";
cin >> ele;
queue[++rear] = ele;
}
}
template<class T>
void Queue<T>::deletion()
{
if (isempty())
cout << "\nSorry the queue is empty!";
else
cout << "\nDeleted element of the queue is : " << queue[front+
+];
}
template<class T>
void Queue<T>::display()
{
if (isempty())
cout << "\nSorry the queue is empty!";
else
{
cout << "\nQueue elements are : ";
for (int i = front; i <= rear; i++)
{
cout << "\t" << queue[i];
}
}
}
int main()
{
int ch;
Queue<int> q(10);
cout <<
"\n 1.Insertion \n 2.Deletion \n 3.Display Front Element \n
4.Display Rear Element \n 5.Display Queue \n 6.Exit \n";
do
{
cout << "\nEnter your Choice:";
cin >> ch;
switch (ch)
{
case 1:
q.insert();
break;
case 2:
q.deletion();
break;
case 3:
q.atfront();
break;
case 4:
q.atrear();
break;
case 5:
q.display();
break;
case 6:
break;
default:
cout << "\nWrong Choice Entered!";
}
} while (ch <= 5);
return 0;
}
Output
1.Insertion 2.Deletion 3.Display Front Element 4.Display Rear Element 5.Display Queue
6.Exit Enter your Choice:1 Enter the element to insert : 10 Enter your Choice:1 Enter the
element to insert : 20 Enter your Choice:1 Enter the element to insert : 30 Enter your
Choice:1 Enter the element to insert : 40 Enter your Choice:1 Enter the element to insert :
50 Enter your Choice:5 Queue elements are : 10 20 30 40 50 Enter your Choice:2 Deleted
element of the queue is : 10 Enter your Choice:3 Front element of the queue is : 20 Enter
your Choice:4 Rear element of the queue is : 50 Enter your Choice:2 Deleted element of
the queue is : 20 Enter your Choice:2 Deleted element of the queue is : 30 Enter your
Choice:6
Circular Queue
#include <iostream>
#define MAX 5
using namespace std;
class Circular_Queue
{
private:
int *cqueue_arr;
int front, rear;
public:
Circular_Queue()
{
cqueue_arr = new int[MAX];
rear = front = -1;
}
void del()
{
if (front == -1)
{
cout << "Queue Underflow\n";
return;
}
cout << "Element deleted from queue is : " << cqueue_arr[front]
<< endl;
if (front == rear)
{
front = -1;
rear = -1;
}
else
{
if (front == MAX - 1)
front = 0;
else
front = front + 1;
}
}
void display()
{
int front_pos = front, rear_pos = rear;
if (front == -1)
{
cout << "Queue is empty\n";
return;
}
cout << "Queue elements :\n";
if (front_pos <= rear_pos)
{
while (front_pos <= rear_pos)
{
cout << cqueue_arr[front_pos] << " ";
front_pos++;
}
}
else
{
while (front_pos <= MAX - 1)
{
cout << cqueue_arr[front_pos] << " ";
front_pos++;
}
front_pos = 0;
while (front_pos <= rear_pos)
{
cout << cqueue_arr[front_pos] << " ";
front_pos++;
}
}
cout << endl;
}
};
int main()
{
int choice, item;
Circular_Queue cq;
cout << "1.Insert\n";
cout << "2.Delete\n";
cout << "3.Display\n";
cout << "4.Quit\n";
do
{
cout << "\nEnter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Input the element for insertion in queue : ";
cin >> item;
cq.insert(item);
break;
case 2:
cq.del();
break;
case 3:
cq.display();
break;
case 4:
break;
default:
cout << "Wrong choice\n";
}
}
while (choice != 4);
return 0;
}
Output
1.Insert
2.Delete
3.Display
4.Quit
struct node {
int info;
struct node *link;
} *top;
class stack_list {
public:
node *push(node *, int);
stack_list()
{
top = NULL;
}
};
int main()
{
int choice, item;
stack_list sl;
-------------
1.Push Element into the Stack
2.Pop Element from the Stack
3.Traverse the Stack
4.Quit
int main()
{
int a[100], i, n, item, s = 0;
cout << "\n------------ LINEAR SEARCH ------------ \n\n";
cout << "Enter No. of Elements=";
cin >> n;
if (s == 0)
{
cout << "Data is Not Found";
}
return 0;
}
Output
Enter Elements=
1
8
4
7
6
int main()
{
int a[100], n, i, beg, end, mid, item;
cout << "\n------------ BINARY SEARCH ------------ \n\n";
cout << "Enter No. of Elements= ";
cin >> n;
beg = 1;
end = n;
if (a[mid] == item)
{
cout << "\nElement found at location : " << mid;
}
else
{
cout << "Element not found";
}
return 0;
}
Output
------------ BINARY SEARCH ------------ Enter No. of Elements= 5 Enter Elements in
Sorted Order= 10 20 30 40 50 Enter Item you want to Search= 40 Element found at
location : 4
Priority Queue
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
class Priority_Queue {
private:
node *front;
public:
Priority_Queue()
{
front = NULL;
}
void del()
{
node *tmp;
if (front == NULL)
cout << "Queue Underflow\n";
else
{
tmp = front;
cout << "Deleted item is: " << tmp->info << endl;
front = front->link;
free(tmp);
}
}
void display()
{
node *ptr;
ptr = front;
if (front == NULL)
cout << "Queue is empty\n";
else
{
cout << "Queue is :\n";
cout << "Priority Item\n";
while (ptr != NULL)
{
cout << ptr->priority << " " << ptr-
>info << endl;
ptr = ptr->link;
}
}
}
};
int main()
{
int choice, item, priority;
Priority_Queue pq;
cout << "1.Insert\n";
cout << "2.Delete\n";
cout << "3.Display\n";
cout << "4.Quit\n";
do
{
cout << "\nEnter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Input the item value to be added in the queue :
";
cin >> item;
cout << "Enter its priority : ";
cin >> priority;
pq.insert(item, priority);
break;
case 2:
pq.del();
break;
case 3:
pq.display();
break;
case 4:
break;
default :
cout << "Wrong choice\n";
}
}
while (choice != 4);
return 0;
}
Output
1.Insert
2.Delete
3.Display
4.Quit
class BinarySearchTree {
private:
struct tree_node {
tree_node *left;
tree_node *right;
int data;
};
tree_node *root;
public:
BinarySearchTree()
{
root = NULL;
}
void print_inorder();
void print_preorder();
void print_postorder();
void insert(int);
void remove(int);
};
void BinarySearchTree::remove(int d)
{
//Locate the element
bool found = false;
if (isEmpty())
{
cout << " This Tree is empty! " << endl;
return;
}
tree_node *curr;
tree_node *parent;
curr = root;
while (curr != NULL)
{
if (curr->data == d)
{
found = true;
break;
}
else
{
parent = curr;
if (d > curr->data) curr = curr->right;
else curr = curr->left;
}
}
if (!found)
{
cout << " Data not found! " << endl;
return;
}
// 3 cases :
// 1. We're removing a leaf node
// 2. We're removing a node with a single child
// 3. we're removing a node with 2 children
if ((curr->right)->left != NULL)
{
tree_node *lcurr;
tree_node *lcurrp;
lcurrp = curr->right;
lcurr = (curr->right)->left;
while (lcurr->left != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
curr->data = lcurr->data;
delete lcurr;
lcurrp->left = NULL;
}
else
{
tree_node *tmp;
tmp = curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
delete tmp;
}
}
return;
}
void BinarySearchTree::print_inorder()
{
inorder(root);
}
void BinarySearchTree::print_preorder()
{
preorder(root);
}
void BinarySearchTree::print_postorder()
{
postorder(root);
}
int main()
{
BinarySearchTree b;
int ch, tmp, tmp1;
cout << " Binary Search Tree Operations " << endl;
cout << " ----------------------------- " << endl;
cout << " 1. Insertion/Creation " << endl;
cout << " 2. In-Order Traversal " << endl;
cout << " 3. Pre-Order Traversal " << endl;
cout << " 4. Post-Order Traversal " << endl;
cout << " 5. Removal " << endl;
cout << " 6. Exit " << endl;
while (1)
{
cout << " Enter your choice : ";
cin >> ch;
switch (ch)
{
case 1 :
cout << " Enter Number to be inserted : ";
cin >> tmp;
b.insert(tmp);
break;
case 2 :
cout << endl;
cout << " In-Order Traversal " << endl;
cout << " -------------------" << endl;
b.print_inorder();
break;
case 3 :
cout << endl;
cout << " Pre-Order Traversal " << endl;
cout << " -------------------" << endl;
b.print_preorder();
break;
case 4 :
cout << endl;
cout << " Post-Order Traversal " << endl;
cout << " --------------------" << endl;
b.print_postorder();
break;
case 5 :
cout << " Enter data to be deleted : ";
cin >> tmp1;
b.remove(tmp1);
break;
case 6 :
return 0;
}
}
}
OUTPUT
Binary Search Tree Operations ----------------------------- 1. Insertion/Creation 2. In-Order
Traversal 3. Pre-Order Traversal 4. Post-Order Traversal 5. Removal 6. Exit Enter your
choice : 1 Enter Number to be inserted : 4 Binary Search Tree Operations
----------------------------- 1. Insertion/Creation 2. In-Order Traversal 3. Pre-Order
Traversal 4. Post-Order Traversal 5. Removal 6. Exit Enter your choice : 1 Enter Number
to be inserted : 5 Binary Search Tree Operations ----------------------------- 1.
Insertion/Creation 2. In-Order Traversal 3. Pre-Order Traversal 4. Post-Order Traversal 5.
Removal 6. Exit Enter your choice : 1 Enter Number to be inserted : 6 Binary Search Tree
Operations ----------------------------- 1. Insertion/Creation 2. In-Order Traversal 3. Pre-
Order Traversal 4. Post-Order Traversal 5. Removal 6. Exit Enter your choice : 2 In-
Order Traversal ------------------- 4 5 6 Binary Search Tree Operations
----------------------------- 1. Insertion/Creation 2. In-Order Traversal 3. Pre-Order
Traversal 4. Post-Order Traversal 5. Removal 6. Exit Enter your choice : 5 Enter data to
be deleted : 5 Binary Search Tree Operations ----------------------------- 1.
Insertion/Creation 2. In-Order Traversal 3. Pre-Order Traversal 4. Post-Order Traversal 5.
Removal 6. Exit Enter your choice : 2 In-Order Traversal ------------------- 4 6 Binary
Search Tree Operations ----------------------------- 1. Insertion/Creation 2. In-Order
Traversal 3. Pre-Order Traversal 4. Post-Order Traversal 5. Removal 6. Exit Enter your
choice : 6 Press any key to continue . . .
Heap Sort
#include <iostream>
int main()
{
int n, i, x;
cout << "Enter no of elements of array : ";
cin >> n;
int a[20];
for (i = 1; i <= n; i++)
{
cout << "Enter element " << (i) << " : ";
cin >> a[i];
}
build_maxheap(a, n);
heapsort(a, n);
cout << "Heap Sort Output" << endl;
for (i = 1; i <= n; i++)
{
cout << a[i] << endl;
}
return 0;
}
Output
Enter no of elements of array : 5
Enter element 1 : 6
Enter element 2 : 2
Enter element 3 : 1
Enter element 4 : 8
Enter element 5 : 3
Heap Sort Output
1
2
3
6
8
Insertion Sort
#include <iostream>
int main()
{
int a[100], n, i, j, k, temp;
cout << "Enter no of element of array : ";
cin >> n;
for (i = 1; i <= n; i++)
{
cout << "Enter " << i << " element : ";
cin >> a[i];
}
for (i = 1; i <= n; i++)
{
for (j = i; j >= 1; j--)
{
if (a[j] < a[j - 1])
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
else
break;
}
}
return 0;
}
Output
Enter no of element of array : 5
Enter 1 element : 1
Enter 2 element : 6
Enter 3 element : 7
Enter 4 element : 4
Enter 5 element : 3
Insertion Sort Output
1
3
4
6
7
Queue using Stack
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void push1(int);
void push2(int);
int pop1();
int pop2();
void enqueue();
void dequeue();
void display();
void create();
int main()
{
int ch;
switch (ch)
{
case 1:
enqueue();
break;
case 2:
display();
break;
case 3:
exit(0);
default:
cout<<"wrong choice";
}
}
}
/*Function to create a queue*/
void create()
{
top1 = top2 = -1;
}
int pop2()
{
return(st2[top2--]);
}
void display()
{
int i;
}
}
Output
1-enter element into queue 2-display elements 3-exit from execution enter your choice :1
enter data into queue :4 enter your choice :1 enter data into queue :2 enter your choice :1
enter data into queue :5 enter your choice :2 4 2 5 enter your choice :3
dequeue
#include <iostream>
class DequeEmptyException {
public:
DequeEmptyException()
{
cout << "Deque empty" << endl;
}
};
class Node {
public:
int data;
Node *next;
Node *prev;
};
class Deque {
private:
Node *front;
Node *rear;
int count;
public:
Deque()
{
front = NULL;
rear = NULL;
count = 0;
}
if (isEmpty())
{
// Add the first element
front = rear = tmp;
}
else
{
// Prepend to the list and fix links
tmp->next = front;
front->prev = tmp;
front = tmp;
}
count++;
}
int RemoveFront()
{
if (isEmpty())
{
throw new DequeEmptyException();
}
return ret;
}
if (isEmpty())
{
// Add the first element
front = rear = tmp;
}
else
{
// Append to the list and fix links
rear->next = tmp;
tmp->prev = rear;
rear = tmp;
}
count++;
}
int RemoveBack()
{
if (isEmpty())
{
throw new DequeEmptyException();
}
return ret;
}
int Front()
{
if (isEmpty())
throw new DequeEmptyException();
return front->data;
}
int Back()
{
if (isEmpty())
throw new DequeEmptyException();
return rear->data;
}
int Size()
{
return count;
}
bool isEmpty()
{
return count == 0 ? true : false;
}
};
int main()
{
// Stack behavior using a general dequeue
Deque qu;
try
{
if (qu.isEmpty())
{
cout << "Deque is empty" << endl;
}
// Push elements
qu.InsertBack(1500);
qu.InsertBack(2020);
qu.InsertBack(1300);
qu.InsertBack(100);
qu.InsertBack(900);
qu.InsertBack(10);
// Size of queue
cout << "Size of dequeue = " << qu.Size() << endl;
// Pop elements
cout << qu.RemoveBack() << endl;
cout << qu.RemoveBack() << endl;
cout << qu.RemoveBack() << endl;
}
catch (...)
{
cout << "Some exception occured" << endl;
}
// Push elements
dq1.InsertBack(4100);
dq1.InsertBack(2400);
dq1.InsertBack(3050);
dq1.InsertBack(100);
dq1.InsertBack(900);
dq1.InsertBack(10);
// Size of queue
cout << "Size of dequeue = " << dq1.Size() << endl;
// Pop elements
cout << dq1.RemoveFront() << endl;
cout << dq1.RemoveFront() << endl;
cout << dq1.RemoveFront() << endl;
}
catch (...)
{
cout << "Some exception occured" << endl;
}
return 0;
}
Output
Deque is empty Size of dequeue = 6 10 900 100 Deque is empty Size of dequeue = 6
4100 2400 3050
Minimum Spanning Tree
#include <iostream>
struct node {
int fr, to, cost;
} p[6];
int main()
{
int a[7];
for (int i = 0; i < 7; i++)
{
a[i] = 0;
}
int b[7][7];
for (int i = 0; i < 7; i++)
{
cout << "enter values for " << (i + 1) << " row : " << endl;
for (int j = 0; j < 7; j++)
{
cin >> b[i][j];
}
}
primsalgo(a, b, 0, 0);
return 0;
}
Output
class nodecreation {
public:
int data;
public:
dqueueoperation()
{
top1 = 0;
top2 = 0;
head = NULL;
tail = NULL;
}
void push(int x)
{
nodecreation *temp;
int ch;
if (top1 + top2 >= 5)
{
cout << "\ndqueue overflow!!!";
return;
}
if (top1 + top2 == 0)
{
head = new nodecreation;
head->data = x;
head->next = NULL;
head->prev = NULL;
tail = head;
top1++;
}
else
{
cout << "\nAdd element 1.FIRST 2.LAST\nEnter your choice :
";
cin >> ch;
if (ch == 1)
{
top1++;
temp = new nodecreation;
temp->data = x;
temp->next = head;
temp->prev = NULL;
head->prev = temp;
head = temp;
}
else
{
top2++;
temp = new nodecreation;
temp->data = x;
temp->next = NULL;
temp->prev = tail;
tail->next = temp;
tail = temp;
}
}
}
void pop()
{
int ch;
cout << "\nDelete \n1.First Node \n2.Last Node\nEnter your
choice : ";
cin >> ch;
if (top1 + top2 <= 0)
{
cout << "\nDqueue under flow!!!!";
return;
}
if (ch == 1)
{
head = head->next;
head->prev = NULL;
top1--;
}
else
{
top2--;
tail = tail->prev;
tail->next = NULL;
}
}
void display()
{
int ch;
nodecreation *temp;
cout << "\nDisplay from \n1.Staring \n2.Ending \nEnter your
choice : ";
cin >> ch;
if (top1 + top2 <= 0)
{
cout << "\nunder flow";
return;
}
if (ch == 1)
{
temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
else
{
temp = tail;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->prev;
}
}
}
};
int main()
{
dqueueoperation d1;
int ch;
cout << "Enter Dequeue Operation you want to perform" << endl;
cout << "1. Insert" << endl;
cout << "2. Delete" << endl;
cout << "3. Display" << endl;
cout << "4. Exit" << endl;
while (1)
{
case 2:
d1.pop();
break;
case 3:
d1.display();
break;
case 4:
return 0;
}
}
}
Output
Enter Dequeue Operation you want to perform
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice : 1
Enter element : 12
Enter your choice : 1
Enter element : 23
Enter element : 45
Delete
1.First Node
2.Last Node
Enter your choice : 1
Enter your choice : 3
Display from
1.Staring
2.Ending
Enter your choice : 1
12 45
Enter your choice : 4
Bubble Sort
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int alen, val;
vector<int> a;
bubble_sort(a);
int main()
{
int a[100], i, n, p, k, min, loc, temp;
return 0;
}
Output
------------ SELECTION SORT ------------ Enter No. of Elements=8 Enter Elements= 6 4
1 8 7 2 5 3 After Sorting : 1 2 3 4 5 6 7 8
Insertion Sort
#include<iostream>
using namespace std;
int main()
{
int a[100], i, n, p, ptr, temp;
a[0] = 0;
a[ptr + 1] = temp;
}
return 0;
}
Output
Enter Elements :
9
7
1
6
3
4
5
8
After Sorting :
1
3
4
5
6
7
8
9
Quick Sort
#include<iostream>
p = p + 1;
}
}
return p;
}
int main()
{
int a[100], i, n, beg, end;
After Sorting :
1
2
3
4
6
7
8
9
Merge Sort
#include <iostream>
int main()
{
int a[20], i;
cout << "Enter 5 elements to sort : \n";
for (i = 0; i < 5; i++)
{
cin >> a[i];
}
mergesort(a, 0, 4);
cout << "sorted array : \n";
for (i = 0; i < 5; i++)
{
cout << a[i] << "\t";
}
return 0;
}
Output
Enter 5 elements to sort :
9
1
5
6
7
sorted array :
1 5 6 7 9
Sorting a Matrix
#include <iostream>
#include <algorithm>
#include <vector>
struct myclass {
bool operator()(int i, int j)
{ return (i < j); }
}
myobject;
int main()
{
int arr[] = {312, 171, 152, 435, 26, 980, 353, 334};
vector<int> myvector(arr, arr + 8);
return 0;
}
Output
sorted matrix contains: 26 152 171 312 334 353 435 980
Linear Sort
#include <iostream>
class linearsort
{
int arr[MAXSIZE], n;
public:
void getdataelements();
void showdataelements();
void sortelements();
};
void linearsort::getdataelements()
{
cout << "How many elements you want : ";
cin >> n;
void linearsort::showdataelements()
{
cout << "\nDisplay sorted elements\n";
}
void linearsort::sortelements()
{
int temp;
//main method
int main()
{
cout << "\nLinear Sort Method\n\n";
linearsort obj;
obj.getdataelements();
obj.sortelements();
obj.showdataelements();
return 0;
}
Output
//Print values
void print_ar(int ar[], int size)
{
for (int i = 0; i < size; ++i)
{
cout << ar[i] << " ";
}
cout << endl;
}
int main()
{
int ar[] = {1, 4, 16, 30, 29, 18, 100, 2, 43, 1};
cout << "Intial Array : ";
print_ar(ar, 10);
shell_sort(ar, 10);
return 0;
}
Output
Intial Array : 1 4 16 30 29 18 100 2 43 1
Sorted Array : 1 1 2 4 16 18 29 30 43 100
Template Function
#include <iostream>
#include <string>
template<typename T>
inline T const &Max(T const &val1, T const &val2)
{
return val1 < val2 ? val2 : val1;
}
int main()
{
int num1 = 9;
int num2 = 210;
cout << "Max(num1, num2): " << Max(num1, num2) << endl;
return 0;
}
Output
Max(num1, num2): 210 Max(dbl1, dbl2): 210.87 Max(str1, str2): maximum here
Pass by value
#include<stdio.h>
#include<iostream>
using namespace std;
//Function prototyping
int add(int, int);
int main()
{
int num1, num2, output;
/*
Pass the value of num1 and num2 as parameter to function add.
The value returned is stored in the variable output
*/
int main()
{
int num1 = 0, num2 = 0, output;
return 0;
}
Output
cout << "add (20,10) : " << add(20, 10) << "\n";
cout << "sub (1220,200) : " << sub(1220, 200) << "\n";
cout << "multiply (100,1010) : " << mult(100, 1010) << "\n";
cout << "division (20,10) : " << div(20, 10) << "\n";
return 0;
}
Output
add (20,10) : 30
sub (1220,200) : 1020
multiply (100,1010) : 101000
division (20,10) : 2
Sort Characters in Ascending order
#include <iostream>
int main()
{
int size, i, j;
cout << "Enter the number of characters:";
cin >> size;
char chars[size];
cout << "Enter " << size << " characters:";
for (i = 0; i < size; i++)
{
cin >> chars[i];
}
char temp;
return 0;
}
Output
int main()
{
string name;
return 0;
}
Output
int main()
{
cout << "hey hello\n";
cout << "you have many letters to read in letter box\n";
//flush clears the output buffer
cout.flush();
return 0;
}
Output
hey hello
you have many letters to read in letter box
Static method and Static Variable
#include <iostream>
//class declaration
class staticDemo
{
private:
//static variable declaration
static int sum;
//normal variable declaration
int x;
public:
//Constructor of the class
staticDemo()
{
sum = sum + 1;
x = sum;
}
int staticDemo::sum = 0;
//
staticDemo stat1, stat2, stat3;
staticDemo::staticFunction();
stat.normalFunctionNumber();
//Normal member function accessed using object stat and the dot
member access operator.
stat1.normalFunctionNumber();
stat2.normalFunctionNumber();
stat3.normalFunctionNumber();
return 0;
}
Output
This is how static method and variable work : Result is : 1 Result is : 4 Number is : 1
Number is : 2 Number is : 3 Number is : 4
flush member function
#include <iostream>
#include <iomanip>
int main()
{
cout << "hey hello\n";
cout << "you have many letters to read in letter box\n";
//flush clears the output buffer
cout.flush();
return 0;
}
Output
you have many letters to read in letter box
While Loop Example
#include <iostream>
int main()
{
int i = 1;
return 0;
}
Output
value of i: 1 value of i: 2 value of i: 3 value of i: 4 value of i: 5 value of i: 6 value of i: 7
value of i: 8 value of i: 9 value of i: 10
For Loop
#include <iostream>
int main()
{
// for loop execution
for (int i = 0; i <= 10; i++)
{
cout << "value of i: " << i << endl;
}
return 0;
}
Output
value of i: 0
value of i: 1
value of i: 2
value of i: 3
value of i: 4
value of i: 5
value of i: 6
value of i: 7
value of i: 8
value of i: 9
value of i: 10
do while Loop
#include <iostream>
int main()
{
int i = 1;
do
{
cout << "value of i: " << i << endl;
i++;
}
while (i <= 10);
return 0;
}
Output
value of i: 1
value of i: 2
value of i: 3
value of i: 4
value of i: 5
value of i: 6
value of i: 7
value of i: 8
value of i: 9
value of i: 10
Vector Example
#include <iostream>
#include <vector>
int main()
{
//Vector to store integers
vector<int> vex;
cout << "added value in vector :\n";
//Checks if empty
if (!vex.empty())
{
//Clears vector
vex.clear();
}
vector<int> another_vector;
another_vector.push_back(10);
vex.push_back(10);
if (vex == another_vector)
{
vex.push_back(20);
}
int main()
{
// Local variable declaration:
int num = 10;
// do loop execution
do
{
cout << "value of number: " << num << endl;
num = num + 1;
if (num > 15)
{
// terminate the loop
break;
}
} while (num < 20);
return 0;
}
Output
value of number: 10
value of number: 11
value of number: 12
value of number: 13
value of number: 14
value of number: 15
Check if the number is Positive or Negative
#include<iostream>
int main()
{
int num;
cout << "Enter any non-zero Number : ";
cin >> num;
if (num > 0)
{
cout << "Number is positive";
}
else
{
cout << "Number is negative";
}
return 0;
}
Output
int main()
{
int num;
num = 50;
int main()
{
int var;
char var_array[10];
return 0;
}
Output
int main()
{
//variable declaration
char asciichar;
return 0;
}
Output
Enter a character : a It's ascii value is : 97
Add Two Numbers
#include<iostream>
int main()
{
//variable declaration
int num1, num2, result;
//display addition
cout << "\nAddition is : " << result;
return 0;
}
Output
int main()
{
int n1, n2;
cout << "enter two numbers for division operation : ";
cin >> n1 >> n2;
double n3 = 0;
//try catch to handle run time error
try
{
n3 = divisionby(n1, n2);
cout << n3 << endl;
}
catch (const char *msg)
{
//it will display error msg
cout << msg << endl;
}
return 0;
}
Output
enter two numbers for division operation : 9 3 answer = 3
Excetpion
//program to show how exception handling work
#include <iostream>
using namespace std;
//method definition
double divisionby(int num1, int num2)
{
if( num2 == 0 )
{
throw "Division by zero condition!";
}
cout<<"answer = ";
return (num1/num2);
}
int main ()
{
//variable declaration
int n1,n2;
return 0;
}
Output
int main()
{
//variable declaration
ofstream outfile;
ifstream infile;
char fname1[10], fname2[20];
char ch, uch;
//user Input
cout << "Enter a file name to be copied ";
cin >> fname1;
cout << "Enter new file name";
cin >> fname2;
infile.open(fname1);
if (infile.fail())
{
cerr << " No such a file Exit";
return 0;
}
outfile.open(fname2);
if (outfile.fail())
{
cerr << "Unable to create a file";
return 0;
}
while (!infile.eof())
{
ch = (char) infile.get();
uch = (char) toupper(ch);
outfile.put(uch);
}
infile.close();
outfile.close();
return 0;
}
Output
int main()
{
char data[1000];
char data[1000];
return 0;
}
Output
Reading content from the file Bhagyashree 22
Depth First Search
#include<iostream>
int main()
{
int cost[10][10], i, j, k, vertice, stk[10], top, v, visit[10],
visited[10], edge;
v = stk[--top];
cout << v << " ";
k++;
visit[v] = 0;
visited[v] = 1;
}
return 0;
}
Output
EDGES
1 2
3 4