C++ Programming Examples

X




Resources > C++ Program Examples > {{currentSubTopic}}

Program to demonstrate creation of objects, access specifiers and member functions


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

class Complex
{
  private:
  int real;
  int imag;
  public:
  void getdata()
  {
      cout<<"Real=\n";
      cin>>real;
      cout<<"Imaginary=\n";
      cin>>imag;
  }
  void displaydata()
  {
      cout<<"Complex no=i"<<real<<"+j"<<imag<<endl;
  }
  Complex add(Complex a)
  {
      // real and imag denotes the data member of the calling object in this case it is
      // num1 since num1 is calling the function add
      Complex x;
      x.real=a.real+real;
      x.imag=a.imag+imag;
      return x;
  }
};

int main()
{
    Complex num1,num2,num3;
    
    num1.getdata();
    num2.getdata();
    num1.displaydata();
    cout<<endl;
    num2.displaydata();
    cout<<endl;
    num3 = num1.add(num2);
    num3.displaydata();
    cout<<endl;
    
    
    return 0;
}

Output

Program to demonstrate default constructor and destructor


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;
struct Complex
{
    private:
    int real;
    int imag;
    public:
    // Default constructor
    Complex()
    {
        cout<<"Hello\n";
        real = imag = 0;
    }
    // Destructor
    ~Complex()
    {
        cout<<"DELETED.\n";
    }
    void display()
    {
        cout<<real<<"+j"<<imag<<endl;
    }
};
int main()
{
    Complex p;
    p.display();
    return 0;
}

Output

Program to demonstrate multiple inheritance and function overriding


 
// Note the program is written using GCC Compiler 
#include <iostream>
#include <string.h>
using namespace std;

class Staff
{
    private:
    string name;
    int age;
    float salary;
    
    public:
    
    void getDetails()
    {
        cout<<"Enter the name.\n";
        getline(cin,name);        
        cout<<"Enter the age.\n";
        cin>>age;
        cout<<"Enter the salary.\n";
        cin>>salary;    
    }
    void showDetails()
    {
        cout<<"Name: "<<name<<endl;
        cout<<"Age: "<<age<<endl;
        cout<<"Salary: "<<salary<<endl<<endl;
    }
};

class Teacher: public Staff
{
    private:
    char qual[5];
    int std;
    
    public:
    //showDetails is overridden in the Teacher class
    void showDetails()
    {
    // Using the scope resolution operator we call the overridden function in the Staff class
        Staff::showDetails();
        cout<<"Qualification: "<<qual<<endl;
        cout<<"Standard: "<<std<<endl;
    }
    void getDetails()
    {
        Staff::getDetails();
        cout<<"Enter qualification.\n";
        cin>>qual;
        cout<<"Enter standard.\n";
        cin>>std;
    }
    
};

class Supervisor: public Teacher
{
    private:
    int exp;
    
    public:
    //showDetails is overridden in the Superivsor class
    void showDetails()
    {
    	// Using the scope resolution operator we call the overridden function in the Teacher class
        Teacher::showDetails();
        cout<<"EXP: "<<exp<<endl;
    }
    //Overridden like showDetails
    void getDetails()
    {
        Teacher::getDetails();
        cout<<"Enter the experience.\n";
        cin>>exp;
    }
};

int main()
{
    Supervisor s;
    s.getDetails();
    s.showDetails();
    
    return 0;
}

Output

Program to demonstrate parameterized constructors in inheritance


 
// Note the program is written using GCC Compiler 
#include <iostream>

using namespace std;

class A
{
  int a;
  public:
  A()
  {
      cout<<"DEFAULT OF A\n";
  }
  A(int x)
  {
      a=x;
  }
  void print()
  {
      cout<<a<<endl;
  }
};
class B: public A
{
  int b;
  public:
  //Calling the parameterized constructor of the base class
  B(int x,int y):A(x)
  {
      b=y;
  }
  B()
  {
      cout<<"DEFAULT OF B.\n";
  }
  void print()
  {
      cout<<b<<endl;
  }
};
class C: public B
{
  int c;
  public:
  //Calling the parameterized constructor of the base class
  C(int x, int y, int z):B(x,y)
  {
      c=z;
  }
  void print()
  {
      A::print();
      B::print();
      cout<<c<<endl;
  }
};

int main()
{
    C obj(4,5,6);
    obj.print();
    return 0;
}

Output

Program to swap 2 numbers using reference variables


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;
void swap(int&,int&);
int main()
{
    int num1,num2;
    cout<<"Enter number 1\n";
    cin>>num1;
    cout<<"Enter number 2\n";
    cin>>num2;
    swap(num1,num2);
    cout<<"Num1="<<num1<<" Num2="<<num2<<endl;
    return 0;
}
void swap(int& x,int& y)
{
    x=x+y;
    y=x-y;
    x=x-y;
}

Output

Program to create matrix using new operator


 
// Note the program is written using GCC Compiler 
#include<iostream>
using namespace std;

int main()
{
    int** matrix;
    int rows, cols;
    int i,j;
    cout<<"Enter the number of rows.\n";
    cin>>rows;
    
    cout<<"Enter the number of columns.\n";
    cin>>cols;
    //creating the rows 
    matrix = new int* [rows];
    //creating the columns for each row
    for(i=0;i<rows;i++)
        matrix[i] = new int [cols] ;
    
    cout<<"Enter the elements.\n";
    
    for(i=0;i<rows;i++)
        for(j=0;j<cols;j++)
            cin>>matrix[i][j];
    
    cout<<"Entered matrix is \n";
    
    for(i=0;i<rows;i++)
    {
        for(j=0;j<cols;j++)
            cout<<matrix[i][j]<<"  ";
        
        cout<<endl;
    }
     cout<<"MEMORY IS BEING DELETED.\n";   
        
    for(i=0;i<rows;i++) //deletion of the column
        delete []matrix[i] ;
    //deletion of the rows that have been created 
    delete []matrix;
    return 0;
}

Output

Program to demonstrate Operator Overloading


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

class Complex
{
    private:
      float real;
      float imag;
    public:
       Complex(): real(0), imag(0){ }
       void input()
       {
           cout << "Enter real and imaginary parts respectively: ";
           cin >> real;
           cin >> imag;
       }

       // Operator overloading
       Complex operator - (Complex c2)
       {
           Complex temp;
           temp.real = real - c2.real;
           temp.imag = imag - c2.imag;

           return temp;
       }

       void output()
       {
           if(imag < 0)
               cout << "Output Complex number: "<< real << imag << "i";
           else
               cout << "Output Complex number: " << real << "+" << imag << "i";
       }
};

int main()
{
    Complex c1, c2, result;

    cout<<"Enter first complex number:\n";
    c1.input();

    cout<<"Enter second complex number:\n";
    c2.input();

    // In case of operator overloading of binary operators in C++ programming, 
    // the object on right hand side of operator is always assumed as argument by compiler.
    result = c1 - c2;
    result.output();

    return 0;
}

Output

Program to calculate average of elements in an array


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, avg;

    cout << "Enter the numbers of data: ";
    cin >> n;

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    avg = sum / n;
    cout << "avg = " << avg;

    return 0;
}

Output

Program to calculate frequency of a character in a string


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    char str[] = "Hello to all";
    char checkCharacter = 'l';
    int count = 0;

    for (int i = 0; str[i] ; i++)
    {
        if (str[i] ==  checkCharacter)
        {
            ++ count;
        }
    }

    cout << "Number of " << checkCharacter << " = " << count;

    return 0;
}

Output

Program to calculate factors of a number


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int n, i;

    cout << "Enter a positive integer: ";
    cin >> n;

    cout << "Factors of " << n << " are: " << endl;  
    for(i = 1; i <= n; ++i)
    {
        if(n % i == 0)
            cout << i << endl;
    }

    return 0;
}

Output

Program to create multiplication table


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter a positive integer: ";
    cin >> n;

    for (int i = 1; i <= 10; ++i) {
        cout << n << " * " << i << " = " << n * i << endl;
    }
    
    return 0;
}

Output

Program to convert Binary number to decimal


 
// Note the program is written using GCC Compiler 
#include <iostream>
#include <cmath>

using namespace std;

int convertBinaryToDecimal(long long);

int main()
{
    long long n;

    cout << "Enter a binary number: ";
    cin >> n;
 
    cout << n << " in binary = " << convertBinaryToDecimal(n) << " in decimal";
    return 0;
}

int convertBinaryToDecimal(long long n)
{
    int decimalNumber = 0, i = 0, remainder;
    while (n!=0)
    {
        remainder = n%10;
        n /= 10;
        decimalNumber += remainder*pow(2,i);
        ++i;
    }
    return decimalNumber;
}

Output

Program to add two matrices


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int r, c, a[100][100], b[100][100], sum[100][100], i, j;

    cout << "Enter number of rows (between 1 and 100): ";
    cin >> r;

    cout << "Enter number of columns (between 1 and 100): ";
    cin >> c;

    cout << endl << "Enter elements of 1st matrix: " << endl;

    // Storing elements of first matrix entered by user.
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element a" << i + 1 << j + 1 << " : ";
           cin >> a[i][j];
       }

    // Storing elements of second matrix entered by user.
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element b" << i + 1 << j + 1 << " : ";
           cin >> b[i][j];
       }

    // Adding Two matrices
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
            sum[i][j] = a[i][j] + b[i][j];

    // Displaying the resultant sum matrix.
    cout << endl << "Sum of two matrix is: " << endl;
    for(i = 0; i < r; ++i)
    {
        for(j = 0; j < c; ++j)
        {
            cout << sum[i][j] << "  ";
        }
        cout<<endl;
    }

    return 0;
}

Output

Program to find length of string


 
// Note the program is written using GCC Compiler 
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[] = "hello";

    // you can also use str.length()
    cout << "String Length = " << strlen(str);

    return 0;
}

Output

Program to calcuate a raised to b using recursion


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int calculatePower(int, int);

int main()
{
    int base, power, result;

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

    cout << "Enter power number(positive integer): ";
    cin >> power;

    result = calculatePower(base, power);
    cout << base << "^" << power << " = " << result;

    return 0;
}

int calculatePower(int base, int power)
{
    if (power != 0)
        return (base*calculatePower(base, power-1));
    else
        return 1;
}

Output

Program to find LCM


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int n1, n2, max;

    cout << "Enter two numbers: ";
    cin >> n1 >> n2;
    
    // maximum value between n1 and n2 is stored in max
    max = (n1 > n2) ? n1 : n2;

    do
    {
        if (max % n1 == 0 && max % n2 == 0)
        {
            cout << "LCM = " << max;
            break;
        }
        else
            ++max;
    } while (1);
    
    return 0;
}

Output

Program to generate fibonacci series


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int n, t1 = 0, t2 = 1, nextTerm = 0;

    cout << "Enter the number of terms: ";
    cin >> n;

    cout << "Fibonacci Series: ";

    for (int i = 1; i <= n; ++i)
    {
        
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        
        cout << t1 << ", ";
    }
    return 0;
}

Output

Program to create Pattern


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int space, rows, k;

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

    for(int i = 1; i <= rows; ++i)
    {
        for(space = 1; space <= rows-i; ++space)
        {
            cout <<"  ";
        }

        for(k = 1; k<=2*i-1; ++k)
        {
            cout <<"* ";
        }
        cout << endl;
    }    
    return 0;
}

Output

Program to create pascals traingle


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int rows, coef = 1;

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

    for(int i = 0; i < rows; i++)
    {
        for(int space = 1; space <= rows-i; space++)
            cout <<"  ";

        for(int j = 0; j <= i; j++)
        {
            if (j == 0 || i == 0)
                coef = 1;
            else
                coef = coef*(i-j+1)/j;

            cout << coef << "   ";
        }
        cout << endl;
    }

    return 0;
}

Output

Program to Floyds triangle


 
// Note the program is written using GCC Compiler 
#include <iostream>
using namespace std;

int main()
{
    int rows, number = 1;

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

    for(int i = 1; i <= rows; i++)
    {
        for(int j = 1; j <= i; ++j)
        {
            cout << number << " ";
            ++number;
        }

        cout << endl;
    }

    return 0;
}

Output

Program to demonstrate virtual function


 
// Note the program is written using GCC Compiler 
#include<iostream>
using namespace std;
 
class base
{
public:
    virtual void print ()
    { cout<< "print base " <<endl; }
 
    void show ()
    { cout<< "show base " <<endl; }
};
 
class derived:public base
{
public:
    void print ()
    { cout<< "print derived " <<endl; }
 
    void show ()
    { cout<< "show derived " <<endl; }
};
 
int main()
{
    base *bptr;
    derived d;
    bptr = &d;
     
    //virtual function, binded at runtime
    bptr->print(); 
     
    // Non-virtual function, binded at compile time
    bptr->show(); 
}

Output

Program to demonstrate abstract class


 
// Note the program is written using GCC Compiler 
#include <iostream>
 
using namespace std;
 
// Base class
class Shape {

   protected:
      int width;
      int height;


   public:
      // pure virtual function makes the class shape as abstract
      virtual int getArea() = 0;
      void setWidth(int w) {
         width = w;
      }
   
      void setHeight(int h) {
         height = h;
      }
   
   
};
 
// Derived classes
class Rectangle: public Shape {
   public:
      // getArea has to be overridden by Rectangle
      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(6);
   Rect.setHeight(7);
   
   // Print the area of the object.
   cout << "Total Rectangle area: " << Rect.getArea() << endl;

   Tri.setWidth(4);
   Tri.setHeight(4);
   
   // Print the area of the object.
   cout << "Total Triangle area: " << Tri.getArea() << endl; 

   return 0;
}

Output

Program to name


 
code

Output