Author: admin

  • Sum of rows and columns in 2d Array in Java

    In this tutorial, we will write two different programs to sum the row elements and column elements separately. You may go through the following topic.

    Sum of the columns in Java

    public class Main 
    {
        public static void main(String[] args)
        {
            
            int arr[][] = {
                            {1,2,3},
                            {4,5,6},
                            {7,8,9}
                          };
            int rows = arr.length;
            int cols = arr[0].length;
            
            int sumCols;
            for(int i=0; i < cols; i++){
                sumCols = 0;
                for(int j=0; j < rows; j++)
                    sumCols += arr[j][i];
                    
                System.out.println("sum of "+(i+1)+ " col: "+ sumCols);
    
            }
            
        }
    }

    Output:

    sum of 1 col: 12
    sum of 2 col: 15
    sum of 3 col: 18


    Sum of the rows in Java

    public class Main
    {
       public static void main(String[] args)
       {
          int arr[][] = {
    		{ 1, 2, 3 },
             { 4, 5, 6 },
             { 7, 8, 9 }
          };
          int rows = arr.length;
          int cols = arr[0].length;
    
          int sumRows;
          for (int i = 0; i < rows; i++)
          {
             sumRows = 0;
             for (int j = 0; j < cols; j++)
                sumRows += arr[i][j];
    
             System.out.println("sum of " + (i + 1) + "row: " + sumRows);
    
          }
       }
    }

    Output:

    sum of 1row: 6
    sum of 2row: 15
    sum of 3row: 24


  • Find a pair with the Given Sum in an Array in Java

    In this tutorial, we will write a java program to find the sum pair in an array. Before that, you may go through the following topics in java.

    The program takes a user input for a number of elements in an array and then the value of elements. After that, the program asks for the number to be checked for the sum and the calculation is done.


    Find a Pair with the Given Sum in an Array in Java

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int[] arr = new int[10];
        int n, value, num = 0;
        Scanner sc = new Scanner(System.in);
    
        System.out.println("How many elements");
        n = sc.nextInt();
    
        System.out.println("Enter the elements: ");
        for (int i = 0; i < n; i++)
          arr[i] = sc.nextInt();
    
        System.out.println("Enter the value to be checked: ");
        value = sc.nextInt();
    
        for (int i = 0; i < (n - 1); i++)
          for (int j = (i + 1); j < n; j++)
            if (arr[i] + arr[j] == value)
            {
              System.out.println("Pair:(" + arr[i] + ", " + arr[j] + ")");
              num = 1;
            }
    
        if (num == 0)
          System.out.println("Pair not found!");
      }
    }

    Output 1:

    How many elements
    5
    Enter the elements:
    1
    2
    3
    4
    5
    Enter the value to be checked:
    80
    Pair not found!

    Output 2:

    How many elements
    5
    Enter the elements:
    1
    2
    3
    4
    5
    Enter the value to be checked:
    7
    Pair:(2, 5)
    Pair:(3, 4)


    The time complexity for the worst case.

    Big O: O(n2)

    All the single line statement states represent with -> 1
    And loop are represented with the number of times it loops and each of the program loops for “n” number of times, hence each loop represents n complexity.

    Now the last for loop has one more for loop nested inside and since for leep here represents n complexity, therefore the last nested loop gices “n2” (n to the power 2) complexity.
    And highest being the “n2”, therefor big O is n2.


  • 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