Tell me if I think correctly-c++Matrix

Initially, it had a code that output the matrix.

I made 2 columns of 3 numbers in the range from 1 to 6.

Then I started experimenting to see what would happen

Originally it was int a[N][M]; cin >> a[i][j]; cout << a[i][j];

I removed [M],[j]

And the result is the values

2 2 2 
4 4 4

I think the following happens

a[N] = a[2]
i<=3 j<=2
i=1
j=1 Пишу число 1 a[i] = {1 , Место для второго числа }
j=2 Пишу число 2 a[i] = {2 , Место для второго числа } (Число 1 перезаписало в число 2)
i=2 
j=1 Пишу число 3 a[i] = {2,3}
j=2 Пишу число 4 a[i] = {2,4}(Число 3 перезаписало в число 4)

Так как a[i] = a[2] Но a[2]={2,4}
То i=3 не выполнится (массив уже полный)

Well, then

i<=2 j<=3 a[2] = {2,4}
i=1 (взяли первый элемент массива)
j=1 2
j=2 2
j=3 2
i=2 (взяли 2 элемент массива)
j=1 4
j=2 4
j=3 4

That's right or I just adjusted the picture for myself so that everything would be fine did it fit?

Code:

#include <iostream>
using namespace std;
int main()
{
setlocale (LC_ALL, "RUS");
int i,j,N,M;
cout << "Введите количество строк матрицы " << endl;
cin >> N;
cout << "Введите количество столбцов матрицы" << endl;
cin >> M;
int a[N];
cout << "Введите числа матрицы" << endl;
for (i=1;i<=M;i++){
   for(j=1;j<=N;j++){
       cin >> a[i];
   }
}
cout << "Ваша матрица \n" ;
for (i=1;i<=N;i++){
   for(j=1;j<=M;j++){
       cout << a[i] <<"\t";
   }
           cout << endl;
}
return 0;
}
Author: ZELIBOBA, 2019-10-19

1 answers

Even if you have compiled GNU :) int a[N];, then you are still doing nonsense - just rewriting the same array elements...

Omit the fact that M and N can be different and you can jump out of the array boundaries. And even that the array elements are numbered with 0.

But if you omit all this and do not pay attention-then yes, here

for (i=1;i<=M;i++){
   for(j=1;j<=N;j++){
       cin >> a[i];
   }
}

You simply N rewrite the a[i] element once, overwriting what was entered earlier.

A here

for (i=1;i<=N;i++){
   for(j=1;j<=M;j++){
       cout << a[i] <<"\t";
   }
   cout << endl;
}

You output

a[1]  a[1]  a[1]  ... (M раз)
a[2]  a[2]  a[2]  ... (M раз)
a[3]  a[3]  a[3]  ... (M раз)
....
a[N]  a[N]  a[N]  ... (M раз)

(Let me remind you again - there is no elementa[N] in your array).

 1
Author: Harry, 2019-10-19 16:46:01