Blog

  • C++ Program to display Pascal Triangle

    In this tutorial, we will write a C++ program to display pascal’s triangle. Before that, you may go through the following topic in C++.


    C++ Program to display Pascal Triangle

    C++ program to print pascal’s triangle: The program takes the user input for the number of rows the user wants in a pascal triangle and by nesting the for loop, the program displays the triangle.

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int rows, i, j, k;
      cout << "Enter the number of rows: ";
      cin >> rows;
    
      for (i = 0; i < rows; i++)
      {
        int val = 1;
        for (j = 1; j < (rows - i); j++)
          cout << "   ";
    
        for (k = 0; k <= i; k++)
        {
          cout << "      " << val;
          val = val *(i - k) / (k + 1);
        }
    
        cout << endl << endl;
      }
    
      return 0;
    }

    Output:

    Enter the 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++ Program to Calculate Sum of Geometric Progression

    In this tutorial, we will learn and write a program to find the sum of GP series in C++. Before that, you may go through the following topics in C++ programming:

    The program takes the first term, the common ratio and the number of terms as input and calculates the GP on a separate function.


    C++ Program to Calculate Sum of Geometric Progression

    #include <iostream>
    using namespace std;
    
    void gpFunc(float, float, int);
    
    int main()
    {
      int n;
      float a, r;
    
      cout << "Enter the first term (a): ";
      cin >> a;
    
      cout << "Enter the common ratio (r): ";
      cin >> r;
    
      cout << "Enter the no. of terms (n): ";
      cin >> n;
    
      //calling function
      gpFunc(a, r, n);
    }
    
    void gpFunc(float a, float r, int n)
    {
      float sum = 0, temp = a;
    
      for (int i = 1; i < n; i++)
      {
        sum = sum + temp;
        temp = temp * r;
      }
    
      cout << "\nSum of geometric progression: " << sum;
    }

    Output:

    Enter the first term (a): 1
    Enter the common ratio (r): 2
    Enter the no. of terms (n): 10

    Sum of geometric progression: 511


  • C++ Program to find the Transpose of a Matrix

    In this tutorial, we will learn and write a program to find the transpose of matric in C++. Before that, you may go through the following topics in C++ programming:

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


    C++ Program to find the Transpose of a Matrix

    Program: Transpose of a matrix in C++ using array.

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int arr[10][10], trans[10][10], row, col, i, j;
    
      cout << "Enter the no. of rows: ";
      cin >> row;
      cout << "Enter the no. of columns: ";
      cin >> col;
    
      //get matrix elements
      cout << "Enter the elements: " << endl;
      for (i = 0; i < row; i++)
      {
        for (j = 0; j < col; j++)
          cin >> arr[i][j];
      }
    
      // transpose computation
      for (i = 0; i < row; ++i)
        for (j = 0; j < col; ++j)
          trans[j][i] = arr[i][j];
    
      //Displaying the result
      cout << "\nTranspose result:" << endl;
      for (int i = 0; i < col; ++i)
        for (int j = 0; j < row; ++j)
        {
          cout << " " << trans[i][j];
          if (j == row - 1)
            cout << endl << endl;
        }
    
      return 0;
    }

    Output:

    Enter the no. of rows: 3
    Enter the no. of columns: 3
    Enter the elements:
    1 2 3
    4 5 6
    7 8 9

    Transpose result:
    1 4 7
    2 5 8
    3 6 9


  • How to Split a String in C++

    Let us learn how to split string in C++ programming language. We will look at a few ways to split a string.

    The splitting of string refers to the grouping of sentences into their individual single word. And splitting is possible only when there is a presence of some delimiters like white space ( ), comma (,), etc. Although there is no straight way to do this as there is no inbuilt function through which we can easily split the string. Hence, we will look at different techniques to split the string in C++.


    Different ways of splitting of string in Cpp.

    1. Use strtok() function to split strings

    How to use strtok: strtok() function splits the string based on some delimiter. We need to pass the string and the delimiter to this function as shown in the example below.

    Syntax for strtok():

    char *ptr = strtok( str, delim)  

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main()
    {
      char str[100];
    
      cout << "Enter a string: ";
      cin.getline(str, 100);
    
      char *ptr;
      ptr = strtok(str, ", ");
    
      cout << "\nAfter splitting: " << endl;
      while (ptr != NULL)
      {
        cout << ptr << endl;
        ptr = strtok(NULL, ", ");
      }
    
      return 0;
    }

    Output:

    Enter a string: This is simple2code.com website

    After splitting:
    This
    is
    simple2code.com
    website


    2. Use std::getline() function to split string

    This is another inbuilt function in C++ that extracts characters from the istream object and stores them into a specified stream until the delimitation character is found.

    getline() function is present in <string> header file. It takes three parameters: string, token, and delimiter.

    Syntax for getline():

    getline(str, token, delim); 

    #include <iostream>
    #include <string>
    #include <vector>
    #include <sstream>
    using namespace std;
    
    int main()
    {
      string str, tok;
    
      cout << "Enter a string: ";
      getline(cin, str);
    
      // S refers the string str
      stringstream S(str);
    
      //while loop to iterate and print words
      while (getline(S, tok, ' '))
      {
        cout << tok << endl; 
      }
    
      return 0;
    }

    Output:

    Enter a string: This is a coding website
    This
    is
    a
    coding
    website


  • C++ Program to calculate Average of Numbers using Arrays

    In this tutorial, we will learn and write a C++ program to find the average of numbers using an array. 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 elements the user wants and the values of those elements. Based on those values, an average is calculated.


    C++ Program to calculate Average of /numbers using Arrays

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int arrNum[200], i, n, sum = 0;
      float avg;
    
      cout << "Enter number of elements: ";
      cin >> n;
    
      // check whether n lies within 1 to 200
      while (n > 200 || n <= 0)
      {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
      }
    
      cout << "Enter " << n << " elements" << endl;
      for (i = 0; i < n; i++)
        cin >> arrNum[i];
    
      for (i = 0; i < n; i++)
        sum += arrNum[i];
    
      avg = (float) sum / n;
      cout << "Average of " << n << " numbers: " << avg;
    
      return 0;
    }

    Output:

    Enter number of elements: 4
    Enter 4 elements
    10
    20
    30
    40
    Average of 4 numbers: 25


  • C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays

    In this tutorial, we will learn and write a C++ program to print the multiplication of two matrices. Before that, you may go through 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.


    C++ Program to Multiply Two Matrix Using Multi-dimensional Arrays

    Multiplication of matrix in C++.

    #include <iostream>
    using namespace std;
    int main()
    {
      int a[10][10], b[10][10], mul[10][10];
      int row, col, i, j, k;
      
      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 >> a[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 >> b[i][j];
        
      }
      
     // matrix multiplication
      for (i = 0; i < row; i++)
      {
        for (j = 0; j < col; j++)
        {
          mul[i][j] = 0;
          for (k = 0; k < col; k++)
            mul[i][j] += a[i][k] *b[k][j];
          
        }
      }
    
     //Displaying the result
      cout << "Multiplication of matrix" << endl;   
      for (i = 0; i < row; i++)
      {
        for (j = 0; j < col; j++)
          cout << mul[i][j] << " ";
    
        cout << "\n";
      }
    
      return 0;
    }

    Output:

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

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

    Enter 2nd Matrix elements:
    1 2 3
    1 2 3
    1 2 3
    Multiplication of matrix
    11 22 33
    11 22 33
    11 22 33


  • C++ Program to Calculate Difference Between Two Time Period

    In this tutorial, we will write a C++ program to find the difference between two time periods. Before that, you may go through the following topic in C++.

    We will look at two different programs:

    • Using if statement
    • Using Structure

    C++ Program to Calculate Difference Between Two Time Periods

    #include <iostream>
    using namespace std;
    
    int main()
    {
      int hour1, minute1, second1;
      int hour2, minute2, second2;
      int diff_in_hour, diff_in_minute, diff_in_second;
    
      cout << "Enter the first time period:" << endl;
      cout << "Hours, Minutes and Seconds respectively: " << endl;
      cin >> hour1 >> minute1 >> second1;
    
      cout << "Enter the second time period:" << endl;
      cout << "Hours, Minutes and Seconds respectively: " << endl;
      cin >> hour2 >> minute2 >> second2;
    
      if (second2 > second1)
      {
        minute1--;
        second1 += 60;
      }
    
      diff_in_second = second1 - second2;
    
      if (minute2 > minute1)
      {
        hour1--;
        minute1 += 60;
      }
    
      diff_in_minute = minute1 - minute2;
    
      diff_in_hour = hour1 - hour2;
    
      cout << "Time Difference between above two time period is: " << endl;
      cout << diff_in_hour << "hr " << diff_in_minute << "min " << diff_in_second << "sec";
    
      return 0;
    }

    Output:

    Hours, Minutes and Seconds respectively:
    8
    25
    68
    Enter the second time period:
    Hours, Minutes and Seconds respectively:
    7
    20
    25
    Time Difference between above two time period is:
    1hr 5min 43sec


    C++ Program to find difference between two time period using structure

    #include <iostream>
    using namespace std;
    
    struct Time
    {
      int hours;
      int minutes;
      int seconds;
    };
    
    //Function to compute the difference in time periods
    void differenceFunction(struct Time tp1, struct Time tp2, struct Time *difference)
    {
    
      if (tp2.seconds > tp1.seconds)
      {
        --tp1.minutes;
        tp1.seconds += 60;
      }
    
      difference->seconds = tp1.seconds - tp2.seconds;
      if (tp2.minutes > tp1.minutes)
      {
        --tp1.hours;
        tp1.minutes += 60;
      }
      difference->minutes = tp1.minutes - tp2.minutes;
      difference->hours = tp1.hours - tp2.hours;
    }
    
    //main function
    int main()
    {
      struct Time tp1, tp2, difference;
    
      cout << "Enter the first time period:" << endl;
      cout << "Hours, Minutes and Seconds respectively: " << endl;
      cin >> tp1.hours >> tp1.minutes >> tp1.seconds;
    
      cout << "Enter the second time period:" << endl;
      cout << "Hours, Minutes and Seconds respectively: " << endl;
      cin >> tp2.hours >> tp2.minutes >> tp2.seconds;
    
      differenceFunction(tp1, tp2, &difference);
    
      cout << endl << "Time Difference: " << tp1.hours << ":" << tp1.minutes << ":" << tp1.seconds;
      cout << " - " << tp2.hours << ":" << tp2.minutes << ":" << tp2.seconds;
      cout << " = " << difference.hours << ":" << difference.minutes << ":" << difference.seconds;
      return 0;
    }

    Output:

    Enter the first time period:
    Hours, Minutes and Seconds respectively:
    10
    20
    50
    Enter the second time period:
    Hours, Minutes and Seconds respectively:
    7
    30
    30

    Time Difference: 10:20:50 - 7:30:30 = 2:50:20


  • C++ Program to store information of a student in a Structure

    In this tutorial, we will write a program to store information of a student in a Structure in C++. You may go through the following topics first.

    C++ program using structure.

    #include <iostream>
    using namespace std;
    
    //creating the structure
    struct student
    {
        char name[50];
        int roll;
        float marks;
        char grade;
    };
    
    //main
    int main() 
    {
        student std;
        cout << "Enter your Detail:" << endl;
        cout << "Name: ";
        cin >> std.name;
        cout << "Roll Number: ";
        cin >> std.roll;
        cout << "Marks: ";
        cin >> std.marks;
        cout << "Grade: ";
        cin >> std.grade;
    
        cout << "\nDisplaying Information," << endl;
        cout << "Name: " << std.name << endl;
        cout << "Roll: " << std.roll << endl;
        cout << "Marks: " << std.marks << endl;
        cout << "Grade: " << std.grade << endl;
        return 0;
    }

    Output:

    Enter your Detail:
    Name: Pushpa
    Roll Number: 1101
    Marks: 80
    Grade: A

    Displaying Information,
    Name: Pushpa
    Roll: 1101
    Marks: 80
    Grade: A


  • Neon Number in C++

    In this tutorial, we will write a neon number program in Cpp. We will write two different programs.

    1. Check for neon number
    2. Display the neon number within the range

    Neon Numbers

    A number is said to be a neon number if the sum of the digits of a square of the number is equal t the original number.

    Example: 9 is a Neon number (see explanation in the diagram).

    Neon Number in C

    Neon Number in C++

    C++ Program to check for neon numbers.

    //Cpp Program to check whether a given number is a Neon number or not
    #include <iostream>
    using namespace std;
    
    int main()
    {
      int num;
    
      cout << "Enter the number: ";
      cin >> num;
    
      int square = num * num;
      int sum = 0;
    
      while (square > 0)
      {
        int lastDigit = square % 10;
        sum = sum + lastDigit;
        square = square / 10;
      }
    
      if (sum == num)
        cout << num << " is a Neon number";
      else
        cout << num << " is NOT a Neon number";
    
      return 0;
    }

    Output:

    Enter the number: 9
    9 is a Neon number


    C++ program to display all the neon number within a given range

    //Cpp Program to check whether a given number is a Neon number or not
    #include <iostream>
    using namespace std;
    
    int checkForNeon(int x)
    {
      int square = x * x;
      int sumOfDigits = 0;
    
      while (square != 0)
      {
        sumOfDigits = sumOfDigits + square % 10;
        square /= 10;
      }
    
      return (sumOfDigits == x);
    }
    
    // Main function
    int main(void)
    {
      int lowestNum, highestNum;
    
      cout << "ENTER THE STARTING AND FINAL NUMBER FOR THE RANGE TO CHECK\n";
    
      cout << "\nEnter the lowest number: ";
      cin >> lowestNum;
    
      cout << "Enter the Highest number: ";
      cin >> highestNum;
    
      cout << "\nNeon Number between them are:";
      for (int i = lowestNum; i <= highestNum; i++)
      {
        if (checkForNeon(i))
          cout << i << " ";
      }
    }

    Output:

    ENTER THE STARTING AND FINAL NUMBER FOR THE RANGE TO CHECK

    Enter the lowest number: 1
    Enter the Highest number: 2000

    Neon Number between them are:1 9


  • Half Diamond number pattern in C

    In this tutorial, we will write a C Program to display full hourglass patterns using numbers. Before that, you may go through the following topic in C.

    Half Diamond number pattern in C

    We will write various programs for the left half and right half diamond with different kinds of number patterns. These programs can also be called the arrowhead pattern programs in C.

    Right Half Diamond number patter

    1. Increasing number pattern

    #include <stdio.h>
    
    int main()
    {
      int i, j, rows;
    
      printf("Enter the no. of rows: ");
      scanf("%d", &rows);
    
      for (i = 1; i <= rows; i++)
      {
        for (j = 1; j <= i; j++)
          printf("%d ", j);
    
        printf("\n");
      }
    
      for (i = rows - 1; i >= 1; i--)
      {
        for (j = 1; j <= i; j++)
          printf("%d ", j);
    
        printf("\n");
      }
    
      return 0;
    }

    Output:

    Enter the no. of rows: 5
    1
    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5
    1 2 3 4
    1 2 3
    1 2
    1


    2. Mirror number pattern

    #include <stdio.h>
    
    int main()
    {
      int i, j, rows;
    
      printf("Enter the no of rows: ");
      scanf("%d", &rows);
    
      //upper half
      for (i = 1; i <= rows; i++)
      {
        for (j = 1; j <= i; j++)
          printf("%d", j);
    
        for (j = i - 1; j >= 1; j--)
          printf("%d", j);
    
        printf("\n");
      }
    
      //lower half
      for (i = rows - 1; i >= 1; i--)
      {
        for (j = 1; j <= i; j++)
          printf("%d", j);
    
        for (j = i - 1; j >= 1; j--)
          printf("%d", j);
    
        printf("\n");
      }
    
      return 0;
    }

    Output:

    Enter the no of rows: 5
    1
    121
    12321
    1234321
    123454321
    1234321
    12321
    121
    1


    3. Increment in two numbers

    #include <stdio.h>
    
    int main()
    {
      int i, j, rows;
    
      printf("Enter the no. of rows: ");
      scanf("%d", &rows);
    
      // Upper half
      for (i = 1; i <= rows; i++)
      {
        for (j = 1; j <= (i *2) - 1; j++)
          printf("%d", j);
    
        printf("\n");
      }
    
      // Lower Half
      for (i = rows - 1; i >= 1; i--)
      {
        for (j = 1; j <= (i *2) - 1; j++)
          printf("%d", j);
    
        printf("\n");
      }
    
      return 0;
    }

    Output:

    Enter the no. of rows: 5
    1
    123
    12345
    1234567
    123456789
    1234567
    12345
    123
    1


    Left half diamond pattern in C

    Pattern 1:

    #include <stdio.h>
    
    int main()
    {
      int i, j, rows;
    
      printf("Enter the no of rows: ");
      scanf("%d", &rows);
    
      // upper half
      for (i = 1; i <= rows; i++)
      {
        for (j = rows - 1; j >= i; j--)
          printf(" ");
    
        for (j = 1; j <= i; j++)
          printf("%d", j);
    
        printf("\n");
      }
    
      //lower part
      for (i = rows - 1; i >= 1; i--)
      {
        for (j = i; j < rows; j++)
          printf(" ");
    
        for (j = 1; j <= i; j++)
          printf("%d", j);
    
        printf("\n");
      }
    
      return 0;
    }

    Output:

    Enter the no of rows: 5
        1
       12
      123
     1234
    12345
     1234
      123
       12
        1

    Pattern 2:

    #include <stdio.h>
    
    int main()
    {
      int i, j, rows;
    
      printf("Enter the no. of rows: ");
      scanf("%d", &rows);
    
      // Upper half
      for (i = 1; i <= rows; i++)
      {
        for (j = (i *2); j < (rows *2); j++)
          printf(" ");
    
        for (j = 1; j <= (i *2 - 1); j++)
          printf("%d", j);
    
        printf("\n");
      }
    
      // Lower Half
      for (i = rows - 1; i >= 1; i--)
      {
        for (j = (i *2); j < (rows *2); j++)
          printf(" ");
    
        for (j = 1; j <= (i *2 - 1); j++)
          printf("%d", j);
    
        printf("\n");
      }
    
      return 0;
    }

    Output

    Enter the no. of rows: 5
            1
          123
        12345
      1234567
    123456789
      1234567
        12345
          123
            1