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)
Here are the pieces I have so far
[commented and edited to make a program that compiles in my head]
// global array to populate
float array[4][3];
// prototype of some function
float function(int i, float j);
int main(void)
{
int row, col;
for (col = 0; col< 3; col++)
for (row = 0; row< 4; row++)
array[ row ][ col ] = function( row + 20, 0.1 * ( col + 1 ) );
return 0;
}
Seasoned programmers avoid duplication of numerical constants,
especially when they are index bounds like 3 and 4 in the above.
That's by far the most important remark in this post. One way
to fix this is define preprocessor constants for 3 and 4, then
use them. Another method is illustrated at the end of this post.
Beware that above code may not exactly meet the original
statement, due to rounding errors.
Also, it is not immediately clear if the following code fragment
which at some point was in the thread:
float j;
for (j = 0.1; j < 0.4; j = j + 0.1)
loops 3 or 4 times, and if the third value of j will be
exactly equal to any of the (conceivably different)
(float)0.3
(float)(3*0.1)
3*(float)0.1
Also, seasoned programmers consider using j for a "real"
variable poor taste.
If you want to improve on that, use
double y;
for (y = 0.1; y < 0.35; y += 0.1)
Except for arrays (especially huge ones) and other exceptions,
the first choice should be to define all variables holding
"real" values as double rather than float; <math.h> and other
libraries do this.
When given a choice and dealing with multi-dimensional
arrays, I arrange things so that the right index is the
one in the inner loop; this help hardware because memory
is used linearly; it may also help humans doing debug.
I prefer ++col to col++ because
- the intend (incrementation) is the first thing read;
- it is a closer equivalent to col += 1 or col = col+1;
- some old or minimalist compilers generate better code.
So all in all that gives:
// global array[col][row] to populate
float array[3][4];
const int ncol = sizeof( array)/sizeof( *array);
const int nrow = sizeof(*array)/sizeof(**array);
// prototype of some function
double function(int i, double y);
int main(void)
{
int col, row;
for (col = 0; col<ncol; ++col)
for (row = 0; row<nrow; ++row)
array[col][row] = function( row+20, (col+1)*0.1 );
return 0;
}
Francois Grieu