C++ Program to Add Two Matrices

In the previous article, we have discussed C++ Program to Find Transpose of a Matrix. In this article, we will see C++ Program to Add Two Matrices.

C++ Program to Add Two Matrices

  • Write a C++ program to addition two matrices of same dimensions.

In this program, we will add two matrices of size M X N and store the sum matrix in another 2D array.

Algorithm to add two matrices

  • Let A and B are two matrices of dimension M X N and S is the sum matrix(S = A + B) of dimension M X N.
  • To add two matrices we have to add their corresponding elements. For example, S[i][j] = A[i][j] + B[i][j].
  • Traverse both matrices row wise(first all elements of a row, then jump to next row) using two for loops.
  • For every element A[i][j], add it with corresponding element B[i][j] and store the result in Sum matrix at S[i][j].

C++ Program to Add Two Matrices

C++ Program to Add two Matrices

C++ Program to Add two Matrices

// C++ program to find sum of two matrix
#include <iostream>
using namespace std;
  
int main(){
    int rows, cols, i, j;
    int one[50][50], two[50][50], sum[50][50];
     
    cout <<"Enter Rows and Columns of Matrix\n";
    cin >> rows >> cols;
      
    cout <<"Enter first Matrix of size "<<rows<<" X "<<cols;
    //  Input first matrix*/
    for(i = 0; i < rows; i++){
        for(j = 0; j < cols; j++){
            cin >> one[i][j];
        }
    }
    //  Input second matrix
    cout <<"\nEnter second Matrix of size "<<rows<<" X "<<cols;
    for(i = 0; i < rows; i++){
        for(j = 0; j < cols; j++){
            cin >> two[i][j];
        }
    }
    /* adding corresponding elements of both matrices 
       sum[i][j] = one[i][j] + two[i][j] */
    for(i = 0; i < rows; i++){
        for(j = 0; j < cols; j++){
            sum[i][j] = one[i][j] + two[i][j];
        }
    }
      
    cout <<"Sum Matrix\n";
    for(i = 0; i < rows; i++){
        for(j = 0; j < cols; j++){
            cout << sum[i][j] << " ";
        }
        cout << "\n";
    }
 
    return 0;
}

Output

Enter Rows and Columns of Matrix
3 3
Enter first Matrix of size 3 X 3
1 2 3
4 5 6
7 8 9

Enter second Matrix of size 3 X 3
9 8 7 
6 5 4
3 2 1
Sum Matrix
10 10 10
10 10 10
10 10 10

In above program, we first user to enter the dimensions of input matrices and store it in variable rows and cols. The dimentions of matrices must be less than 50X50. Then one by one, using two for loops we take input for both input matrices and store. Finally, using two for loops we add the corresponding elements of two input matrices and store it in corresponding element of sum matrix.

Points to Remember
Let A, B, and C be M X N matrices, and let 0 denote the M X N zero matrix.

  • Two matrices can be added only if their dimensions are same. If the size of matrices are not same, then the sum of these two matrices is said to be undefined.
  • The sum of two M × N matrices A and B, denoted by A + B, is again a M × N matrix computed by adding corresponding elements.
  • Matrix Addition is Associativity : (A + B) + C = A + (B + C)
  • Matrix Addition is Commutativity : A + B = B + A
  • Identity for Addition : 0 + A = A and A + 0 = A

Access the online Sample C++ Programs list from here and clear all your queries regarding the coding and give your best in interviews and other examinations.

C++ Program to Delete a Word from Sentence

In the previous article, we have discussed C++ Program to Count Words in Sentence. In this article, we will see C++ Program to Delete a Word from Sentence.

C++ Program to Delete a Word from Sentence

  • Write a C++ program to remove a word from a sentence.

Given a sentence and a word(may not be part of sentence), we have to delete given word from sentence and print it on screen. Given word may or may not be present in sentence.

For Example :

Input : I love C++ programming
Word to Remove : C++
Output : I love programming

Algorithm to Delete a Word from Sentence

  • Find the length of word. Let it be L.
  • Search word in sentence. If word is not present in sentence then print original sentence.
  • If we found word at index i, then copy string from index i+L to i. This will override all characters of word.
  • Print modified sentence on screen.

C++ Program to Delete Word from Sentence

C++ Program to Delete Word from Sentence

//C++ Program to delete a word from a sentence
#include <iostream>
#include <cstring>
using namespace std;
  
int main(){
   char string[100], pattern[100];
   char *ptr;
   int length;
     
   cout << "Enter a string\n";
   cin.getline(string, 100);
    
   cout << "Enter string to remove\n";
   cin.getline(pattern, 100);
   // Find length of pattern
   length = strlen(pattern);
   // Search pattern inside input string 
   ptr = strstr(string, pattern);
    
   // Delete pattern from string by overwriting it 
   strcpy(ptr, ptr+length);
    
   cout << "Final String\n" << string;
     
   return(0);
}
</cstring></iostream>

Output

Enter a string
I love C++ programming
Enter string to remove
C++
Final String
I love  programming

In above program, we first take a sentence as input from user using cin. Then we ask user to enter word for deletion. Then we find the length of word using strlen function and store it in a variable length. Here we are using strstr function to search word inside sentence, If found we overwrite the characters of given word by shifting sentence by “length” positions.

Coding in C++ Programming language helps beginners & expert coders to use the classes for various concepts programs. So, look at the C++ Code Examples of all topics and write a logic with ease.

C++ Program to Find Largest Element of an Array

In the previous article, we have discussed C++ Program to Calculate Grade of Student Using Switch Case. In this article, we will see C++ Program to Find Largest Element of an Array.

C++ Program to Find Largest Element of an Array

  • How to find maximum element of an array in C++.

C++ Program to find maximum element of an array

C++ Program to find maximum element of an array

#include <iostream>
 
using namespace std;
   
int main(){
    int inputArray[500], N, i, max;
       
    cout << "Enter Number of Elements in Array\n";
    cin >> N;
    cout << "Enter " << N << " numbers\n";
      
    /* Read array elements */
    for(i = 0; i < N; i++){
        cin >> inputArray[i];
    }
      
    max = inputArray[0];
    /* traverse array elements */
    for(i = 1; i < N; i++){
        if(inputArray[i] > max)
            max = inputArray[i];
    }
      
    cout << "Maximum Element : " << max;
           
    return 0;
}

Output

Enter Number of Elements in Array
7
Enter 7 numbers
2 7 1 5 3 10 8
Maximum Element : 10

Discover a comprehensive collection of C++ Program Examples ranging from easy to complex ones and get help during your coding journey.

C++ Program to Print Floyd Triangle

In the previous article, we have discussed C++ Program to Find Area and Perimeter of Parallelogram. In this article, we will see C++ Program to Print Floyd Triangle.

C++ Program to Print Floyd Triangle

In this C++ program we will print a Floyd Triangle of N rows. A Floyd’s triangle is a right angled triangle of natural numbers arranged in increasing order from left to right such that Nth row contains N numbers.

A floyd’s triangle of 6 rows :

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21

In this program, we first take number of rows of Floyd’s triangle as input from user and store it in a variable rows. Then using two for loops we will print N consecutive natural numbers in Nth row. Here outer for loop prints one row in every iteration where as inner for loop prints numbers of one row. Between any two consecutive numbers in a line we will print a space character.
Here we are using for loop but same program can be rewritten using while loop or do while loop.

C++ Program to Print Floyd Triangle

C++ Program to Print Floyd Triangle

// C++ program to print Floyd's triangle
 
#include <iostream>
using namespace std;
  
int main() {
    int i, j, rows, counter;
  
    cout << "Enter the number of rows of Floyd's triangle\n";
    cin >> rows;
  
    // Print Floyd's triangle
    for (counter = 1, i = 1; i <= rows; i++) {
     // Print ith row 
        for (j = 1; j <= i; j++) {
            cout << counter++ << " ";
        }
        cout << endl;
    }
      
    return 0;
}

Output

Enter the number of rows of Floyd's triangle
4
1
2  3
4  5  6
7  8  9 10

Want to get a good grip on all concepts of C++ programming language? Just click on Important C++ Programs with Solutions and kickstart your learnings with coding.

C++ Program to Find Area and Circumference of a Circle

In the previous article, we have discussed C++ Program to Store Information of an Employee in Structure. In this article, we will see C++ Program to Find Area and Circumference of a Circle.

C++ Program to Find Area and Circumference of a Circle

In this C++ program, we will calculate circumference and area of circle given radius of the circle.

The area of circle is the amount of two-dimensional space taken up by a circle. We can calculate the area of a circle if you know its radius. Area of circle is measured in square units.

Area of Circle = PI X Radius X Radius.
Where, Where PI is a constant which is equal to 22/7 or 3.141(approx)
C++ Program to Find Area and Circumference of a Circle

C++ Program to Find Area of Circle

C++ Program to Find Area of Circle

// C Program to calculate area of a circle
 
#include <iostream>
using namespace std;
  
#define PI 3.141
  
int main(){
    float radius, area;
    cout << "Enter radius of circle\n";
    cin >> radius;
    // Area of Circle = PI x Radius X Radius
    area = PI*radius*radius;
    cout << "Area of circle : " << area;
      
    return 0;
}

Output

Enter radius of circle
7
Area of circle : 153.909

In above program, we first take radius of circle as input from user and store it in variable radius. Then we calculate the area of circle using above mentioned formulae and print it on screen using cout.

C++ Program to Find Circumference of Circle

Circumference of circle is the length of the curved line which defines the boundary of a circle. The perimeter of a circle is called the circumference.
We can compute the circumference of a Circle if you know its radius using following formulae.

Circumference or Circle = 2 X PI X Radius
We can compute the circumference of a Circle if you know its diameter using following formulae.

Circumference or Circle = PI X Diameter
C++ Program to Find Circumference of Circle

// C Program to calculate circumference of a circle
 
#include <iostream>
using namespace std;
  
#define PI 3.141
  
int main(){
    float radius, circumference;
    cout << "Enter radius of circle\n";
    cin >> radius;
    // Circumference of Circle = 2 X PI x Radius
    circumference = 2*PI*radius;
    cout << "Circumference of circle : " << circumference;
      
    return 0;
}

Output

Enter radius of circle
7
Circumference of circle : 43.974

In above program, we first take radius of circle as input from user and store it in variable radius. Then we calculate the circumference of circle using above mentioned formulae and print it on screen using cout.

Are you fed up with browsing all concepts related to C++ Programming Programs? Not anymore because all the basic and complex Programs for C++ are covered on our main page just tap on the link available here & save your time to practice more.

C++ Program to Add Two Distances in Inch and Feet Using Structures

In the previous article, we have discussed C++ Program to Add Two Complex Numbers Using Structure. In this article, we will see C++ Program to Add Two Distances in Inch and Feet Using Structures.

C++ Program to Add Two Distances in Inch and Feet Using Structures

  • Write a C++ program to add two distances in inch and feet using structure variable.

In this C++ program, we will add two distances in inch and feet system using a user defined structure. We created a custom structure name “Distance” which contains two member variables feet and inch.

struct Distance{
    int feet;
    float inch;
};

We will use variable of structure Distance, to store the distance in inch and feet. Here is the feet to inch conversion equation:

1 feet = 12 inches.

C++ Program to Add Two Distances in Inch and Feet

C++ Program to Add Two Distances in Inch and Feet

// C++ program to add two distances in inch feet using structure
#include <iostream>
using namespace std;
 
// Structure storing distance in inch and feet
struct Distance{
    int feet;
    float inch;
};
 
int main() {
 Distance d1, d2, d3;
  
    cout << "Enter first distance as [feet inch]\n";
    cin >> d1.feet >> d1.inch;
 
    cout << "Enter second distance as [feet inch]\n";
    cin >> d2.feet >> d2.inch;
 
    // Adding d1 and d2 and storing the sum in d3
    d3.feet = d1.feet + d2.feet;
    d3.inch = d1.inch + d2.inch;
 
    // NOTE : 12 inch = 1 feet
 // If feet > 12 then feet = feet%12 and inch++  
    if(d3.inch > 12){
        d3.feet++;
        d3.inch = d3.inch - 12;
    } 
 
    cout << "Total distance = " << d3.feet << " feet, " << d3.inch <<" inches";
    return 0;
}

Output

Enter first distance as [feet inch]
5 7
Enter second distance as [feet inch]
3 8
Total distance = 9 feet, 3 inches

In this program, we first ask user to enter two distances in inch-feet system and store it in Distance variable d1 and d2. To find the sum of d1 and d2, we add the inch and feet member of both structure variables and store it in inch and feet members of d3 respectively. If the value of inch is greater than 12 than we convert it to feet.

Learn and explore basic C++ Practice Programs that help to enhance your skills & knowledge of the programming language. Get to know how to write simple and clear code on this page.

C++ Program to Add Two Complex Numbers Using Structure

In the previous article, we have discussed C++ Program to Calculate Difference Between Two Time Periods Using Structure. In this article, we will see C++ Program to Add Two Complex Numbers Using Structure.

C++ Program to Add Two Complex Numbers Using Structure

  • Write a C++ program to find sum of two complex numbers using structure.

In this C++ program, we will add two complex numbers using a user defined structure. A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers and i is the imaginary unit, which satisfies the equation i2 = -1.

In complex number a + bi, a is the real part and b is the imaginary part.

For Example :

5 + 7i, -3 -2i, 2 - 6i

How to Add Two Complex Numbers.

Let Sum(x + iy) is the sum of C1 and C2
Sum = C1 + C2
(x + iy) = (a + ib) + (c + id)
(x + iy) = (a + c) + i(b + d)
x = (a + c) and,
y = (b + d)
We will create a custom structure name “complex” which contains two member variables realPart and imaginaryPart.

struct Complex {
   int realPart;
   int imaginaryPart;
};

We will use variables of structure Complex, to store complex numbers.

C++ Program to Find Sum of Two Complex Numbers Using Structure

C++ Program to Find Sum of Two Complex Numbers Using Structure

// C++ program to add two complex numbers using structure and function
#include <iostream>
using namespace std;
  
/* Structure to store complex number in the form of x + yi, 
 * realPart = x and imaginaryPart = y;
 */
struct Complex {
   int realPart;
   int imaginaryPart;
};
   
int main() {
   Complex c1, c2, sum;
   
   cout << "Enter value of A and B  where A + iB is first complex number\n";
   cin >> c1.realPart >> c1.imaginaryPart;
     
   cout << "Enter value of A and B  where A + iB is second complex number\n";
   cin >> c2.realPart >> c2.imaginaryPart;
     
   /* (A + Bi) + (C + Di) = (A+C) + (B+D)i */
   sum.realPart = c1.realPart + c2.realPart;
   sum.imaginaryPart = c1.imaginaryPart + c2.imaginaryPart;
      
   if(sum.imaginaryPart >= 0 )
      cout << sum.realPart << " + " << sum.imaginaryPart<<"i";
   else
      cout << sum.realPart << " - " << sum.imaginaryPart<<"i";
     
   return 0;
}

Output

Enter value of A and B  where A + iB is first complex number
2 5
Enter value of A and B  where A + iB is second complex number
7 4
9 + 9i

In this program, we take two complex numbers as input from user in the form of A + iB and store in structure variable c1 and c2. We will add real parts of input complex numbers to get the real part of sum complex and add imaginary part of input complex numbers to get imaginary part of sum complex number.

Explore various CPP Codes lists that are used in C++ programming to write a sample program. These codes play an important role while learning the programs.

C++ Program to Calculate Difference Between Two Time Periods Using Structure

In the previous article, we have discussed C++ Program to Store Information of a Book in a Structure. In this article, we will see C++ Program to Calculate Difference Between Two Time Periods Using Structure.

C++ Program to Calculate Difference Between Two Time Periods Using Structure

In this C++ program, we will find the difference between two time periods using a user defined structure. A time period is uniquely defined as triplets of hours, minutes and seconds.

For Example :
2 hour 20 minutes and 10 seconds.

Points to remember about Structures in C++

  • Keyword struct is used to declare a structure.
  • Structure in C++ programming language is a user defined data type that groups logically related information of different data types into a single unit.
  • We can declare any number of member variables inside a structure.
  • We can access the member of structure either using dot operator(.) or arrow operator(->) in case of structure pointer.

To store a time period we will define a user defined structure “Time” having three member variables hour, mins and secs.

struct Time {
  int hour;
  int mins;
  int secs;
};

We will use variables of structure Time, to time periods.

C++ Program to Calculate Difference Between Two Time Periods

C++ Program to Calculate Difference Between Two Time Periods

// C++ program to find difference between two time periods
#include <iostream>
using namespace std;
 
struct Time {
  int hour;
  int mins;
  int secs;
};
 
Time findTimeDifference(Time t1, Time t2);
 
int main() {
    Time t1, t2, diff;
     
    cout << "Enter earlier time in hours, minutes and seconds\n";
    cin >> t1.hour >> t1.mins >> t1.secs;
 
    cout << "Enter current time in hours, minutes and seconds\n";
    cin >> t2.hour >> t2.mins >> t2.secs;
     
    diff = findTimeDifference(t1, t2);
 
    cout << "Difference = "<< diff.hour << ":" << diff.mins << ":" << diff.secs;
    return 0;
}
 
Time findTimeDifference(Time t1, Time t2){
 Time diff;
    if(t2.secs > t1.secs){
        --t1.mins;
        t1.secs += 60;
    }
 
    diff.secs = t1.secs - t2.secs;
    if(t2.mins > t1.mins) {
        --t1.hour;
        t1.mins += 60;
    }
     
    diff.mins = t1.mins-t2.mins;
    diff.hour = t1.hour-t2.hour;
     
    return diff;
}

Output

Enter earlier time in hours, minutes and seconds
5 15 40
Enter current time in hours, minutes and seconds
2 40 14
Difference = 2:35:26

In this program, we take two Time periods as input from user in the form of hours, minutes and seconds and store in structure variable t1 and t2. To find the difference between t1 and t2, we call “findTimeDifference” function by passing t1 and t2. Finally, we display the difference of time periods in screen using cout.

We know that C++ is an object oriented programming language. The advanced C++ Topics are enumerated constants, multi-dimensional arrays, character arrays, structures, reading and writing files and many more. Check the complete details of all those from this article.

C++ Program to Store Information of a Book in a Structure

In the previous article, we have discussed C++ Program to Multiply Two Numbers Without Using ‘*’ Operator. In this article, we will see C++ Program to Store Information of a Book in a Structure.

C++ Program to Store Information of a Book in a Structure

In this C++ program, we will store the information of a book in a structure variable and then display it in screen. We want to store following information for a book Name, Price and ISBN. Here is a sample book record :
Name : Harry Potter
Price : 500
ISBN Code : 7645364
To store the information of a book, we will define an Book structure having three member variable name, price and ISBN.

struct Book {
    char name[100];
    int price;
    int ISBN;
};

Then we will create a variable of structure Book, let’s say book1. Then to access the members of book1, we will use member access operator or dot(.) operator.

Points to remember about Structures in C++.

  • We can declare any number of member variables inside a structure.
  • Structure in C++ programming language is a user defined data type that groups logically related information of different data types into a single unit.
  • Keyword struct is used to declare a structure.
  • We can access the member of structure either using dot operator(.) or arrow operator(->) in case of structure pointer.

C++ Program to Store Information of a Book in a Structure

C++ Program to Store Information of a Book in a Structure

// C++ program to store and print data from a structure variable
#include <iostream>
using namespace std;
 
// A structure for book
struct Book {
    char name[100];
    int price;
    int ISBN;
};
 
int main() {
    Book b;
     
    cout << "Enter name of book\n";
    cin.getline(b.name, 100);
    cout << "Enter price of employee\n";
    cin >> b.price;
    cout << "Enter ISBN code\n";
    cin >> b.ISBN;
     
    // Printing Book details 
    cout << "\n*** Book Details ***" << endl;
    cout << "Name : " << b.name << endl;
 cout << "Price : " << b.price << endl;
    cout << "ISBN Code : " << b.ISBN;
     
    return 0;
}

Output

Enter name of book
Harry Potter
Enter price of employee
500
Enter ISBN code
6453645

*** Book Details ***
Name : Harry Potter
Price : 500
ISBN Code : 7645364

In above program, we first declare a variable of type Book as Book b;

Then we ask user to enter book details i.e Name, Price and ISBN and store it in corresponding fields of structure variable b. Finally we print the information of variable b on screen using cout.

C++ Codes list contains the general functions, nested loops, statements, libraries. Beginners can get the important codes list of C++ programming language from this page easily.

C++ Program to Find GCD or HCF of Two Numbers Using Recursion

In the previous article, we have discussed C++ Program to Find Sum of Natural Numbers Using Recursion. In this article, we will see C++ Program to Find GCD or HCF of Two Numbers Using Recursion.

C++ Program to Find GCD or HCF of Two Numbers Using Recursion

  • How to find GCD (Greatest Common Divisor) or two numbers using recursion in C++.
  • Write a C++ program to calculate GCD or HCF of two numbers using recursion.

C++ program to calculate GCD using recursion

C++ program to calculate GCD using recursion

#include <iostream>
 
using namespace std;
   
int getGcd(int a, int b);
 
int main(){
    int num1, num2, gcd;
     
 cout << "Enter two numbers\n";
    cin >> num1 >> num2;
     
    gcd = getGcd(num1, num2);
 
    cout << "GCD of " << num1 << " and " << num2 << " is " << gcd;
 
    return 0;
}
/*
 * Function to calculate Greatest Common Divisor of two number
 */
 int getGcd(int a, int b) {
  if (b == 0) {
    return a;
  }
  else {
    return getGcd(b, a % b);
  }
}

Output

Enter two numbers
8 60
GCD of 8 and 60 is 4

Exploring basic to advanced concepts in the C++ programming language helps beginners and experienced programmers to excel in C++ Programs. Go with this page & enhance your coding skills.