SlideShare a Scribd company logo
C++ Programms
cs567
Abstract Class Example
#include <iostream>
using namespace std;
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
C++ Programms
cs567
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
Accessing Characters In Strings
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string text;
cout << "Counts words. Enter a text and terminate with a period and
return:n";
getline( cin, text, '.'); // Reads a text up to the first '.'
int i, // Index
numberOfWhiteSpace = 0, // Number of white spaces
numberOfWords = 0; // Number of words
bool fSpace = true; // Flag for white space
for( i = 0; i < text.length(); ++i)
{
if( isspace( text[i]) ) // white space?
{
C++ Programms
cs567
++numberOfWhiteSpace;
fSpace = true;
}
else if( fSpace) // At the beginning of a word?
{
++numberOfWords;
fSpace = false;
}
}
cout << "nYour text contains (without periods)"
<< "ncharacters: " << text.length()
<< "nwords: " << numberOfWords
<< "nwhite spaces: " << numberOfWhiteSpace
<< endl;
return 0;
}
Armstrong Number
# include <iostream.h>
# include <conio.h>
# include <math.h>
void main ()
{
clrscr();
int a,b=0,sum=0;
long int n;
cout<<"Enter the NO. : ";
cin>>n;
for(;n>0;)
//counts the digits
{
a=n%10;
n=n/10;
b++;
}
for(;n>0;)
C++ Programms
cs567
{
a=n%10;
sum=sum+pow(a,b);
n=n/10;
}
if(sum==n)
{
cout<<"IT IS AN ARMSTRONG NUMBER...";
getch();
}
else
{
cout<<"IT IS NOT AN ARMSTRONG NUMBER...";
getch();
}
}
Accessing Data in a File
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
template <class T>
void print(T & c)
{
for( typename T::iterator i = c.begin(); i != c.end(); i++ )
{
std::cout << *i << endl;
}
}
int main()
{
C++ Programms
cs567
vector <int> output_data( 10 );
generate( output_data.begin(), output_data.end(), rand );
transform( output_data.begin(), output_data.end(),output_data.begin(),
bind2nd( modulus<int>(), 10 ) );
ofstream out( "data.txt" );
if( !out )
{
cout << "Couldn't open output filen";
return 0;
}
copy( output_data.begin(), output_data.end(),ostream_iterator<int>( out,
"n" ) );
out.close();
ifstream in( "data.txt" );
if( !in )
{
cout << "Couldn't open input filen";
return 0;
}
vector<int> input_data( (istream_iterator<int>( in )),istream_iterator<int>()
);
in.close();
print( output_data );
print( input_data );
}
Accessing Static members without an object
#include <iostream>
using namespace std;
class Cat
{
public:
Cat(int age):itsAge(age){count++; }
virtual ~Cat() { count--; }
virtual int GetAge() { return itsAge; }
virtual void SetAge(int age) { itsAge = age; }
C++ Programms
cs567
static int count;
private:
int itsAge;
};
int Cat::count = 0;
void TelepathicFunction();
int main()
{
const int MaxCats = 5; int i;
Cat *CatHouse[MaxCats];
for (i = 0; i< MaxCats; i++)
{
CatHouse[i] = new Cat(i);
TelepathicFunction();
}
for ( i = 0; i< MaxCats; i++)
{
delete CatHouse[i];
TelepathicFunction();
}
return 0;
}
void TelepathicFunction()
{
cout << "There are ";
cout << Cat::count << " cats alive!n";
}
A Generic bubble sort
#include <iostream>
using namespace std;
template <class X>
void bubble(X *data, int size)
{
register int a, b;
X t;
C++ Programms
cs567
for(a=1; a < size; a++)
for(b=size-1; b >= a; b--)
if(data[b-1] > data[b])
{
t = data[b-1];
data[b-1] = data[b];
data[b] = t;
}
}
int main()
{
int i[] = {3, 2, 5, 6, 1, 8, 9, 3, 6, 9};
double d[] = {1.2, 5.5, 2.2, 3.3};
int j;
bubble(i, 10); // sort ints
bubble(d, 4); // sort doubles
for(j=0; j<10; j++)
cout << i[j] << ' ';
cout << endl;
for(j=0; j<4; j++)
cout << d[j] << ' ';
cout << endl;
return 0;
}
Area Overloded
#include<iostream.h>
#include<conio.h>
#define phi 3.14
int area(int,int);
float area(int);
void main()
{
int a,b,c,cho;
clrscr();
cout<<"t What do you want to do?n";
C++ Programms
cs567
cout<<"1. area of rectangle"<<endl;
cout<<"2. area of circle"<<endl;
cout<<"Choice:";
cin>>cho;
switch(cho)
{
case 1:
cout<<"Enter lengt and breath (with white space):";
cin>>a>>b;
cout<<"Area of RECTANGLE:"<<area(a,b);
break;
case 2:
cout<<"Enter radius:";
cin>>c;
cout<<"Area of CIRCLE:"<<area(c);
break;
}
getch();
}
int area(int x,int y)
{
return (x*y);
}
float area(int s)
{
return (phi*s*s);
}
A Simple Example of Inheritance
#include <iostream>
using namespace std;
class BaseClass
{
int i;
public:
void setInt(int n);
C++ Programms
cs567
int getInt();
};
class DerivedClass : public BaseClass
{
int j;
public:
void setJ(int n);
int mul();
};
void BaseClass::setInt(int n)
{
i = n;
}
int BaseClass::getInt()
{
return i;
}
void DerivedClass::setJ(int n)
{
j = n;
}
int DerivedClass::mul()
{
return j * getInt();
}
int main()
{
DerivedClass ob;
ob.setInt(10); // load i in BaseClass
ob.setJ(4); // load j in DerivedClass
cout << ob.mul(); // displays 40
return 0;
}
C++ Programms
cs567
A simple stack example: push, empty, pop and top
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<char> stackObject;
stackObject.push('A');
stackObject.push('B');
stackObject.push('C');
stackObject.push('D');
while(!stackObject.empty())
{
cout << "Popping: ";
cout << stackObject.top() << endl;
stackObject.pop();
}
return 0;
}
A Static member variable example.
#include <iostream>
using namespace std;
class myclass
{
static int i;
public:
void setInt(int n)
{
i = n;
}
int getInt()
{
return i;
}
};
C++ Programms
cs567
int myclass::i; // Definition of myclass::i. i is still private to myclass.
int main()
{
myclass object1, object2;
object1.setInt(10);
cout << "object1.i: " << object1.getInt() << 'n'; // displays 10
cout << "object2.i: " << object2.getInt() << 'n'; // also displays 10
return 0;
}
Binary Search
#include < iostream.h >
template < class T >
int binarySearch(T a[], int n, T & x)
{
int left = 0; // left end of segment
int right = n - 1; // right end of segment
while (left <= right)
{
int middle = (left + right)/2; // middle of segment
if (x == a[middle])
return middle;
if (x > a[middle])
left = middle + 1;
else
right = middle - 1;
}
return -1; // x not found
}
int main()
{
int a[10],n,t;
cout<<"Enter the size:";
cin>>n;
cout<<"enter the elements in sorted order:";
for(int i=0;i< n;i++)
C++ Programms
cs567
cin >>a[i];
cout<<"enter the element to search:";
cin>>t;
int f=binarySearch(a,n,t);
if(f==-1)
cout<<"element not found";
else
cout<<"element found at index:"<
}
Complex Number
#include<iostream.h>
#include<conio.h>
class complex
{
private:
float real,img;
public:
void assign(float x,float y)
{
real=x;
img=y;
}
void print()
{
if(img>=0)
cout<< real<<"+"<< img<<"i";
else
cout<< real<< img<<"i";
getch();
}
};
void add( float a,float b,float c, float d)
{
float e,f;complex g;
e=a+c;
C++ Programms
cs567
f=b+d;
g.assign(e,f);
g.print();
}
void sub( float a,float b,float c, float d)
{
float e,f;complex g;
e=a-c;
f=b-d;
g.assign(e,f);
g.print();
}
void mul( float a,float b,float c, float d)
{
float e,f; complex g;
e=a*c-b*d;
f=b*c+a*d;
g.assign(e,f);
g.print();
}
void main()
{
float a,b,c,d;
complex x,y,z;
clrscr();
cout<<" for complex 1:";
cout<<"real part:";
cin>>a;
cout<<"imaginary part:";
cin>>b;
cout<<" for complex 2:";
cout<<"real part:";
cin>>c;
cout<<"imaginary part:";
cin>>d;
x.assign(a,b);
y.assign(c,d);
C++ Programms
cs567
cout<<"***original data:***n";
cout<<"Complex 1:n";x.print();
cout<<"n Complex 2:n";y.print();
cout<<"n***n";
cout<<"n Addition:n";add(a,b,c,d);
cout<<"n Subtraction:n";sub(a,b,c,d);
cout<<"n Multipication:n";mul(a,b,c,d);
}
Constructor and Destructor
#include <iostream>
using namespace std;
#define SIZE 10
class stack
{
int stck[SIZE];
int topOfStack;
public:
stack(); // constructor
~stack(); // destructor
void push(int i);
int pop();
};
// constructor
stack::stack()
{
topOfStack = 0;
cout << "Stack Initializedn";
}
// destructor
stack::~stack()
{
cout << "Stack Destroyedn";
}
void stack::push(int i)
{
C++ Programms
cs567
if( topOfStack == SIZE )
{
cout << "Stack is full.n";
return;
}
stck[ topOfStack ] = i;
topOfStack++;
}
int stack::pop()
{
if( topOfStack == 0 )
{
cout << "Stack underflow.n";
return 0;
}
topOfStack--;
return stck[ topOfStack ];
}
int main()
{
stack a, b;
a.push(1);
b.push(2);
a.push(3);
b.push(4);
cout << a.pop() << " ";
cout << a.pop() << " ";
cout << b.pop() << " ";
cout << b.pop() << endl;
return 0;
}
Convert Temperatures from Celsius to Fahrenheit and vice versa.
#include <iostream.h>
#include <conio.h>
void main()
C++ Programms
cs567
{
clrscr();
int choice;
float ctemp,ftemp;
cout << "1.Celsius to Fahrenheit" << endl;
cout << "2.Fahrenheit to Celsius" << endl;
cout << "Choose between 1 & 2 : " << endl;
cin>>choice;
if (choice==1)
{
cout << "Enter the temperature in Celsius : " << endl;
cin>>ctemp;
ftemp=(1.8*ctemp)+32;
cout << "Temperature in Fahrenheit = " << ftemp << endl;
}
else
{
cout << "Enter the temperature in Fahrenheit : " << endl;
cin>>ftemp;
ctemp=(ftemp-32)/1.8;
cout << "Temperature in Celsius = " << ctemp << endl;
}
getch();
}
Copy One File to another File
#include < iostream.h >
#include < conio.h >
#include < iomanip.h >
#include < stdlib.h >
#include < ctype.h >
#include < fstream.h >
void main( )
{
ofstream outfile;
ifstream infile;
C++ Programms
cs567
char fname1[10],fname2[20];
char ch,uch;
clrscr( );
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";
getch();
exit(1);
}
outfile.open( fname2);
if(outfile.fail( ))
{
cerr<<"Unable to create a file";
getch();
exit(1);
}
while( !infile.eof( ) )
{
ch = (char) infile.get( );
uch = toupper(ch);
outfile.put(uch);
}
infile.close( );
outfile.close( );
getch( );
}
Data Abstraction
#include <iostream>
using namespace std;
class Adder
C++ Programms
cs567
{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
Data Encapsulation
#include <iostream>
using namespace std;
class Adder
{
C++ Programms
cs567
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
cout << "Total " << a.getTotal() <<endl;
return 0;
}
C++ Programms
cs567
Enum example
#include <iostream.h>
int main()
{
enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday};
Days TheDay;
int j;
cout<<"Please enter the day of the week (0 to 6)";
cin>>j;
TheDay = Days(j);
if(TheDay == Sunday || TheDay == Saturday)
cout<<"Hurray it is the weekend"< else
cout<<"Curses still at work"< return 0;
}
Euclid's algorithm
#include <iostream.h>
// Fundamental idea of Euclid's algorithm (one of the oldest known
algorithms)
// gcd(a,0) = a
// gcd(a,b) = gcd(b,a%b)
int gcd (int a, int b)
{
int temp;
while (b != 0)
{
temp = a % b;
a = b;
b = temp;
C++ Programms
cs567
}
return(a);
}
int main ()
{
int x, y;
cout << "Enter two natural numbers: ";
cin >> x >> y;
cout << "gcd(" << x << ", " << y << ") = " << gcd(x,y) << endl;
return(0);
}
Exception Handling
#include <iostream>
using namespace std;
int main()
{
unsigned int TypeOfLoan = 0;
const char *LoanType[] =
{ "Personal",
"Car",
"Furniture",
"Musical Instrument",
"Boat"
};
try
{
cout << "Enter the type of loann";
for(int i = 0; i < 4; i++)
cout << i + 1 << ") " << LoanType[i] << endl;
cout << "Your choice: ";
cin >> TypeOfLoan;
if( TypeOfLoan < 1 || TypeOfLoan > 5 )
throw "Number out of rangen";
cout << "nType of Loan: " << LoanType[TypeOfLoan] << endl;
}
C++ Programms
cs567
catch(const char* Msg)
{
cout << "Error: " << Msg << endl;
}
catch(...)
{
cout << "nSomething went wrongnn";
}
return 0;
}
Exponentiation using multiplication
#include <iostream.h>
int exp (int b, int e)
{
int result;
result = 1;
while (e != 0)
{
result = result * b;
e = e - 1;
}
return(result);
}
int main ()
{
int b, e;
cout << "Enter base and exponent: ";
cin >> b >> e;
cout << b << " to the " << e << " = " << exp(b,e) << endl;
return(0);
}
Factorial
#include <iostream>
#include <iomanip>
C++ Programms
cs567
using namespace std;
#define LENGTH 20
long double iterativeFunction(unsigned int n); // Iterative solution
long double recursiveFunction(unsigned int n); // Recursive solution
int main()
{
unsigned int n;
cout << fixed << setprecision(0);
cout << setw(10) << "n" << setw(30) << "Factorial of n"
<< " (Iterative solution)n" << endl;
for( n = 0; n <= LENGTH; ++n)
cout << setw(10) << n << setw(30) << iterativeFunction(n)
<< endl;
cout << "Go on with ";
cin.get();
cout << setw(10) << "n" << setw(30) << "Factorial of n"
<< " (Recursive solution)n" << endl;
for( n = 0; n <= LENGTH; ++n)
cout << setw(10) << n << setw(30) << recursiveFunction(n)
<< endl;
cout << endl;
return 0;
}
long double iterativeFunction(unsigned int n) // Iterative solution.
{
long double result = 1.0;
for( unsigned int i = 2; i <= n; ++i)
result *= i;
return result;
}
long double recursiveFunction(unsigned int n) // Recursive solution.
{
if( n <= 1)
return 1.0;
else
return recursiveFunction(n-1) * n;
}
C++ Programms
cs567
Factorial
#include <iostream.h>
// sequence is 0, 1, 1, 2, 3, 5, 8, 13, ...
int fib (int i)
{
int pred, result, temp;
pred = 1;
result = 0;
while (i > 0)
{
temp = pred + result;
result = pred;
pred = temp;
i = i-1;
}
return(result);
}
int main ()
{
int n;
cout << "Enter a natural number: ";
cin >> n;
while (n < 0)
{
cout << "Please re-enter: ";
cin >> n;
}
cout << "fib(" << n << ") = " << fib(n) << endl;
return(0);
}
Fibonacci Series
#include<iostream.h>
#include<conio.h>
main()
C++ Programms
cs567
{
const unsigned long limit=4294967295;
unsigned long next=0;
unsigned long last=1;
long sum;
clrscr();
cout<<"nnThis program will print the Fibonacci series :nn ";
while(next<limit/2)
{
cout<<last <<" ";
sum=next+last;
next=last;
last=sum;
}
getch();
}
File Operations
#include< iostream.h >
#include< conio.h >
#include< fstream.h >
class student
{
private:
int rno;
char name[10];
float fees;
public:
void getdata()
{
cout<<"roll number";
cin>>rno;
cout<< endl;
cout<<"enter name:";
cin >> name;
cout<< endl <<"enter fees:";
C++ Programms
cs567
cin>>fees;
}
void dispdata()
{
cout<<"Roll number"<< rno << endl;
cout<<"Name"<< name << endl;
cout<<"Fees"<< fees;
}
};
void main()
{
student s1;
clrscr();
ofstream stdfile("c:std.txt");
//fstream stdfile;
//stdfile.open("c:std.txt",ios::out|ios::in); //open file for output
char wish;
//writing to the file
do
{
s1.getdata();
stdfile.write((char*)& s1,sizeof(student));
cout << "continue ? y/n";
cin >> wish;
}
while(wish=='y'||wish=='Y');
stdfile.close(); //close the file
getch();
}
C++ Programms
cs567
Find out Number is Even or Odd
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int x;
cout << "Enter an integer : ";
cin>>x;
if(x%2==0)
cout << "The number " << x << " is even.";
else
cout << "The number " << x << " is odd.";
getch();
}
Floyd warshall algorithm
#include<piostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
class path
{
int n;
int p[10][10];
int a[10][10];
int c[10][10];
public:
void get();
void pm();
C++ Programms
cs567
void ap();
void disp();
};
void path::get()
{
int i,j,k;
clrscr();
cout<<"Enter the no. of nodes in the graph :";
cin>>n;
cout<<"Enter the adjacency matrix :";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>a[i][j];
p[i][j]=0;
}
}
cout<<"Enter The cost matrix is :";
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>c[i][j];
}
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
p[i][j]=a[i][j];
}
}
}
void path::disp()
{
// cout<<"The output matrix for the given graph is :";
C++ Programms
cs567
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cout<<p[i][j]<< " ";
}
cout<<endl;
}
}
void path::pm()
{
int i,j,k;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
p[i][j]=p[i][j] || p[i][k] && p[k][j];
}
}
}
}
void path::ap()
{
int i,j,k;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
p[i][j]=c[i][j];
}
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
C++ Programms
cs567
for(j=1;j<=n;j++)
{
if(p[i][j]<p[i][k]+p[k][j])
{
p[i][j]=p[i][j];
}
else
{
p[i][j]=p[i][k]+p[k][j];
}
}
}
}
}
void main()
{
path p;
p.get();
p.pm();
cout<<"path matrix is :";
p.disp();
getch();
p.ap();
cout<<"all pair shortest path matrix is :";
p.disp();
getch();
}
Function overloading
# include<iostream.h>
# include<conio.h>
int area(int side)
{
return side*side;
}
int area(int l , int b)
C++ Programms
cs567
{
return l*b;
}
void main()
{
clrscr();
int (*p1)(int);
int (*p2)(int,int);
p1=area;
p2=area;
cout<<"Address of area(int)="<<(unsigned int)p1<
cout<<"Address of area(int,int)="<<(unsigned int)p2<
cout<<"Invoking area(int) via p1 "<<p1(20)<
cout<<"Invoking area(int,int) via p2 "<
getch();
}
Heap Sort
#include < iostream.h >
const int MAX = 10 ;
class array
{
private :
int arr[MAX] ;
int count ;
public :
array( ) ;
void add ( int num ) ;
void makeheap(int ) ;
void heapsort( ) ;
void display( ) ;
} ;
array :: array( )
{
count = 0 ;
for ( int i = 0 ; i < MAX ; i++ )
C++ Programms
cs567
arr[MAX] = 0 ;
}
void array :: add ( int num )
{
if ( count < MAX )
{
arr[count] = num ;
count++ ;
}
else
cout << "nArray is full" << endl ;
}
void array :: makeheap(int c)
{
for ( int i = 1 ; i < c ; i++ )
{
int val = arr[i] ;
int s = i ;
int f = ( s - 1 ) / 2 ;
while ( s > 0 && arr[f] < val )
{
arr[s] = arr[f] ;
s = f ;
f = ( s - 1 ) / 2 ;
}
arr[s] = val ;
}
}
void array :: heapsort( )
{
for ( int i = count - 1 ; i > 0 ; i-- )
{
int ivalue = arr[i] ;
arr[i] = arr[0] ;
arr[0]=ivalue;
makeheap(i);
}
C++ Programms
cs567
}
void array :: display( )
{
for ( int i = 0 ; i < count ; i++ )
cout << arr[i] << "t" ;
cout << endl ;
}
void main( )
{
array a ;
a.add ( 11 ) ;
a.add ( 2 ) ;
a.add ( 9 ) ;
a.add ( 13 ) ;
a.add ( 57 ) ;
a.add ( 25 ) ;
a.add ( 17 ) ;
a.add ( 1 ) ;
a.add ( 90 ) ;
a.add ( 3 ) ;
a.makeheap(10) ;
cout << "nHeap Sort.n" ;
cout << "nBefore Sorting:n" ;
a.display( ) ;
a.heapsort( ) ;
cout << "nAfter Sorting:n" ;
a.display( ) ;
}
Inline Functions
#include <iostream>
using namespace std;
inline double Sum(const double * Numbers, const int Count)
{
double s = 0;
for(int i = 0; i < Count; i++)
C++ Programms
cs567
s += Numbers[i];
return s;
}
int main()
{
double Nbr[] = { 15.66, 18, 25, 128.62, 12.06, 22.18 };
double Total = Sum(Nbr, 6);
cout << "Sum = " << Total << endl;
return 0;
}
If you first declare a function that would be defined somewhere else, when
implementing the function, you can type or omit the inline keyword:
#include <iostream>
using namespace std;
inline double Sum(const double * Numbers, const int Count);
int main()
{
double Nbr[] = { 15.66, 18, 25, 128.62, 12.06, 22.18 };
double Total = Sum(Nbr, 6);
cout << "Sum = " << Total << endl;
return 0;
}
inline double Sum(const double * Numbers, const int Count)
{
double s = 0;
for(int i = 0; i < Count; i++)
s += Numbers[i];
return s;
}
Insertion Sort
#include < iostream.h >
const int MAX = 10 ;
class array
{
private :
C++ Programms
cs567
int arr[MAX] ;
int count ;
public :
array( ) ;
void add ( int item ) ;
void sort( ) ;
void display( ) ;
} ;
array :: array( )
{
count = 0 ;
for ( int i = 0 ; i < MAX ; i++ )
arr[i] = 0 ;
}
void array :: add ( int item )
{
if ( count < MAX )
{
arr[count] = item ;
count++ ;
}
else
cout << "nArray is full" << endl ;
}
void array :: sort( )
{
int temp ;
for ( int i = 1 ; i <= count - 1 ; i++ )
{
for ( int j = 0 ; j < i ; j++ )
{
if ( arr[j] > arr[i] )
{
temp = arr[j] ;
arr[j] = arr[i] ;
for ( int k = i ; k > j ; k-- )
arr[k] = arr[k - 1] ;
C++ Programms
cs567
arr[k + 1] = temp ;
}
}
}
}
void array :: display( )
{
for ( int i = 0 ; i < count ; i++ )
cout << arr[i] << "t" ;
cout << endl ;
}
void main( )
{
array a ;
a.add ( 25 ) ;
a.add ( 17 ) ;
a.add ( 31 ) ;
a.add ( 13 ) ;
a.add ( 2 ) ;
cout << "nInsertion sort.n" ;
cout << "nArray before sorting:" << endl ;
a.display( ) ;
a.sort( ) ;
cout << "nArray after insertion sorting:" << endl ;
a.display( ) ;
}
Linear Search
#include < iostream.h >
#include < constream.h >
void read(int a[10],int n)
{
cout<<"readingn";
for(int i=0;i < n;i++)
cin>>a[i];
}
C++ Programms
cs567
void display(int a[10],int n)
{
for(int i=0;i < n;i++)
cout << a[i]<<"t";
}
void linearsearch ( int a[10],int n )
{
int k,flag=0;
read(a,n);
display(a,n);
cout<<"nenter an element to be searchn";
cin>>k;
for(int i=0;i < n;i++)
{
if(a[i]==k)
flag=1;
break;
}
if(flag==1)
cout << "nsearching is successful,element is found at position " << i +1
<< endl;
else
cout<<"searching not successfuln";
}
void main()
{
int a[10], n;
clrscr();
cout <<"enter n value..n";
cin>>n;
linearsearch(a,n);
getch();
}
C++ Programms
cs567
Matrix Multiplication
void main()
{
int row1=0,
col1=1,
row2=0,
col2=0,
**matrix1,
**matrix2,
**result;
clrscr();
printf(" Enter number of row for first matrix ");
scanf("%d",&row1);
while (col1!=row2)
{
printf(" Enter number of column for first matrix ");
scanf("%d",&col1);
printf(" Enter number of row for second matrix ");
scanf("%d",&row2);
if (col1!=row2)
{
clrscr();
printf("Column number of first matrix must be same as the row number
of second matrix");
}
}
printf(" Enter number of column for second matrix ");
scanf("%d",&col2);
matrix1=init(matrix1,row1,col1);
matrix2=init(matrix2,row2,col2);
/* setting values in matrix */
printf("First matrix n");
set(matrix1,row1,col1);
printf("Second matrix n");
set(matrix2,row2,col2);
/* printint matrix */
C++ Programms
cs567
clrscr();
printf(" [ First matrix ]n");
get(matrix1,row1,col1);
printf(" [ Second matrix ]n");
get(matrix2,row2,col2);
printf(" [ Multiplication Result ]n");
result=mul(matrix1,matrix2,row1,col2,col1);
get(result,row1,col2);
printf("nt Thanks from debmalya jash");
getch();
free(matrix1);
free(matrix2);
fress(result);
} /* end main */
/* to initialize matrix */
int** init(int** arr,int row,int col)
{
int i=0,
j=0;
arr=(int**)malloc(sizeof(int)*row*col);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
*((arr+i)+j)=(int*)malloc(sizeof(int));
*(*(arr+i)+j)=0;
}
}
return arr;
}
/* to set value in matrix */
int** set(int** arr,int row,int col)
{
int i=0,
j=0,
val=0;
for(i=0;i<row;i++)
C++ Programms
cs567
{
for(j=0;j<col;j++)
{
printf("Enter value for row %d col %d :",(i+1),(j+1));
scanf("%d",&val);
*(*(arr+i)+j)=val;
}
}
return arr;
}
/* print values of the passed matrix */
void get(int** arr,int row,int col)
{
int i=0,
j=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%dt",*(*(arr+i)+j));
}
printf("n");
}
}
/* mutiply two matrices and return the resultant matrix */
int** mul(int** arr1,int** arr2,int row,int col,int col1)
{
int **result,
i=0,
j=0,
k=0;
result=init(result,row,col);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
for(k=0;k<col1;k++)
C++ Programms
cs567
{
printf("%dX%d(%d)",*(*(arr1+i)+k),*(*(arr2+k)+j),(*(*(arr1+i)+k))*(*(*(arr2
+k)+j)));
*(*(result+i)+j)+=(*(*(arr1+i)+k))*(*(*(arr2+k)+j));
if (k!=(col1-1))
printf("+");
}
printf("t");
}
printf("n");
}
return result;
}
Merge Sort
#include <iostream.h>
int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
C++ Programms
cs567
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++)
a[k]=b[k];
}
void main()
{
int num,i;
cout<<"MERGE SORT PROGRAM"<<endl;
cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN
C++ Programms
cs567
PRESS ENTER]:"<<endl;
cin>>num;
cout<<endl;
cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS)
[THEN
PRESS ENTER]:"<<endl;
for(i=1;i<=num;i++)
{
cin>>a[i] ;
}
merge_sort(1,num);
cout<<endl;
cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl;
cout<<endl<<endl;
for(i=1;i<<=num;i++)
cout<<a[i]<<" ";
cout<<endl<<endl<<endl<<endl;
}
Multiple Inheritance
#include <iostream>
using namespace std;
class base1
{
protected:
int x;
public:
void showx() { cout << x << "n"; }
};
class base2
{
protected:
int y;
public:
void showy() { cout << y << "n"; }
};
C++ Programms
cs567
// Inherit multiple base classes.
class derived: public base1, public base2
{
public:
void set(int i, int j) { x = i; y = j; }
};
int main()
{
derived ob;
ob.set(10, 20); // provided by derived
ob.showx(); // from base1
ob.showy(); // from base2
return 0;
}
Multiply a number by a power
#include <iostream>
using namespace std;
int main()
{
int number,power,count,i;
cout << "Enter Number: "; cin >> number;
cout << "Enter the power: "; cin >> power;
count = 1;
for (i=1; i <=power; i++)
count = count*number;
cout << count << endl;
return 0;
}
Namespace can be nested within another
#include <iostream>
using namespace std;
namespace MyNameSpace1
{
int i;
C++ Programms
cs567
namespace MyNameSpace2
{ // a nested namespace
int j;
}
}
int main()
{
MyNameSpace1::i = 19;
MyNameSpace1::MyNameSpace2::j = 10;
cout << MyNameSpace1::i << " "<< MyNameSpace1::MyNameSpace2::j <<
"n";
using namespace MyNameSpace1;
cout << i * MyNameSpace2::j;
return 0;
}
Number of Bytes in a Text file
#include<fstream.h<
#include<process.h<
#include<stdio.h<
#include<iostream.h<
#include<process.h<
#include<conio.h<
main()
{
clrscr();
int c=0;
char ch,file[30];
cout<<"Enter the name of the file:";
gets(file);
fstream f1;
f1.open(file,ios::in);
if(f1.bad())
{
cout<<"File can not be opened.";
exit(0);
C++ Programms
cs567
}
if(f1.good())
{
cout<<"The current contents of the file are:";
while(f1)
{
f1.get(ch);
c++;
cout<<ch;
}
}
cout<<"Total no. of Bytes are "<<c;
f1.close();
cout<<"Press Enter key to continue...";
getch();
return(0);
}
Octal - Hexadecimal - Decimal conversion
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout<<"The decimal value of 15 is "<<15<<endl;
cout<<"The octal value of 15 is "<<setiosflags(ios::oct)<<15<<endl;
cout<<"The hex value of 15 is "<<setiosflags(ios::hex)<<15<<endl;
return 0;
}
C++ Programms
cs567
Operator Overload
#include <cstdlib>
#include <new>
using namespace std;
class MyClass
{
int x, y;
public:
MyClass()
{
x = y = 0;
}
MyClass(int lg, int lt)
{
x = lg;
y = lt;
}
void show()
{
cout << x << " ";
cout << y << endl;
}
void *operator new(size_t size);
void operator delete(void *p);
void *operator new[](size_t size);
void operator delete[](void *p);
};
// overloaded new operator
void *MyClass::operator new(size_t size)
{
void *p;
cout << "In overloaded new.n";
p = malloc(size);
if(!p)
{
C++ Programms
cs567
bad_alloc ba;
throw ba;
}
return p;
}
// delete operator overloaded
void MyClass::operator delete(void *p)
{
cout << "In overloaded delete.n";
free(p);
}
// new operator overloaded for arrays.
void *MyClass::operator new[](size_t size)
{
void *p;
cout << "Using overload new[].n";
p = malloc(size);
if( !p )
{
bad_alloc ba;
throw ba;
}
return p;
}
// delete operator overloaded for arrays.
void MyClass::operator delete[](void *p)
{
cout << "Freeing array using overloaded delete[]n";
free(p);
}
int main()
{
MyClass *objectPointer1, *objectPointer2;
int i;
try
{
objectPointer1 = new MyClass (10, 20);
C++ Programms
cs567
}
catch (bad_alloc xa)
{
cout << "Allocation error for objectPointer1.n";
return 1;;
}
try
{
objectPointer2 = new MyClass [10]; // allocate an array
}
catch (bad_alloc xa)
{
cout << "Allocation error for objectPointer2.n";
return 1;
}
objectPointer1->show();
for( i = 0; i < 10; i++)
objectPointer2[i].show();
delete objectPointer1; // free an object
delete [] objectPointer2; // free an array
return 0;
}
Overloads assignment operator (=)
#include <iostream>
using namespace std;
class alpha
{
private:
int data;
public:
alpha(){ }
alpha(int d){ data = d; }
void display(){ cout << data; }
alpha operator = (alpha& a)
{
C++ Programms
cs567
data = a.data;
cout << "nAssignment operator invoked";
return alpha(data);
}
};
int main()
{
alpha a1(37);
alpha a2;
a2 = a1;
cout << "na2=";
a2.display();
alpha a3 = a2;
cout << "na3=";
a3.display();
cout << endl;
return 0;
}
First 10 lines of Pascal's Triangle
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
long triangle(int x,int y);
int main()
{
clrscr();
const lines=10;
for (int i=0;i<lines;i++)
for (int j=1;j<lines-i;j++)
cout << setw(2) << " ";
for (int j=0;j<=i;j++)
cout << setw(4) << triangle(i,j);
cout << endl;
getch();
}
C++ Programms
cs567
long triangle(int x,int y)
{
if(x<0||y<0||y>x)
return 0;
long c=1;
for (int i=1;i<=y;i++,x--)
c=c*x/i;
return c;
}
Example of Pass-by-Reference
#include <iostream.h>
#include <stdlib.h>
int exp (int,int);
void readnums (int&, int&);
void main ()
{
int b, e;
readnums(b,e);
cout << b << " to the " << e << " = " << exp(b,e) << endl;
}
void readnums (int& b, int& e)
{
int correctInput;
cout << "Enter the base and the exponent: ";
cin >> b >> e;
if (!cin)
{
cout << "Disaster! Terminating program." << endl;
exit(-1);
}
correctInput = (b >= 0) && (e >= 0);
while (!correctInput)
{
cout << "Something wrong! Try again ..." << endl;
cout << "Re-enter base and exponent: ";
C++ Programms
cs567
cin >> b >> e;
if (!cin)
{
cout << "Disaster! Terminating program." << endl;
exit(-1);
}
correctInput = (b >= 0) && (e >= 0);
}
}
int exp (int b, int e)
{
int result;
result = 1;
while (e != 0)
{
result = result * b;
e = e - 1;
}
return(result);
}
Polymorphism
#include <iostream>
using namespace std;
class Shape
{
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
C++ Programms
cs567
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape
{
public:
Rectangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape
{
public:
Triangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Rectangle class area :"<<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
C++ Programms
cs567
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
Quick Sort
#include<process.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int Partition(int low,int high,int arr[]);
void Quick_sort(int low,int high,int arr[]);
void main()
{
int *a,n,low,high,i;
clrscr();
cout<<"Quick Sort Algorithm";<< endl
cout<<"Enter number of elements:";
cin>>n;
a=new int[n];
/* cout<<"enter the elements:";
for(i=0;i< n;i++)
cin>>a;*/
for(i=0;i < n;i++)
a[i]=rand()%100;
clrscr();
cout<<"Initial Order of elements";
for(i=0;i< n;i++)
cout<< a[i] <<" ";
cout <<"";
high=n-1;
C++ Programms
cs567
low=0;
Quick_sort(low,high,a);
cout <<"Final Array After Sorting:";
for(i=0;i < n;i++)
cout << a[i] <<" ";
getch();
}
/*Function for partitioning the array*/
int Partition(int low,int high,int arr[])
{
int i,high_vac,low_vac,pivot/*,itr*/;
pivot=arr[low];
while(high>low)
{
high_vac=arr[high];
while(pivot< high_vac)
{
if(high < =low) break;
high--;
high_vac=arr[high];
}
arr[low]=high_vac;
low_vac=arr[low];
while(pivot > low_vac)
{
if(high < =low) break;
low++;
low_vac=arr[low];
}
arr[high]=low_vac;
}
arr[low]=pivot;
return low;
}
void Quick_sort(int low,int high,int arr[])
{
C++ Programms
cs567
int Piv_index,i;
if(low < high)
{
Piv_index=Partition(low,high,arr);
Quick_sort(low,Piv_index-1,arr);
Quick_sort(Piv_index+1,high,arr);
}
}
Find the Roots of a Quadratic Equation
#include <iostream.h>
#include <conio.h>
#include <math.h>
int main()
{
clrscr();
float a,b,c,d,root1,root2;
cout << "Enter the 3 coefficients a, b, c : " << endl;
cin>>a>>b>>c;
if(!a)
{
if(!b)
cout << "Both a and b cannot be 0 in ax^2 + bx + c = 0" << "n";
else
{
d=-c/b;
cout << "The solution of the linear equation is : " << d << endl;
}
}
else
{
d=b*b-4*a*c;
C++ Programms
cs567
if(d>0)
root1=(-b+sqrt(d))/(2*a);
root2=(-b-sqrt(d))/(2*a);
cout << "The first root = " << root1 << endl;
cout << "The second root = " << root2 << endl;
}
getch();
return 0;
}
Selection Sort
#include < iostream.h >
const int MAX = 10 ;
class array
{
private :
int arr[MAX] ;
int count ;
public :
array( ) ;
void add ( int item ) ;
void sort( ) ;
void display( ) ;
} ;
array :: array( )
{
count = 0 ;
for ( int i = 0 ; i < MAX ; i++ )
arr[i] = 0 ;
}
void array :: add ( int item )
{
if ( count < MAX )
{
arr[count] = item ;
count++ ;
C++ Programms
cs567
}
else
cout << "nArray is full" << endl ;
}
void array :: sort( )
{
int temp ;
for ( int i = 0 ; i <= count - 2 ; i++ )
{
for ( int j = i + 1 ; j <= count - 1 ; j++ )
{
if ( arr[i] > arr[j] )
{
temp = arr[i] ;
arr[i] = arr[j] ;
arr[j] = temp ;
}
}
}
}
void array :: display( )
{
for ( int i = 0 ; i < count ; i++ )
cout << arr[i] << " " ;
cout << endl ;
}
void main( )
{
array a ;
a.add ( 25 ) ;
a.add ( 17 ) ;
a.add ( 31 ) ;
a.add ( 13 ) ;
a.add ( 2 ) ;
cout << "nSelection sort.n" ;
cout << "nArray before sorting:" << endl ;
a.display( ) ;
C++ Programms
cs567
a.sort( ) ;
cout << "nArray after selection sorting:" << endl ;
a.display( ) ;
}
Shell Sort
#include< iostream.h >
#include< constream.h >
void read(int a[10],int n)
{
cout << "readingn";
for(int i=0;i < n;i++)
cin >> a[i];
}
void display(int a[10],int n)
{
for(int i=0;i < n;i++)
cout << a[i] <<"t";
}
void shellsort(int a[10],int n)
{
int gap=n/2;
do
{
int swap;
do
{
swap=0;
for(int i=0;i < n-gap;i++)
if(a[i] > a[i+gap])
{
int t=a[i];
a[i]=a[i+gap];
a[i+gap]=t;
swap=1;
}
C++ Programms
cs567
}
while(swap);
}
while(gap=gap/2);
}
void main()
{
int a[10];
int n;
clrscr();
cout<<"enter nn";
cin>>n;
read(a,n);
cout<<"before sortingn";
display(a,n);
shellsort(a,n);
cout<<"nafter sortingn";
display(a,n);
getch();
}
Sort a heap
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
int a[ 10 ] = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 };
std::vector< int > v( a, a + 10 ); // copy of a
std::vector< int > v2;
std::ostream_iterator< int > output( cout, " " );
std::copy( v.begin(), v.end(), output );
std::make_heap( v.begin(), v.end() );
C++ Programms
cs567
std::sort_heap( v.begin(), v.end() );
cout << "nn";
std::copy( v.begin(), v.end(), output );
cout << endl;
return 0;
}
Sort all characters inside the string
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
const string hello("Hello, how are you?");
string s(hello.begin(),hello.end());
// iterate through all of the characters
string::iterator pos;
for (pos = s.begin(); pos != s.end(); ++pos)
{
cout << *pos;
}
cout << endl;
sort (s.begin(), s.end());
cout << "ordered: " << s << endl;
}
String Operation
#include<stdio.h>
#include<conio.h>
#include<string.h>
int STRLEN(char*);
int STRCPY(char*,char*);
int STRCMP(char*,char*);
int STRCAT(char*,char*,char*);
int STRREV(char*);
C++ Programms
cs567
void main()
{
int c;
char str[20],str1[10],str2[10],str3[20];
clrscr();
re:
printf("
Enter choice=>");
printf("
1:string len.
2:string copy
3:string cmp.
4:string cat.
5:string rev.");
printf("6:for exit=>");
scanf("%d",&c);
switch(c)
{
case 1:
printf("Enter the string=>");
scanf("%s",&str1);
printf("string length=>%d
",STRLEN(str1));
break;
case 2:
printf("
Enter the string=>");
scanf("%s",str1);
STRCPY(str2,str1);
printf("copied string=>");
puts(str2);
break;
case 3:
printf("Enter two string=>");
scanf("%s",&str1);
scanf("%s",&str2);
if(STRCMP(str2,str1))
C++ Programms
cs567
printf("string is equal");
else
printf("String is not equal");
break;
case 4:
printf("Enter two string=>");
scanf("%s",str1);
scanf("%s",str2);
STRCAT(str3,str2,str1);
puts(str3);
break;
case 5:
printf("Enter the string=>");
scanf("%s",str1);
STRREV(str1);
printf("Reverse stringis=>");
puts(str1);
break;
default:
goto end;
}
goto re;
end:
getch();
}
int STRLEN(char *s)
{
int i=0;
while(*s!=NULL)
{
i++;
s++;
}
return i;
}
int STRCPY(char *s2,char *s1)
{
C++ Programms
cs567
while(*s1!=NULL)
{
*s2=*s1;
s2++;
s1++;
}
*s2=NULL;
return 1;
}
int STRCMP(char *s2,char *s1)
{
int i=0,len1,len2;
len1=strlen(s1);
len2=strlen(s2);
if(len1==len2)
{
while(*s2==*s1 && *s2 != NULL && *s1!=NULL)
{
i++;
s1++;
s2++;
}
if(i==len1)
return 1;
else
return 0;
}
else
{
return 0;
}
}
int STRREV(char *s)
{
int len;
char *s1;
char *ptr;
C++ Programms
cs567
len=strlen(s);
s1=(char *)malloc(sizeof(char));
strcpy(s1,s);
ptr=s1+len-1;
while(*s!=NULL)
{
*s=*ptr;
ptr--;
s++;
s1++;
}
*s=NULL;
return 1;
}
int STRCAT(char *s3,char *s2,char *s1)
{
while(*s1!=NULL)
{
*s3=*s1;
s3++;
s1++;
}
s3++;
while(*s2!=NULL)
{
*s3=*s2;
s3++;
s2++;
}
*s3=NULL;
return 1;
}
Structure
#include <iostream>
using namespace std;
C++ Programms
cs567
int main()
{
// Defining a structure
struct PersonalData
{
char *FirstName;
char *LastName;
char *Birthday; // in the format of 12/30/1978
int PhoneNum;
}; // don't forget the ending ";"
// Declaring a variable of type PersonalData
PersonalData PersonOne;
// Populate PersonOne with data
PersonOne.FirstName = "John";
PersonOne.LastName = "Doe";
PersonOne.Birthday = "12/30/1978";
PersonOne.PhoneNum = 5855555;
// Print the data out
cout << "PersonOne's First name is: " << PersonOne.FirstName << endl;
cout << "PersonOne's Last name is: " << PersonOne.LastName<< endl;
cout << "PersonOne's Birthday is: " << PersonOne.Birthday<< endl;
cout << "PersonOne's Phone number is: " << PersonOne.PhoneNum<<
endl;
return 0;
}
Tower Of Hanoi Alogithm Using Recursion.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class tower
{
int *t1,*t2,*t3;
int x,y,z;
public:
void disp_tower();
C++ Programms
cs567
void move_disk(int tx,int ty);
void toh(int n,int a,int b,int c);
tower(int no);
~tower();
};
tower :: tower(int no)
{
t1 = new int[no+1];
t2 = new int[no+1];
t3 = new int[no+1];
x = no;
y = z = 0;
for(int i=0,j=no ; i
{
t1[i] = j;
t2[i] = t2[i] = 0;
}
t1[no] = t2[no] = t3[no] = 0;
}
tower :: ~tower()
{
delete []t1;
delete []t2;
delete []t3;
}
void tower :: disp_tower()
{
clrscr();
cout<<"
X :: ";
for(int i=0;i
{
cout<<" "<
}
cout<<"
Y :: ";
for(i=0;i
C++ Programms
cs567
{
cout<<" "<
}
cout<<"
Z :: ";
for(i=0;i
{
cout<<" "<
}
getch();
}
void tower :: toh(int n,int tx,int ty,int tz) //x to y using z
{
if(n>=1)
{
toh(n-1,tx,tz,ty);
move_disk(tx,ty); //x to y
disp_tower();
toh(n-1,tz,ty,tx);
}
}
void tower :: move_disk(int tx,int ty)
{
switch(tx)
{
case 1:
{
if(ty==2)
t2[y++] = t1[--x];
else
t3[z++] = t1[--x];
}break;
case 2:
{
if(ty==1)
t1[x++] = t2[--y];
else
C++ Programms
cs567
t3[z++] = t2[--y];
}break;
case 3:
{
if(ty==1)
t1[x++] = t3[--z];
else
t2[y++] = t3[--z];
}break;
}//end of switch
}
Use of Pointers
#include <iostream>
using namespace std;
int main()
{
// declare an integer and a float variable
int IntNum;
float FloatNum;
// declare integer and float pointers
int *pIntNum;
float *pFloatNum;
// initialize the integer and float variables
IntNum = 10;
FloatNum = 12.34;
// store addresses in pointers
pIntNum = & IntNum;
pFloatNum = & FloatNum;
// print out the original values
cout << "Before increment: " << endl;
cout << "t IntNum is: " << IntNum << endl;
cout << "t FloatNum is: " << FloatNum << endl;
// note that we need to dereference a pointer in order
// to extract the value it contains.
cout << "t pIntNum contains: " << *pIntNum << endl;
C++ Programms
cs567
cout << "t pFloatNum contains: " << *pFloatNum << endl;
// increment values of the integer and float variables
(*pIntNum)++; // dereference and then increment
(*pFloatNum)++;
// print out the values after increment
cout << "After increment: " << endl;
cout < < "t IntNum is: " << IntNum << endl;
cout < < "t FloatNum is: " << FloatNum << endl;
cout < < "t pIntNum contains: " << *pIntNum << endl;
cout < < "t pFloatNum contains: " << *pFloatNum << endl;
return 0;
}
Virtual Function
#include <iostream>
using namespace std;
class BaseClass
{
public:
int i;
BaseClass(int x)
{
i = x;
}
virtual void myFunction()
{
cout << "Using BaseClass version of myFunction(): ";
cout << i << 'n';
}
};
class DerivedClass1 : public BaseClass
{
public:
DerivedClass1(int x) : BaseClass(x) {}
void myFunction()
{
C++ Programms
cs567
cout << "Using DerivedClass1's version of myFunction(): ";
cout << i*i << 'n';
}
};
class DerivedClass2 : public BaseClass
{
public:
DerivedClass2(int x) : BaseClass(x) {}
void myFunction()
{
cout << "Using DerivedClass2's version of myFunction(): ";
cout << i+i << 'n';
}
};
int main()
{
BaseClass *p;
BaseClass ob(10);
DerivedClass1 derivedObject1(10);
DerivedClass2 derivedObject2(10);
p = &ob;
p->myFunction(); // use BaseClass's myFunction()
p = &derivedObject1;
p->myFunction(); // use DerivedClass1's myFunction()
p = &derivedObject2;
p->myFunction(); // use DerivedClass2's myFunction()
return 0;
}
Word Frequency
#include <stdio.h>
#define SIZE 80
#define LEN 80
int strword(char[],char[][]);
int strword_p(char*,char**);
void main()
C++ Programms
cs567
{
char* s;
char** w;
char ch;
do
{
clrscr();
gotoxy(10,1);
printf("Enter a string :");
gets(s);
gotoxy(10,2);
printf("nNumber of words :%d",strword_p(s,w));
gotoxy(10,24);
printf(" Continue(y/n)?");
ch=getch();
} while (ch=='y' || ch=='Y');
}
int strword_p(char *s,char **w)
{
int is_space=0,
i=0,
word_counter=0,
j=0,
is_printed=0,
frequency=0;
while (*(s+i)!='0')
{
if (*(s+i)==' ' ||
*(s+i)==',' ||
*(s+i)=='.' ||
*(s+i)==':')
{
if (is_space==0)
{
*(*(w+word_counter)+j)='0';
word_counter++;
is_space=1;
C++ Programms
cs567
j=0;
}
}
else
{
*(*(w+word_counter)+j)=*(s+i);
j++;
is_space=0;
}
i++;
}
if (is_space==0)
{
*(*(w+word_counter)+j)='0';
word_counter++;
}
for(j=0;j
{
frequency=0;
is_printed=0;
for(i=0;i
{
if (strcmp(w[i],w[j])==0)
{
frequency++;
if (j
is_printed=1;
}
}
if (!is_printed)
printf("n Word %d : %s ,frequency->%d",j+1,w[j],frequency);
}
printf("n");
return word_counter;
}
C++ Programms
cs567
Write text to a file
#include <iostream.h>
#include <fstream.h>
const char *FILENAME = "myfile.txt";
int main()
{
//create output object associated w/ file
ofstream fout(FILENAME);
cout << "Enter your text: ";
char str[100];
cin >> str;
//write the text to the file
fout << "here is your textn";
fout << str << endl;
//close file
fout.close();
ifstream fin(FILENAME);
char ch;
while (fin.get(ch))
cout << ch;
fin.close();
return 0;
}

More Related Content

DOCX
C++ file
DOCX
Java Programs Lab File
PDF
Cours java avance débutant facile l'essentiel swing ,events
PPTX
Templates presentation
PDF
Corrige exercices pascal_fenni_2018
PDF
JAVASCRIPT PROGRAM.pdf
DOCX
Oops practical file
PPTX
HTML Forms
C++ file
Java Programs Lab File
Cours java avance débutant facile l'essentiel swing ,events
Templates presentation
Corrige exercices pascal_fenni_2018
JAVASCRIPT PROGRAM.pdf
Oops practical file
HTML Forms

What's hot (20)

PPT
Rust Programming Language
PDF
LET US C (5th EDITION) CHAPTER 4 ANSWERS
PPTX
Mapping Data Types In Python.pptx
PPTX
Java- Nested Classes
PPTX
Java script arrays
PDF
3.2 javascript regex
PPT
JavaScript Arrays
PDF
The solution manual of c by robin
PDF
01 - Introduction à Python chaines de caractères.pdf
PPTX
html forms
PPTX
Data Types In C
PDF
Algorithmes d'approximation
PPT
Intro to html
DOCX
Basic Programs of C++
PDF
Cours php
PPT
Structures
PDF
Exercices en turbo pascal sur les nombres
DOCX
Let us C (by yashvant Kanetkar) chapter 3 Solution
PPTX
Dictionary
PPTX
Rust vs C++
Rust Programming Language
LET US C (5th EDITION) CHAPTER 4 ANSWERS
Mapping Data Types In Python.pptx
Java- Nested Classes
Java script arrays
3.2 javascript regex
JavaScript Arrays
The solution manual of c by robin
01 - Introduction à Python chaines de caractères.pdf
html forms
Data Types In C
Algorithmes d'approximation
Intro to html
Basic Programs of C++
Cours php
Structures
Exercices en turbo pascal sur les nombres
Let us C (by yashvant Kanetkar) chapter 3 Solution
Dictionary
Rust vs C++
Ad

Viewers also liked (20)

DOCX
Pratik Bakane C++
DOCX
Pratik Bakane C++
DOCX
Pratik Bakane C++
DOCX
Pratik Bakane C++
DOCX
Pratik Bakane C++
DOCX
Travel management
PPT
C++ programming
PDF
Pointers & References in C++
DOC
Ada file
DOCX
Doubly linklist
DOCX
Computer graphics programs in c++
PDF
3. c++ by example
PPTX
Mathematical Induction
DOCX
Write a program to print out all armstrong numbers between 1 and 500
PPTX
PDF
Chapter 2 basic element of programming
PDF
C++ TUTORIAL 6
PDF
Automotive electrical and electromechanical system design
Pratik Bakane C++
Pratik Bakane C++
Pratik Bakane C++
Pratik Bakane C++
Pratik Bakane C++
Travel management
C++ programming
Pointers & References in C++
Ada file
Doubly linklist
Computer graphics programs in c++
3. c++ by example
Mathematical Induction
Write a program to print out all armstrong numbers between 1 and 500
Chapter 2 basic element of programming
C++ TUTORIAL 6
Automotive electrical and electromechanical system design
Ad

Similar to C++ programs (20)

DOC
Pads lab manual final
PPS
C++ Language
PDF
C program
KEY
Blocks+gcd入門
DOC
C basics
PDF
C lab programs
PDF
C lab programs
PDF
PDF
TypeScript Introduction
PDF
Object Oriented Programming (OOP) using C++ - Lecture 3
PPTX
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
KEY
Sbaw091006
PDF
All I know about rsc.io/c2go
PPT
An imperative study of c
PPT
C++: Constructor, Copy Constructor and Assignment operator
PDF
C programms
PPT
Cquestions
PPTX
C++ lectures all chapters in one slide.pptx
PDF
Oop Presentation
Pads lab manual final
C++ Language
C program
Blocks+gcd入門
C basics
C lab programs
C lab programs
TypeScript Introduction
Object Oriented Programming (OOP) using C++ - Lecture 3
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
Sbaw091006
All I know about rsc.io/c2go
An imperative study of c
C++: Constructor, Copy Constructor and Assignment operator
C programms
Cquestions
C++ lectures all chapters in one slide.pptx
Oop Presentation

More from Mukund Gandrakota (11)

PDF
Edc unit 8
PDF
Edc unit 7
PDF
Edc unit 6
PDF
Edc unit 5
PDF
Edc unit 4
PDF
Edc unit 3
PDF
Edc unit 2
PDF
Edc unit 1
PDF
Java script programms
PDF
Java programs
PDF
career after graduated in cse
Edc unit 8
Edc unit 7
Edc unit 6
Edc unit 5
Edc unit 4
Edc unit 3
Edc unit 2
Edc unit 1
Java script programms
Java programs
career after graduated in cse

Recently uploaded (20)

PPT
Project quality management in manufacturing
PDF
PPT on Performance Review to get promotions
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
composite construction of structures.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
Welding lecture in detail for understanding
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
bas. eng. economics group 4 presentation 1.pptx
DOCX
573137875-Attendance-Management-System-original
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
CH1 Production IntroductoryConcepts.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
Project quality management in manufacturing
PPT on Performance Review to get promotions
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
composite construction of structures.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Welding lecture in detail for understanding
Foundation to blockchain - A guide to Blockchain Tech
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
bas. eng. economics group 4 presentation 1.pptx
573137875-Attendance-Management-System-original
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Model Code of Practice - Construction Work - 21102022 .pdf
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
CH1 Production IntroductoryConcepts.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Arduino robotics embedded978-1-4302-3184-4.pdf

C++ programs

  • 1. C++ Programms cs567 Abstract Class Example #include <iostream> using namespace std; // Base class class Shape { public: // pure virtual function providing interface framework. virtual int getArea() = 0; void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derived classes class Rectangle: public Shape { public: int getArea() { return (width * height); } }; class Triangle: public Shape { public: int getArea() { return (width * height)/2;
  • 2. C++ Programms cs567 } }; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total Rectangle area: " << Rect.getArea() << endl; Tri.setWidth(5); Tri.setHeight(7); // Print the area of the object. cout << "Total Triangle area: " << Tri.getArea() << endl; return 0; } Accessing Characters In Strings #include <iostream> #include <string> #include <cctype> using namespace std; int main() { string text; cout << "Counts words. Enter a text and terminate with a period and return:n"; getline( cin, text, '.'); // Reads a text up to the first '.' int i, // Index numberOfWhiteSpace = 0, // Number of white spaces numberOfWords = 0; // Number of words bool fSpace = true; // Flag for white space for( i = 0; i < text.length(); ++i) { if( isspace( text[i]) ) // white space? {
  • 3. C++ Programms cs567 ++numberOfWhiteSpace; fSpace = true; } else if( fSpace) // At the beginning of a word? { ++numberOfWords; fSpace = false; } } cout << "nYour text contains (without periods)" << "ncharacters: " << text.length() << "nwords: " << numberOfWords << "nwhite spaces: " << numberOfWhiteSpace << endl; return 0; } Armstrong Number # include <iostream.h> # include <conio.h> # include <math.h> void main () { clrscr(); int a,b=0,sum=0; long int n; cout<<"Enter the NO. : "; cin>>n; for(;n>0;) //counts the digits { a=n%10; n=n/10; b++; } for(;n>0;)
  • 4. C++ Programms cs567 { a=n%10; sum=sum+pow(a,b); n=n/10; } if(sum==n) { cout<<"IT IS AN ARMSTRONG NUMBER..."; getch(); } else { cout<<"IT IS NOT AN ARMSTRONG NUMBER..."; getch(); } } Accessing Data in a File #include <algorithm> #include <cstdlib> #include <fstream> #include <functional> #include <iostream> #include <iterator> #include <vector> using namespace std; template <class T> void print(T & c) { for( typename T::iterator i = c.begin(); i != c.end(); i++ ) { std::cout << *i << endl; } } int main() {
  • 5. C++ Programms cs567 vector <int> output_data( 10 ); generate( output_data.begin(), output_data.end(), rand ); transform( output_data.begin(), output_data.end(),output_data.begin(), bind2nd( modulus<int>(), 10 ) ); ofstream out( "data.txt" ); if( !out ) { cout << "Couldn't open output filen"; return 0; } copy( output_data.begin(), output_data.end(),ostream_iterator<int>( out, "n" ) ); out.close(); ifstream in( "data.txt" ); if( !in ) { cout << "Couldn't open input filen"; return 0; } vector<int> input_data( (istream_iterator<int>( in )),istream_iterator<int>() ); in.close(); print( output_data ); print( input_data ); } Accessing Static members without an object #include <iostream> using namespace std; class Cat { public: Cat(int age):itsAge(age){count++; } virtual ~Cat() { count--; } virtual int GetAge() { return itsAge; } virtual void SetAge(int age) { itsAge = age; }
  • 6. C++ Programms cs567 static int count; private: int itsAge; }; int Cat::count = 0; void TelepathicFunction(); int main() { const int MaxCats = 5; int i; Cat *CatHouse[MaxCats]; for (i = 0; i< MaxCats; i++) { CatHouse[i] = new Cat(i); TelepathicFunction(); } for ( i = 0; i< MaxCats; i++) { delete CatHouse[i]; TelepathicFunction(); } return 0; } void TelepathicFunction() { cout << "There are "; cout << Cat::count << " cats alive!n"; } A Generic bubble sort #include <iostream> using namespace std; template <class X> void bubble(X *data, int size) { register int a, b; X t;
  • 7. C++ Programms cs567 for(a=1; a < size; a++) for(b=size-1; b >= a; b--) if(data[b-1] > data[b]) { t = data[b-1]; data[b-1] = data[b]; data[b] = t; } } int main() { int i[] = {3, 2, 5, 6, 1, 8, 9, 3, 6, 9}; double d[] = {1.2, 5.5, 2.2, 3.3}; int j; bubble(i, 10); // sort ints bubble(d, 4); // sort doubles for(j=0; j<10; j++) cout << i[j] << ' '; cout << endl; for(j=0; j<4; j++) cout << d[j] << ' '; cout << endl; return 0; } Area Overloded #include<iostream.h> #include<conio.h> #define phi 3.14 int area(int,int); float area(int); void main() { int a,b,c,cho; clrscr(); cout<<"t What do you want to do?n";
  • 8. C++ Programms cs567 cout<<"1. area of rectangle"<<endl; cout<<"2. area of circle"<<endl; cout<<"Choice:"; cin>>cho; switch(cho) { case 1: cout<<"Enter lengt and breath (with white space):"; cin>>a>>b; cout<<"Area of RECTANGLE:"<<area(a,b); break; case 2: cout<<"Enter radius:"; cin>>c; cout<<"Area of CIRCLE:"<<area(c); break; } getch(); } int area(int x,int y) { return (x*y); } float area(int s) { return (phi*s*s); } A Simple Example of Inheritance #include <iostream> using namespace std; class BaseClass { int i; public: void setInt(int n);
  • 9. C++ Programms cs567 int getInt(); }; class DerivedClass : public BaseClass { int j; public: void setJ(int n); int mul(); }; void BaseClass::setInt(int n) { i = n; } int BaseClass::getInt() { return i; } void DerivedClass::setJ(int n) { j = n; } int DerivedClass::mul() { return j * getInt(); } int main() { DerivedClass ob; ob.setInt(10); // load i in BaseClass ob.setJ(4); // load j in DerivedClass cout << ob.mul(); // displays 40 return 0; }
  • 10. C++ Programms cs567 A simple stack example: push, empty, pop and top #include <iostream> #include <stack> using namespace std; int main() { stack<char> stackObject; stackObject.push('A'); stackObject.push('B'); stackObject.push('C'); stackObject.push('D'); while(!stackObject.empty()) { cout << "Popping: "; cout << stackObject.top() << endl; stackObject.pop(); } return 0; } A Static member variable example. #include <iostream> using namespace std; class myclass { static int i; public: void setInt(int n) { i = n; } int getInt() { return i; } };
  • 11. C++ Programms cs567 int myclass::i; // Definition of myclass::i. i is still private to myclass. int main() { myclass object1, object2; object1.setInt(10); cout << "object1.i: " << object1.getInt() << 'n'; // displays 10 cout << "object2.i: " << object2.getInt() << 'n'; // also displays 10 return 0; } Binary Search #include < iostream.h > template < class T > int binarySearch(T a[], int n, T & x) { int left = 0; // left end of segment int right = n - 1; // right end of segment while (left <= right) { int middle = (left + right)/2; // middle of segment if (x == a[middle]) return middle; if (x > a[middle]) left = middle + 1; else right = middle - 1; } return -1; // x not found } int main() { int a[10],n,t; cout<<"Enter the size:"; cin>>n; cout<<"enter the elements in sorted order:"; for(int i=0;i< n;i++)
  • 12. C++ Programms cs567 cin >>a[i]; cout<<"enter the element to search:"; cin>>t; int f=binarySearch(a,n,t); if(f==-1) cout<<"element not found"; else cout<<"element found at index:"< } Complex Number #include<iostream.h> #include<conio.h> class complex { private: float real,img; public: void assign(float x,float y) { real=x; img=y; } void print() { if(img>=0) cout<< real<<"+"<< img<<"i"; else cout<< real<< img<<"i"; getch(); } }; void add( float a,float b,float c, float d) { float e,f;complex g; e=a+c;
  • 13. C++ Programms cs567 f=b+d; g.assign(e,f); g.print(); } void sub( float a,float b,float c, float d) { float e,f;complex g; e=a-c; f=b-d; g.assign(e,f); g.print(); } void mul( float a,float b,float c, float d) { float e,f; complex g; e=a*c-b*d; f=b*c+a*d; g.assign(e,f); g.print(); } void main() { float a,b,c,d; complex x,y,z; clrscr(); cout<<" for complex 1:"; cout<<"real part:"; cin>>a; cout<<"imaginary part:"; cin>>b; cout<<" for complex 2:"; cout<<"real part:"; cin>>c; cout<<"imaginary part:"; cin>>d; x.assign(a,b); y.assign(c,d);
  • 14. C++ Programms cs567 cout<<"***original data:***n"; cout<<"Complex 1:n";x.print(); cout<<"n Complex 2:n";y.print(); cout<<"n***n"; cout<<"n Addition:n";add(a,b,c,d); cout<<"n Subtraction:n";sub(a,b,c,d); cout<<"n Multipication:n";mul(a,b,c,d); } Constructor and Destructor #include <iostream> using namespace std; #define SIZE 10 class stack { int stck[SIZE]; int topOfStack; public: stack(); // constructor ~stack(); // destructor void push(int i); int pop(); }; // constructor stack::stack() { topOfStack = 0; cout << "Stack Initializedn"; } // destructor stack::~stack() { cout << "Stack Destroyedn"; } void stack::push(int i) {
  • 15. C++ Programms cs567 if( topOfStack == SIZE ) { cout << "Stack is full.n"; return; } stck[ topOfStack ] = i; topOfStack++; } int stack::pop() { if( topOfStack == 0 ) { cout << "Stack underflow.n"; return 0; } topOfStack--; return stck[ topOfStack ]; } int main() { stack a, b; a.push(1); b.push(2); a.push(3); b.push(4); cout << a.pop() << " "; cout << a.pop() << " "; cout << b.pop() << " "; cout << b.pop() << endl; return 0; } Convert Temperatures from Celsius to Fahrenheit and vice versa. #include <iostream.h> #include <conio.h> void main()
  • 16. C++ Programms cs567 { clrscr(); int choice; float ctemp,ftemp; cout << "1.Celsius to Fahrenheit" << endl; cout << "2.Fahrenheit to Celsius" << endl; cout << "Choose between 1 & 2 : " << endl; cin>>choice; if (choice==1) { cout << "Enter the temperature in Celsius : " << endl; cin>>ctemp; ftemp=(1.8*ctemp)+32; cout << "Temperature in Fahrenheit = " << ftemp << endl; } else { cout << "Enter the temperature in Fahrenheit : " << endl; cin>>ftemp; ctemp=(ftemp-32)/1.8; cout << "Temperature in Celsius = " << ctemp << endl; } getch(); } Copy One File to another File #include < iostream.h > #include < conio.h > #include < iomanip.h > #include < stdlib.h > #include < ctype.h > #include < fstream.h > void main( ) { ofstream outfile; ifstream infile;
  • 17. C++ Programms cs567 char fname1[10],fname2[20]; char ch,uch; clrscr( ); 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"; getch(); exit(1); } outfile.open( fname2); if(outfile.fail( )) { cerr<<"Unable to create a file"; getch(); exit(1); } while( !infile.eof( ) ) { ch = (char) infile.get( ); uch = toupper(ch); outfile.put(uch); } infile.close( ); outfile.close( ); getch( ); } Data Abstraction #include <iostream> using namespace std; class Adder
  • 18. C++ Programms cs567 { public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main( ) { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0; } Data Encapsulation #include <iostream> using namespace std; class Adder {
  • 19. C++ Programms cs567 public: // constructor Adder(int i = 0) { total = i; } // interface to outside world void addNum(int number) { total += number; } // interface to outside world int getTotal() { return total; }; private: // hidden data from outside world int total; }; int main( ) { Adder a; a.addNum(10); a.addNum(20); a.addNum(30); cout << "Total " << a.getTotal() <<endl; return 0; }
  • 20. C++ Programms cs567 Enum example #include <iostream.h> int main() { enum Days{Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday}; Days TheDay; int j; cout<<"Please enter the day of the week (0 to 6)"; cin>>j; TheDay = Days(j); if(TheDay == Sunday || TheDay == Saturday) cout<<"Hurray it is the weekend"< else cout<<"Curses still at work"< return 0; } Euclid's algorithm #include <iostream.h> // Fundamental idea of Euclid's algorithm (one of the oldest known algorithms) // gcd(a,0) = a // gcd(a,b) = gcd(b,a%b) int gcd (int a, int b) { int temp; while (b != 0) { temp = a % b; a = b; b = temp;
  • 21. C++ Programms cs567 } return(a); } int main () { int x, y; cout << "Enter two natural numbers: "; cin >> x >> y; cout << "gcd(" << x << ", " << y << ") = " << gcd(x,y) << endl; return(0); } Exception Handling #include <iostream> using namespace std; int main() { unsigned int TypeOfLoan = 0; const char *LoanType[] = { "Personal", "Car", "Furniture", "Musical Instrument", "Boat" }; try { cout << "Enter the type of loann"; for(int i = 0; i < 4; i++) cout << i + 1 << ") " << LoanType[i] << endl; cout << "Your choice: "; cin >> TypeOfLoan; if( TypeOfLoan < 1 || TypeOfLoan > 5 ) throw "Number out of rangen"; cout << "nType of Loan: " << LoanType[TypeOfLoan] << endl; }
  • 22. C++ Programms cs567 catch(const char* Msg) { cout << "Error: " << Msg << endl; } catch(...) { cout << "nSomething went wrongnn"; } return 0; } Exponentiation using multiplication #include <iostream.h> int exp (int b, int e) { int result; result = 1; while (e != 0) { result = result * b; e = e - 1; } return(result); } int main () { int b, e; cout << "Enter base and exponent: "; cin >> b >> e; cout << b << " to the " << e << " = " << exp(b,e) << endl; return(0); } Factorial #include <iostream> #include <iomanip>
  • 23. C++ Programms cs567 using namespace std; #define LENGTH 20 long double iterativeFunction(unsigned int n); // Iterative solution long double recursiveFunction(unsigned int n); // Recursive solution int main() { unsigned int n; cout << fixed << setprecision(0); cout << setw(10) << "n" << setw(30) << "Factorial of n" << " (Iterative solution)n" << endl; for( n = 0; n <= LENGTH; ++n) cout << setw(10) << n << setw(30) << iterativeFunction(n) << endl; cout << "Go on with "; cin.get(); cout << setw(10) << "n" << setw(30) << "Factorial of n" << " (Recursive solution)n" << endl; for( n = 0; n <= LENGTH; ++n) cout << setw(10) << n << setw(30) << recursiveFunction(n) << endl; cout << endl; return 0; } long double iterativeFunction(unsigned int n) // Iterative solution. { long double result = 1.0; for( unsigned int i = 2; i <= n; ++i) result *= i; return result; } long double recursiveFunction(unsigned int n) // Recursive solution. { if( n <= 1) return 1.0; else return recursiveFunction(n-1) * n; }
  • 24. C++ Programms cs567 Factorial #include <iostream.h> // sequence is 0, 1, 1, 2, 3, 5, 8, 13, ... int fib (int i) { int pred, result, temp; pred = 1; result = 0; while (i > 0) { temp = pred + result; result = pred; pred = temp; i = i-1; } return(result); } int main () { int n; cout << "Enter a natural number: "; cin >> n; while (n < 0) { cout << "Please re-enter: "; cin >> n; } cout << "fib(" << n << ") = " << fib(n) << endl; return(0); } Fibonacci Series #include<iostream.h> #include<conio.h> main()
  • 25. C++ Programms cs567 { const unsigned long limit=4294967295; unsigned long next=0; unsigned long last=1; long sum; clrscr(); cout<<"nnThis program will print the Fibonacci series :nn "; while(next<limit/2) { cout<<last <<" "; sum=next+last; next=last; last=sum; } getch(); } File Operations #include< iostream.h > #include< conio.h > #include< fstream.h > class student { private: int rno; char name[10]; float fees; public: void getdata() { cout<<"roll number"; cin>>rno; cout<< endl; cout<<"enter name:"; cin >> name; cout<< endl <<"enter fees:";
  • 26. C++ Programms cs567 cin>>fees; } void dispdata() { cout<<"Roll number"<< rno << endl; cout<<"Name"<< name << endl; cout<<"Fees"<< fees; } }; void main() { student s1; clrscr(); ofstream stdfile("c:std.txt"); //fstream stdfile; //stdfile.open("c:std.txt",ios::out|ios::in); //open file for output char wish; //writing to the file do { s1.getdata(); stdfile.write((char*)& s1,sizeof(student)); cout << "continue ? y/n"; cin >> wish; } while(wish=='y'||wish=='Y'); stdfile.close(); //close the file getch(); }
  • 27. C++ Programms cs567 Find out Number is Even or Odd #include <iostream.h> #include <conio.h> void main() { clrscr(); int x; cout << "Enter an integer : "; cin>>x; if(x%2==0) cout << "The number " << x << " is even."; else cout << "The number " << x << " is odd."; getch(); } Floyd warshall algorithm #include<piostream.h> #include<conio.h> #include<stdio.h> #include<stdlib.h> class path { int n; int p[10][10]; int a[10][10]; int c[10][10]; public: void get(); void pm();
  • 28. C++ Programms cs567 void ap(); void disp(); }; void path::get() { int i,j,k; clrscr(); cout<<"Enter the no. of nodes in the graph :"; cin>>n; cout<<"Enter the adjacency matrix :"; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { cin>>a[i][j]; p[i][j]=0; } } cout<<"Enter The cost matrix is :"; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { cin>>c[i][j]; } } for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { p[i][j]=a[i][j]; } } } void path::disp() { // cout<<"The output matrix for the given graph is :";
  • 29. C++ Programms cs567 for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { cout<<p[i][j]<< " "; } cout<<endl; } } void path::pm() { int i,j,k; for(k=1;k<=n;k++) { for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { p[i][j]=p[i][j] || p[i][k] && p[k][j]; } } } } void path::ap() { int i,j,k; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { p[i][j]=c[i][j]; } } for(k=1;k<=n;k++) { for(i=1;i<=n;i++) {
  • 30. C++ Programms cs567 for(j=1;j<=n;j++) { if(p[i][j]<p[i][k]+p[k][j]) { p[i][j]=p[i][j]; } else { p[i][j]=p[i][k]+p[k][j]; } } } } } void main() { path p; p.get(); p.pm(); cout<<"path matrix is :"; p.disp(); getch(); p.ap(); cout<<"all pair shortest path matrix is :"; p.disp(); getch(); } Function overloading # include<iostream.h> # include<conio.h> int area(int side) { return side*side; } int area(int l , int b)
  • 31. C++ Programms cs567 { return l*b; } void main() { clrscr(); int (*p1)(int); int (*p2)(int,int); p1=area; p2=area; cout<<"Address of area(int)="<<(unsigned int)p1< cout<<"Address of area(int,int)="<<(unsigned int)p2< cout<<"Invoking area(int) via p1 "<<p1(20)< cout<<"Invoking area(int,int) via p2 "< getch(); } Heap Sort #include < iostream.h > const int MAX = 10 ; class array { private : int arr[MAX] ; int count ; public : array( ) ; void add ( int num ) ; void makeheap(int ) ; void heapsort( ) ; void display( ) ; } ; array :: array( ) { count = 0 ; for ( int i = 0 ; i < MAX ; i++ )
  • 32. C++ Programms cs567 arr[MAX] = 0 ; } void array :: add ( int num ) { if ( count < MAX ) { arr[count] = num ; count++ ; } else cout << "nArray is full" << endl ; } void array :: makeheap(int c) { for ( int i = 1 ; i < c ; i++ ) { int val = arr[i] ; int s = i ; int f = ( s - 1 ) / 2 ; while ( s > 0 && arr[f] < val ) { arr[s] = arr[f] ; s = f ; f = ( s - 1 ) / 2 ; } arr[s] = val ; } } void array :: heapsort( ) { for ( int i = count - 1 ; i > 0 ; i-- ) { int ivalue = arr[i] ; arr[i] = arr[0] ; arr[0]=ivalue; makeheap(i); }
  • 33. C++ Programms cs567 } void array :: display( ) { for ( int i = 0 ; i < count ; i++ ) cout << arr[i] << "t" ; cout << endl ; } void main( ) { array a ; a.add ( 11 ) ; a.add ( 2 ) ; a.add ( 9 ) ; a.add ( 13 ) ; a.add ( 57 ) ; a.add ( 25 ) ; a.add ( 17 ) ; a.add ( 1 ) ; a.add ( 90 ) ; a.add ( 3 ) ; a.makeheap(10) ; cout << "nHeap Sort.n" ; cout << "nBefore Sorting:n" ; a.display( ) ; a.heapsort( ) ; cout << "nAfter Sorting:n" ; a.display( ) ; } Inline Functions #include <iostream> using namespace std; inline double Sum(const double * Numbers, const int Count) { double s = 0; for(int i = 0; i < Count; i++)
  • 34. C++ Programms cs567 s += Numbers[i]; return s; } int main() { double Nbr[] = { 15.66, 18, 25, 128.62, 12.06, 22.18 }; double Total = Sum(Nbr, 6); cout << "Sum = " << Total << endl; return 0; } If you first declare a function that would be defined somewhere else, when implementing the function, you can type or omit the inline keyword: #include <iostream> using namespace std; inline double Sum(const double * Numbers, const int Count); int main() { double Nbr[] = { 15.66, 18, 25, 128.62, 12.06, 22.18 }; double Total = Sum(Nbr, 6); cout << "Sum = " << Total << endl; return 0; } inline double Sum(const double * Numbers, const int Count) { double s = 0; for(int i = 0; i < Count; i++) s += Numbers[i]; return s; } Insertion Sort #include < iostream.h > const int MAX = 10 ; class array { private :
  • 35. C++ Programms cs567 int arr[MAX] ; int count ; public : array( ) ; void add ( int item ) ; void sort( ) ; void display( ) ; } ; array :: array( ) { count = 0 ; for ( int i = 0 ; i < MAX ; i++ ) arr[i] = 0 ; } void array :: add ( int item ) { if ( count < MAX ) { arr[count] = item ; count++ ; } else cout << "nArray is full" << endl ; } void array :: sort( ) { int temp ; for ( int i = 1 ; i <= count - 1 ; i++ ) { for ( int j = 0 ; j < i ; j++ ) { if ( arr[j] > arr[i] ) { temp = arr[j] ; arr[j] = arr[i] ; for ( int k = i ; k > j ; k-- ) arr[k] = arr[k - 1] ;
  • 36. C++ Programms cs567 arr[k + 1] = temp ; } } } } void array :: display( ) { for ( int i = 0 ; i < count ; i++ ) cout << arr[i] << "t" ; cout << endl ; } void main( ) { array a ; a.add ( 25 ) ; a.add ( 17 ) ; a.add ( 31 ) ; a.add ( 13 ) ; a.add ( 2 ) ; cout << "nInsertion sort.n" ; cout << "nArray before sorting:" << endl ; a.display( ) ; a.sort( ) ; cout << "nArray after insertion sorting:" << endl ; a.display( ) ; } Linear Search #include < iostream.h > #include < constream.h > void read(int a[10],int n) { cout<<"readingn"; for(int i=0;i < n;i++) cin>>a[i]; }
  • 37. C++ Programms cs567 void display(int a[10],int n) { for(int i=0;i < n;i++) cout << a[i]<<"t"; } void linearsearch ( int a[10],int n ) { int k,flag=0; read(a,n); display(a,n); cout<<"nenter an element to be searchn"; cin>>k; for(int i=0;i < n;i++) { if(a[i]==k) flag=1; break; } if(flag==1) cout << "nsearching is successful,element is found at position " << i +1 << endl; else cout<<"searching not successfuln"; } void main() { int a[10], n; clrscr(); cout <<"enter n value..n"; cin>>n; linearsearch(a,n); getch(); }
  • 38. C++ Programms cs567 Matrix Multiplication void main() { int row1=0, col1=1, row2=0, col2=0, **matrix1, **matrix2, **result; clrscr(); printf(" Enter number of row for first matrix "); scanf("%d",&row1); while (col1!=row2) { printf(" Enter number of column for first matrix "); scanf("%d",&col1); printf(" Enter number of row for second matrix "); scanf("%d",&row2); if (col1!=row2) { clrscr(); printf("Column number of first matrix must be same as the row number of second matrix"); } } printf(" Enter number of column for second matrix "); scanf("%d",&col2); matrix1=init(matrix1,row1,col1); matrix2=init(matrix2,row2,col2); /* setting values in matrix */ printf("First matrix n"); set(matrix1,row1,col1); printf("Second matrix n"); set(matrix2,row2,col2); /* printint matrix */
  • 39. C++ Programms cs567 clrscr(); printf(" [ First matrix ]n"); get(matrix1,row1,col1); printf(" [ Second matrix ]n"); get(matrix2,row2,col2); printf(" [ Multiplication Result ]n"); result=mul(matrix1,matrix2,row1,col2,col1); get(result,row1,col2); printf("nt Thanks from debmalya jash"); getch(); free(matrix1); free(matrix2); fress(result); } /* end main */ /* to initialize matrix */ int** init(int** arr,int row,int col) { int i=0, j=0; arr=(int**)malloc(sizeof(int)*row*col); for(i=0;i<row;i++) { for(j=0;j<col;j++) { *((arr+i)+j)=(int*)malloc(sizeof(int)); *(*(arr+i)+j)=0; } } return arr; } /* to set value in matrix */ int** set(int** arr,int row,int col) { int i=0, j=0, val=0; for(i=0;i<row;i++)
  • 40. C++ Programms cs567 { for(j=0;j<col;j++) { printf("Enter value for row %d col %d :",(i+1),(j+1)); scanf("%d",&val); *(*(arr+i)+j)=val; } } return arr; } /* print values of the passed matrix */ void get(int** arr,int row,int col) { int i=0, j=0; for(i=0;i<row;i++) { for(j=0;j<col;j++) { printf("%dt",*(*(arr+i)+j)); } printf("n"); } } /* mutiply two matrices and return the resultant matrix */ int** mul(int** arr1,int** arr2,int row,int col,int col1) { int **result, i=0, j=0, k=0; result=init(result,row,col); for(i=0;i<row;i++) { for(j=0;j<col;j++) { for(k=0;k<col1;k++)
  • 41. C++ Programms cs567 { printf("%dX%d(%d)",*(*(arr1+i)+k),*(*(arr2+k)+j),(*(*(arr1+i)+k))*(*(*(arr2 +k)+j))); *(*(result+i)+j)+=(*(*(arr1+i)+k))*(*(*(arr2+k)+j)); if (k!=(col1-1)) printf("+"); } printf("t"); } printf("n"); } return result; } Merge Sort #include <iostream.h> int a[50]; void merge(int,int,int); void merge_sort(int low,int high) { int mid; if(low<high) { mid=(low+high)/2; merge_sort(low,mid); merge_sort(mid+1,high); merge(low,mid,high); } } void merge(int low,int mid,int high) { int h,i,j,b[50],k; h=low; i=low; j=mid+1; while((h<=mid)&&(j<=high))
  • 43. C++ Programms cs567 PRESS ENTER]:"<<endl; cin>>num; cout<<endl; cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS) [THEN PRESS ENTER]:"<<endl; for(i=1;i<=num;i++) { cin>>a[i] ; } merge_sort(1,num); cout<<endl; cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl; cout<<endl<<endl; for(i=1;i<<=num;i++) cout<<a[i]<<" "; cout<<endl<<endl<<endl<<endl; } Multiple Inheritance #include <iostream> using namespace std; class base1 { protected: int x; public: void showx() { cout << x << "n"; } }; class base2 { protected: int y; public: void showy() { cout << y << "n"; } };
  • 44. C++ Programms cs567 // Inherit multiple base classes. class derived: public base1, public base2 { public: void set(int i, int j) { x = i; y = j; } }; int main() { derived ob; ob.set(10, 20); // provided by derived ob.showx(); // from base1 ob.showy(); // from base2 return 0; } Multiply a number by a power #include <iostream> using namespace std; int main() { int number,power,count,i; cout << "Enter Number: "; cin >> number; cout << "Enter the power: "; cin >> power; count = 1; for (i=1; i <=power; i++) count = count*number; cout << count << endl; return 0; } Namespace can be nested within another #include <iostream> using namespace std; namespace MyNameSpace1 { int i;
  • 45. C++ Programms cs567 namespace MyNameSpace2 { // a nested namespace int j; } } int main() { MyNameSpace1::i = 19; MyNameSpace1::MyNameSpace2::j = 10; cout << MyNameSpace1::i << " "<< MyNameSpace1::MyNameSpace2::j << "n"; using namespace MyNameSpace1; cout << i * MyNameSpace2::j; return 0; } Number of Bytes in a Text file #include<fstream.h< #include<process.h< #include<stdio.h< #include<iostream.h< #include<process.h< #include<conio.h< main() { clrscr(); int c=0; char ch,file[30]; cout<<"Enter the name of the file:"; gets(file); fstream f1; f1.open(file,ios::in); if(f1.bad()) { cout<<"File can not be opened."; exit(0);
  • 46. C++ Programms cs567 } if(f1.good()) { cout<<"The current contents of the file are:"; while(f1) { f1.get(ch); c++; cout<<ch; } } cout<<"Total no. of Bytes are "<<c; f1.close(); cout<<"Press Enter key to continue..."; getch(); return(0); } Octal - Hexadecimal - Decimal conversion #include <iostream.h> #include <iomanip.h> int main() { cout<<"The decimal value of 15 is "<<15<<endl; cout<<"The octal value of 15 is "<<setiosflags(ios::oct)<<15<<endl; cout<<"The hex value of 15 is "<<setiosflags(ios::hex)<<15<<endl; return 0; }
  • 47. C++ Programms cs567 Operator Overload #include <cstdlib> #include <new> using namespace std; class MyClass { int x, y; public: MyClass() { x = y = 0; } MyClass(int lg, int lt) { x = lg; y = lt; } void show() { cout << x << " "; cout << y << endl; } void *operator new(size_t size); void operator delete(void *p); void *operator new[](size_t size); void operator delete[](void *p); }; // overloaded new operator void *MyClass::operator new(size_t size) { void *p; cout << "In overloaded new.n"; p = malloc(size); if(!p) {
  • 48. C++ Programms cs567 bad_alloc ba; throw ba; } return p; } // delete operator overloaded void MyClass::operator delete(void *p) { cout << "In overloaded delete.n"; free(p); } // new operator overloaded for arrays. void *MyClass::operator new[](size_t size) { void *p; cout << "Using overload new[].n"; p = malloc(size); if( !p ) { bad_alloc ba; throw ba; } return p; } // delete operator overloaded for arrays. void MyClass::operator delete[](void *p) { cout << "Freeing array using overloaded delete[]n"; free(p); } int main() { MyClass *objectPointer1, *objectPointer2; int i; try { objectPointer1 = new MyClass (10, 20);
  • 49. C++ Programms cs567 } catch (bad_alloc xa) { cout << "Allocation error for objectPointer1.n"; return 1;; } try { objectPointer2 = new MyClass [10]; // allocate an array } catch (bad_alloc xa) { cout << "Allocation error for objectPointer2.n"; return 1; } objectPointer1->show(); for( i = 0; i < 10; i++) objectPointer2[i].show(); delete objectPointer1; // free an object delete [] objectPointer2; // free an array return 0; } Overloads assignment operator (=) #include <iostream> using namespace std; class alpha { private: int data; public: alpha(){ } alpha(int d){ data = d; } void display(){ cout << data; } alpha operator = (alpha& a) {
  • 50. C++ Programms cs567 data = a.data; cout << "nAssignment operator invoked"; return alpha(data); } }; int main() { alpha a1(37); alpha a2; a2 = a1; cout << "na2="; a2.display(); alpha a3 = a2; cout << "na3="; a3.display(); cout << endl; return 0; } First 10 lines of Pascal's Triangle #include <iostream.h> #include <conio.h> #include <iomanip.h> long triangle(int x,int y); int main() { clrscr(); const lines=10; for (int i=0;i<lines;i++) for (int j=1;j<lines-i;j++) cout << setw(2) << " "; for (int j=0;j<=i;j++) cout << setw(4) << triangle(i,j); cout << endl; getch(); }
  • 51. C++ Programms cs567 long triangle(int x,int y) { if(x<0||y<0||y>x) return 0; long c=1; for (int i=1;i<=y;i++,x--) c=c*x/i; return c; } Example of Pass-by-Reference #include <iostream.h> #include <stdlib.h> int exp (int,int); void readnums (int&, int&); void main () { int b, e; readnums(b,e); cout << b << " to the " << e << " = " << exp(b,e) << endl; } void readnums (int& b, int& e) { int correctInput; cout << "Enter the base and the exponent: "; cin >> b >> e; if (!cin) { cout << "Disaster! Terminating program." << endl; exit(-1); } correctInput = (b >= 0) && (e >= 0); while (!correctInput) { cout << "Something wrong! Try again ..." << endl; cout << "Re-enter base and exponent: ";
  • 52. C++ Programms cs567 cin >> b >> e; if (!cin) { cout << "Disaster! Terminating program." << endl; exit(-1); } correctInput = (b >= 0) && (e >= 0); } } int exp (int b, int e) { int result; result = 1; while (e != 0) { result = result * b; e = e - 1; } return(result); } Polymorphism #include <iostream> using namespace std; class Shape { protected: int width, height; public: Shape( int a=0, int b=0) { width = a; height = b; } int area() {
  • 53. C++ Programms cs567 cout << "Parent class area :" <<endl; return 0; } }; class Rectangle: public Shape { public: Rectangle( int a=0, int b=0) { Shape(a, b); } int area () { cout << "Rectangle class area :" <<endl; return (width * height); } }; class Triangle: public Shape { public: Triangle( int a=0, int b=0) { Shape(a, b); } int area () { cout << "Rectangle class area :"<<endl; return (width * height / 2); } }; // Main function for the program int main( ) { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); // store the address of Rectangle
  • 54. C++ Programms cs567 shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; } Quick Sort #include<process.h> #include<iostream.h> #include<conio.h> #include<stdlib.h> int Partition(int low,int high,int arr[]); void Quick_sort(int low,int high,int arr[]); void main() { int *a,n,low,high,i; clrscr(); cout<<"Quick Sort Algorithm";<< endl cout<<"Enter number of elements:"; cin>>n; a=new int[n]; /* cout<<"enter the elements:"; for(i=0;i< n;i++) cin>>a;*/ for(i=0;i < n;i++) a[i]=rand()%100; clrscr(); cout<<"Initial Order of elements"; for(i=0;i< n;i++) cout<< a[i] <<" "; cout <<""; high=n-1;
  • 55. C++ Programms cs567 low=0; Quick_sort(low,high,a); cout <<"Final Array After Sorting:"; for(i=0;i < n;i++) cout << a[i] <<" "; getch(); } /*Function for partitioning the array*/ int Partition(int low,int high,int arr[]) { int i,high_vac,low_vac,pivot/*,itr*/; pivot=arr[low]; while(high>low) { high_vac=arr[high]; while(pivot< high_vac) { if(high < =low) break; high--; high_vac=arr[high]; } arr[low]=high_vac; low_vac=arr[low]; while(pivot > low_vac) { if(high < =low) break; low++; low_vac=arr[low]; } arr[high]=low_vac; } arr[low]=pivot; return low; } void Quick_sort(int low,int high,int arr[]) {
  • 56. C++ Programms cs567 int Piv_index,i; if(low < high) { Piv_index=Partition(low,high,arr); Quick_sort(low,Piv_index-1,arr); Quick_sort(Piv_index+1,high,arr); } } Find the Roots of a Quadratic Equation #include <iostream.h> #include <conio.h> #include <math.h> int main() { clrscr(); float a,b,c,d,root1,root2; cout << "Enter the 3 coefficients a, b, c : " << endl; cin>>a>>b>>c; if(!a) { if(!b) cout << "Both a and b cannot be 0 in ax^2 + bx + c = 0" << "n"; else { d=-c/b; cout << "The solution of the linear equation is : " << d << endl; } } else { d=b*b-4*a*c;
  • 57. C++ Programms cs567 if(d>0) root1=(-b+sqrt(d))/(2*a); root2=(-b-sqrt(d))/(2*a); cout << "The first root = " << root1 << endl; cout << "The second root = " << root2 << endl; } getch(); return 0; } Selection Sort #include < iostream.h > const int MAX = 10 ; class array { private : int arr[MAX] ; int count ; public : array( ) ; void add ( int item ) ; void sort( ) ; void display( ) ; } ; array :: array( ) { count = 0 ; for ( int i = 0 ; i < MAX ; i++ ) arr[i] = 0 ; } void array :: add ( int item ) { if ( count < MAX ) { arr[count] = item ; count++ ;
  • 58. C++ Programms cs567 } else cout << "nArray is full" << endl ; } void array :: sort( ) { int temp ; for ( int i = 0 ; i <= count - 2 ; i++ ) { for ( int j = i + 1 ; j <= count - 1 ; j++ ) { if ( arr[i] > arr[j] ) { temp = arr[i] ; arr[i] = arr[j] ; arr[j] = temp ; } } } } void array :: display( ) { for ( int i = 0 ; i < count ; i++ ) cout << arr[i] << " " ; cout << endl ; } void main( ) { array a ; a.add ( 25 ) ; a.add ( 17 ) ; a.add ( 31 ) ; a.add ( 13 ) ; a.add ( 2 ) ; cout << "nSelection sort.n" ; cout << "nArray before sorting:" << endl ; a.display( ) ;
  • 59. C++ Programms cs567 a.sort( ) ; cout << "nArray after selection sorting:" << endl ; a.display( ) ; } Shell Sort #include< iostream.h > #include< constream.h > void read(int a[10],int n) { cout << "readingn"; for(int i=0;i < n;i++) cin >> a[i]; } void display(int a[10],int n) { for(int i=0;i < n;i++) cout << a[i] <<"t"; } void shellsort(int a[10],int n) { int gap=n/2; do { int swap; do { swap=0; for(int i=0;i < n-gap;i++) if(a[i] > a[i+gap]) { int t=a[i]; a[i]=a[i+gap]; a[i+gap]=t; swap=1; }
  • 60. C++ Programms cs567 } while(swap); } while(gap=gap/2); } void main() { int a[10]; int n; clrscr(); cout<<"enter nn"; cin>>n; read(a,n); cout<<"before sortingn"; display(a,n); shellsort(a,n); cout<<"nafter sortingn"; display(a,n); getch(); } Sort a heap #include <iostream> using std::cout; using std::endl; #include <algorithm> #include <vector> #include <iterator> int main() { int a[ 10 ] = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 }; std::vector< int > v( a, a + 10 ); // copy of a std::vector< int > v2; std::ostream_iterator< int > output( cout, " " ); std::copy( v.begin(), v.end(), output ); std::make_heap( v.begin(), v.end() );
  • 61. C++ Programms cs567 std::sort_heap( v.begin(), v.end() ); cout << "nn"; std::copy( v.begin(), v.end(), output ); cout << endl; return 0; } Sort all characters inside the string #include <string> #include <iostream> #include <algorithm> using namespace std; int main() { const string hello("Hello, how are you?"); string s(hello.begin(),hello.end()); // iterate through all of the characters string::iterator pos; for (pos = s.begin(); pos != s.end(); ++pos) { cout << *pos; } cout << endl; sort (s.begin(), s.end()); cout << "ordered: " << s << endl; } String Operation #include<stdio.h> #include<conio.h> #include<string.h> int STRLEN(char*); int STRCPY(char*,char*); int STRCMP(char*,char*); int STRCAT(char*,char*,char*); int STRREV(char*);
  • 62. C++ Programms cs567 void main() { int c; char str[20],str1[10],str2[10],str3[20]; clrscr(); re: printf(" Enter choice=>"); printf(" 1:string len. 2:string copy 3:string cmp. 4:string cat. 5:string rev."); printf("6:for exit=>"); scanf("%d",&c); switch(c) { case 1: printf("Enter the string=>"); scanf("%s",&str1); printf("string length=>%d ",STRLEN(str1)); break; case 2: printf(" Enter the string=>"); scanf("%s",str1); STRCPY(str2,str1); printf("copied string=>"); puts(str2); break; case 3: printf("Enter two string=>"); scanf("%s",&str1); scanf("%s",&str2); if(STRCMP(str2,str1))
  • 63. C++ Programms cs567 printf("string is equal"); else printf("String is not equal"); break; case 4: printf("Enter two string=>"); scanf("%s",str1); scanf("%s",str2); STRCAT(str3,str2,str1); puts(str3); break; case 5: printf("Enter the string=>"); scanf("%s",str1); STRREV(str1); printf("Reverse stringis=>"); puts(str1); break; default: goto end; } goto re; end: getch(); } int STRLEN(char *s) { int i=0; while(*s!=NULL) { i++; s++; } return i; } int STRCPY(char *s2,char *s1) {
  • 64. C++ Programms cs567 while(*s1!=NULL) { *s2=*s1; s2++; s1++; } *s2=NULL; return 1; } int STRCMP(char *s2,char *s1) { int i=0,len1,len2; len1=strlen(s1); len2=strlen(s2); if(len1==len2) { while(*s2==*s1 && *s2 != NULL && *s1!=NULL) { i++; s1++; s2++; } if(i==len1) return 1; else return 0; } else { return 0; } } int STRREV(char *s) { int len; char *s1; char *ptr;
  • 65. C++ Programms cs567 len=strlen(s); s1=(char *)malloc(sizeof(char)); strcpy(s1,s); ptr=s1+len-1; while(*s!=NULL) { *s=*ptr; ptr--; s++; s1++; } *s=NULL; return 1; } int STRCAT(char *s3,char *s2,char *s1) { while(*s1!=NULL) { *s3=*s1; s3++; s1++; } s3++; while(*s2!=NULL) { *s3=*s2; s3++; s2++; } *s3=NULL; return 1; } Structure #include <iostream> using namespace std;
  • 66. C++ Programms cs567 int main() { // Defining a structure struct PersonalData { char *FirstName; char *LastName; char *Birthday; // in the format of 12/30/1978 int PhoneNum; }; // don't forget the ending ";" // Declaring a variable of type PersonalData PersonalData PersonOne; // Populate PersonOne with data PersonOne.FirstName = "John"; PersonOne.LastName = "Doe"; PersonOne.Birthday = "12/30/1978"; PersonOne.PhoneNum = 5855555; // Print the data out cout << "PersonOne's First name is: " << PersonOne.FirstName << endl; cout << "PersonOne's Last name is: " << PersonOne.LastName<< endl; cout << "PersonOne's Birthday is: " << PersonOne.Birthday<< endl; cout << "PersonOne's Phone number is: " << PersonOne.PhoneNum<< endl; return 0; } Tower Of Hanoi Alogithm Using Recursion. #include<iostream.h> #include<stdio.h> #include<conio.h> class tower { int *t1,*t2,*t3; int x,y,z; public: void disp_tower();
  • 67. C++ Programms cs567 void move_disk(int tx,int ty); void toh(int n,int a,int b,int c); tower(int no); ~tower(); }; tower :: tower(int no) { t1 = new int[no+1]; t2 = new int[no+1]; t3 = new int[no+1]; x = no; y = z = 0; for(int i=0,j=no ; i { t1[i] = j; t2[i] = t2[i] = 0; } t1[no] = t2[no] = t3[no] = 0; } tower :: ~tower() { delete []t1; delete []t2; delete []t3; } void tower :: disp_tower() { clrscr(); cout<<" X :: "; for(int i=0;i { cout<<" "< } cout<<" Y :: "; for(i=0;i
  • 68. C++ Programms cs567 { cout<<" "< } cout<<" Z :: "; for(i=0;i { cout<<" "< } getch(); } void tower :: toh(int n,int tx,int ty,int tz) //x to y using z { if(n>=1) { toh(n-1,tx,tz,ty); move_disk(tx,ty); //x to y disp_tower(); toh(n-1,tz,ty,tx); } } void tower :: move_disk(int tx,int ty) { switch(tx) { case 1: { if(ty==2) t2[y++] = t1[--x]; else t3[z++] = t1[--x]; }break; case 2: { if(ty==1) t1[x++] = t2[--y]; else
  • 69. C++ Programms cs567 t3[z++] = t2[--y]; }break; case 3: { if(ty==1) t1[x++] = t3[--z]; else t2[y++] = t3[--z]; }break; }//end of switch } Use of Pointers #include <iostream> using namespace std; int main() { // declare an integer and a float variable int IntNum; float FloatNum; // declare integer and float pointers int *pIntNum; float *pFloatNum; // initialize the integer and float variables IntNum = 10; FloatNum = 12.34; // store addresses in pointers pIntNum = & IntNum; pFloatNum = & FloatNum; // print out the original values cout << "Before increment: " << endl; cout << "t IntNum is: " << IntNum << endl; cout << "t FloatNum is: " << FloatNum << endl; // note that we need to dereference a pointer in order // to extract the value it contains. cout << "t pIntNum contains: " << *pIntNum << endl;
  • 70. C++ Programms cs567 cout << "t pFloatNum contains: " << *pFloatNum << endl; // increment values of the integer and float variables (*pIntNum)++; // dereference and then increment (*pFloatNum)++; // print out the values after increment cout << "After increment: " << endl; cout < < "t IntNum is: " << IntNum << endl; cout < < "t FloatNum is: " << FloatNum << endl; cout < < "t pIntNum contains: " << *pIntNum << endl; cout < < "t pFloatNum contains: " << *pFloatNum << endl; return 0; } Virtual Function #include <iostream> using namespace std; class BaseClass { public: int i; BaseClass(int x) { i = x; } virtual void myFunction() { cout << "Using BaseClass version of myFunction(): "; cout << i << 'n'; } }; class DerivedClass1 : public BaseClass { public: DerivedClass1(int x) : BaseClass(x) {} void myFunction() {
  • 71. C++ Programms cs567 cout << "Using DerivedClass1's version of myFunction(): "; cout << i*i << 'n'; } }; class DerivedClass2 : public BaseClass { public: DerivedClass2(int x) : BaseClass(x) {} void myFunction() { cout << "Using DerivedClass2's version of myFunction(): "; cout << i+i << 'n'; } }; int main() { BaseClass *p; BaseClass ob(10); DerivedClass1 derivedObject1(10); DerivedClass2 derivedObject2(10); p = &ob; p->myFunction(); // use BaseClass's myFunction() p = &derivedObject1; p->myFunction(); // use DerivedClass1's myFunction() p = &derivedObject2; p->myFunction(); // use DerivedClass2's myFunction() return 0; } Word Frequency #include <stdio.h> #define SIZE 80 #define LEN 80 int strword(char[],char[][]); int strword_p(char*,char**); void main()
  • 72. C++ Programms cs567 { char* s; char** w; char ch; do { clrscr(); gotoxy(10,1); printf("Enter a string :"); gets(s); gotoxy(10,2); printf("nNumber of words :%d",strword_p(s,w)); gotoxy(10,24); printf(" Continue(y/n)?"); ch=getch(); } while (ch=='y' || ch=='Y'); } int strword_p(char *s,char **w) { int is_space=0, i=0, word_counter=0, j=0, is_printed=0, frequency=0; while (*(s+i)!='0') { if (*(s+i)==' ' || *(s+i)==',' || *(s+i)=='.' || *(s+i)==':') { if (is_space==0) { *(*(w+word_counter)+j)='0'; word_counter++; is_space=1;
  • 73. C++ Programms cs567 j=0; } } else { *(*(w+word_counter)+j)=*(s+i); j++; is_space=0; } i++; } if (is_space==0) { *(*(w+word_counter)+j)='0'; word_counter++; } for(j=0;j { frequency=0; is_printed=0; for(i=0;i { if (strcmp(w[i],w[j])==0) { frequency++; if (j is_printed=1; } } if (!is_printed) printf("n Word %d : %s ,frequency->%d",j+1,w[j],frequency); } printf("n"); return word_counter; }
  • 74. C++ Programms cs567 Write text to a file #include <iostream.h> #include <fstream.h> const char *FILENAME = "myfile.txt"; int main() { //create output object associated w/ file ofstream fout(FILENAME); cout << "Enter your text: "; char str[100]; cin >> str; //write the text to the file fout << "here is your textn"; fout << str << endl; //close file fout.close(); ifstream fin(FILENAME); char ch; while (fin.get(ch)) cout << ch; fin.close(); return 0; }