Category: CPlusPlus Programs

c++ logo

  • C++ Program to Swap two Numbers using Functions

    In this tutorial, we will write a program for swapping of two numbers in C++ Using functions. The swapping number can be achieved in two ways through function.

    1. Call by Value
    2. Call by Reference

    You may click on the above link to go through the call by value and call by reference in C++.

    Explanation: Both of the programs take user input for the numbers to be swapped and pass it to the function as a parameter. The swapping computation is processed on the user-defined function


    2. C++ Program to Swap two Numbers using Call by Value

    #include <iostream>
    using namespace std;
    
    //user-defined function for swapping
    void swap(int x, int y)
    {
      int temp;
      temp = x;
      x = y;
      y = temp;
    
      cout << "\nResult after Swapping Two Numbers:\n";
      cout << "num1: " << x;
      cout << "\nnum2: " << y;
    }
    
    //main function
    int main()
    {
      int num1, num2;
    
      cout << "Enter num1: ";
      cin >> num1;
      cout << "Enter num2: ";
      cin >> num2;
    
      swap(num1, num2);
    
      return 0;
    }

    Output:

    Enter num1: 2
    Enter num2: 3

    Result after Swapping Two Numbers:
    num1: 3
    num2: 2


    2. C++ Program to Swap two Numbers using Call by Reference

    Since the call by reference deals with the address of the variable. Hence the use of pointer in the following program.

    #include <iostream>
    using namespace std;
    
    //user-defined function for swapping
    void swap(int *x, int *y)
    {
      int temp;
      temp = *x;
      *x = *y;
      *y = temp;
    }
    
    //main function
    int main()
    {
      int num1, num2;
    
      cout << "Enter num1: ";
      cin >> num1;
      cout << "Enter num2: ";
      cin >> num2;
    
      swap(&num1, &num2);
    
      cout << "\nResult after Swapping Two Numbers:\n";
      cout << "num1: " << num1;
      cout << "\nnum2: " << num2;
    
      return 0;
    }

    Output:

    Enter num1: 10
    Enter num2: 20

    Result after Swapping Two Numbers:
    num1: 20
    num2: 10

    You may go through the following program in C++:


  • C++ Program to Multiply two Numbers

    In this tutorial, we will write a C++ program to calculate the multiplication of two numbers. You may go through the following topics in C++ before writing a C++ program to find a product of two numbers.

    It is a simple program that takes two numbers from the user as input and multiplies them. We will use an arithmetic operator (*) to compute the product.

    Example: 3 * 5 = 15.


    C++ Program to Multiply two Numbers

    //C++ Program to Calculate Multiplication of two Numbers
    #include <iostream>
    using namespace std;
    
    int main()
    {
      double num1, num2, product;
    
      cout << "Enter the 1st number: ";
      cin >> num1;
    
      cout << "Enter the 2nd number: ";
      cin >> num2;
    
      //computing the product
      product = num1 * num2;
    
      cout << "\nProduct: " << product;
    
      return 0;
    }

    Output:

    Enter the 1st number: 5
    Enter the 2nd number: 8

    Product: 40

    You can change the data type as required to find the product of two numbers in C++.


  • C++ Program to Find Quotient and Remainder

    In this tutorial, we will write a C++ program to find the quotient and remainder of a given dividend and divisor.

    The program asked the user to enter the numbers (divisor and dividend). And to compute and find the quotient and remainder, we will use the division(/) and modulus(%) operators.


    C++ Program to Find Quotient and Remainder

    #include <iostream>
    using namespace std;
    
    int main()
    {    
       int denominator, numerator, quotient, remainder;
    
       cout << "Enter numerator: ";
       cin >> numerator;
    
       cout << "Enter denominator: ";
       cin >> denominator;
    
       quotient = numerator / denominator;
       remainder = numerator % denominator;
    
       cout << "\nQuotient: " << quotient << endl;
       cout << "Remainder: " << remainder;
    
       return 0;
    }

    Output:

    Enter numerator: 20
    Enter denominator: 10

    Quotient: 2
    Remainder: 0

    Enter numerator: 15
    Enter denominator: 4

    Quotient: 3
    Remainder: 3


  • C++ Program to Add Two Numbers

    In this tutorial, we will write a C++ program for the addition of two numbers. We can add the integers, floats, double, etc using the same program just changing the type.

    The program takes the user inputs for the number to be added then displays the result. We will see to add two numbers in three different ways in C++

    • Add two numbers in main function
    • Add two numbers using function
    • Add Two Numbers in using Class

    C++ Program to Add Two Numbers

    #include<iostream>
    using namespace std;
    
    int main()
    {
        int num1, num2, sum;
        
        cout << "Enter First Numbers: ";
        cin >> num1;
        
        cout << "Enter Second Numbers: ";
        cin >> num2;
        
        sum = num1 + num2;
        
        cout << "\nAddition Result: " << sum;
        
        return 0;
    }

    Output:

    Enter First Numbers: 5
    Enter Second Numbers: 3

    Addition Result: 8

    You can change the data type as required and use the same code.


    Add two numbers using Function in C++

    The program takes the user input the same as above, the only difference is the function is created for the calculation and return the result.

    #include<iostream>
    using namespace std;
    
    int add(int n1, int n2)
    {
        return (n1 + n2);
    }
    
    int main()
    {
        int num1, num2, sum;
        
        cout << "Enter First Numbers: ";
        cin >> num1;
        
        cout << "Enter Second Numbers: ";
        cin >> num2;
        
        sum = add(num1, num2);
        
        cout << "\nAddition Result: " << sum;
        
        return 0;
    }

    Output:

    Enter First Numbers: 20
    Enter Second Numbers: 5

    Addition Result: 25


    Add Two Numbers in C++ using Class

    Here separate class is created to get the values and add the numbers and return to the main function.

    #include <iostream>
    using namespace std;
    
    class AddClass
    {
       private:
          int num1, num2;
    
       public:
       void getData()
       {
          cout << "Enter First Numbers: ";
          cin >> num1;
    
          cout << "Enter Second Numbers: ";
          cin >> num2;
       }
    
       int add()
       {
          return (num1 + num2);
       }
    };
    
    int main()
    {
       int sum;
       AddClass obj;
    
       obj.getData();
       sum = obj.add();
    
       cout << "\nAddition result: " << sum;
    
       return 0;
    }

    Output:

    Enter First Numbers: 10
    Enter Second Numbers: 6

    Addition result: 16


  • Print Count Down Timer in C++

    In this tutorial, we will learn how to create a count down timer program in C++. To understand better, you may go through the following first.

    The program takes the value to start the countdown and then reverse the countdown from there. The while loop is used to reverse the entered value.


    Print Count Down Timer in C++

    #include <iostream>
    #include <Windows.h>
    using namespace	std;
    
    int main()
    {
        int	timer;
        
        cout << "Set the timer: ";
        cin	>> timer;
        
        while(timer > 0)
        {
            cout << "Time Remaining:" << timer <<endl;
            Sleep(1000);
            --timer;
        }
        
        cout << "\nTime Up!";
        
        return 0;
    }

    Output:

    Set the timer: 4
    Time Remaining: 4
    Time Remaining: 3
    Time Remaining: 2
    Time Remaining: 1

    Time Up!


  • C++ Program to Subtract Two Matrices

    In this tutorial, we will learn and write a C++ program to print the subtraction of two matrices. To understand the coding, you should have knowledge of the following topics in C++ programming:

    The program takes the user input for the number of rows and columns and then the elements for both the matrices.

    Lastly, subtract the matrices and store them in a separate array and display the result. Let us go through the program.


    C++ Program to Subtract Two Matrices

    During the subtraction of matrices, it is important that both of the matrices should have the same dimensions such as the 2×3 matrix can be subtracted only with a 2×3 matrix.

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int arr1[50][50], arr2[50][50], sub[50][50];
      int row, col, i, j;
    
      cout << "Enter the no. of rows: ";
      cin >> row;
      cout << "Enter the no. of columns: ";
      cin >> col;
    
      // 1st matrix user input
      cout << endl << "Enter 1st Matrix elements: " << endl;
      for (i = 0; i < row; ++i)
        for (j = 0; j < col; ++j)
          cin >> arr1[i][j];
    
      // 2nd matrix user input
      cout << endl << "Enter 2nd Matrix elements: " << endl;
      for (i = 0; i < row; ++i)
        for (j = 0; j < col; ++j)
          cin >> arr2[i][j];
    
      // matrix adition
      for (i = 0; i < row; ++i)
        for (j = 0; j < col; ++j)
          sub[i][j] = arr1[i][j] - arr2[i][j];
    
      // Displaying the result
      cout << endl << "Result of the subtraction of the matrices: " << endl;
      for (i = 0; i < row; ++i)
        for (j = 0; j < col; ++j)
        {
          cout << sub[i][j] << "  ";
          if (j == col - 1)
            cout << endl;
        }
    
      return 0;
    }

    Output:

    Enter the no. of rows: 2
    Enter the no. of columns: 3

    Enter 1st Matrix elements:
    6
    5
    4
    3
    2
    1

    Enter 2nd Matrix elements:
    3
    2
    3
    3
    1
    1

    Result of the subtraction of the matrices:
    3 3 1
    0 1 0


  • C++ Program to Find Smallest Element in an Array

    In this tutorial, we will learn and write a print the smallest element in an array in C++. To understand the coding, you should have knowledge of the following topics in C++ programming:


    1. C++ program to find the smallest element in an array

    The program takes user input for the size and the values of elements of an array. Lastly, displays the smallest element present in the array.

    The first element in an array is assumed to be the smallest element then iterating the array using for loop, we compare each of the elements present in an array. Whenever the element is found to be smaller then the value is inserted into the smallest variable.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int arr[50], size, smallest, i;
    
       cout << "Enter the size of an array: ";
       cin >> size;
    
       cout << "Enter " << size << " Array Elements:\n";
       for (i = 0; i < size; i++)
          cin >> arr[i];
    
       smallest = arr[0];
       for (i = 1; i < size; i++)
       {
          if (smallest > arr[i])
             smallest = arr[i];
       }
    
       cout << "\nSmallest Element in an array: " << smallest;
    
       return 0;
    }

    Output:

    Enter the size of an array: 5
    Enter 5 Array Elements:
    23
    65
    12
    19
    16

    Smallest Element in an array: 12


    2. Using Function

    The program logic is the same as the above only difference is we will create a separate function to search for the smallest element and return the value from that function.

    #include <iostream>
    using namespace std;
    
    //function to find smallest element
    int findSmallest(int a[], int s)
    {
      int i, small;
      small = a[0];
    
      for (i = 1; i < s; i++)
      {
        if (small > a[i])
          small = a[i];
      }
    
      return small;
    }
    
    //main function
    int main()
    {
      int arr[50], size, smallest, i;
    
      cout << "Enter the size of an array: ";
      cin >> size;
    
      cout << "Enter " << size << " Array Elements:\n";
      for (i = 0; i < size; i++)
        cin >> arr[i];
    
      smallest = findSmallest(arr, size);
    
      cout << "\nSmallest Element in an array: " << smallest;
    
      return 0;
    }

    Enter the size of an array: 5
    Enter 5 Array Elements:
    3
    56
    2
    98
    12

    Smallest Element in an array: 2


    3. Find Smallest Number in Array using Pointer in C++

    If you want to learn about the pointer and how it works then click the link below.

    Source code:

    #include<iostream>
    using namespace std;
    int main()
    {
        int arr[50], size, i, small;
        int *ptr;
        
        cout << "Enter the Size for an Array: ";
        cin >> size;
        
        cout << "Enter " << size << " Array Elements:\n";
        for(i=0; i<size; i++)
            cin>>arr[i];
            
        ptr = &arr[0];
        small = *ptr;
        
        while(*ptr)
        {
            if(small > (*ptr))
                small = *ptr;
            ptr++;
        }
        
        //Display
        cout << "\nSmallest Element: " << small;
        
        return 0;
    }

    Output:

    Enter the Size for an Array: 5
    Enter 5 Array Elements:
    12
    45
    11
    36
    30

    Smallest Element: 11


  • C++ Program to Find Largest Number in an Array

    In this tutorial, we will learn and write a print the largest element in an array in C++. To understand the coding, you should have knowledge of the following topics in C++ programming:


    1. C++ program to find the largest element in an array

    The program takes user input for the size and the values of elements of an array. Lastly, displays the largest element present in the array.

    The first element in an array is assumed to be the largest element then iterating the array using for loop, we compare each of the elements present in an array. Whenever the element is found to be smaller then the value is inserted into the largest variable.

    #include<iostream>
    using namespace std;
    
    int main()
    {
        int arr[50], size, largest, i;
        
        cout<<"Enter the size of an array: ";
        cin>>size;
        
        cout<<"Enter " << size << " Array Elements:\n";
        for(i = 0; i < size; i++)
            cin>>arr[i];
            
        //assuming first element to be largest
        largest = arr[0];
        
        for(i = 1; i < size; i++)
        {
            if(largest<arr[i])
                largest = arr[i];
        }
        
        //Display the result
        cout << "\nLargest Element in an array: " << largest;
        
        return 0;
    }

    Output:

    Enter the size of an array: 5
    Enter 5 Array Elements:
    25
    12
    58
    5
    12

    Largest Element in an array: 58


    2. Using Function

    The program logic is the same as the above only difference is we will create a separate function to search for the largest element and return the value from that function.

    #include<iostream>
    using namespace std;
    
    //function to find largest element
    int findLargest(int a[], int s)
    {
        int i, large;
        large = a[0];
        for(i=1; i<s; i++)
        {
           if(large < a[i])
               large = a[i];
        }
        return large;
    }
    
    //main function
    int main()
    {
        int arr[100], size, largest, i;
        
        cout<<"Enter the size of an array: ";
        cin>>size;
        
        cout<<"Enter " << size << " Array Elements:\n";
        for(i=0; i<size; i++)
            cin>>arr[i];
            
        largest = findLargest(arr, size);
        
        cout<<"\nLargest Element in an array: "<<largest;
        
        return 0;
    }
    

    Output:

    Enter the size of an array: 5
    Enter 5 Array Elements:
    53
    2
    70
    23
    11

    Largest Element in an array: 70


  • C++ Program to Find if an Array is an Identity Matrix

    In this tutorial, we will learn and write a C++ program to check whether a given matrix is an identity matrix or not. To understand the coding, you should have knowledge of the following topics in C++ programming:


    Identity Matrix:

    A square matrix is said to be an identity matrix if each entry on its diagonal is equal to 1 and the rest are 0. Example:

    Matrix of dimension 3 by 3:
    1 0 0
    0 1 0
    0 0 1


    Explanation: The program takes user input for the number of rows and columns of a matrix. The values are of each element are also taken from the user.

    Before entering the elements of the matrix, the program also checks for the matrix to be a square matrix. If it is a square matrix then the execution control moves to the next line but if not then the program is exited.

    The program checks the diagonals matrix for 1 and the rest for 0. If the conditions are found to be true then the entered matrix is identity matrix else not.

    Now let us go through a program for Identity Matrix in C++.


    C++ Program to Find if an Array is an Identity Matrix

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int i, j, row, col, arr[10][10], flag = 0;
    
      cout << "Enter the number of rows: ";
      cin >> row;
      cout << "Enter the number of column: ";
      cin >> col;
    
      //Checking for square matrix
      if (row != col)
      {
        cout << "\nMatrix is not a square matrix. Try Again!";
        exit(0);
      }
    
      cout << "\nEnter the elements of matrix:\n";
      for (i = 0; i < row; i++)
        for (j = 0; j < col; j++)
          cin >> arr[i][j];
    
      //Checking for diagonals and rest
      for (i = 0; i < row; i++)
      {
        for (j = 0; j < col; j++)
        {
          if ((arr[i][j] != 1) && (arr[j][i] != 0))
          {
            flag = 1;
            break;
          }
        }
      }
    
      //Display accordingly
      if (flag == 0)
        cout << "\nThe entered matirix is an identity matrix.\n";
      else
        cout << "\nThe entered matirix is NOT an identity matrix.";
    
      //Display the matrix
      for (i = 0; i < row; i++)
      {
        for (j = 0; j < col; j++)
          cout << arr[i][j] << " ";
        cout << "\n";
      }
    
      return 0;
    }

    Output:

    identity matrix in C++

  • C++ Program to Insert an Element in an Array

    In this tutorial, we will learn and write a program to insert an element in an array in C++. To understand the coding, you should have knowledge of the following topics in C++ programming:


    We will learn two ways to insert an element in an array in C++:

    1. Insert an element at the end of an array
    2. Insert an element at a specific position of an array

    1. Insert an element at the end of an array

    The program takes user input for the size and the values of elements of an array.

    Also takes the user inputs for the value of an element to be inserted at the end of an array. Lastly, displays the new array formed after insertion.

    //C++ Program to insert an Element in an array
    #include <iostream>
    using namespace std;
    
    int main()
    {
      int arr[30], size, i, insElem, count = 0;
    
      cout << "Enter the size of an array (Max size: 30): ";
      cin >> size;
    
      cout << "Enter array elements:\n";
      for (i = 0; i < size; i++)
        cin >> arr[i];
    
      cout << "\nEnter element to be inserted: ";
      cin >> insElem;
      
      arr[i] = insElem;
      
      //Display new array
      cout << "New Array after Insertion:\n";
      for (i = 0; i < (size+1); i++)
          cout << arr[i] << " ";
    
      return 0;
    }

    Output:

    insert element in an array in C++

    2. Insert Element in Array at a Specific Position

    Here too, the program takes input from the user but in addition to the above, the position at which the element is to be inserted is also taken as user input.

    //C++ Program to insert an Element at any position
    #include <iostream>
    using namespace std;
    
    int main()
    {
      int arr[30], size, pos, i, insElem, count = 0;
    
      cout << "Enter the size of an array (Max size: 30): ";
      cin >> size;
    
      cout << "Enter array elements:\n";
      for (i = 0; i < size; i++)
        cin >> arr[i];
    
      cout << "\nEnter element to be inserted: ";
      cin >> insElem;
    
      cout << "Enter the position: "; //position specified
      cin >> pos;
    
      for (i = size; i >= pos; i--)
        arr[i] = arr[i - 1];
    
      arr[i] = insElem;
    
      //Display new array
      cout << "New Array after Insertion:\n";
      for (i = 0; i < (size + 1); i++)
        cout << arr[i] << " ";
    
      return 0;
    }

    Output:

    Enter the size of an array (Max size: 30): 5
    Enter array elements:
    1
    2
    3
    4
    5

    Enter element to be inserted: 6
    Enter the position: 3
    New Array after Insertion:
    1 2 6 3 4 5