-
Populating 2-D arrays
Hello,
I'd like to populate the 4x3 array below using the function "function"
to determine the value of each element. This function takes 2
arguments, which will vary in a systematic way (see below). How can I
use for loops in C to accomplish this task? Thanks!
function(20,0.1) function(20,0.2) function(20,0.3)
function(21,0.1) function(21,0.2) function(21,0.3)
function(22,0.1) function(22,0.2) function(22,0.3)
function(23,0.1) function(23,0.2) function(23,0.3)
-
What have you tried? What do those function arguments mean in the context of a 4x3 matrix?
-
Set up a loop to count out this part.
function(20,0.1) function(20,0.2) function(20,0.3)
Then set up another loop to take care of the integer part. If you nest the loops properly, then by the time you are done with the integer part, you are done with the whole thing.
-
Here's another way to look at the problem: in the example below, how can I change the code to set each element of the array to a value that comes from a function that doesn't use x and y as arguments?
If this function is the one described in my first post, I guess I would need one more nested loop to solve the problem. Something like this:
for (j = 0.1; j < 0.4; j = j + 0.1)
for (i = 20; i < 24; i++)
... but I don't really know how to integrate this loop with the one for the array below. Sorry if this doesn't make much sense!
thanks
---------------------------
Code:
#include <stdio.h>
int main()
{
int x;
int y;
int array[4][3]; /* Declares an array */
for ( x = 0; x < 3; x++ ) {
for ( y = 0; y < 4; y++ )
array[y][x] = x * y; /* Set each element to a value */
}
}
-
Here's what seems to be a nice solution in case anyone else is interested:
Code:
#include <stdio.h>
int function(int a,double x) {
int b = (x+0.05)*10;
return a*100+b;
}
int main(void){
#define rows 4
#define cols 3
int col,row;
int array[cols][rows]={0};
for (row=0; row<rows; ++row)
for (col=0; col<cols; ++col)
array[col][row] = function (row+20, (col+1)*0.1);
for (row=0; row<rows; ++row) {
for (col=0; col<cols; ++col)
printf("%d ",array[col][row]);
printf("\n");
}
}
(I think array could have been defined as array[rows][cols] too, with other
subscripts also reversed.)
--
Bartc