Click here to Skip to main content
15,072,267 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
#include <iostream>
using namespace std;
int main()  
     int rows, cols;  
    //Initialize matrix a  
    int a[3][3] = {  
                    {1, 0, 1},  
                    {4, 5, 6},  
                    {1, 2, 3}  
    //Initialize matrix b  
    int b[3][3] = {  
                      {1, 1, 1},  
                      {2, 3, 1},  
                      {1, 5, 1}
        cout<< a[3][3] + b[3][3] <<"";
   cout << endl;
    return 0;

What I have tried:

i tried to write a C++ program to add two matrices A and B of size 2*2 . Also print the sum of all the diagonal elements of the resultant matrix
Updated 24-Apr-21 2:03am
[no name] 24-Apr-21 7:30am
The matrices you show are 3x3 and not 2x2. Keep in mind indices do start at 0 and end at N-1 which is in your case 3-1= 2. That said, think about this:
cout<< a[2][2] + b[2][2] <<"";

1 solution

Arrays in C++ (and most other programming languages) are not indexed in the same way as you count in "human languages" where you go "1, 2, 3, ..."
In arrays, your index specifies an offset from the "bottom", and each index specifies a number of spaces to move to the next - so the first item in the array is at index 0, teh second at index 1, and so on.

If you think of a pointer which points at the start of the array, the each actual element is located at
address = start + (index * elementWidth)
where the element width is in bytes - so an array of integers would have an element width of 4 (32 bits wide), an array of doubles would be 8, and a string (array of characters) would be 1.

So as Member 15168018 said, a three by three array will have elements at
0,0   0,1   0,2
1,0   1,1   1,2
2,0   2,1   2,2
And you will get an error if you try to use 3 for either index.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900