I have to fill a 6x5 array with numbers: 52, 62, 72 etc till array is full. But I don't have an idea how to do it. Thank you for the help.
I tried this:
int main() {
int a[6][5];
int start = 52;
for (int i = 0; i < 6; i )
for (int j = 0; j < 5; j ) {
a[i][j] = start;
start ;
}
for (int i = 0; i < 6; i ) {
for (int j = 0; j < 5; j )
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}
CodePudding user response:
Your code would appear to work just fine. It produces:
52 53 54 55 56
57 58 59 60 61
62 63 64 65 66
67 68 69 70 71
72 73 74 75 76
77 78 79 80 81
If you expect to see:
52 62 72 ...
You just need to increment by 10
when initializing your matrix, instead of incrementing by 1
using the
operator.
CodePudding user response:
You can do everything inside two nested for loops:
#include <stdio.h>
int main() {
int a[6][5];
int start = 52;
for (int i = 0; i < 6; i ) {
for (int j = 0; j < 5; j ) {
a[i][j] = start;
start = 10;
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Note: start = 10
equals to start = start 10
This will result:
52 62 72 82 92
102 112 122 132 142
152 162 172 182 192
202 212 222 232 242
252 262 272 282 292
302 312 322 332 342
CodePudding user response:
If you wish to increment by 10 horizontally and by 1 vertically, you can modify your code this way:
#include <stdio.h>
int main() {
int a[6][5];
int start = 52, col_incr = 10, row_incr = 1;
for (int i = 0; i < 6; i ) {
for (int j = 0; j < 5; j ) {
a[i][j] = start i * row_incr j * col_incr;
}
}
for (int i = 0; i < 6; i ) {
for (int j = 0; j < 5; j ) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
Output:
52 62 72 82 92
53 63 73 83 93
54 64 74 84 94
55 65 75 85 95
56 66 76 86 96
57 67 77 87 97