You are on page 1of 40

C++

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

#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? { ++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; }

Accessing Characters In Strings

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;) { 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() { 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 file\n"; 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 file\n"; 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; } 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; 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"; 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); 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; }

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; } }; 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++) 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; 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); 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 Initialized\n"; } // destructor stack::~stack() { cout << "Stack Destroyed\n"; } void stack::push(int i) { 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() { 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; 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 { 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 { 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; }

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; } 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 loan\n"; 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 range\n"; cout << "\nType of Loan: " << LoanType[TypeOfLoan] << endl; } catch(const char* Msg) { cout << "Error: " << Msg << endl; } catch(...) { cout << "\nSomething went wrong\n\n"; } 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> 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; }

Factorial
#include <iostream.h> // sequence is 0, 1, 1, 2, 3, 5, 8, 13, ... int fib (int i) { int pred, result, temp;

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

pred = 1; result = 0; while (i > 0) { temp = pred + result; result = pred; pred = temp; i = i-1; } return(result);

Fibonacci Series
#include<iostream.h> #include<conio.h> main() { const unsigned long limit=4294967295; unsigned long next=0; unsigned long last=1; long sum; clrscr(); cout<<"\n\nThis program will print the Fibonacci series :\n\n "; 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:"; 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(); }

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(); 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 :"; 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++) { 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) { 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(); } </p1(20)<

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++ ) 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); } } 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++) 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 : 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] ; 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<<"reading\n"; 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 linearsearch ( int a[10],int n ) { int k,flag=0; read(a,n); display(a,n); cout<<"\nenter an element to be search\n"; 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 successful\n"; } void main() { int a[10], n; clrscr(); cout <<"enter n value..\n"; cin>>n; linearsearch(a,n); getch(); }

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 */ 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("\n\t 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++) { 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("%d\t",*(*(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++) { 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)) { 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 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"; } }; // 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; 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); } 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; }

You might also like