Reputation: 48
I'm trying to make a 2D array that has 2 column and some row. The first column is inputted by using scanf is the radius, while the second column are dependent on the first column is the area.
I already tried to leave them out of loops (manual input) then output them immediately but somehow only the last and first input are correct
#define circlecol 1
#define circlerow 1
int main() {
float circles[circlerow][circlecol];
for(int x = 0; x <= circlerow; x++) {
scanf("%f", &circles[x][0]);
circles[x][1] = 3.14*circles[x][0]*circles[x][0];
}`
With the input of 8 and 3 I expected this to be the output
Your Circle: 8.000000 200.960000 3.000000 28.260000
But I get this instead
Your Circle: 8.000000 0.000000 0.000000 28.260000
The format was
Your Circle: [0][0] [0][1] [1][0] [1][1]
Upvotes: 3
Views: 67
Reputation: 73366
Change this:
for(int x = 0; x <= circlerow; x++)
to this:
for(int x = 0; x < circlerow; x++)
since array indexing starts from 0 and ends at size of array - 1.
Similarly, you would do for(int j = 0; j < circlecol; j++)
.
In general, if an array is declared as:
array[rows][cols]
then its dimensions are rows x cols
. array[0][0]
is the element in the 1st row and 1st column, and array[rows - 1][cols - 1]
is the element in the last column and in the last row.
Minimal complete example:
#include <stdio.h>
#define circlecol 1
#define circlerow 1
int main(void) {
float circles[circlerow][circlecol];
for(int x = 0; x < circlerow; x++) {
scanf("%f", &circles[x][0]);
circles[x][1] = 3.14*circles[x][0]*circles[x][0];
}
for(int i = 0; i < circlerow; i++)
for(int j = 0; j < circlecol; j++)
printf("%f", circles[i][j]);
return 0;
}
Upvotes: 1
Reputation: 310980
This array
float circles[circlerow][circlecol];
in fact is declared as
float circles[1][1];
that is it has one row and one column that is only one element that can be accessed using expression circle[0][0]
.
It seems you mean the following
#define circlecol 2
#define circlerow 2
int main( void ) {
float circles[circlerow][circlecol];
for(int x = 0; x < circlerow; x++) {
scanf("%f", &circles[x][0]);
circles[x][1] = 3.14*circles[x][0]*circles[x][0];
}
}
That is the array shall have two rows and two columns.
Upvotes: 0