I've been trying to use nested loops to insert integers into a two dimensional array in the following format:
1, 2, 3, 4, ,5 ,6 ,7 ,8 ,9 ,10
2, 4 ,6 ,8 ,10, 12, 14, 16, 18, 20
3, 6, 9, 12, 15, 18, 21, 24 ,27, 30
...
...
10, 20 , 30 ,40 , 50, 60, 70, 80, 90, 100
I used the following code to generate the result:
#include <iostream>
using namespace std;
int main() {
int table[10][10];
for(int i = 1; i <= 10; i++) {
for(int j = 1; j <= 10; j++) {
table[i][j] = (j * i);
cout << table[i][j] << "\t"<< flush;
}
cout << endl;
}
return 0;
}
The code runs successfully but gives an error in middle of executing:
I'm currently using Code::Blocks + GNU GCC Compiler. How can I solve the issue? Is it because of my code? or the compiler?
You should start iterating from 0 (inclusive) to 10 (exclusive):
#include <iostream>
using namespace std;
int main() {
int table[10][10];
for(int i = 0; i < 10; ++i) {
for(int j = 0; j < 10; ++j) {
table[i][j] = ((j+1) * (i+1));
cout << table[i][j] << "\t"<< flush;
}
cout << endl;
}
return 0;
}
Note: if you use C++17, you can use std::size to avoid hard-coding the array size multiple times. (Alternatively, you can use some compiler specific macros.)
User contributions licensed under CC BY-SA 3.0