Sie sind auf Seite 1von 217

Function Overloading Example

# include<iostream>

using namespace std;

int area(int side)


{
return side*side;
}

int area(int l , int b)


{
return l*b;
}

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";

cout<<"Invoking area(int) via p1 "<<p1(20)<<endl;


cout<<"Invoking area(int,int) via p2 "<<p2(10,20);

return 0;
}
Output
Address of area(int)=4199220
Address of area(int,int)=4199232

Invoking area(int) via p1 400


Invoking area(int,int) via p2 200
Simple Class example
# include<iostream>
# include<math.h>

using namespace std;

class point
{
int x,y,z;
public:
point()
{
x=y=z=0;
}

point(int i,int j,int k)


{
x=i;
y=j;
z=k;
}

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);

cout<<"The point has the coordinates\n";


p.print();
cout<<"The point coordinates after negation\n";

p.negate();
p.print();

cout<<"Normal Distance of the point from (0,0,0) is


\n"<<p.norm()<<"\n";
cout<<"The coordinates of the point p1 after copy constructor
is \n";
p1.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>

using namespace std;

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();

//object.variable; Will produce an error because variable is private

return 0;
}
Output
function input_value, Enter an integer 5 Variable entered is 5
Minus Operator Overloading
#include<iostream>

using namespace std;

class MinusOperatorOverloading
{
int x,y,z;

public:
void get_data(int a,int b,int c)
{
x = a;
y = b;
z = c;
}

void operator -()


{
x = x - 10;
y = y - 10;
z = z - 10;
}

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>

using namespace std;

class Add
{
public:
void add(int a,int b)
{
int c;
c=(a+b);
cout<<a<<" + "<<b<<" = "<<c<<endl;
}

void add(float a,float b)


{
float c;
c=(a+b);
cout<<a<<" + "<<b<<" = "<<c<<endl;
}

void add(int a,int b,int c)


{
int d;
d=(a+b+c);
cout<<a<<" + "<<b<<" + "<<c<<" = "<<d<<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>

using namespace std;


class Shape
{
protected:
float width, height;

public:
void set_data (float a, float b)
{
width = a;
height = b;
}
};

//inheriting Shape class


class Rectangle: public Shape
{
public:
float area ()
{
return (width * height);
}
};

//inheriting Shape class


class Triangle: public Shape
{
public:
float area ()
{
return (width * height / 2);
}
};

int main ()
{
Rectangle rect;
Triangle tri;

rect.set_data (5,3);
tri.set_data (2,5);

cout <<"Area of Rectangle : " <<rect.area() << endl;


cout <<"Area of Triangle : "<< tri.area() << endl;

return 0;
}
Output
Area of Rectangle : 15
Area of Triangle : 5
Multiple Inheritance Example
#include <iostream>

using namespace std;


class Area
{
public:
float area_calc(float l,float b)
{
return l*b;
}
};

class Perimeter
{
public:
float peri_calc(float l,float b)
{
return 2*(l+b);
}
};

//Rectangle class is derived from classes Area and Perimeter.


class Rectangle : private Area, private Perimeter
{
private:
float length, breadth;

public:
Rectangle() : length(0.0), breadth(0.0) { }

void get_data( )
{
cout<<"Enter length: ";
cin>>length;

cout<<"Enter breadth: ";


cin>>breadth;
}

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>

using namespace std;

class Value
{
protected:
int val;

public:
void set_values (int a)
{
val=a;
}
};

class Cube: public Value


{
public:
int cube()
{
return (val*val*val);
}
};

int main()
{
Cube cub;
cub.set_values (5);

cout << "The Cube of 5 is : " << cub.cube() << endl;

return 0;
}
Output
The Cube of 5 is : 125
Multilevel Inheritance Example
#include<iostream>
#include<string.h>

using namespace std;

class student
{
private:
int rl;
char nm[20];

public:
void read();
void display();
};

class marks : public student


{
protected:
int s1;
int s2;
int s3;

public:
void getmarks();
void putmarks();
};

class result : public marks


{
private:
int t;
float p;
char div[10];

public:
void process();
void printresult();
};

void student::read()
{
cout<<"Enter Roll no. : ";
cin>>rl;

cout<<"Enter Name : ";


cin>>nm;
}

void student:: display()


{
cout <<"\nRoll no. : "<<rl<<endl;
cout<<"Name : "<<nm<<endl;

cout<<"\n";
}

void marks ::getmarks()


{
cout<<"Enter marks for 3 subjects : "<<endl;
cin>>s1>>s2>>s3;
}

void marks ::putmarks()


{
cout<<"Subject 1 :"<<s1<<endl;
cout<<"Subject 2 : "<<s2<<endl;
cout<<"Subject 3 : "<<s3<<endl;
}

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>

using namespace std;

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

Result (l*b*h) : 210


Operator Overloading Example
#include <iostream>
using namespace std;

class Box
{
public:

double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}

void setBreadth( double bre )


{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Main function for the program
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// 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;

// Add two object as follows:


Box3 = Box1 + Box2;

// 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>

using namespace std;

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;

//Abstract base class


class Base
{
public:
//Pure Virtual Function
virtual void show() = 0;
};

class Derived:public Base


{
public:
void show()
{
cout << "Implementation of Virtual Function in Derived class";
}
};

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>

using namespace std;

typedef struct linked_list


{
int data;
struct linked_list *next;
}
Linked_list;

//for adding node


int add_node(Linked_list **head, int d)
{
Linked_list *l = new Linked_list;
if(l == NULL) return 0;

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;
}

//print the value which are there in linked list


void print_list(Linked_list *head)
{
while(head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << endl;
}

void del_list(Linked_list *head)


{
while(head != NULL)
{
Linked_list *t = head ->next;
delete head;
head = t;
}
}

Linked_list * merge_list(Linked_list *l1, Linked_list *l2)


{
Linked_list *h = l1, *r = l1, t;

if(l1 == NULL)
{
return l2;
}

if(l2 == NULL)
{
return l1;
}

if(l1->data < l2->data)


{
h = r = l1;
l1 = l1->next;
}
else
{
h = r = l2;
l2 = l2->next;
}

while(l1->next != NULL && l2->next != NULL)


{
if(l1->data < l2->data)
{
r->next = l1;
l1 = l1->next;
r = r->next;
}
else
{
r->next = l2;
l2 = l2->next;
r = r->next;
}
}

if(l1->next != NULL)
{
r->next = l1;
}

if(l2->next != NULL)
{
r->next = l2;
}

return h;
}

//declaration of main method


int main(int argc, char* argv[])
{
Linked_list *l1 = NULL;
Linked_list *l2 = NULL;

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


{
add_node(&l1, i * 3);
}

print_list(l1);//it will print first linked list


for(int i = 0; i < 10; i ++)
{
add_node(&l2, i * 7);
}

print_list(l2); //it will print 2nd linked list

Linked_list *h = merge_list(l1, l2);

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;

public:prime(int x) //declaration of constructor


{
num=x;
}

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.";
}
}
};

//declaration of main function


int main()
{

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;

//use while displaying a floating point value


cout << setprecision (1) << result << endl;
cout << setprecision (2) << result << endl;
cout << setprecision (3) << result << endl;
cout << setprecision (4) << result << endl;

}
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 : ";

//ws is use to add white spaces


cin>>ws;
cin>>empname;
cout<<"\n";
cout<<"Employee name = "<<empname;
}
Output
Enter a employee name : John Employee name = John
Operations using Class
#include <iostream>
using namespace std;

//define class
class operations
{
//member variables
public:
int num1,num2;

//member function or methods


public:
void add()
{
cout<<"enter two number for addition : ";
cin>>num1>>num2;
cout<<"addition = "<<num1+num2;
cout<<"\n";
}

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

enter two number for addition : 1 2


addition = 3
enter two number for subtraction : 5 2
addition = 3
enter two number for multiplication : 4 6
addition = 24
enter two number for division : 6 8
addition = 0.75
Constructor and Destructor Demo
#include<iostream>
using namespace std;

//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>

using namespace std;

//area method with one parameter


int area(int side)
{
return side*side;
}

//area method with two parameter


int area(int l , int b)
{
return l*b;
}

int main()
{

int (*para1)(int);
int (*para2)(int,int);

para1=area;
para2=area;

cout<<"Address of area(int) : "<<(unsigned int)para1<<endl;


cout<<"Address of area(int,int) : "<<(unsigned int)para2<<endl;

cout<<"Invoking area(int) via para1 : "<<para1(20)<<endl;


cout<<"Invoking area(int,int) via para2 : "<<para2(10,20);
}
Output
Address of area(int) : 4199232 Address of area(int,int) : 4199244 Invoking area(int) via
para1 : 400 Invoking area(int,int) via para2 : 200
Swap two numbers using Call By Value
//program to show how call by value works

#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;
}

int main (int argc, char *argv[])


{
//variable declaration
int a ,b;

//take user input


cout<<"Enter Two numbers : ";
cin>>a>>b;

cout<<"Original values of a and b are : "<<endl;


cout<<"Value of a is : "<<a<<endl;
cout<<"Value of b is : "<<b<<endl;

//call to swap function


swap(a, b);
}
OUTPUT
Enter Two numbers : 4 5 Original values of a and b are : Value of a is : 4 Value of b is : 5
Swapped value of a is : 5 Swapped value of b is : 4
Sum of Numbers using Function
//program to add N integers using function
#include<iostream>
using namespace std;

//function declaration
int add(int num);

//main method
int main()
{
//variable declaration
int num;

//take input from user


cout << "Enter a positive integer : ";
cin >> num;
//calling add function
cout << "Sum of n integer is : " << add(num);
return 0;
}

//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>

using namespace std;

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>

using namespace std;

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

cout<<"\n24 Hours Format\n";

cout<<"Hours : Mins : Seconds\n"<<" "<<hours<<" : "<<mins<<"


: "<<seconds<<"\n";

if(hours > 12)

hours=hours-12;

cout<<"12 Hours Format\n";

cout<<"Hours : Mins : Seconds\n"<<" "<<hours<<" : "<<mins<<"


: "<<seconds;

else

cout<<"12 Hours Format\n";

cout<<"Hours : Mins : Seconds\n"<<" "<<hours<<": "<<mins<<" :


"<<seconds;

} // 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>

using namespace std;

int main()
{
cout << "Hello World\n";
return 0;
}
OUTPUT
Hello World
Hello World using Class
#include<iostream>

using namespace std;

// 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>

using namespace std;


int main()
{
int num;

cout<<"Enter number to find multiplication table : ";


cin>>num;

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;

cout<<"Input a character : ";


cin>>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");

printf("\n\tEnter your option : ");


scanf("%d",&op);

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];

printf("\n\tEnter the label : ");


scanf("%s",l);

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;
}
}

int Search(char lab[])


{
int i,flag=0;
struct SymbTab *p;
p=first;

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
{

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=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);

printf("\n\tEnter the new address : ");


scanf("%d",&add);

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;

printf("\n\tEnter the label to be deleted : ");


scanf("%s",l);
a=Search(l);

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;

cout<<"Enter how many elements : ";


cin>>num;

int vec[num],large,small;

cout<<"Enter values in the vector";


cout<<endl;

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];
}

cout<<endl<<"Largest element = "<<large;


cout<<endl<<"Smallest element = "<<small;
}
Output
Enter how many elements : 5 Enter values in the vector 6 1 3 9 3 Largest element = 9
Smallest element = 1
Leap Year
#include<iostream>
#include<conio.h>
using namespace std;

int main()
{

//declare variable
int year;

//take user input for year


cout<<"Enter year : ";
cin>>year;

if(year%4==0 || year%400==0 || year%100==0)


cout<<"This is a leap year"<<endl;

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>

using namespace std;

int main( )
{
// current date/time based on your system
time_t nowuptime = time(0);

// convert current time to string format


char* date = ctime(&nowuptime);

//print the value


cout << "The localhost date and time is : " <<"\n";
cout<<date << endl;

}
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;

//take input from user


cout << "Enter a string : " << endl;
cin.getline(str, 150);

//logic for checking vowels,consonants,digit and blank spaces


for(i=0;str[i]!='\0';++i)
{
if(str[i]=='a'|| str[i]=='e'|| str[i]=='i'|| str[i]=='o'||
str[i]=='u'|| str[i]=='A'|| str[i]=='E'|| str[i]=='I'
|| str[i]=='O'|| str[i]=='U')
{
++vowel;
}
else if((str[i]>='a'&& str[i]<='z')|| (str[i]>='A'&&
str[i]<='Z'))
{
++cons;
}

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:

/// Default constructor.


Date()
{
time_t t = time(0);
localtime_r(&t, &ltime);
}

std::string getDate(const char* fmt)


{
char out[200];
size_t result = strftime(out, sizeof out, fmt, &ltime);
return std::string(out, out + result);
}

std::string getISODate() {return getDate("%F");}

std::string getTextDate() {return getDate("%A, %B %d, %Y");}


};

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();
};

Calendar :: Calendar (int _month, int _year)


{
month = _month;
year = _year;
}

void Calendar :: setFirstDay()


{
//This part determines which day will be the first day of that year
(0 for Sunday, 1 for Monday, etc.)
int day=1;
int y = year - (14-month)/12;
int m = month +12 * ((14-month) / 12) -2;
firstday= (day + y + y / 4 - y / 100 + y / 400 + (31 * m / 12)) % 7;
}

void Calendar :: print()


{
int NumberOfDaysInMonth;
int FirstDayOfMonth = 0;
int DayOfWeekCounter = 0;
int DateCounter = 1;

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;

//Display the days at the top of each month

cout<<"\nSun Mon Tue Wed Thu Fri Sat";


cout<<"\n\n"<<setw(2);

//Determine where the first day begins

for (FirstDayOfMonth; FirstDayOfMonth < firstday; ++FirstDayOfMonth)


{

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

for (DateCounter; DateCounter <= NumberOfDaysInMonth; ++DateCounter)


{
cout<<DateCounter<<setw(6);
++DayOfWeekCounter;
if (DayOfWeekCounter > 6)
{
cout<<"\n\n"<<setw(2);
DayOfWeekCounter = 0;
}
}
cout << " \n" ;

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;

string generate(int n, char left = '[', char right = ']')


{
string str(std::string(n, left) + std::string(n, right));
random_shuffle(str.begin(), str.end());
return str;
}

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>

const int UniqueSymbols = 1 << CHAR_BIT;


const char* SampleString = "this is an example for huffman encoding";

typedef std::vector<bool> HuffCode;


typedef std::map<char, HuffCode> HuffCodeMap;
class INode
{
public:
const int f;

virtual ~INode() {}

protected:
INode(int f) : f(f) {}
};

class InternalNode : public INode


{
public:
INode *const left;
INode *const right;

InternalNode(INode* c0, INode* c1) : INode(c0->f + c1->f), left(c0),


right(c1) {}
~InternalNode()
{
delete left;
delete right;
}
};

class LeafNode : public INode


{
public:
const char c;

LeafNode(int f, char c) : INode(f), c(c) {}


};

struct NodeCmp
{
bool operator()(const INode* lhs, const INode* rhs) const { return
lhs->f > rhs->f; }
};

INode* BuildTree(const int (&frequencies)[UniqueSymbols])


{
std::priority_queue<INode*, std::vector<INode*>, NodeCmp> trees;
for (int i = 0; i < UniqueSymbols; ++i)
{
if(frequencies[i] != 0)
trees.push(new LeafNode(frequencies[i], (char)i));
}
while (trees.size() > 1)
{
INode* childR = trees.top();
trees.pop();

INode* childL = trees.top();


trees.pop();

INode* parent = new InternalNode(childR, childL);


trees.push(parent);
}
return trees.top();
}

void GenerateCodes(const INode* node, const HuffCode& prefix, HuffCodeMap&


outCodes)
{
if (const LeafNode* lf = dynamic_cast<const LeafNode*>(node))
{
outCodes[lf->c] = prefix;
}
else if (const InternalNode* in = dynamic_cast<const InternalNode*>(node))
{
HuffCode leftPrefix = prefix;
leftPrefix.push_back(false);
GenerateCodes(in->left, leftPrefix, outCodes);

HuffCode rightPrefix = prefix;


rightPrefix.push_back(true);
GenerateCodes(in->right, rightPrefix, outCodes);
}
}

int main()
{
// Build frequency table
int frequencies[UniqueSymbols] = {0};
const char* ptr = SampleString;
while (*ptr != '\0')
++frequencies[*ptr++];

INode* root = BuildTree(frequencies);

HuffCodeMap codes;
GenerateCodes(root, HuffCode(), codes);
delete root;

for (HuffCodeMap::const_iterator it = codes.begin(); it != codes.end(); ++it)


{
std::cout << it->first << " ";
std::copy(it->second.begin(), it->second.end(),
std::ostream_iterator<bool>(std::cout));

std::cout << std::endl;


}
return 0;
}
Output
110 a 1001 c 101010 d 10001 e 1111 f 1011 g 101011 h 0101 i 1110 l 01110 m 0011 n
000 o 0010 p 01000 r 01001 s 0110 t 01111 u 10100 x 10000
Generate Random numbers
#include<iostream>
#include<conio.h>
#include<stdlib.h>
#include<time.h>

using namespace std;

int main()
{

int min,max,i,range,r,x;
unsigned first = time(NULL);

cout<<"FIRST = " << first <<endl;


srand(first);
cout<<"ENTER THE MINIMUM NUMBER :";
cin>>min;
cout<<"ENTER THE MAXIMUM NUMBER :";
cin>>max;
cout<<"ENTER THE NO.OF TERMS YOU WANT :";
cin>>x;

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>

using namespace std;

int main() //Start of main


{

int i=1, u=1, sum=0;


while(i<=500)
{ // start of first loop.

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;

cout<<" Enter value for second number ";


cin>>num2;
cout<<" Enter value for third number ";
cin>>num3;
if(num1>num2&&num1>num3)
{
cout<<" First number is greatest:"<<endl<<"which is= "<<num1;
}
else if(num2>num1&&num2>num3)
{
cout<<" Second number is greatest"<<endl<<"which is= "<<num2;
}
else
{
cout<<" Third number is greatest"<<endl<<"whick is= "<<num3;
}
return 0;
}
Output
Enter value for first number 5
Enter value for second number 6
Enter value for third number 3
Second number is greatest
which is= 6
Factorial of a number
#include<iostream>

using namespace std;

int main()

int num,factorial=1;

cout<<"Enter Number To Find Its Factorial: ";

cin>>num;

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

factorial=factorial*a;

cout<<"Factorial of Given Number is = "<<factorial<<endl;

return 0;

}
Output
Enter Number To Find Its Factorial: 5
Factorial of Given Number is = 120
Swap two numbers
#include<iostream>

using namespace std;

int main()

int var1, var2, swap;

cout<<"Enter value for first integer: ";

cin>>var1;

cout<<"Enter value for second integer: ";

cin>>var2;

cout<<"\nValues Before swapping: \n"<<endl;

cout<<"First Integer ="<<var1<<endl;

cout<<"Second Interger ="<<var2<<endl;

swap=var1;

var1=var2;

var2=swap;

cout<<"\nValues After swapping: \n"<<endl;

cout<<"First Integer ="<<var1<<endl;

cout<<"Second Interger ="<<var2<<endl;

return 0;

}
Output
Enter value for first integer: 4
Enter value for second integer: 5

Values Before swapping:

First Integer =4
Second Interger =5

Values After swapping:

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>

using namespace std;


int main()
{
int a = 33, b = 5;
cout << "Quotient = " << a / b << endl;
cout << "Remainder = "<< a % b << endl;
return 0;
}
Output
Quotient = 6
Remainder = 3
Check Prime Number
#include<iostream>
using namespace std;
int main()
{
int number,count=0;
cout<<"Enter number to check its Prime or Not : ";
cin>>number;

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>

using namespace std;

void recurse (float sum, int i ) // Each call gets its own count
{
int num = 0;

cout<<"Enter another positive integer: ";


cin>>num;

if(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 {

sum = sum + num;


i++;
recurse (sum, i );
}
}

int main()
{

float num;
float sum = 0;
int i = 0;

cout<<"Enter a positive integer: ";


cin>>num;

if(num < 0){

cout<<"ERROR\n";
recurse (sum, i ); //First function call, so it starts at one

}
else if(num == 0){

cout<<"NO AVERAGE";

}
else {

sum = sum + num;


i++;
recurse (sum, i );
}

return(0);
}
Output
Enter a positive integer: -1
ERROR
Enter another positive integer: 2
Enter another positive integer: 3
Enter another positive integer: 0

The Average of Positive Integers is 2.5

Sum of n Numbers
#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 add:";


cin >> times;

for (i=times; i>0; i--)


{
cout << "Enter a number:";
cin >> Inp;
sum=sum+Inp;
}

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;

for (i=times; i>0; i--)


{
cout<<"Enter a number:";
cin>>Inp;
sum=sum+(Inp*Inp);
}

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;

cout<<"Enter a positive integer: ";


cin>>n;
n1 = n;

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;

cout << "Enter the binary number(1s and 0s) : ";


cin >> num;
bin = num;
while (num > 0)
{
rem = num % 10;
dec = dec + rem * base;
base = base * 2;
num = num / 10;
}
cout << "The decimal equivalent of " << bin << " : " << dec << endl;
return 0;
}
Output
Enter the binary number(1s and 0s) : 1111
The decimal equivalent of 1111 : 15
Decimal to Binary
#include<iostream>
using namespace std;

void binary(int num)


{
int rem;

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;

int check(int a,int b)


{
int s=0,i;
for(i=1;i<a;i++)
{
if(a%i==0)
{
s=s+i;
}
}

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;

cout<<"Enter 1st no. : ";


cin>>a;
cout<<"Enter 2nd no. : ";
cin>>b;

if(check(a,b))
{
cout<<a<<" and "<<b<<" are Amicable Number";
}
else
{
cout<<a<<" and "<<b<<" are not Amicable Number";
}
}
Output
Example 1

Enter 1st no. : 220


Enter 2nd no. : 284
220 and 284 are Amicable Number

Example 2

Enter 1st no. : 110


Enter 2nd no. : 184
110 and 184 are not Amicable Number
Swap two numbers using friend function
#include<iostream>

using namespace std;

class Sample
{
private:
int x,y;
public:
void setdata(int a,int b)
{
x=a;
y=b;
}
void showdata()
{
cout<<"x="<<x<<"\ny="<<y;
}

friend void swap(Sample &s);


};

void swap(Sample &s)


{
int temp;
temp=s.x;
s.x=s.y;
s.y=temp;
}

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>

using namespace std;

void primeFactors(int n)
{
while (n%2 == 0)
{
cout<<"2 ";
n = n/2;
}

for (int i = 3; i <= sqrt(n); i = i+2)


{
while (n%i == 0)
{
cout<<i<<" ";
n = n/i;
}
}

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>

using namespace std;

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>

using namespace std;

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>

using namespace std;

int main()
{
int i,temp,d,revrs=0;

cout<<"Enter the number : ";


cin>>i;
temp=i;
while(temp>0)
{
d=temp%10;
temp/=10;
revrs=revrs*10+d;

}
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>

using namespace std;

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];

cout<<"Enter number START of range : ";


cin>>startNum;
cout<<"Enter number END of range : ";
cin>>endNum;

for(i=2;i<endNum;i++)
{
b[i]=true;
}

cout<<"Prime number from "<<startNum<<" to "<<endNum<<" : "<<endl;

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;

cout<<"Enter a number: ";


cin>>num;

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;

//take input from user


cout << "Please enter 3 numbers : "<<"" ;
cin >> num1 >> num2 >> num3;

//assign initial value for comparison


smallest = num1;
largest = num1;

if (num2 > largest)


{
largest = num2;
}
if (num3 > largest)
{
largest = num3;
}

if (num2 < smallest)


{
smallest = num2;
}

if (num3 < smallest)


{
smallest = num3;
}

//display largest number and smallest number


cout << "largest: " << largest << "\nsmallest: " << smallest <<
"\n";
}
Output
Please enter 3 numbers : 88 34 54 largest: 88 smallest: 34
Magic Square
#include <stdio.h>
#include<iostream>
using namespace std;

void magicsquare(int, int [][10]);

//
int main( )
{
int size;
int num[10][10];

cout<<"enter size but number should be odd number : ";


cin>>size;

if (size % 2 == 0)
{
cout<<"Magic square works for an odd numbered size\n";
}
else
{
magicsquare(size, num);
}
return 0;
}

//magicsquare method declaration


void magicsquare(int size, int a[][10])
{
int sqr = size * size;
int i = 0, j = size / 2, k;

for (k = 1; k <= sqr; ++k)


{
a[i][j] = k;
i--;
j++;

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;

//take user input


cout << " Enter an Integer Number : ";
cin >> Number;
if (Number <= 0)
{
cout << " Invalid number." << endl;
cout << " Press enter to continue..." << endl;
cin.ignore();
cin.get();
return 0;
}

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;

cout << " Roman Numeral = ";


for (j = 1; j <= m; j++)
cout << "M";

for (j = 1; j <= d; j++)


cout << "D";
for (j = 1; j <= c; j++)
cout << "C";

for (j = 1; j <= l; j++)


cout << "L";

for (j = 1; j <= x; j++)


cout << "X";

for (j = 1; j <= ix; j++)


cout << "IX";
for (j = 1; j <= v; j++)
cout << "V";

for (j = 1; j <= iv; j++)


cout << "IV";

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


cout << "I";

cout << endl;

cout << " Press enter to continue..." << endl;


cin.ignore();
cin.get();
return 0;
}
Output
Enter an Integer Number : 32 Roman Numeral = XXXII
automorphic Number
#include<iostream>
using namespace std;
int main()
{
//variable declaration
int s,c,p,n,i,t;

//take user input


cout<<"Enter a number : ";
cin>>n;

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;

//take user input


cout << "Enter your choice : " << endl;
cout << "1. Enter alphabet 'o' to convert decimal to octal." <<
endl;
cout << "2. Enter alphabet 'd' to convert octal to decimal." <<
endl;
cin >> c;
if (c =='d' || c == 'D')
{
cout << "Enter a octal number : ";
cin >> n;
cout << n << " in octal : " << octal_decimal(n) << " in
decimal";
}

if (c =='o' || c == 'O')
{
cout << "Enter a decimal number : ";
cin >> n;
cout << n << " in decimal : " << decimal_octal(n) << " in
octal";
}

return 0;
}

/* Function to convert decimal to octal */


int decimal_octal(int n)
{
int rem, i=1, octal=0;
while (n!=0)
{
rem=n%8;
n/=8;
octal+=rem*i;
i*=10;
}

return octal;
}

/* Function to convert octal to decimal */


int octal_decimal(int n)
{
int decimal=0, i=0, rem;
while (n!=0)
{
rem = n%10;
n/=10;
decimal += rem*pow(8,i);
++i;
}
return decimal;
}
Output
Enter your choice : 1. Enter alphabet 'o' to convert decimal to octal. 2. Enter alphabet 'd'
to convert octal to decimal. o Enter a decimal number : 34 34 in decimal : 42 in octal
Convert Number to Word
#include<iostream>
using namespace std;
void convetTo(int);
int main()
{
int num;
cout<<"Enter a number : ";
cin>>num;
cout<<endl;
convetTo(num);
}

void convetTo(int value)


{
const char * const ones[20] = {"zero", "one", "two",
"three","four","five","six","seven",

"eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","
sixteen","seventeen",
"eighteen","nineteen"};

const char * const tens[10] = {"", "ten", "twenty",


"thirty","forty","fifty","sixty","seventy",
"eighty","ninety"};

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);
}
}

else if(value >= 100)


{
convetTo(value / 100);
cout<<" hundred";

if(value % 100)
{
cout << " and ";
convetTo (value % 100);
}
}

else if(value >= 20)


{
cout << tens[value / 10];
if(value % 10)
{
cout << " ";
convetTo(value % 10);
}
}

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

std:: cout << "Enter the number : ";


std:: cin >> n;

a = n;

while(a > 0) // Finding the sum of digit


{
d = a % 10;
sum = sum + d;
a = a / 10;
}

if(n % sum == 0) //Checking if the remainder is zero or not


std:: cout << "\nThe number is Niven Number ";
else
std:: cout << "\nThe number is not a Niven Number ";

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>

using namespace std;

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>

using namespace std;


void print(const string& item)
{
cout<< endl << item ;
}

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>

using namespace std;

int main ()
{
string str1 = "Programming";
string str2 = "Hub";
string str3;
int len ;

// copy str1 into str3


str3 = str1;
cout << "str3 : " << str3 << endl;

// concatenates str1 and str2


str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;

// total lenghth of str3 after concatenation


len = str3.size();
cout << "str3.size() : " << len << endl;

return 0;
}
Output
str3 : Programming
str1 + str2 : ProgrammingHub
str3.size() : 14
Length of String without inbuilt method
#include<iostream>
#include<stdio.h>

using namespace std;

int main( )
{
char str[80];
int i = 0;
cout<<"Enter a string : ";
gets(str);

for(i=0;str[i]!='\0';i++);

cout<<"Length of string is : "<<i;


return 0;
}
OUTPUT
Enter a string : C++ Programs
Length of string is : 12
Reverse the String
#include<iostream>
#include<stdio.h>

using namespace std;

int main( )
{
char str[80];
int temp,l,i,j;
cout<<"Enter string : ";
gets(str);

for(l=0;str[l]!='\0';l++); //finding length of string

for(i=0,j=l-1;i<l/2;i++,j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}

cout<<"Reverse of String : "<<str;

return 0;
}
Output
Enter string : programs
Reverse of String : smargorp
Convert String to Lowercase
#include<iostream>
#include<stdio.h>

using namespace std;

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>

using namespace std;

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>

using namespace std;

int main()
{
char a[100], b[100];

printf("Enter the string to check if it is a palindrome : ");


gets(a);

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>

using namespace std;

int main()
{
string tmp = "C Plus Plus";

cout<<"String : "<<tmp<<endl;

cout<<"Converting string to char array : ";

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>

using namespace std;

int main()

int width,height,area,perimeter;

cout<<"Enter Width of Rectangle = ";

cin>>width;

cout<<"Enter Height of Rectangle = ";

cin>>height;

area=height*width;

cout<<"Area of Rectangle = "<<area<<endl;

perimeter=2*(height+width);

cout<<"Perimeter of rectangle are = "<<perimeter<<endl;

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;

cout<<"Enter Radius : ";


cin>>r;

a=3.14*r*r;

cout<<"Area of Circle : "<<a;

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;

// define identifier PI with a constant


#define PI 3.14159
// define identifier TWO with a constant
#define TWO 2.0

int main(void)
{

float area, circumference, radius;

cout<<"\nEnter a radius of the circle in meter: ";


cin>>radius;
// circle area = PI*radius*radius
area = PI * radius * radius;

// 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

Circumference = 12.5664 meter


Circle area = 12.5664 square meter

Convert Gregorian Date to Julian Day


#include <iostream>

using namespace std;

long gregorian_calendar_to_jd(int y, int m, int d)


{
y+=8000;
if(m<3) { y--; m+=12; }
return (y*365) +(y/4) -(y/100) +(y/400) -1200820
+(m*153+3)/5-92
+d-1;

int main()
{

int year = 2014;


int month = 11;
int day = 26;

cout<<"Day in Julian Calendar is


"<<gregorian_calendar_to_jd(year,month,day)<<"\n";
return(0);

}
Output
Day in Julian Calendar is 2456988

Convert Celsius to Fahrenheit


#include<iostream>
using namespace std;

int main()
{
float fahrenheit, celsius;

cout << "Enter the temperature in Celsius : ";


cin >> celsius;
fahrenheit = (celsius * 9.0) / 5.0 + 32;
cout << "The temperature in Celsius : " << celsius << endl;
cout << "The temperature in Fahrenheit : " << fahrenheit << endl;
return 0;
}
Output
Enter the temperature in Celsius : 32
The temperature in Celsius : 32
The temperature in Fahrenheit : 89.6
Find the roots of a Quadratic Equation
#include <iostream>
#include <cmath>
using namespace std;

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>

using namespace std;

int main()
{
float base,height;
float area;

cout<<"Enter base of Triangle : ";


cin>>base;
cout <<"Enter height of Triangle : ";
cin>>height;

area = 0.5 * (base * height);


cout<<"Area of Triangle :"<<area;
return 0;
}
Output
Enter base of Triangle : 5
Enter height of Triangle : 8
Area of Triangle :20
(a+b)^2
#include <iostream>

using namespace std;

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;

if (bmi < 18.5)


{
cout<<"You are underweight!"<<endl;
cout<<"Eat more!!"<<endl;
}
else if (bmi >= 18.5 && bmi < 25)
{
cout<<"You are normal!"<<endl;
}
else if (bmi >= 25)
{
cout<<"You are overweight!"<<endl;
}
else
{
cin.get();
}

cin.get();
cout<<endl;

cout<<"Would you like to enter the information again? ";


cin>>response;
}
while (toupper(response) == 'Y');
cout<<"Okay, see you next time.."<<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);

cout<<"Radius of circle is : "<<radius;


}
Output
enter area of circle : 314 Radius of circle is : 10
Perfect Square
#include <stdio.h>
#include <math.h>
#include<iostream>

using namespace std;

int main()
{
int num, tempnum;

cout<<"Enter a number: ";


cin>>num;

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;

//formula to calculate compound intrest


CI=PA*pow((1+R/100),Time) - PA;
cout<<"Compound Interest is : "<<CI;

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;

cout<<"Enter Principle : ";


cin>>p;
cout<<"Enter Rate : ";
cin>>r;
cout<<"Enter Time(in years) : ";
cin>>t;

//formula to calculate intrest


i=(p*r*t)/100;
cout<<"Simple interest is : "<<i;

return 0;
}
Output
Enter Principle : 400 Enter Rate : 7 Enter Time(in years) : 2 Simple interest is : 56
(a-b)^2
#include <iostream>

using namespace std;

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;

cout<<"Enter Hexadecimal Number : ";


cin >> hex >> num;

cout<<"Decimal number for given hexadecimal number is : ";


cout << num << endl;

return 0;
}
Output
Enter Hexadecimal Number : fffh Decimal number for given hexadecimal number is :
4095
GCD and LCM
#include<iostream>

using namespace std;

int main()
{

//variable declaration
int num1, num2, gcd = 1;

//take input from user


cout << "Enter two numbers : ";
cin >> num1;
cin >> num2;

//logic to calculate gcd and lcm


for (int i = 1; i < 1000; ++i)
{
if ((num1 % i == 0) && (num2 % i == 0))
{
gcd = i;
}
}

//print calculated value of gcd and lcm

cout << "\nGCD of two number is : " << gcd;


cout << "\nLCM of two number is : " << (num1 * num2) / gcd;
}
Output

Enter two numbers : 5


2

GCD of two number is : 1


LCM of two number is : 10
Convert Centimeter to Meters and Kilometres
#include<iostream>

using namespace std;

int main()
{
//variable declaration
float meter, cmeter, kmeter;
//user input
cout << "\nEnter length in centimeters : ";
cin >> cmeter;

// Convert centimeter into meter and kilometer

meter = cmeter / 100.0;


kmeter = cmeter / 100000.0;

//display converted values

cout << "\nLength in Meter : ";


cout << meter;

cout << "\nLength in Kilometer : ";


cout << kmeter;

cout << endl;

return 0;
}
Output

Enter length in centimeter : 100

Length in Meter : 1
Length in Kilometer : 0.001
Square and Cube Root
#include <iostream>
#include <cmath>

using namespace std;

int main()
{

//variable declaration
int number;

//take input for number from user


cout << "Enter number : ";
cin >> number;

//use of sqrt function to find square root


cout << "square root of " << number << " is " << sqrt(number);

cout << "\n\n";

//use of cbrt function to find cube root


cout << "cube root of " << number << " is " << cbrt(number);

cout << "\n";

return 0;
}
Output
Enter number : 27 square root of 27 is 5.19615 cube root of 27 is 3
Volume of box
#include <iostream>

using namespace std;

int main()
{
double length;
double width;
double height;
double volume;

cout << "Please Enter a Length for your box: ";


cin >> length;

cout << "\nPlease Enter a Width for your box: ";


cin >> width;

cout << "\nPlease Enter a Height for your box: ";


cin >> height;

volume = length * width * height;


cout << "\n\nThe Volume of your box is: " << volume << endl;

return 0;
}
Output
Please Enter a Length for your box:2

Please Enter a Width for your box:3

Please Enter a Height for your box:4

The Volume of your box is:24


Star Half Pyramid
#include <iostream>

using namespace std;

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>

using namespace std;

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>

using namespace std;

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>

using namespace std;

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>

using namespace std;

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>

using namespace std;


void drawTriangle(char border, char filler, int length)
{
int start = 2;
int base = 4;
int i;
for (i = start; i <= length; i++)
{
for (int sp = 0; sp <= length - i; sp++)
{
cout << " ";
}
if (i > start)
{
cout << border << " ";
}
if (i > start)
{
for (int b = base; b <= i; b++)
{
cout << filler << " ";
}
}
cout << border << " ";
cout << endl;
}

for (int j = base; j < length + base; j++)


{
cout << border << " ";
}
cout << endl;
}

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;

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


{
for (j = 0; j < (n - i - 1); j++)
cout << " ";
for (k = 0; k < (2 * i + 1); k++)
cout << "*";

cout << endl;


}
for (i = 0; i < n - 1; i++)
{
for (j = 0; j <= i; j++)
cout << " ";
for (k = (2 * n - 2 * i - 3); k > 0; k--)
cout << "*";
cout << endl;
}
return 0;
}
Output
Enter the number of lines to be printed: 5
*
***
*****
*******
*********
*******
*****
***
*
Reverse Star Triangle
#include<iostream>

using namespace std;

int main()
{
int i, n, j;

cout << "Enter number of lines for Pattern : ";


cin >> n;

for (i = n; i > 0; i--)


{
for (j = n - i; j > 0; j--)
{
cout << " ";
}
for (j = 2 * i - 1; j > 0; j--)
{
cout << " *";
}
cout << endl;
}
return 0;
}
Output
Enter number of lines for Pattern : 5
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Star Pattern 1
#include <iostream>

using namespace std;

int main()
{
//variable declaration
int i, j, rows;

//take number of rows


cout << "Enter the number of rows : ";
cin >> rows;

for (i = rows; i >= 1; --i)


{
for (j = 1; j <= i; ++j)
{
cout << "* ";
}
cout << "\n";
}
return 0;
}
Output
Enter the number of rows: 9 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
************
Number Pattern 1
#include<iostream>

using namespace std;


int main()
{
int num, c, k;

cout << "Enter number of rows : ";


cin >> num;
cout << "\n";

for (c = 1; c <= num; c++)


{
for (k = 1; k <= c; k++)
{
cout << c;
}

cout << "\n";


}
}
Output
Enter number of rows : 9 1 22 333 4444 55555 666666 7777777 88888888 999999999
Alphabet Pattern 1
#include<iostream>
#include<stdio.h>

using namespace std;

int main()
{
//variable declaration
int x, y, n;
char ch;
cout << "Number of rows : ";
cin >> n;

for (x = 1; x <= n; x++)


{
cout << "\n";
ch = 'A';
for (y = 1; y <= x; y++)
{
cout << ch;
ch++;
}
}
return 0;
}
Output

Number of rows : 9

A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
Number Pattern 2
#include<stdio.h>
#include<iostream>

using namespace std;

int main()
{
//variable declaration
int i, j, k, rows;
k = 1;

//user input for rows

cout << "Enter how many rows you want : ";


cin >> rows;

//to generate pattern


for (i = 1; i <= rows; i++)
{
for (j = 1; j <= i; j++)
{
cout << k++;
}
cout << "\n";
}
return 0;
}
Output
Enter how many rows you want : 4 1 23 456 78910
Matrix Multiplication
#include<iostream>

using namespace std;

int main()
{

int a[5][5], b[5][5], c[5][5], m, n, p, q, i, j, k;

cout << "Enter rows and columns of first matrix: ";


cin >> m >> n;
cout << "Enter rows and columns of second matrix: ";
cin >> p >> q;

if (n == p)
{
cout << "\nEnter first matrix:\n";
for (i = 0; i < m; ++i)
for (j = 0; j < n; ++j)
cin >> a[i][j];

cout << "\nEnter second matrix:\n";


for (i = 0; i < p; ++i)
for (j = 0; j < q; ++j)
cin >> b[i][j];

cout << "\nThe new matrix is:\n";

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


{
for (j = 0; j < q; ++j)
{
c[i][j] = 0;
for (k = 0; k < n; ++k)
c[i][j] = c[i][j] + (a[i][k] * b[k][j]);
cout << c[i][j] << "\t";
}
cout << "\n";
}
}
else
cout << "\nSorry!!!! Matrix multiplication can't be done";

return 0;
}
Output
Enter rows and columns of first matrix: 2
3
Enter rows and columns of second matrix: 3
2

Enter first matrix:


1
2
3
4
5
6

Enter second matrix:


1

2
3
4
5
6

The new matrix is:


22 28
49 64
Accessing Two-Dimensional Array Elements
#include <iostream>

using namespace std;

int main()
{
// an array with 5 rows and 2 columns.
int a[5][2] = {{0, 0},
{1, 2},
{2, 4},
{3, 6},
{4, 8}};

// output each array element's value


for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 2; j++)
{
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j] << endl;
}
}

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};

// Initial values of pressure(variable) undefined.


float pressure[10];

// Remaining characters zero.


char greeting[100] = "Hello";

// Array size is 6 (final zero on strings).


char goodbye[] = "Adios";

return 0;
}
Output
Matrix Addition
#include<iostream>

using namespace std;

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";

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
cin >> first[c][d];

cout << "Enter the elements of second matrix : \n";

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
cin >> second[c][d];

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
sum[c][d] = first[c][d] + second[c][d];

cout << "Sum of entered matrices:-\n";

for (c = 0; c < m; c++)


{
for (d = 0; d < n; d++)
cout << sum[c][d] << "\t";

cout << endl;


}

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>

using namespace std;

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";

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
cin >> first[c][d];

cout << "Enter the elements of second matrix : \n";

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
cin >> second[c][d];

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
sub[c][d] = first[c][d] - second[c][d];

cout << "Subtraction of entered matrices:-\n";

for (c = 0; c < m; c++)


{
for (d = 0; d < n; d++)
cout << sub[c][d] << "\t";

cout << endl;


}
return 0;
}
Output
Enter the number of rows and columns of matrix : 3 3
Enter the elements of first matrix :
7 6 4
1 9 8
2 3 0
Enter the elements of second matrix :
2 6 4
5 6 1
2 0 9
Subtraction of entered matrices:-
5 0 0
-4 3 7
0 3 -9
Array of Objects
#include <iostream>

using namespace std;

class Demo
{
int x;

public:

void setX(int i)
{
x = i;
}

int getX()
{
return x;
}
};

int main()
{
Demo obj[4];
int i;

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


{
obj[i].setX(i);
}

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


{
cout << "obj[" << i << "].getX() : " << obj[i].getX() << endl;
}
return 0;
}
Output
obj[0].getX() : 0
obj[1].getX() : 1
obj[2].getX() : 2
obj[3].getX() : 3
Inverse Matrix using Gauss jordan method
#include<iostream>

using namespace std;

int main()
{
int i, j, k, n;
float a[10][10] = {0}, d;

cout << "Enter the order of matrix : ";


cin >> n;
cout << "Enter the elements : " << endl;
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
cin >> a[i][j];

for (i = 1; i <= n; i++)


for (j = 1; j <= 2 * n; j++)
if (j == (i + n))
a[i][j] = 1;

for (i = n; i > 1; i--)


{
if (a[i - 1][1] < a[i][1])
for (j = 1; j <= n * 2; j++)
{
d = a[i][j];
a[i][j] = a[i - 1][j];
a[i - 1][j] = d;
}
}
cout << "Augmented : " << endl;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n * 2; j++)
cout << a[i][j] << " ";
cout << endl;
}

for (i = 1; i <= n; i++)


{
for (j = 1; j <= n * 2; j++)
if (j != i)
{
d = a[j][i] / a[i][i];
for (k = 1; k <= n * 2; k++)
a[j][k] -= a[i][k] * d;
}
}

for (i = 1; i <= n; i++)


{
d = a[i][i];
for (j = 1; j <= n * 2; j++)
a[i][j] = a[i][j] / d;
}

cout << "Inverse Matrix : " << endl;


for (i = 1; i <= n; i++)
{
for (j = n + 1; j <= n * 2; j++)
cout << a[i][j] << " ";
cout << endl;
}

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>

using namespace std;

//declaration of constant value


#define MAX 5
int top, state;
// for deletion of element from stack-POP FUNCTION

int pop(int stack[])


{
int value;
if (top == -1)
{
value = 0;
state = 0;
}
else
{
state = 1;
value = stack[top];
--top;
}
return value;
}

// for insertion of element into stack -PUSH FUNCTION

void push(int stack[], int item)


{
if (top == (MAX - 1))
{
state = 0;
}
else
{
state = 1;
++top;
stack[top] = item;
}
}

void showstack(int stack[])


{
int i;

cout << "\n Stack contain: ";

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;

cout << "\nSelect one choice from following Menu : ";


cout << "\n\n1.push item in stack";
cout << "\n2.pop item from stack";
cout << "\n3.Exit ";

do
{
do
{
cout << "\n\nEnter your choice : ";
cin >> ch;

if (ch < 1 || ch > 3)


{
cout << "invalid choice";
}
}

while (ch < 1 || ch > 3);

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);

if (top == (MAX - 1))


{
cout << "\n stack is full";
}
}

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... ";

}//close switch case


}//close do

while (ch != 3);

return 0;
}
OUTPUT
Select one choice from following Menu :

1.push item in stack


2.pop item from stack
3.Exit

Enter your choice : 1


enter element you want to push :12
12
after push operation
Stack contain: 12

Enter your choice : 1


enter element you want to push :23
23
after push operation
Stack contain: 23 12

Enter your choice : 1


enter element you want to push :34
34
after push operation
Stack contain: 34 23 12

Enter your choice : 2


poped item is :34
after pop operation
Stack contain: 23 12

Enter your choice : 3


Exit...
Display Even numbers in an Array
#include<iostream>
using namespace std;

int main()
{

int numarr[100],evenarr[100],i,j=0,k=0,num;

cout<<"Enter Size of Array : ";


cin>>num;

cout<<"Enter "<<num<<" Data elements in Array : ";


for(i=0; i<num;i++)
{
cin>>numarr[i];
}

for(i=0; i<num;i++)
{
if(numarr[i]%2==0)
{
evenarr[j]=numarr[i];
j++;
}
}

cout<<"\nEven Elements : ";

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


{
cout<<evenarr[i]<<" ";
}
}
Output
Enter Size of Array : 10 Enter 10 Data elements in Array : 9 8 12 44 23 53 28 30 49 48
Even Elements : 8 12 44 28 30 48
Deletions in Array
#include<iostream>

using namespace std;

int main()
{

int i, inputarray[10], no, pos;

cout << "Enter 10 data elements in array: ";


for (i = 0; i < 10; i++)
{
cin >> inputarray[i];
}
cout << "\nEnter position of element to delete: ";
cin >> pos;

if (pos > 10)


{
cout << "\n position value is not in range: ";
}
else
{
--pos;
for (i = pos; i <= 9; i++)
{
inputarray[i] = inputarray[i + 1];
}

cout << "\n\nNew data in array: ";

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


{
cout << inputarray[i];
cout << " ";
}
}
return 0;
}
Output

Enter 10 data elements in array: 65


56
86
96
35
12
85
65
52
18

Enter position of element to delete: 3


New data in array: 65 56 96 35 12 85 65 52 18
Array Sort
// for std::swap, use <utility> instead if C++11
#include <algorithm>
#include <iostream>

#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};

cout << "sorted values : ";

// Step through each element of the array


for (int startIndex = 0; startIndex < SIZE; ++startIndex)
{
// smallestIndex is the index of the smallest element we've
encountered so far.
int smallestIndex = startIndex;

// Look for smallest element remaining in the array (starting at


startIndex+1)
for (int nowIndex = startIndex + 1; nowIndex < SIZE; ++nowIndex)
{
// If the current element is smaller than our previously
found smallest
if (array[nowIndex] < array[smallestIndex])
// This is the new smallest number for this iteration
{
smallestIndex = nowIndex;
}
}

// Swap our start element with our smallest element


swap(array[startIndex], array[smallestIndex]);
}

// Now print our sorted array as proof it works


for (int index = 0; index < SIZE; ++index)
{
cout << array[index] << ' ';
}

cout << "\n";


return 0;
}
Output
array values : 132, 520, 210, 510, 140 ,125,52,96,55,85 sorted values : 52 55 85 96 125
132 140 210 510 520
Merging two Arrays
#include<iostream>

using namespace std;

int main()
{

int arr1[100], arr2[100], resultarr[100], n, m, i, j, k, s;

cout << " Merging Two Arrays";


cout << "\n\nEnter No. of Elements in First Array : ";
cin >> n;

cout << "\nEnter Elements : \n";

for (i = 1; i <= n; i++)


{
cin >> arr1[i];
}

cout << "\nEnter No. of Elements in Second Array : ";


cin >> m;

cout << "\nEnter Elements in Sorted Order : \n";

for (i = 1; i <= m; i++)


{
cin >> arr2[i];
}

i = 1, j = 1;

for (k = 1; k <= n + m; k++)


{
// Compare Elements of Array A and Array B
if (arr1[i] < arr2[j])
{
resultarr[k] = arr1[i];
i++;

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];
}

cout << "\n\nAfter Merging Two Arrays:\n";

for (k = 1; k <= n + m; k++)


{
cout << resultarr[k] << endl;
}
return 0;
}
Output

Merging Two Arrays

Enter No. of Elements in First Array : 4

Enter Elements :
7
5
8
6
Enter No. of Elements in Second Array : 4

Enter Elements in Sorted Order :


8
4
1
3

After Merging Two Arrays:


7
5
8
4
1
3
8
6
Display Lower Triangle of a Matrix
#include<iostream>

using namespace std;

//method declaration
void lower_halfmatrix(int mat[10][10], int row);

//define main method


int main()
{
//variable declaration
int mat[10][10], i, j, row, col;

//enter number of row and column you want


cout << "Enter how many numbers of row and column you want : ";
cout << "\n";
cin >> row;
cout << "\n";
cin >> col;
cout << "\n";
cout << "enter elements";
cout << "\n";

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


{
cout << "\n";
for (j = 0; j < col; j++)
{
cin >> mat[i][j];
}
}
lower_halfmatrix(mat, row);

return 0;
}
//method definition
void lower_halfmatrix(int mat[10][10], int row)
{
int i, j;
cout << "\n";

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


{
for (j = 0; j <= i; j++)
{
cout << mat[i][j] << " ";
}
cout << "\n";
}
}
Output
Enter how many numbers of row and column you want : 3 3 enter elements 7 5 2 1 3 6 4
98713498
Display upper half of matrix
#include<iostream>

using namespace std;

//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";

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


{
for (j = 0; j < col; j++)
{
cin >> mat[i][j];
}
}
upper_halfofmatrix(mat, col, row);

return 0;
}

//method definition
void upper_halfofmatrix(int mat[10][10], int col, int row)
{
int i, j;

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


{
for (j = 0; j < col; j++)
{
if (i <= j)
cout << mat[i][j];

else
cout << " ";
}

cout << "\n";


}
}
Output

enter how many numbers of row and column you want : 3


3
enter elements:
1
2
3
4
5
6
7
8
9
123
56
9
Smallest and Largest number in an Array
#include<iostream>

using namespace std;

int main()
{

int size;
cout << "enter size of array : ";
cin >> size;

int arra[size];

int smallelement, largestelement;

cout << "\nenter array elements : ";


for (int i = 0; i < size; i++)
{
cin >> arra[i];
}
largestelement = smallelement = arra[0];
for (int i = 0; i < size; i++)
{
if (arra[i] > largestelement)
{
largestelement = arra[i];
}
if (arra[i] < smallelement)
{
smallelement = arra[i];
}
}
cout << "The biggest number is " << largestelement << endl;
cout << "The smallest number is " << smallelement << endl;

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>

using namespace std;

int main()
{
//variable declaration
int arr[100], i, temp, size;

cout << "enter array size : ";


cin >> size;

cout << "enter elements in to array : \n";


for (i = 0; i < size; ++i)
{
cin >> arr[i];
}

cout << "\narray before swaping elements : \n";


for (i = 0; i < size; ++i)
{
cout << arr[i] << " ";
}

//element swapping logic


for (i = 1; i < size; i += 2)
{
temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}

cout << "\narray after swapping elements : \n";


for (i = 0; i < size; ++i)
{
cout << arr[i] << " ";
}

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>

using namespace std;

int main()
{
int mat[5][5], order, i, j, flag = 0;

cout << "Enter size of matrix : ";


cin >> order;

cout << "Enter matrix element : \n";


for (i = 0; i < order; i++)
{
cout << "\n";
for (j = 0; j < order; j++)
{
cin >> mat[i][j];
}
}

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


{
for (j = 0; j < order; j++)
{
if (i == j)
{
if (mat[i][j] != 1)
{
flag = 1;
break;
}
}
else
{
if (mat[i][j] != 0)
{
flag = 1;
break;
}
}
}
}

cout << "The given matrix is ";


if (flag == 0)
cout << "an identity matrix.\n";
else
cout << "not an identity matrix.\n";

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>

using namespace std;

int main()
{
int arr[10][10], i, j, size;

cout << "Enter size of matrix : ";


cin >> size;

cout << "Enter values in matrix : \n";


for (i = 1; i <= size; i++)
{
for (j = 1; j <= size; j++)
{
cin >> arr[i][j];
}
}
for (i = 1; i <= size; i++)
{
for (j = 1; j <= size; j++)
{
if (arr[i][j] != arr[j][i])
{
cout << "\n\nMatrix is not symmetric";

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>

using namespace std;

int main()
{
int arr[10][10], i, j, size;

cout << "Enter order of square matrix : ";


cin >> size;

cout << "\nEnter matrix values : \n";


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

cin >> arr[i][j];


}
}
for (i = 1; i <= size; i++)
{
for (j = 1; j <= size; j++)
{
if (arr[i][j] != -arr[j][i])
{
cout << "\nMatrix is not skew matrix ";
exit(0);
}
}
}
cout << "\nMatrix is skew matrix";

return 0;
}
Output

Enter order of square matrix : 3

Enter matrix values :


0 2 -1
-2 0 -4
1 4 0

Matrix is skew matrix


Search Array
#include <iostream>

using namespace std;

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;

cout << "\nEnter array element : \n";


for (int i = 0; i < size; i++)
{
cin >> arr[i];
}

cout << "Enter the number to search : ";


cin >> searchelement;

for (c = 0; c < size; c++)


{
if (arr[c] == searchelement)
{
cout << "Element is present at location : " << c + 1;
flag = 1;
break;
}
}
if (!flag)
cout << "Element is not present in array.\n";

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>

using namespace std;

int main()
{
//variable declaration
int a[20], i, j, k, n;

//take user input


cout << "Enter array size : ";
cin >> n;

//ask for array elements


cout << "\nEnter array " << n << " element : \n";
for (i = 0; i < n; i++)
{
cin >> a[i];
}

//display array elements


cout << "\nOriginal array Elements are : ";

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


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

//display new array elements and remove duplicate numbers from array
cout << "\nNew array Element are : ";

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


{
for (j = i + 1; j < n;)
{
if (a[j] == a[i])
{
for (k = j; k < n; k++)
{
a[k] = a[k + 1];
}
n--;
}
else
{
j++;
}
}
}

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


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

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>

using namespace std;

int main()
{
//variable declaration
int size;

//take user input for array size


cout << "Enter how many elements you want to insert in array : ";
cin >> size;

int num[size];

//take user input for array elements


cout << "\nEnter Array elements : \n";

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


{
cin >> num[i];
}

cout << "\nElements in array : \n";

//loop to display array items


for (int i = 0; i < size; i++)
{
cout << num[i] << "\n";
}

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;

typedef vector<int> IntRow;


typedef vector<IntRow> IntTable;

auto_ptr<IntTable> getSpiralArray(int dimension)


{
auto_ptr<IntTable> spiralArrayPtr(new IntTable(
dimension, IntRow(dimension)));

int numConcentricSquares = static_cast< int >( ceil(


static_cast< double >( dimension ) / 2.0));

int j;
int sideLen = dimension;
int currNum = 0;

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


{
// do top side
for (j = 0; j < sideLen; j++)
(*spiralArrayPtr)[i][i + j] = currNum++;

// 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;
}

void printSpiralArray(const auto_ptr<IntTable> &spiralArrayPtr)


{
size_t dimension = spiralArrayPtr->size();

int fieldWidth = static_cast< int >( floor(log10(


static_cast< double >( dimension * dimension - 1 )))) + 2;

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>

using namespace std;

int main()
{
int a[10][10], trans[10][10], r, c, i, j;
cout << "Enter rows and columns of matrix: ";
cin >> r >> c;

// Storing element of matrix entered by user in array a[][].


cout << endl << "Enter elements of matrix: " << endl;
for (i = 0; i < r; ++i)
{
for (j = 0; j < c; ++j)
{
cout << "\nEnter elements a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}
}

// Displaying the matrix a[][]


cout << endl << "Entered Matrix: " << endl;
for (i = 0; i < r; ++i)
{
for (j = 0; j < c; ++j)
{
cout << " " << a[i][j];
if (j == c - 1)
cout << endl << endl;
}
}
// Finding transpose of matrix a[][] and storing it in array trans[]
[].
for (i = 0; i < r; ++i)
{
for (j = 0; j < c; ++j)
{
trans[j][i] = a[i][j];
}
}
// Displaying the transpose,i.e, Displaying array trans[][].
cout << endl << "Transpose of Matrix: " << endl;
for (i = 0; i < c; ++i)
{
for (j = 0; j < r; ++j)
{
cout << " " << trans[i][j];
if (j == r - 1)
cout << endl << endl;
}
}

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>

using namespace std;

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>

using namespace std;

int main()
{
int i, Num_arr[50], sum, num;

cout << "Enter size of array : ";


cin >> num;

//Reading values into Array


cout << "\nEnter array elements : ";
for (i = 0; i < num; i++)
{
cin >> Num_arr[i];
}

//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

Enter array elements : 1


2
5
9
6

Sum of array element is : 23


Singly Linked List
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

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;
}
}
}

node *single_llist::create_node(int value)

{
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
---------------------------------

Operations on singly linked 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
The List is Empty.

---------------------------------

Operations on singly linked 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 : 5
Delete a particular node:
List is empty
---------------------------------

Operations on singly linked 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 : 6
Update Node Value:
List is empty

---------------------------------

Operations on singly linked 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 : 7
Search element in Link List:
List is empty

---------------------------------

Operations on singly linked 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 : 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

---------------------------------

Operations on singly linked 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 : 1
Inserting Node at Beginning:
Enter the value to be inserted: 100
Element Inserted at beginning

---------------------------------

Operations on singly linked 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 : 1
Inserting Node at Beginning:
Enter the value to be inserted: 200
Element Inserted at beginning

---------------------------------

Operations on singly linked 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:
200->100->NULL

---------------------------------

Operations on singly linked 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 : 2
Inserting node at last:
Enter the value to be inserted: 50
Element Inserted at last

---------------------------------

Operations on singly linked 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 : 2
Inserting node at last:
Enter the value to be inserted: 150
Element Inserted at last

---------------------------------

Operations on singly linked 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:
200->100->50->150->NULL

---------------------------------

Operations on singly linked 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 : 3
Inserting node at a given position:
Enter the value to be inserted: 1111
Enter the position at which node to be inserted: 4

---------------------------------

Operations on singly linked 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:
200->100->50->1111->150->NULL
---------------------------------

Operations on singly linked 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 : 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

---------------------------------

Operations on singly linked 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:
200->100->50->1111->150->NULL

---------------------------------

Operations on singly linked 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 : 5
Delete a Particular node:
Enter the position of value to be deleted: 1

---------------------------------

Operations on singly linked 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:
100->50->1111->150->NULL

---------------------------------

Operations on singly linked 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 : 6
Update Node Value:
Enter the node position to be updated: 1
Enter the new value: 1010
Node Updated

---------------------------------

Operations on singly linked 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:
1010->50->1111->150->NULL

---------------------------------

Operations on singly linked 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 : 7
Search element in Link List:
Enter the value to be searched: 50
Element 50 is found at position 2

---------------------------------

Operations on singly linked 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 : 9
Reverse elements of Link List

---------------------------------

Operations on singly linked 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

---------------------------------

Operations on singly linked 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 : 4
Sort Link List:

---------------------------------

Operations on singly linked 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

---------------------------------

Operations on singly linked 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 : 10
Exiting...
Doubly linked list
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

// 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;

cout<<endl<<"Operations on Doubly linked list"<<endl;


cout<<"1.Create Node"<<endl;
cout<<"2.Add at begining"<<endl;
cout<<"3.Add after position"<<endl;
cout<<"4.Delete"<<endl;
cout<<"5.Display"<<endl;
cout<<"6.Count"<<endl;
cout<<"7.Reverse"<<endl;
cout<<"8.Quit"<<endl;
while (1)
{
cout<<"Enter your choice : ";
cin>>choice;
switch ( choice )
{
case 1:
cout<<"Enter the element: ";
cin>>element;
dl.create_list(element);
cout<<endl;
break;
case 2:
cout<<"Enter the element: ";
cin>>element;
dl.add_begin(element);
cout<<endl;
break;
case 3:
cout<<"Enter the element: ";
cin>>element;
cout<<"Insert Element after postion: ";
cin>>position;
dl.add_after(element, position);
cout<<endl;
break;
case 4:
if (start == NULL)
{
cout<<"List empty,nothing to delete"<<endl;
break;
}
cout<<"Enter the element for deletion: ";
cin>>element;
dl.delete_element(element);
cout<<endl;
break;
case 5:
dl.display_dlist();
cout<<endl;
break;
case 6:
dl.count();
break;
case 7:
if (start == NULL)
{
cout<<"List empty,nothing to reverse"<<endl;
break;
}
dl.reverse();
cout<<endl;
break;
case 8:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
return 0;
}

void double_llist::create_list(int value)


{
struct node *s, *temp;
temp = new(struct node);
temp->info = value;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
}

void double_llist::add_begin(int value)


{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *temp;
temp = new(struct node);
temp->prev = NULL;
temp->info = value;
temp->next = start;
start->prev = temp;
start = temp;
cout<<"Element Inserted"<<endl;
}

void double_llist::add_after(int value, int pos)


{
if (start == NULL)
{
cout<<"First Create the list."<<endl;
return;
}
struct node *tmp, *q;
int i;
q = start;
for (i = 0;i < pos - 1;i++)
{
q = q->next;
if (q == NULL)
{
cout<<"There are less than ";
cout<<pos<<" elements."<<endl;
return;
}
}
tmp = new(struct node);
tmp->info = value;
if (q->next == NULL)
{
q->next = tmp;
tmp->next = NULL;
tmp->prev = q;
}
else
{
tmp->next = q->next;
tmp->next->prev = tmp;
q->next = tmp;
tmp->prev = q;
}
cout<<"Element Inserted"<<endl;
}

void double_llist::delete_element(int value)


{
struct node *tmp, *q;
/*first element deletion*/
if (start->info == value)
{
tmp = start;
start = start->next;
start->prev = NULL;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = start;
while (q->next->next != NULL)
{
/*Element deleted in between*/
if (q->next->info == value)
{
tmp = q->next;
q->next = tmp->next;
tmp->next->prev = q;
cout<<"Element Deleted"<<endl;
free(tmp);
return;
}
q = q->next;
}
/*last element deleted*/
if (q->next->info == value)
{
tmp = q->next;
free(tmp);
q->next = NULL;
cout<<"Element Deleted"<<endl;
return;
}
cout<<"Element "<<value<<" not found"<<endl;
}

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

Queue using Array


#include<iostream>

using namespace std;

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 insert(int item)


{
if ((front == 0 && rear == MAX - 1) || (front == rear + 1))
{
cout << "Queue Overflow \n";
return;
}
if (front == -1)
{
front = 0;
rear = 0;
}
else
{
if (rear == MAX - 1)
rear = 0;
else
rear = rear + 1;
}
cqueue_arr[rear] = item;
}

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

Enter your choice : 1


Input the element for insertion in queue : 2

Enter your choice : 1


Input the element for insertion in queue : 3

Enter your choice : 1


Input the element for insertion in queue : 4

Enter your choice : 1


Input the element for insertion in queue : 5

Enter your choice : 1


Input the element for insertion in queue : 6

Enter your choice : 3


Queue elements :
2 3 4 5 6

Enter your choice : 2


Element deleted from queue is : 2

Enter your choice : 1


Input the element for insertion in queue : 65

Enter your choice : 3


Queue elements :
3 4 5 6 65

Enter your choice : 1


Input the element for insertion in queue : 8
Queue Overflow

Enter your choice : 3


Queue elements :
3 4 5 6 65

Enter your choice : 1


Input the element for insertion in queue : 65
Queue Overflow

Enter your choice : 2


Element deleted from queue is : 3

Enter your choice : 2


Element deleted from queue is : 4

Enter your choice : 2


Element deleted from queue is : 5

Enter your choice : 3


Queue elements :
6 65

Enter your choice : 1


Input the element for insertion in queue : 56

Enter your choice : 3


Queue elements :
6 65 56

Enter your choice :4


Stack using Linked List
#include<iostream>
#include<cstdlib>

using namespace std;

struct node {
int info;
struct node *link;
} *top;

class stack_list {

public:
node *push(node *, int);

node *pop(node *);

void traverse(node *);

stack_list()
{
top = NULL;
}
};

int main()
{
int choice, item;
stack_list sl;

cout << "Operations on Stack" << endl;


cout << "\n-------------" << endl;
cout << "1.Push Element into the Stack" << endl;
cout << "2.Pop Element from the Stack" << endl;
cout << "3.Traverse the Stack" << endl;
cout << "4.Quit" << endl;
while (1)
{
cout << "\nEnter your Choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter value to be pushed into the stack: ";
cin >> item;
top = sl.push(top, item);
break;
case 2:
top = sl.pop(top);
break;
case 3:
sl.traverse(top);
break;
case 4:
exit(1);
default:
cout << "Wrong Choice" << endl;
}
}
}

node *stack_list::push(node *top, int item)


{
node *tmp;
tmp = new (struct node);
tmp->info = item;
tmp->link = top;
top = tmp;
return top;
}

node *stack_list::pop(node *top)


{
node *tmp;
if (top == NULL)
cout << "Stack is Empty" << endl;
else
{
tmp = top;
cout << "Element Popped: " << tmp->info << endl;
top = top->link;
free(tmp);
}
return top;
}

void stack_list::traverse(node *top)


{
node *ptr;
ptr = top;
if (top == NULL)
cout << "Stack is empty" << endl;
else
{
cout << "Stack elements :" << endl;
while (ptr != NULL)
{
cout << ptr->info << endl;
ptr = ptr->link;
}
}
}
Output
Operations on Stack

-------------
1.Push Element into the Stack
2.Pop Element from the Stack
3.Traverse the Stack
4.Quit

Enter your Choice: 1


Enter value to be pushed into the stack: 10

Enter your Choice: 1


Enter value to be pushed into the stack: 20

Enter your Choice: 1


Enter value to be pushed into the stack: 30

Enter your Choice: 1


Enter value to be pushed into the stack: 40

Enter your Choice: 3


Stack elements :
40
30
20
10

Enter your Choice: 2


Element Popped: 40

Enter your Choice: 2


Element Popped: 30

Enter your Choice: 3


Stack elements :
20
10

Enter your Choice: 4


Linear Search
#include<iostream>

using namespace std;

int main()
{
int a[100], i, n, item, s = 0;
cout << "\n------------ LINEAR SEARCH ------------ \n\n";
cout << "Enter No. of Elements=";
cin >> n;

cout << "\nEnter Elements=\n";


for (i = 1; i <= n; i++)
{
cin >> a[i];
}

cout << "\nEnter Element you want to Search=";


cin >> item;

for (i = 1; i <= n; i++)


{
if (a[i] == item)
{
cout << "\nElement is Found at Location : " << i;
s = 1;
break;
}
}

if (s == 0)
{
cout << "Data is Not Found";
}
return 0;
}
Output

------------ LINEAR SEARCH ------------

Enter No. of Elements=5

Enter Elements=
1
8
4
7
6

Enter Element you want to Search=4

Element is Found at Location : 3


Binary Search
#include<iostream>

using namespace std;

int main()
{
int a[100], n, i, beg, end, mid, item;
cout << "\n------------ BINARY SEARCH ------------ \n\n";
cout << "Enter No. of Elements= ";
cin >> n;

cout << "\nEnter Elements in Sorted Order=\n";


for (i = 1; i <= n; i++)
{
cin >> a[i];
}

cout << "\nEnter Item you want to Search= ";


cin >> item;

beg = 1;
end = n;

mid = (beg + end) / 2;

while (beg <= end && a[mid] != item)


{
if (a[mid] < item)
beg = mid + 1;
else
end = mid - 1;

mid = (beg + end) / 2;


}

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>

using namespace std;


struct node {
int priority;
int info;
struct node *link;
};

class Priority_Queue {
private:
node *front;
public:
Priority_Queue()
{
front = NULL;
}

void insert(int item, int priority)


{
node *tmp, *q;
tmp = new node;
tmp->info = item;
tmp->priority = priority;
if (front == NULL || priority < front->priority)
{
tmp->link = front;
front = tmp;
}
else
{
q = front;
while (q->link != NULL && q->link->priority <= priority)
q = q->link;
tmp->link = q->link;
q->link = tmp;
}
}

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

Enter your choice : 1


Input the item value to be added in the queue : 45
Enter its priority : 3

Enter your choice : 1


Input the item value to be added in the queue : 58
Enter its priority : 4

Enter your choice : 1


Input the item value to be added in the queue : 68
Enter its priority : 1

Enter your choice : 1


Input the item value to be added in the queue : 50
Enter its priority : 2

Enter your choice : 3


Queue is :
Priority Item
1 68
2 50
3 45
4 58

Enter your choice : 2


Deleted item is: 68

Enter your choice : 3


Queue is :
Priority Item
2 50
3 45
4 58

Enter your choice :4


Binary Search Tree & Operations
#include <iostream>
#include <cstdlib>

using namespace std;

class BinarySearchTree {
private:
struct tree_node {
tree_node *left;
tree_node *right;
int data;
};

tree_node *root;

public:
BinarySearchTree()
{
root = NULL;
}

bool isEmpty() const


{ return root == NULL; }

void print_inorder();

void inorder(tree_node *);

void print_preorder();

void preorder(tree_node *);

void print_postorder();

void postorder(tree_node *);

void insert(int);

void remove(int);

};

// Smaller elements go left


// larger elements go right
void BinarySearchTree::insert(int d)
{
tree_node *t = new tree_node;
tree_node *parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if (isEmpty()) root = t;
else
{
//Note: ALL insertions are as leaf nodes
tree_node *curr;
curr = root;
// Find the Node's parent
while (curr)
{
parent = curr;
if (t->data > curr->data) curr = curr->right;
else curr = curr->left;
}

if (t->data < parent->data)


parent->left = t;
else
parent->right = t;
}
}

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

// Node with single child


if ((curr->left == NULL && curr->right != NULL) || (curr->left !=
NULL
&& curr->right
== NULL))
{
if (curr->left == NULL && curr->right != NULL)
{
if (parent->left == curr)
{
parent->left = curr->right;
delete curr;
}
else
{
parent->right = curr->right;
delete curr;
}
}
else // left child present, no right child
{
if (parent->left == curr)
{
parent->left = curr->left;
delete curr;
}
else
{
parent->right = curr->left;
delete curr;
}
}
return;
}

//We're looking at a leaf node


if (curr->left == NULL && curr->right == NULL)
{
if (parent->left == curr) parent->left = NULL;
else parent->right = NULL;
delete curr;
return;
}

//Node with 2 children


// replace node with smallest value in right subtree
if (curr->left != NULL && curr->right != NULL)
{
tree_node *chkr;
chkr = curr->right;
if ((chkr->left == NULL) && (chkr->right == NULL))
{
curr = chkr;
delete chkr;
curr->right = NULL;
}
else // right child has children
{
//if the node's right child has a left child
// Move all the way down left to locate smallest element

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::inorder(tree_node *p)


{
if (p != NULL)
{
if (p->left) inorder(p->left);
cout << " " << p->data << " ";
if (p->right) inorder(p->right);
}
else return;
}

void BinarySearchTree::print_preorder()
{
preorder(root);
}

void BinarySearchTree::preorder(tree_node *p)


{
if (p != NULL)
{
cout << " " << p->data << " ";
if (p->left) preorder(p->left);
if (p->right) preorder(p->right);
}
else return;
}

void BinarySearchTree::print_postorder()
{
postorder(root);
}

void BinarySearchTree::postorder(tree_node *p)


{
if (p != NULL)
{
if (p->left) postorder(p->left);
if (p->right) postorder(p->right);
cout << " " << p->data << " ";
}
else return;
}

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>

using namespace std;

void max_heapify(int *a, int i, int n)


{
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n)
{
if (j < n && a[j + 1] > a[j])
j = j + 1;
if (temp > a[j])
break;
else if (temp <= a[j])
{
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j / 2] = temp;
return;
}

void heapsort(int *a, int n)


{
int i, temp;
for (i = n; i >= 2; i--)
{
temp = a[i];
a[i] = a[1];
a[1] = temp;
max_heapify(a, 1, i - 1);
}
}

void build_maxheap(int *a, int n)


{
int i;
for (i = n / 2; i >= 1; i--)
{
max_heapify(a, i, n);
}
}

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>

using namespace std;

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;
}
}

cout << "Insertion Sort Output" << endl;


for (k = 0; k < n; k++)
{
cout << a[k] << endl;
}

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 st1[100], st2[100];


int top1 = -1, top2 = -1;
int count = 0;

int main()
{
int ch;

cout<<"1-enter element into queue ";


// printf("\n2 - Dequeu element from queue");
cout<<"\n2-display elements ";
cout<<"\n3-exit from execution";
create();
while (1)
{
cout<<"\n\nenter your choice :";
cin>>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;
}

/*Function to push the element on to the stack*/


void push1(int data)
{
st1[++top1] = data;
}

/*Function to pop the element from the stack*/


int pop1()
{
return(st1[top1--]);
}

/*Function to push an element on to stack*/


void push2(int data)
{
st2[++top2] = data;
}

/*Function to pop an element from the stack*/

int pop2()
{
return(st2[top2--]);
}

/*Function to add an element into the queue using stack*/


void enqueue()
{
int data, i;

cout<<"enter data into queue :";


cin>>data;
push1(data);
count++;
}

/*Function to display the elements in the stack*/

void display()
{
int i;

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


{
cout<<st1[i]<<"\t";

}
}
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>

using namespace std;

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;
}

void InsertFront(int element)


{
// Create a new node
Node *tmp = new Node();
tmp->data = element;
tmp->next = NULL;
tmp->prev = NULL;

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();
}

// Data in the front node


int ret = front->data;

// Delete the front node and fix the links


Node *tmp = front;
if (front->next != NULL)
{
front = front->next;
front->prev = NULL;
}
else
{
front = NULL;
}
count--;
delete tmp;

return ret;
}

void InsertBack(int element)


{
// Create a new node
Node *tmp = new Node();
tmp->data = element;
tmp->next = NULL;
tmp->prev = NULL;

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();
}

// Data in the rear node


int ret = rear->data;

// Delete the front node and fix the links


Node *tmp = rear;
if (rear->prev != NULL)
{
rear = rear->prev;
rear->next = NULL;
}
else
{
rear = NULL;
}
count--;
delete tmp;

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;
}

// Queue behavior using a general dequeue


Deque dq1;
try
{
if (dq1.isEmpty())
{
cout << "Deque is empty" << 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>

using namespace std;

struct node {
int fr, to, cost;
} p[6];

int c = 0, dist1 = 0, dist = 0;

void primsalgo(int *ptr, int b[][7], int i, int j)


{
ptr[i] = 1;
while (c < 6)
{
int min = 999;
for (int i = 0; i < 7; i++)
{
if (ptr[i] == 1)
{
for (int j = 0; j < 7;)
{
if (b[i][j] >= min || b[i][j] == 0)
{
j++;
}
else if (b[i][j] < min)
{
min = b[i][j];
dist = i;
dist1 = j;
}
}
}
}
ptr[dist1] = 1;
p[c].fr = dist;
p[c].to = dist1;
p[c].cost = min;
c++;
b[dist][dist1] = b[dist1][dist] = 1000;
}
for (int k = 0; k < 6; k++)
{
cout << "source node : " << p[k].fr << endl;
cout << "destination node : " << p[k].to << endl;
cout << "weight of node : " << p[k].cost << endl;
}
}

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

enter values for 1 row :


1 1 1 1 1 1 1
enter values for 2 row :
2 2 2 2 2 2 2
enter values for 3 row :
3 3 3 3 3 3 3
enter values for 4 row :
4 4 4 4 4 4 4
enter values for 5 row :
5 5 5 5 5 5 5
enter values for 6 row :
6 6 6 6 6 6 6
enter values for 7 row :
7 7 7 7 7 7 7
source node : 0
destination node : 0
weight of node : 1
source node : 0
destination node : 1
weight of node : 1
source node : 0
destination node : 2
weight of node : 1
source node : 0
destination node : 3
weight of node : 1
source node : 0
destination node : 4
weight of node : 1
source node : 0
destination node : 5
weight of node : 1
Double Queue
#include<iostream>

using namespace std;

class nodecreation {
public:
int data;

class nodecreation *next;

class nodecreation *prev;


};

class dqueueoperation : public nodecreation {


nodecreation *head, *tail;
int top1, top2;

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)
{

cout << "\nEnter your choice : ";


cin >> ch;
switch (ch)
{
case 1:
cout << "\nEnter element : ";
cin >> ch;
d1.push(ch);
break;

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

Add element 1.FIRST 2.LAST


Enter your choice : 1
Enter your choice : 1

Enter element : 45

Add element 1.FIRST 2.LAST


Enter your choice : 2
Enter your choice : 2

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;

void bubble_sort(vector<int> &a)


{
for (int i = a.size(); i > 0; i--)
{
for (int j = 0, k = 1; k < i; j++, k++)
{
if (a[j] > a[k])
{
int swap = a[j];
a[j] = a[k];
a[k] = swap;
}
}
}
}

int main()
{
int alen, val;
vector<int> a;

cout << "Enter the number of elements : ";


cin >> alen;
for (int i = 0; i < alen; i++)
{
cin >> val;
a.push_back(val);
}

bubble_sort(a);

cout << "List of sorted elements: " << endl;


for (int i = 0; i < alen; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}
Output
Enter the number of elements : 8
6
4
2
3
5
1
7
8
List of sorted elements:
1 2 3 4 5 6 7 8
Selection Sort
#include<iostream>

using namespace std;

int main()
{
int a[100], i, n, p, k, min, loc, temp;

cout << "\n------------ SELECTION SORT ------------ \n\n";


cout << "Enter No. of Elements=";
cin >> n;

cout << "\nEnter Elements=\n";


for (i = 1; i <= n; i++)
{
cin >> a[i];
}

for (p = 1; p <= n - 1; p++)


{
min = a[p];
loc = p;

for (k = p + 1; k <= n; k++)


{
if (min > a[k])
{
min = a[k];
loc = k;
}
}
temp = a[p];
a[p] = a[loc];
a[loc] = temp;
}

cout << "\nAfter Sorting : \n";

for (i = 1; i <= n; i++)


{
cout << a[i] << endl;
}

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;

cout << "\n------------ INSERTION SORT ------------ \n\n";


cout << "Enter No. of Elements : ";
cin >> n;

cout << "\nEnter Elements : \n";


for (i = 1; i <= n; i++)
{
cin >> a[i];
}

a[0] = 0;

for (p = 2; p <= n; p++)


{
temp = a[p];
ptr = p - 1;

while (temp < a[ptr])


{
a[ptr + 1] = a[ptr];
ptr--;
}

a[ptr + 1] = temp;
}

cout << "\nAfter Sorting : \n";


for (i = 1; i <= n; i++)
{
cout << a[i] << endl;
}

return 0;
}
Output

------------ INSERTION SORT ------------

Enter No. of Elements : 8

Enter Elements :
9
7
1
6
3
4
5
8

After Sorting :
1
3
4
5
6
7
8
9
Quick Sort
#include<iostream>

using namespace std;

int Partition(int a[], int beg, int end)


{
int p = beg, pivot = a[beg], loc;

for (loc = beg + 1; loc <= end; loc++)


{
if (pivot > a[loc])
{
a[p] = a[loc];
a[loc] = a[p + 1];
a[p + 1] = pivot;

p = p + 1;
}
}
return p;
}

void QuickSort(int a[], int beg, int end)


{
if (beg < end)
{
int p = Partition(a, beg, end);
QuickSort(a, beg, p - 1);
QuickSort(a, p + 1, end);
}
}

int main()
{
int a[100], i, n, beg, end;

cout << "\n------- QUICK SORT -------\n\n";


cout << "Enter the No. of Elements : ";
cin >> n;

for (i = 1; i <= n; i++)


{
cin >> a[i];
}
beg = 1;
end = n;

QuickSort(a, beg, end);

cout << "\nAfter Sorting : \n";


for (i = 1; i <= n; i++)
{
cout << a[i] << endl;
}
return 0;
}
Output
------- QUICK SORT -------

Enter the No. of Elements : 8


9
1
6
4
2
8
3
7

After Sorting :
1
2
3
4
6
7
8
9
Merge Sort
#include <iostream>

using namespace std;

void merge(int *, int, int, int);

void mergesort(int *a, int low, int high)


{
int mid;
if (low < high)
{
mid = (low + high) / 2;
mergesort(a, low, mid);
mergesort(a, mid + 1, high);
merge(a, low, high, mid);
}
return;
}

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


{
int i, j, k, c[50];
i = low;
k = low;
j = mid + 1;
while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
c[k] = a[i];
k++;
i++;
}
else
{
c[k] = a[j];
k++;
j++;
}
}
while (i <= mid)
{
c[k] = a[i];
k++;
i++;
}
while (j <= high)
{
c[k] = a[j];
k++;
j++;
}
for (i = low; i < k; i++)
{
a[i] = c[i];
}
}

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>

using namespace std;

bool myfunction(int i, int j)


{
return (i < j);
}

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);

sort(myvector.begin(), myvector.begin() + 4);

// using function as comp


sort(myvector.begin() + 4, myvector.end(), myfunction);

// using object as comp


sort(myvector.begin(), myvector.end(), myobject);

// print out content:

cout << "sorted matrix contains:";


for (vector<int>::iterator it = myvector.begin(); it !=
myvector.end(); ++it)
cout << ' ' << *it;

cout << '\n';

return 0;
}
Output

sorted matrix contains: 26 152 171 312 334 353 435 980
Linear Sort
#include <iostream>

#define MAXSIZE 100


using namespace std;

class linearsort
{
int arr[MAXSIZE], n;

public:
void getdataelements();

void showdataelements();

void sortelements();
};

void linearsort::getdataelements()
{
cout << "How many elements you want : ";
cin >> n;

cout << "enter elements :\n";


for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
}

void linearsort::showdataelements()
{
cout << "\nDisplay sorted elements\n";

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


{
cout << arr[i] << " ";
}

}
void linearsort::sortelements()
{
int temp;

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


{
for (int j = i; j < n; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

//main method
int main()
{
cout << "\nLinear Sort Method\n\n";
linearsort obj;
obj.getdataelements();
obj.sortelements();
obj.showdataelements();

return 0;
}
Output

Linear Sort Method

How many elements you want : 7


enter elements :
2
5
3
6
7
4
6

Display sorted elements


2 3 4 5 6 6 7
Radix Sort
#include<iostream>

using namespace std;

// A utility function to get maximum value in arr[]


int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
{
if (arr[i] > mx)
mx = arr[i];
}
return mx;
}

// A function to do counting sort of arr[] according to


// the digit represented by exp.
void countSort(int arr[], int n, int exp)
{
int output[n]; // output array
int i, count[10] = {0};

// Store count of occurrences in count[]


for (i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;

// Change count[i] so that count[i] now contains actual


// position of this digit in output[]
for (i = 1; i < 10; i++)
count[i] += count[i - 1];

// Build the output array


for (i = n - 1; i >= 0; i--)
{
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

// Copy the output array to arr[], so that arr[] now


// contains sorted numbers according to current digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}

// The main function to that sorts arr[] of size n using


// Radix Sort
void radixsort(int arr[], int n)
{
// Find the maximum number to know number of digits
int m = getMax(arr, n);

// Do counting sort for every digit. Note that instead


// of passing digit number, exp is passed. exp is 10^i
// where i is current digit number
for (int exp = 1; m / exp > 0; exp *= 10)
countSort(arr, n, exp);
}

// A utility function to print an array


void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}

// Driver program to test above functions


int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}
Output
2 24 45 66 75 90 170 802
Shell Sort
#include <iostream>

using namespace std;

//Print values
void print_ar(int ar[], int size)
{
for (int i = 0; i < size; ++i)
{
cout << ar[i] << " ";
}
cout << endl;
}

//Shell sort function


void shell_sort(int ar[], int size)
{
int j;

//Narrow the array by 2 everytime


for (int gap = size / 2; gap > 0; gap /= 2)
{
for (int i = gap; i < size; ++i)
{
int temp = ar[i];
for (j = i; j >= gap && temp < ar[j - gap]; j -= gap)
{
ar[j] = ar[j - gap];
}
ar[j] = temp;
}
}
}

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);

cout << "Sorted Array : ";


print_ar(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>

using namespace std;

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;

double dbl1 = 1.5;


double dbl2 = 210.87;
cout << "Max(dbl1, dbl2): " << Max(dbl1, dbl2) << endl;

string str1 = "Hey";


string str2 = "maximum here";
cout << "Max(str1, str2): " << Max(str1, str2) << 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;

cout << "enter two numbers : ";


cin >> num1;
cin >> num2;

/*
Pass the value of num1 and num2 as parameter to function add.
The value returned is stored in the variable output
*/

output = add(num1, num2);


cout << "addition of number " << num1 << " and " << num2 << " = " <<
output;

// Defining the function add()


int add(int no1, int no2)
{
int result;
result = no1 + no2;
return result;
}
Output
enter two numbers : 5 6 addition of number 5 and 6 = 11
Call by Reference
#include<stdio.h>
#include<iostream>

using namespace std;

int add(int *, int *);

int main()
{
int num1 = 0, num2 = 0, output;

cout << "enter two numbers : ";


cin >> num1;
cin >> num2;

output = add(&num1, &num2);


cout << "addition of two numbers = " << num1 << " + " << num2 << " =
" << output;

// Defining the function add()


int add(int *n1, int *n2)
{
int result;
result = *n1 + *n2;
return result;

return 0;
}
Output

enter two numbers : 5 5


addition of two numbers = 5 + 5 = 10
Calculation using inline function
#include <iostream>

using namespace std;

inline int add(int num1, int num2)


{
return num1 + num2;
}

inline int sub(int num1, int num2)


{
return num1 - num2;
}

inline int mult(int num1, int num2)


{
return num1 * num2;
}

inline int div(int num1, int num2)


{
return num1 / num2;
}

// Main function for the program


int main()
{

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>

using namespace std;

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;

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


{
for (j = 0; j < size - 1; j++)
{
if (chars[j + 1] < chars[j])
{
temp = chars[j];
chars[j] = chars[j + 1];
chars[j + 1] = temp;
}
}
}

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


{
cout << chars[i] << " ";
}

return 0;
}
Output

Enter the number of characters:6


Enter 6 characters:batman
a a b m n t
inline function
#include <iostream>

using namespace std;

inline int add(int num1, int num2)


{
return num1 + num2;
}

inline int sub(int num1, int num2)


{
return num1 - num2;
}

inline int mult(int num1, int num2)


{
return num1 * num2;
}

inline int div(int num1, int num2)


{
return num1 / num2;
}

// Main function for the program


int main()
{
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
getline function
#include<iostream>

using namespace std;

int main()
{
string name;

cout << "Enter your full name: ";


getline(cin, name);
cout << "Hello, " << name << "!\n";

return 0;
}
Output

Enter your full name: Creative Cub


Hello, Creative Cub!
Using flush member function
#include <iostream>
#include <iomanip>

using namespace std;

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>

using namespace std;

//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;
}

//Static function staticFunction( ) defined with keyword static


static void staticFunction()
{
cout << "\nResult is : " << sum;
}
//Normal member function normalFunctionNumber()
void normalFunctionNumber()
{
cout << "\nNumber is : " << x;
}
};

int staticDemo::sum = 0;

//declaration of main method


int main()
{
cout << "This is how static method and variable work : \n";
//creation of object
staticDemo stat;

//Static function staticFunction() accessed using class name


staticDemo and the scope resolution operator ::
staticDemo::staticFunction();

//
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>

using namespace std;

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>

using namespace std;

int main()
{

int i = 1;

while (i <= 10)


{
cout << "value of i: " << i << endl;
i++;
}

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>

using namespace std;

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>

using namespace std;

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>

using namespace std;

int main()
{
//Vector to store integers
vector<int> vex;
cout << "added value in vector :\n";

//add value in vector


vex.push_back(130);
vex.push_back(500);
vex.push_back(353);
for (int x = 0; x < vex.size(); x++)
{
//Should output 130 500 353
cout << vex[x] << " ";
}

//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);
}

for (int y = 0; y < vex.size(); y++)


{
//Should output 10 20
cout << vex[y] << " ";
}
return 0;
}
Output

added value in vector :


130 500 353 10 20
break keyword
#include<iostream>

using namespace std;

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>

using namespace std;

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

Enter any non-zero Number : -9


Number is negative
endl keyword
#include <iostream>

using namespace std;

int main()
{
int num;
num = 50;

cout << "number is=" << num << endl;


//endl is manipulator
//endl is output manipulator
cout << "value of number=" << num << "\n";
}
Output
number is=50 value of number=50
Pointer Example
#include <iostream>

using namespace std;

int main()
{
int var;
char var_array[10];

cout << "Address of variable1 is : ";


cout << &var << "\n";

cout << "Address of variable2 is : ";


cout << &var_array << "\n";

return 0;
}
Output

Address of variable1 is : 0x29feec


Address of variable2 is : 0x29fee2
Find ASCII value of a character
#include <iostream>

using namespace std;

int main()
{
//variable declaration
char asciichar;

//take user input


cout << "Enter a character : ";
cin >> asciichar;

//display ascii value of character


cout << "\nIt's ascii value is : " << (int) asciichar << endl;

return 0;
}
Output
Enter a character : a It's ascii value is : 97
Add Two Numbers
#include<iostream>

using namespace std;

int main()
{
//variable declaration
int num1, num2, result;

//take user input


cout << "Enter first Number : ";
cin >> num1;

cout << "\nEnter second Number : ";


cin >> num2;

//to add two number


result = num1 + num2;

//display addition
cout << "\nAddition is : " << result;

return 0;
}
Output

Enter first Number : 2 3

Enter second Number :


Addition is : 5
Try catch
#include <iostream>

using namespace std;

double divisionby(int num1, int num2)


{
if (num2 == 0)
{
throw "Division by zero condition!";
}
cout << "answer = ";
return (num1 / num2);
}

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;

//take user input


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 : 3 5


answer = 0
Copy contents from file A to B
#include<iostream>
#include<iomanip>
#include<fstream>

using namespace std;

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

Enter a file name to be copied : old.txt


Enter new file name : new.txt
Writing content to the text file
#include <fstream>
#include <iostream>

using namespace std;

int main()
{

char data[1000];

//in write mode.


ofstream outfile;
outfile.open("file.txt");

cout << "Writing content to the text file" << endl;


cout << "Enter your name : ";
cin.getline(data, 1000);

// write data into the file.


outfile << data << endl;

cout << "Enter your age : ";


cin >> data;
cin.ignore();

// again write inputted data into the file.


outfile << data << endl;

cout << "successfully inserted data into file";


// close the opened file.
outfile.close();
return 0;
}
Output

Writing content to the text file


Enter your name : Yogesh
Enter your age : 22
successfully inserted data into file
Reading content from the file
#include <fstream>
#include <iostream>

using namespace std;


//main method declaration
int main()
{

char data[1000];

// open a file in read mode.


ifstream infile;
infile.open("file.cpp");

cout << "Reading content from the file" << endl;


infile >> data;

// write the data


cout << data << endl;

//read the data from the file and display it.


infile >> data;
cout << data << endl;

// close the opened file.


infile.close();

return 0;
}
Output
Reading content from the file Bhagyashree 22
Depth First Search
#include<iostream>

using namespace std;

int main()
{
int cost[10][10], i, j, k, vertice, stk[10], top, v, visit[10],
visited[10], edge;

cout << "Enter numbers of vertice : ";


cin >> vertice;
cout << "\nEnter numbers of edge : ";
cin >> edge;
cout << "\nEDGES \n";

for (k = 1; k <= edge; k++)


{
cin >> i >> j;
cost[i][j] = 1;
}

cout << "\nEnter initial vertex : ";


cin >> v;
cout << "\nORDER OF VISITED VERTICES IS : ";
cout << v << " ";
visited[v] = 1;
k = 1;
while (k < vertice)
{
for (j = vertice; j >= 1; j--)
{
if (cost[v][j] != 0 && visited[j] != 1 && visit[j] != 1)
{
visit[j] = 1;
stk[top] = j;
top++;
}
}

v = stk[--top];
cout << v << " ";
k++;
visit[v] = 0;
visited[v] = 1;
}

return 0;
}
Output

Enter numbers of vertice : 3

Enter numbers of edge : 2

EDGES
1 2
3 4

Enter initial vertex : 2

ORDER OF VISITED VERTICES IS : 2 1 3