Multidimensional Array
Aug 26, 2017 at 10:34pm UTC
I am required to write a program to generate a 5x6 array, elements of which must be equal to the sum of indices of the line and the column.
That's not the whole task, but for now I will ask only about this and then further if needed.
I wrote something like this below, it either crashes, outputs 0-30 and then 0 at the end or gives a strange 196619 at the end. What did go wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int Array[5][6];
for (int i = 0; i < 5; i++)
{
for (int j = 0; i < 6; j++)
{
Array[i][j] = i + j;
printf("%d\n" , Array[i][j]);
}
}
}
Aug 26, 2017 at 10:37pm UTC
Here's how you could have found the answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int Array[5][6];
for (int i = 0; i < 5; i++)
{
for (int j = 0; i < 6; j++)
{
printf("i=%d j=%d\n" , i, j);
Array[i][j] = i + j;
printf("%d\n" , Array[i][j]);
}
}
}
Being able to debug your own code is a necessary skill. In this case, your mistake is in this line:
for (int j = 0; i < 6; j++)
Aug 26, 2017 at 11:56pm UTC
Well, that went unnoticed.
Can you tell me how do I ouput array's each row? I tried using two do's to make C++ output another row only when the first one is finished in that way:
1 2 3 4 5 6 7 8 9 10 11
int z = 0, x = 0;
do
{
do
{
cout<<Array[z][x];
x++;
}while (x != 6);
z++;
}while (z != 5);
Aug 27, 2017 at 2:06am UTC
Nevermind, I added if between while x and z++ so that x comes back to 0 before looping again.
Everything works now, thank you.
Topic archived. No new replies allowed.