Link to home
Start Free TrialLog in
Avatar of deadite
deaditeFlag for United States of America

asked on

C - Generating 5x5 array

Using C, I am trying to generate a 5x5 array filled with random numbers from 0.0 to 1.0 (including 0.0 and 1.0).  Each row should add up to 1, which is a markov table.  The output should look similar as follows:
Row 1 [ 0.3 0.4 0.1 0.0 0.2 ]
Row 2 [ 0.0 1.0 0.0 0.0 0.0 ]
Row 3 [ 0.8 0.0 0.0 0.2 0.0 ]
Row 4 [ 0.1 0.6. 0.2 0.0 0.1]
Row 5 [ 0.9 0.0 0.0 0.0 0.0 ]

I was going to fill the table with random numbers, then normalize them (divide each by the row's sum).  I was able to generate the random numbers, but am getting a segmentation fault or mismatches from storing in the array and printing it later.  Here is the code (compiled by CC).

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

/*
 * MAIN FUNCTION - Generate Random Markov Table
 */
int main() {

/* Set Random Seed from System Time for rand() */
srand(time(NULL));

/* Create Markov array */
int MAXROW = 4;
int MAXCOL = 4;
float arrMarkov[MAXROW][MAXCOL];

/* Fill Markov array with Random numbers */
int row;
int col;
float rnum;
for (row = 0; row <= MAXROW; row++) {
    printf("Row %i [", row);
    for (col = 0; col <= MAXCOL; col++) {
        rnum = (float)(rand() % 11) / 10;
        arrMarkov[row][col] = rnum;
        printf("%f ", rnum);
    }
    printf("]\n");
}

/* Print array */
printf("\n");
for (row = 0; row <= MAXROW; row++) {
    printf("Row %i [", row);
    for (col = 0; col <= MAXCOL; col++) {
        printf("%f ", arrMarkov[row][col]);
    }
    printf("]\n");
}

return 0;
}
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
#define MAXROW  4
#define MAXCOL 4
float arrMarkov[MAXROW+1][MAXCOL+1];
Avatar of deadite

ASKER

ozo,

that worked!  The only question I have is why?  Shouldn't C array elements start at 0, so declaring an array[4] should have the elements array[0] [1] [2] [3] [4] right?
Thanks
>>elements array[0] [1] [2] [3] [4] right?
no, it should be
elements array[0] [1] [2] [3]

~marchent~
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of deadite

ASKER

DUH,

writing programs for 30+ hrs really does affect your mind!  I see exactly where my error was now.   Also, I had another typo up there in my explanation question... obviously there will not be a [4] element since the array is 0 indexed.  Thank you all for pointing out the obvious...
> writing programs for 30+ hrs really does affect your mind!  I see exactly where my error was now.

Don't worry, mate. It happens. Glad you've worked it out. :)