-3

I'm trying to figure out the value of A, B and C at the end of the program. When I try to cout using for loop, I get a whole list of values. I need a matrix format only.

#include <iostream>
using namespace std;

int main()
{
    int m = 3;
    int A[m] [m] = {};
    int B[m] [m + 1] = {};
    int C[m + 1] [m] = {};

    int counter = 0, k = 2;
    
    for (int i=1; i<=m; i++)
    {
        for (int j=1; j<=m; j++) 
        {
            A[i-1][i-1] = counter;
            B[i][j] = counter;
            C[j-1][j-1] = k;
        }
        counter++;
        k += 3;
    }

    //Printing C
    //get array columns and rows
    int rows =  sizeof C/ sizeof A[0]; 
    int cols = sizeof C[0] / sizeof(int); 
      
    // Print 2d Array
    cout << "your_array data "<<endl<<endl;
    for (int i = 0; i < rows; ++i)
    {
        for (int j = 0; j < cols; ++j)
        {
            std::cout << C[i][j] << std::endl;
        }
    }

    return 0;
}
Mohamed Arham
  • 69
  • 1
  • 8

2 Answers2

1

Your A and C are

int A[3][3] = {};
int C[4][3] = {};

Then you use

int rows =  sizeof C/ sizeof A[0]; 
int cols = sizeof C[0] / sizeof(int); 

to get its size. Thats

int rows = 3; 
int cols = 4;

Then in the loop

for (int i = 0; i < rows; ++i)
{
    for (int j = 0; j < cols; ++j)
    {
        std::cout << C[i][j] << std::endl;
    }
}

you have swapped values for rows and cols. C is int C[4][3]; not int C[3][4];.

If you want to print several elements in one line you just need to move the std::endl to only add a new line only after a row:

for (int i = 0; i < rows; ++i)
{
    for (int j = 0; j < cols; ++j)
    {
        std::cout << C[i][j] << " ";
    }
    std::cout << "\n";
}

Also note that this is not standard C++

int m = 3;
int A[m] [m] = {};
int B[m] [m + 1] = {};
int C[m + 1] [m] = {};

Read Why aren't variable-length arrays part of the C++ standard? for more on that.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
-1

`

 for(i=0;i<rows;i++)
 {
     for(j=0;j<cols;j++)
     {
         cout<<C[i][j]<<" ";
     }
     cout<<"\n";
 }

` std:: is unnecessary because you have using namespace std; You don't have to do endl because doing this you will print the next value on the next line. So you have to put another cout out of the nested loop.