C++ Tutorial Examples




C++ Hello World Program Examples

#include <iostream>
using namespace std;
 
int main()
{
  // print output to user
  cout << "Hello World!" << endl;
  return 0;
}

Output

Hello World!

C++ Simple calculator Examples

#include<iostream>
#include<cmath>

using namespace std;

int main()
{

    double num1,num2;
    char operation,redo;

    cout<<"Welcome to the calculater program v.1.0 written by Your Name"<<endl;
    cout<<"***************************************************************"<<endl;
    cout<<endl<<endl<<endl;

    do
    {
        cout<<" Please enter an operation which you like to calculate (+,-,*,/,s)";
        cout<<"[s stands for swap]:";
        cin>>operation ;
        cout<<endl<<endl;
        cout<<" Please enter two numbers to apply your requested operation(";
        cout<<operation<<"):"<<endl<<"1st num:";
        cin>>num1;
        cout<<"2nd num:" ;
        cin>>num2;
        cout<<endl;
        switch (operation)
        {

        case'+':
            cout<<"The addition of two numbers ("<<num1<<","<<num2<<"):";
            cout<<num1+num2<<endl;
            break;
        case'-':
            cout<<"The substraction of two numbers ("<<num1<<","<<num2<<"):";
            cout<<num1-num2<<endl;
            break;
        case'*':
            cout<<"The multiplication of two numbers ("<<num1<<","<<num2<<"):";
            cout<<num1*num2<<endl;
            break;
        case'/':
            cout<<"The division of two numbers ("<<num1<<","<<num2<<"):";
            if(num2==0)
            {
                cout<<"not valid"<<endl;
            }
            cout<<(num1/num2)<<endl;
            break;
        case's':
            cout<<"The swap of two numbers ("<<num1<<","<<num2<<"):";
            swap(num1,num2);
            cout<<"1stnumber="<<num1<<"and 2nd number="<<num2<<endl<<endl;
            break;
        default:
            cout<<"unknown command"<<endl;

        }

        cout<<"enter y or Y to continue:";
        cin>>redo;
        cout<<endl<<endl;
    }
    while(redo=='y'||redo=='Y');

    return 0;

}

Output

Welcome to the calculater program v.1.0 written by Your Name
***************************************************************
Please enter an operation which you like to calculate (+,-,*,/,s)[s stands for swap]:
Please enter two numbers to apply your requested operation():
1st num:2nd num:
unknown command
enter y or Y to continue:

C++ Even and Odd Examples

#include <iostream>
using namespace std;
 
int main(int argc, char *argv[])
{
  int no;
  cout << "Enter any number: ";
  cin >> no;
  if(no%2==0)
  {
    cout<<"Even number";
  }
  else
  {
    cout<<"Odd number";
  }
  return 0;
}

Output

Enter any number: Even number

C++ Swap two numbers Examples

#include <iostream>

using namespace std;
 
int main()
{
    int a,b,c;
    cout << "Enter value of a: ";
    cin >> a;
    cout << "Enter value of b: ";
    cin >> b;
    c=a;
    a=b;
    b=c;
    cout<<"After swaping a: "<< a << " b: " << b;
    return 0;
}

Output

Enter value of a: Enter value of b: After swaping a: 32765 b: 0

C++ Prime Number Examples

#include <iostream>
#include <iomanip>      
 
using namespace std;
 
int main()
{
    int num,i,count,n;
    cout << "Enter max range: ";
    cin >> n;
    for(num = 1;num<=n;num++){
        count = 0;
        for(i=2;i<=num/2;i++){
            if(num%i==0){
                count++;
                break;
            }
        }
 
        if(count==0 && num!= 1)
            cout << num << setw(3);
    }
    return 0;
}

Output

Enter max range: 2  3  5  7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 

C++ Find Perfect Number Examples

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
  int n,i=1,sum=0;
  cout<<"Enter a number: ";
  cin >> n;
  while(i<n){
         if(n%i==0)
               sum=sum+i;
              i++;
  }
  if(sum==n)
         cout << i  <<  " is a perfect number";
  else
         cout << i << " is not a perfect number";
  system("pause");
  return 0;
}

Output

4 = 2×2
25 = 5×5
1= 1×1
64 = 8×8
81 = 9×9
36 = 6×6

C++ Factorial of Number Examples

#include <iostream>
using namespace std;
int fact (int i) {
    int result = 1;
    while (i > 0) {
        result = result * i;
        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 << n << "! = " << fact(n) << endl;
    return(0);
}

Output

Enter a natural number: 0! = 1

C++ Fibonacci Series Examples

#include <stdio.h>
#include <stdlib.h>
int main () {
  int r=0,a=0,n,b=1,i,c;
  char redo;
  do {
    a=0;
    b=1;
    printf("enter the the value of n:");
    scanf("%d", &n);
    if(n>100) {
      printf("enter some lessor value\n");
    }
    else {
      for (i=0;i<=n;i++) {
        c=a+b;
        a=b;
        b=c;
        printf("serial no.%d => ", i+1);
        printf("%d\n",a);
      }
      printf("enter y or Y to continue:");
      scanf("%s", &redo);
      printf("\n");
    }
  }
  while(redo=='y'||redo=='Y');
 
  return 0;
}

Output

enter the the value of n:10
serial no.1 => 1
serial no.2 => 1
serial no.3 => 2
serial no.4 => 3
serial no.5 => 5
serial no.6 => 8
serial no.7 => 13
serial no.8 => 21
serial no.9 => 34
serial no.10 => 55
serial no.11 => 89
enter y or Y to continue:

C++ Calculate number of characters, words, sentences

#include <iostream> 
#include <sstream> 
#include <cstring> 
#include <algorithm>  
#include <vector>   
#include <cctype>   
 
using namespace std;
 
int main()
{
 
    int i = 0, count = 0,a=0;
    char text[256];
    
    vector<string> sV;
    
    cout<<" Welcome to the  program 2.4 written by Your Name"<<endl;
    cout<<"********************************************************************************"<<endl;
    cout<<endl<<endl<<endl;
    cout << "Enter text (max. 256 characters): ";    
    cin.getline(text, 256, '\n');              
 
    string s(text), word;
    
    cout << "Your text was: " << endl;
    
    for (i=0; i<s.size(); i++){
        if (i == 0) {
            s[i] = toupper(s[i]);
            cout << s[i];
        }
        if (isalpha(s[i])){
            if (s[i-1] =='?' || s[i-1] == '!' || s[i-1] =='.') {
                s[i] = toupper(s[i]);
                cout << s[i];
            }
            else{
                s[i] = tolower(s[i]);
                cout << s[i];
            }
        }
        else if (isdigit(s[i])){
            cout << s[i];
        }
        else if (isspace(s[i])){
            if (s[i-1] != ' ' || s[i+1] != ' ') {
                cout << s[i];
            }
        }
        
        else if (s[i] =='?' || s[i] == '!' || s[i] =='.'){
            if (s[i+1] != ' ' || s[i+1] != ' ') {
                cout << s[i] << " ";
            }
            else {
                cout << s[i];
            }
            count=count+1;
        }
        
    }
     while(s[i] ==' ' || s[i] == '!' || s[i] =='.')
    {
    cout << s[i];
          
            a=a+1;
    }  
    cout << endl;
    
    istringstream instr(s);
    
    while (instr >> word){

        sV.push_back(word);
    }
    
    cout << "Number of characters in text: " << s.length() << endl; 
    cout << "Number of words in text: " <<sV.size() << endl;   
    cout << "Number of sentences in text: " << count << endl;
    system ("pause");
    return 0;
}

Output

Welcome to the  program 2.4 written by Your Name
***********************************************
*********************************
Enter text (max. 256 characters): Your text was:
Number of characters in text: 0
Number of words in text: 0
Number of sentences in text: 0
sh: pause: command not found

C++ Program with Matrices Examples

#include<conio.h>
#include<iostream>
#include<String.h>
#include<stdio.h>
using namespace std;
string str1,str2;
char str3[256];
bool a= true;
 
void String1();
 
int main()
{
    char redo;
    
    cout<<"Welcome to the  program 2.3 written by Your Name"<<endl;
    cout<<"**************************************************************************"<<endl;
    cout<<endl<<endl<<endl;
 
    cout<<"\nEnter the First string: ";
    cin>>str1;
    cout<<"\nEnter the Second string:";
    cin>>str2; 
    while(a)
    {
    String1();
    }
    cout<<"New  String after deleting first string from second : "<<endl<<str2;
     cout<<endl<<endl;
     cout<<"enter y or Y to continue:";
           cin>>redo;
           cout<<endl<<endl;    
    getch();
}
void String1()
{

     int len1,len2;
     int len3,k=0,b=0, match=0,i,j,count=0;
     len1=str1.length();
     len2=str2.length();
     
      for(i=0;i<len2;i++)
      {
         b=i;   
          for(j=0;j<len1;j++)
          {
             if(str2[b]==str1[j])
             {
              match=  match+1;
              b=b+1;
             }
             else
              break;      
          }
   
          if(match!=len1)
          {
            match=0;             
  
            str3[count]=str2[i];
            count++;
   
          }
          else
          {
             match=0; 
             a=true;
             i=i+len1-1;
          }            
     }
  
     str2=str3;
     if(str2.length()==len2)
     {
         a=false;                   
     }
     str3[0]='\0';
     
     for(int i=0;i<len2;i++)
             str3[i]='\0';
  
}

C++ Program with Matrices Examples

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

    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element a" << i + 1 << j + 1 << " : ";
           cin >> a[i][j];
       }

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


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


    cout << endl << "Sum of two matrix is: " << endl;
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
        {
            cout << sum[i][j] << "  ";
            if(j == c - 1)
                cout << endl;
        }

    return 0;
}

Output

Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 2
Enter elements of 1st matrix:
Enter element a11: -4
Enter element a12: 5
Enter element a21: 6
Enter element a22: 8
Enter elements of 2nd matrix:
Enter element b11: 3
Enter element b12: -9
Enter element b21: 7
Enter element b22: 2
Sum of two matrix is:
-1 -4
13 6

C++ Calculate Equation Examples

#include <iostream>
#include <cmath>
using namespace std;

int main() {

    float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
    cout << "Enter coefficients a, b and c: ";
    cin >> a >> b >> c;
    discriminant = b*b - 4*a*c;
    
    if (discriminant > 0) {
        x1 = (-b + sqrt(discriminant)) / (2*a);
        x2 = (-b - sqrt(discriminant)) / (2*a);
        cout << "Roots are real and different." << endl;
        cout << "x1 = " << x1 << endl;
        cout << "x2 = " << x2 << endl;
    }
    
    else if (discriminant == 0) {
        cout << "Roots are real and same." << endl;
        x1 = (-b + sqrt(discriminant)) / (2*a);
        cout << "x1 = x2 =" << x1 << endl;
    }

    else {
        realPart = -b/(2*a);
        imaginaryPart =sqrt(-discriminant)/(2*a);
        cout << "Roots are complex and different."  << endl;
        cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
        cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
    }

    return 0;
}

Output

Enter coefficients a, b and c: 4
5
1
Roots are real and different.
x1 = -0.25
x2 = -1

C++ Arrange Numbers in Ascending order Examples

#include <stdio.h>
#include <stdlib.h>
using namespace std;
 
int main()
{
    int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
    int n = sizeof(arr)/sizeof(arr[0]);
 
    sort(arr, arr+n);
 
    cout << "\nArray after sorting using "
         "default sort is : \n";
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
 
    return 0;
}

Output

Array after sorting using default sort is :
0 1 2 3 4 5 6 7 8 9

C++ Check Armstrong Number Examples

#include <iostream>
#include <iomanip>
int main(){
    int num,r,sum,temp;
    for(num=1;num<=500;num++){
         temp=num;
         sum = 0;
         while(temp!=0){
             r=temp%10;
             temp=temp/10;
             sum=sum+(r*r*r);
         }
         if(sum==num)
             cout << num << setw(2);
    }
    return 0;
}

C++ HCF and LCM Examples

#include <iostream>
#include <string>
using namespace std;
int main()
{
  int a,b,c;
  cout<< "Enter two nos :"<<endl;
  cout<< "Enter first no. : ";
  cin>>a;
  cout<< "Enter sec. no. : ";
  cin>>b;
  c=a*b;
  while(a!=b)
    {
      if(a>b)
        a=a-b;
      else
        b=b-a;
    }
  cout<< "HCF = " << a<<endl;
  cout<< "LCM = " << c/a<<endl;
  return 0;
}

Output

Enter two nos :
Enter first no. : 5
Enter sec. no. : 9
HCF = 1
LCM = 45

C++ Square Root of a Number Examples

#include <iostream>
#include <cmath>

using namespace std;
int main()
{
  int number, result;
  cout <<"Enter any number: ";
  cin >> number;
  result = pow(number, 0.5);
  cout<<"\nSqure of "<<number<<" is: " << result << endl;
}

Output

Enter any number: 
Squre of 0 is: 0

C++ Cube Root of a Number Examples

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
  int number, result;
  cout << "Enter any number : ";
  cin >> number;
  result = pow(number, 1.0/3.0);
  cout << "\n\Cube root of " << number << " is: " << result;
}

Output

Enter any number : 27
Cube root of 27 is: 3

C++ ASCII Code for Characters and Numbers

#include <iostream>
using namespace std;
 
int main(){
  char ascii;
  int numeric;
  cout << "Give character: ";
  cin >> ascii;
  cout << "Its ascii value is: " << (int) ascii << endl;
  cout << "Give a number to convert to ascii: ";
  cin >> numeric;
  cout << "The ascii value of " << numeric << " is " << (char) numeric;
  return 0;
}

Output

Give character: Its ascii value is: 0
Give a number to convert to ascii: The ascii value of 0 is

C++ Check Palindrome Number Examples

#include <stdio.h>
#include <iostream>

using namespace std;

int main(){
  int num,r,sum=0,temp;

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

  for(temp=num;num!=0;num=num/10){
    r=num%10;
    sum=sum*10+r;
  }
  if(temp==sum)
    cout << temp << " is a palindrome";
  else
    cout << temp << " is not a palindrome";

  return 0;
}

Output

Enter a number: 293646336 is not a palindrome

C++ Bubble sort Examples

#include <iostream>

using namespace std;
 
int main(){

  int array[5];
  cout<<"Enter 5 numbers randomly : "<<endl;
  for(int i=0; i<5; i++)
  {

    cin>>array[i];
  }
  cout<<endl;
  cout<<"Input array is: "<<endl;
 
  for(int j=0; j<5; j++)
  {

    cout<<"\t\t\tValue at "<<j<<" Index: "<<array[j]<<endl;
  }
  cout<<endl;

  int temp;
  for(int i2=0; i2<=4; i2++)
  {
    for(int j=0; j<4; j++)
    {

      if(array[j]>array[j+1])
      {
        temp=array[j];
        array[j]=array[j+1];
        array[j+1]=temp;
      }
    }
  }

  cout<<"  Sorted Array is: "<<endl;
  for(int i3=0; i3<5; i3++)
  {
    cout<<"\t\t\tValue at "<<i3<<" Index: "<<array[i3]<<endl;
  }
  return 0;
}

Output

Enter 5 numbers randomly :
Input array is:
Value at 0 Index: 4545
Value at 1 Index: 1184
Value at 2 Index: 0
Value at 3 Index: 0
Value at 4 Index: 4197008
Sorted Array is:
Value at 0 Index: 0
Value at 1 Index: 0
Value at 2 Index: 1184
Value at 3 Index: 4545
Value at 4 Index: 4197008

C++ Random Number Generator

#include<iostream>
#include<time.h>
#include<stdlib.h>
#define MAX_NUM 10
using namespace std;
void randnum()
{
  int random;
  srand(time(NULL));
  for(int i=0;i<10;i++)
  {
    random=rand()%MAX_NUM;
    cout<<random<<endl;
  }
}
int main()
{
  cout<<"The ten random number are "<<endl;
  randnum();
  return 0;
}

Output

The ten random number are
3
0
8
9
6
4
8
8
8
0

C++ Sum of ODD Numbers in the Given Range

#include <stdio.h>
#include <iostream>

using namespace std;
 
int main(){
 
  int number;
  int min,max;
  long sum =0;
 
  cout << "Enter the minimum range: ";
  cin >> min;
 
  cout << "Enter the maximum range: ";
  cin >> max;
 
  for(number = min;number <= max; number++)
    if(number % 2 !=0)
      sum = sum + number;
 
  cout << "Sum of odd numbers in given range is: " << sum;
 
  return 0;
 
}

Output

Enter the minimum range:
Enter the maximum range:
Sum of odd numbers in given range is: 4401637568064

C++ Display current date and time

#include <iostream>
#include <cmath>
#include <ctime>

using namespace std;

int main()
{

  time_t t = time(NULL);
  tm* timePtr = localtime(&t);

  cout << "seconds= " << (timePtr->tm_sec) << endl;
  cout << "minutes = " << (timePtr->tm_min) << endl;
  cout << "hours = " << (timePtr->tm_hour) << endl;
  cout << "day of month = " << (timePtr->tm_mday) << endl;
  cout << "month of year = " << (timePtr->tm_mon)+1 << endl;
  cout <<"year = " << (timePtr->tm_year)+1900 << endl;
  cout << "weekday = " << (timePtr->tm_wday )<< endl;
  cout << "day of year = " << (timePtr->tm_yday )<< endl;
  cout << "daylight savings = " <<(timePtr->tm_isdst )<< endl;
  cout << endl;
  cout << endl;


   cout << "Date " <<(timePtr->tm_mday)<<"/"<<
  (timePtr->tm_mon)+1 <<"/"<< (timePtr->tm_year)+1900<< endl;
  cout << "Time " << (timePtr->tm_hour)<<":"<< 
  (timePtr->tm_min)<<":"<< (timePtr->tm_sec) << endl;
  return 0;
}

Output

seconds= 17
minutes = 18
hours = 11
day of month = 12
month of year = 7
year = 2018
weekday = 4
day of year = 192
daylight savings = 0
Date 12/7/2018
Time 11:18:17

C++ Reverse a Number Examples

#include <iostream>
using namespace std;
 
int main() {
int number, reverse = 0;
cout<<"Enter a Number to Reverse and press Enter: ";
cin>> number; 
 
   for( ; number!= 0 ; )
   {
      reverse = reverse * 10;
      reverse = reverse + number%10;
      number = number/10;
   }
   cout<<"Reversed Number is:  "<< reverse;
   return 0;
 
}

Output

Enter a Number to Reverse and press Enter: 123456789 
Reversed Number is: 987654321

C++ Leap Year Examples

#include <iostream>
using namespace std;

int main()
{
    int year;

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

    if (year % 4 == 0)
    {
        if (year % 100 == 0)
        {
            if (year % 400 == 0)
                cout << year << " is a leap year.";
            else
                cout << year << " is not a leap year.";
        }
        else
            cout << year << " is a leap year.";
    }
    else
        cout << year << " is not a leap year.";

    return 0;
}


Output

Enter a year: 2014
2014 is not a leap year

C++ Surface Area and volume of cone

#include <iostream>
#include <cmath>

using namespace std;
int main()
{
    double r,h,a;
    cout<<"enter the radius="<<endl;
    cin>>r;
     cout<<"enter the hight="<<endl;
    cin>>h;
    if (r==0 || h==0)
    {
             cout<<"invalid operation"<<endl;
             
             }
    if(r!=0 && h!=0)
    {
            a=(3.14*r*r*h)/3;
            cout<<"the area="<<a<<endl;
            }    
            system("pause");
            return 0;
            
            
    }

Output

enter the radius=
enter the hight=
the area=0
sh: pause: command not found

C++ Solve Quadratic equation Examples

#include <iostream>
#include <cmath>

using namespace std;

int main() {

    float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
    cout << "Enter coefficients a, b and c: ";
    cin >> a >> b >> c;
    discriminant = b*b - 4*a*c;
    
    if (discriminant > 0) {
        x1 = (-b + sqrt(discriminant)) / (2*a);
        x2 = (-b - sqrt(discriminant)) / (2*a);
        cout << "Roots are real and different." << endl;
        cout << "x1 = " << x1 << endl;
        cout << "x2 = " << x2 << endl;
    }
    
    else if (discriminant == 0) {
        cout << "Roots are real and same." << endl;
        x1 = (-b + sqrt(discriminant)) / (2*a);
        cout << "x1 = x2 =" << x1 << endl;
    }

    else {
        realPart = -b/(2*a);
        imaginaryPart =sqrt(-discriminant)/(2*a);
        cout << "Roots are complex and different."  << endl;
        cout << "x1 = " << realPart << "+" << imaginaryPart << "i" << endl;
        cout << "x2 = " << realPart << "-" << imaginaryPart << "i" << endl;
    }

    return 0;
}


Output

Enter coefficients a, b and c: 4
5
1
Roots are real and different.
x1 = -0.25
x2 = -1

C++ Factorial using recursive function

#include <iostream>
using namespace std;

int factorial(int n);

int main()
{
    int n;

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

    cout << "Factorial of " << n <<<< " = " << factorial(n);

    return 0;
}

int factorial(int n)
{
    if(n > 1)
        return n * factorial(n - 1);
    else
        return 1;
}

Output

Enter an positive integer: 6
Factorial of 6 = 720

C++ String into Upper case or lower case

#include <iostream>
#include <string>

using namespace std;
 
int main()
{
char str1 [30], temp[30];
cout < < "Enter the string:";
cin > > str1;
strcpy ( temp, str1);
cout < < "strupr ( temp ) : " < < strupr (temp) < < end1;
cout < < "strlwr (temp) : " < < strlwr ( temp) < < end1;
system("pause");
 
return 0;
}

C++ Concatenate Strings Examples

#include <iostream>

using namespace std;

int main()
{
    string s1, s2, result;

    cout << "Enter string s1: ";
    getline (cin, s1);

    cout << "Enter string s2: ";
    getline (cin, s2);

    result = s1 + s2;

    cout << "Resultant String = "<< result;

    return 0;
}

Output

Enter string s1: C++ Programming
Enter string s2: is awesome.
Resultant String = C++ Programming is awesome.

C++ Program with Matrices Examples

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

    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element a" << i + 1 << j + 1 << " : ";
           cin >> a[i][j];
       }

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


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


    cout << endl << "Sum of two matrix is: " << endl;
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
        {
            cout << sum[i][j] << "  ";
            if(j == c - 1)
                cout << endl;
        }

    return 0;
}

Output

Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 2
Enter elements of 1st matrix:
Enter element a11: -4
Enter element a12: 5
Enter element a21: 6
Enter element a22: 8
Enter elements of 2nd matrix:
Enter element b11: 3
Enter element b12: -9
Enter element b21: 7
Enter element b22: 2
Sum of two matrix is:
-1 -4
13 6

C++ Print 5 rows of 10 Stars (*)

#include <iostream>

using namespace std;
const int STARS_PER_LINE = 10;
const int NUM_LINES      = 5;
 
int main()
{
  int stars_printed, lines_printed;
  lines_printed = 0;
  while ( lines_printed < NUM_LINES )
  {
    stars_printed = 0;
    while ( stars_printed < STARS_PER_LINE )
    {
      cout << '*';
      stars_printed++;
    }
    cout << endl;
    lines_printed++;
  }
  return 0;
}

Output

**********
**********
**********
**********
**********

C++ Half Pyramid of Stars (*)

#include <iostream>

using namespace std;
int main()
{
  int i,j,rows;
  cout<<"Enter the number of rows: ";
  cin>>rows;
  for(i=1;i<=rows;++i)
    {
      for(j=1;j<=i;++j)
        {
          cout<<"* ";
        }
      cout<<"\n";
    }
  return 0;
}

Output

Enter the number of rows: 5
*
* *
* * *
* * * *
* * * * *

C++ Half Pyramid of numbers

#include <iostream>

using namespace std;
int main()
{
  int i,j,rows;
  cout<<"Enter the number of rows: ";
  cin>>rows;
  for(i=1;i<=rows;++i)
    {
      for(j=1;j<=i;++j)
        {
          cout<<j<<" ";
        }
      cout<<"\n";
    }
  return 0;
}

Output

Enter the number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

C++ Print Triangle of Stars

#include <iostream>

using namespace std;
int main()
{
  int i,j,k;
  for(i=1; i<=5; i++)
    {
      for(j=4; j>=i; j--)
        {
          cout<<" ";
        }
      for(k=1; k<=(2*i-1); k++)
        {
          cout<<"*";
        }
      cout<<"\n";
    }
  return 0;
}

Output

    
         *
        ***
       *****
      *******
     *********

C++ Display Reverse pyramid

#include <iostream>

using namespace std;
int main()
{
  int rows,i,j,space;
  cout<<"Enter number of rows: ";
  cin>>rows;
  for(i=rows;i>=1;--i)
  {
    for(space=0;space<rows-i;++space)
      cout<<"  ";
    for(j=i;j<=2*i-1;++j)
      cout<<"* ";
    for(j=0;j<i-1;++j)
      cout<<"* ";
    cout<<endl;
  }
  return 0;
}

Output

Enter number of rows: 6
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

C++ Print Alphabet Pattern

#include <iostream>

using namespace std;
int main()
{
  int i,j;
  char input,temp='A';
  cout<<"Enter uppercase character you want in triange at last row: ";
  cin>>input;
  for(i=1;i<=(input-'A'+1);++i)
  {
    for(j=1;j<=i;++j)
      cout<<temp<<" ";
    ++temp;
    cout<<endl;
  }
  return 0;
}


Output

enter uppercase character you want in triange at last row: F
A
B B
C C C
D D D D
E E E E E
F F F F F F

C++ Diamond of Star Examples

#include <iostream>

using namespace std;
int main()
{
  int n, c, k, space = 1;
  cout<<"\n\nEnter number of rows: ";
  cin>>n;
  space = n - 1;
 
  for (k = 1; k<=n; k++)
  {
    for (c = 1; c<=space; c++)
      cout<<" ";
 
    space--;
 
    for (c = 1; c<= 2*k-1; c++)
      cout<<"*";
 
    cout<<"\n";
  }
 
  space = 1;
 
  for (k = 1; k<= n - 1; k++)
  {
    for (c = 1; c<= space; c++)
      cout<<" ";
 
    space++;
 
    for (c = 1 ; c<= 2*(n-k)-1; c++)
      cout<<"*";
 
    cout<<"\n";
  }
  return 0;
}

Output

Enter number of rows: 6
*
***
*****
*******
*********
***********
*********
*******
*****
***
*

C++ Pascal Triangle Examples

#include <iostream>

using namespace std;
int main()
{
  int rows,coef=1,space,i,j;
  cout<<"Enter number of rows: ";
  cin>>rows;
  for(i=0;i<rows;i++)
  {
    for(space=1;space<=rows-i;space++)
      cout<<"  ";
    for(j=0;j<=i;j++)
    {
      if (j==0||i==0)
        coef=1;
      else
        coef=coef*(i-j+1)/j;
      cout<<"    "<<coef;
    }
    cout<<endl;
  }
}

Output

Enter number of rows: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

C++ Floyd Triangle Examples

#include <iostream>

using namespace std;
int main()
{
  int rows,i,j,k=0;
  cout<<"Enter number of rows: ";
  cin>>rows;
  for(i=1;i<=rows;i++)
  {
    for(j=1;j<=i;++j)
      cout<<k+j<<" ";
    ++k;
    cout<<endl;
  }
  return 0;
}

Output

Enter number of rows: 6
1
2 3
3 4 5
4 5 6 7
5 6 7 8 9
6 7 8 9 10 11

C++ Convert decimal to Hexadecimal Examples

#include <iostream>
using namespace std;
 
int main(void)
{
int mynum;
cout << "\nEnter a number: ";
cin >> mynum;
cout.unsetf(ios::dec);
cout.setf(ios::hex | ios::showbase);
cout << "In hex: " << mynum;
cout.unsetf(ios::hex);
cout.setf(ios::oct);
cout << "\nIn Octal: " << mynum;
cout.unsetf(ios::oct | ios::showbase);
cout.setf(ios::dec);
system("pause");
return 0;
}

Output

Enter a number: In hex: 0
In Octal: 0sh: pause: command not found

C++ Decimal to Binary Examples

#include <iostream>
#include <math.h>

using namespace std ;
int main()
{
unsigned short int x=0,b=128 ,z=0,a=8 ;
cout<<"please enter the number between 0 and 255 \n";
cin >> x;
if (x>255)
cout<<" out of range ";
else
{
cout << x <<" converted to binary number :" ; 
 while (a!=0)
 {
  z=x&b ;
  if (z==128)
  cout << "1" ;
  else
  cout << "0";
  x=(x << 1);
  a-- ;
}
}
cout<<"\n";
system("pause");
return 0 ;
}

Output

please enter the number between 0 and 255 
0 converted to binary number :00000000
sh: pause: command not found

C++ Binary To Decimal Examples

#include <iostream>
#include <iomanip>
#include <string>
#include <climits>

 
using namespace std;
 
const size_t maxBits = sizeof(short) * CHAR_BIT;
 
int main(int argc, char *argv[]) {
  string line;
  bool inputOk;
  short n;
 
  while (true) {
      cout << "Enter binary number (" << maxBits;
      cout << " bits or less) : " << endl;
      do {
          cout << "> ";
          getline(cin,line);
          inputOk = true;
          for (size_t i = 0; (i < line.size()) && (inputOk == true); i++) {
              if ((line[i] != '0') && (line[i] != '1')) {
                  inputOk = false;
                  cout << "non-bit entered" << endl;
                }
            }
          if ((inputOk == true) && (line.size() > maxBits)) {
              inputOk = false;
              cout << "too big for " << maxBits << "-bit integer" << endl;
            }
        } while (inputOk == false);
 
   
      n = 0;
      for (int i = line.size()-1, j = 0; i >= 0; --i,j++) {
          n |= (line[i] - '0') << j;
        }
      cout << line << " = " << n << endl;
    }
  return 0;
}

Output

Enter binary number (16 bits or less) :
> 101000
101000 = 40
Enter binary number (16 bits or less) :
> 10
10 = 2
Enter binary number (16 bits or less) :
> 10
10 = 2
Enter binary number (16 bits or less) :
> 101
101 = 5
Enter binary number (16 bits or less) :
>

C++ Decimal to Octal Examples

#include <iostream>
#include <cmath>

using namespace std;
 
void DecToOct(int decnum){
 
  int digits=1;
  int howbig=1;
 
  while(1){
      if((8*howbig)>decnum){
          break;
        }else{
          howbig*=8;
          digits++;
        }
    }
 
  for(int i=digits;i>0;i--)
    cout<<((decnum>>((i-1)*3))&7);
}
 
void DecToQuat(int decnum){
  int digits=1;
  int howbig=1;
 

  while(1){
      if((4*howbig)>decnum){
          break;
        }else{
          howbig*=4;
          digits++;
        }
    }
 
  for(int i=digits;i>0;i--)
    cout<<((decnum>>((i-1)*2))&3);
}
 

int main(){
 
  int decimalnum;
  cout<<"Enter the decimal to be converted:";
  cin>>decimalnum;
  DecToOct(decimalnum);
  cout<<endl;
  DecToQuat(decimalnum);
 
  return 0;
}

Output

Enter the decimal to be converted:0
0

C++ Hexadecimal to Decimal Examples

#include <iostream>

int main()
{
  int integer;
  std::cout<<"Entex Hex to Convert hex to decimal"<<std::endl;
  std::cin >> std::hex >> integer;
  std::cout << integer << std::endl;
  return 0;
}


Output

Entex Hex to Convert hex to decimal
10
16

C++ Integer to String Examples

#include <string>
#include <sstream>
#include <iostream>
#include <class T>

std::string to_string(T t, std::ios_base & (*f)(std::ios_base&))
{
    std::ostringstream oss;
    oss << f << t;
                return oss.str();
}
int main()
{
                
std::cout<<to_string<long>(123456, std::hex)<<std::endl;
std::cout<<to_string<long>(123456, std::oct)<<std::endl;
return 0;
}


Output

1e240
361100

C++ Bubble sort Examples

#include <iostream>

using namespace std;
 
int main(){

  int array[5];
  cout<<"Enter 5 numbers randomly : "<<endl;
  for(int i=0; i<5; i++)
  {

    cin>>array[i];
  }
  cout<<endl;
  cout<<"Input array is: "<<endl;
 
  for(int j=0; j<5; j++)
  {

    cout<<"\t\t\tValue at "<<j<<" Index: "<<array[j]<<endl;
  }
  cout<<endl;

  int temp;
  for(int i2=0; i2<=4; i2++)
  {
    for(int j=0; j<4; j++)
    {

      if(array[j]>array[j+1])
      {
        temp=array[j];
        array[j]=array[j+1];
        array[j+1]=temp;
      }
    }
  }

  cout<<"  Sorted Array is: "<<endl;
  for(int i3=0; i3<5; i3++)
  {
    cout<<"\t\t\tValue at "<<i3<<" Index: "<<array[i3]<<endl;
  }
  return 0;
}

Output

Enter 5 numbers randomly :
Input array is:
Value at 0 Index: 4545
Value at 1 Index: 1184
Value at 2 Index: 0
Value at 3 Index: 0
Value at 4 Index: 4197008
Sorted Array is:
Value at 0 Index: 0
Value at 1 Index: 0
Value at 2 Index: 1184
Value at 3 Index: 4545
Value at 4 Index: 4197008

C++ Insertion Sort Examples

#include <iostream>

 
void PrintArray(int *array, int n) {
  for (int i = 0; i < n; ++i)
    std::cout << array[i] << " " << std::flush;
  std::cout << std::endl;
}
 
void InsertionSort(int arr[], int arr_size){
  if(arr_size > 1){
    int size = arr_size;
    for(int i = 1; i < size; ++i){
      int j = i - 1;
      int key = arr[i];
      while(j >= 0 && arr[j] > key){
        arr[j+1] = arr[j];
        --j;
      }
      arr[j+1] = key;
    }
  }
}
 
int main() {
  int array[] = {94, 42, 50, 95, 333, 65, 54, 456, 1, 1234};
  int n = sizeof(array)/sizeof(array[0]);
 
  std::cout << "Before Insertion Sort :" << std::endl;
  PrintArray(array, n);
 
  InsertionSort(array, n);
 
  std::cout << "After Insertion Sort :" << std::endl;
  PrintArray(array, n);
  return (0);
}

Output

Before Insertion Sort :
94 42 50 95 333 65 54 456 1 1234
After Insertion Sort :
1 42 50 54 65 94 95 333 456 1234

C++ Selection Sort Examples

#include <iostream>

 
void PrintArray(int *array, int n) {
  for (int i = 0; i < n; ++i)
    std::cout << array[i] << " " << std::flush;
  std::cout << std::endl;
}
 
inline void Swap(int &a, int &b){
  int k = a;
  a = b;
  b = k;
}
 
void SelectionSort(int arr[], int arr_size){
  for(int i = 0; i < arr_size - 1; ++i){
    int min = i;
    for(int j = i+1; j < arr_size; ++j)
      if(arr[j] < arr[min])
        min = j;
    Swap(arr[min], arr[i]);
  }
}
 
int main() {
  int array[] = {94, 42, 50, 95, 333, 65, 54, 456, 1, 1234};
  int n = sizeof(array)/sizeof(array[0]);
 
  std::cout << "Before Selection Sort :" << std::endl;
  PrintArray(array, n);
 
  SelectionSort(array, n);
 
  std::cout << "After Selection Sort :" << std::endl;
  PrintArray(array, n);
  return (0);
}

Output

Before Selection Sort :
94 42 50 95 333 65 54 456 1 1234
After Selection Sort :
1 42 50 54 65 94 95 333 456 1234

C++ Merge Sort Examples

#include <iostream>

 
void PrintArray(int *array, int n) {
  for (int i = 0; i < n; ++i)
    std::cout << array[i] << " " << std::flush;
  std::cout << std::endl;
}
 
void Merger(int arr[], int lo, int  mi, int hi){
    int *temp = new int[hi-lo+1];//temporary merger array
    int i = lo, j = mi + 1;//i is for left-hand,j is for right-hand
    int k = 0;//k is for the temporary array
    while(i <= mi && j <=hi){
        if(arr[i] <= arr[j])
            temp[k++] = arr[i++];
        else
            temp[k++] = arr[j++];
    }
   
    while(i <= mi)
        temp[k++] = arr[i++];
    
    while(j <= hi)
        temp[k++] = arr[j++];
    
    for(k = 0, i = lo; i <= hi; ++i, ++k)
        arr[i] = temp[k];
 
    delete []temp;
}
void MergeSortHelper(int arr[], int lo, int hi){
    int mid;
    if(lo < hi){
        mid = (lo + hi) >> 1;
        MergeSortHelper(arr, lo, mid);
        MergeSortHelper(arr, mid+1, hi);
        Merger(arr, lo, mid, hi);
    }
}
void MergeSort(int arr[], int arr_size){
    MergeSortHelper(arr, 0, arr_size-1);
}
 
int main() {
  int array[] = {94, 42, 50, 95, 333, 65, 54, 456, 1, 1234};
  int n = sizeof(array)/sizeof(array[0]);
 
  std::cout << "Before Merge Sort :" << std::endl;
  PrintArray(array, n);
 
  MergeSort(array, n);
 
  std::cout << "After Merge Sort :" << std::endl;
  PrintArray(array, n);
  return (0);
}

Output

Before Merge Sort :
94 42 50 95 333 65 54 456 1 1234
After Merge Sort :
1 42 50 54 65 94 95 333 456 1234

C++ Quick Sort Examples

#include <iostream>

void PrintArray(int *array, int n) {
  for (int i = 0; i < n; ++i)
    std::cout << array[i] << " " << std::flush;
  std::cout << std::endl;
}
 
inline void Swap(int &a, int &b){
    int k = a;
    a = b;
    b = k;
}
 

inline int rand(int p, int q){
    int size = q - p + 1;
//    srand(time(NULL));
    return (p + rand() % size);
}
int Partition(int arr[], int lo, int hi){
    //produce ramdom subscript
    int t = rand(lo, hi);
    Swap(arr[t], arr[hi]);
 
    int index = lo - 1;
    int key = arr[hi];
    for(int i = lo ; i < hi; i++){
        if(arr[i] <= key)
            Swap(arr[++index], arr[i]);
    }
    Swap(arr[++index], arr[hi]);
    return index;
}
void QuickSortHelper(int arr[], int lo, int hi){
    if(lo < hi){
        int index = Partition(arr, lo, hi);
        QuickSortHelper(arr, lo, index-1);
        QuickSortHelper(arr, index+1, hi);
    }
}
 
void QuickSort(int arr[], int arr_size){
    QuickSortHelper(arr, 0, arr_size-1);
}
 
 
int main() {
  int array[] = {94, 42, 50, 95, 333, 65, 54, 456, 1, 1234};
  int n = sizeof(array)/sizeof(array[0]);
 
  std::cout << "Before Quick Sort :" << std::endl;
  PrintArray(array, n);
 
  QuickSort(array, n);
 
  std::cout << "After Quick Sort :" << std::endl;
  PrintArray(array, n);
  return (0);
}

Output

Before Quick Sort :
94 42 50 95 333 65 54 456 1 1234
After Quick Sort :
1 42 50 54 65 94 95 333 456 1234

C++ How to get Current Directory in Linux/Windows

#include <stdio.h>

#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
#include<iostream>
 
std::string GetCurrentWorkingDir( void ) {
  char buff[FILENAME_MAX];
  GetCurrentDir( buff, FILENAME_MAX );
  std::string current_working_dir(buff);
  return current_working_dir;
}
 
int main(){
  std::cout << GetCurrentWorkingDir() << std::endl;
  return 1;
}

C++ How Create a Text File and Write in It Examples

#include <iostream>
#include <fstream>

using namespace std;
 
int main () {
  ofstream file;
  file.open ("codebind.txt");
  file << "Please writr this text to a file.\n this text is written using C++\n";
  file.close();
  return 0;
}

Output

Please writr this text to a file
this text is written using C++

C++ Program find if file exists of not Examples

#include <iostream>
#include <stat.h>

bool FileExists(const std::string& name) {
  struct stat buffer;
  return (stat (name.c_str(), &buffer) == 0);
}
 
int main() {
   std::string filename = "C:/file_name.txt";
   std::cout << "Does file_name.txt Exists ? " << FileExists(filename) << std::endl;
   return 0;
}

C++ Program to list all files in the Directory on Windows / Linux Examples

#include <dirent.h>
#include <cstring>
#include <iostream>
#include <vector>
#include <memory>

 
namespace {
std::vector<std::string> GetDirectoryFiles(const std::string& dir) {
  std::vector<std::string> files;
  std::shared_ptr<DIR> directory_ptr(opendir(dir.c_str()), [](DIR* dir){ dir && closedir(dir); });
  struct dirent *dirent_ptr;
  if (!directory_ptr) {
    std::cout << "Error opening : " << std::strerror(errno) << dir << std::endl;
    return files;
  }
 
  while ((dirent_ptr = readdir(directory_ptr.get())) != nullptr) {
    files.push_back(std::string(dirent_ptr->d_name));
  }
  return files;
}
}   
 
int main() {
  const auto& directory_path = std::string(".");
  const auto& files = GetDirectoryFiles(directory_path);
  for (const auto& file : files) {
    std::cout < file << std::endl;
  }
  return 0;
}

Output

.
main.cpp
main
..