Hi i need to generate a random number (between 0 and 2) in an array[15][3]..the first column should be from 1 to 15 and thats k ive done that but the 2nd and 3rd column should generate a random number of 0 to 2 but its not working...ive done the following till now:

#include<stdio.h> /* for printf */
#include<stdlib.h> /* for rand*/

void main(void)
  int t, i, num[15][3];

  for(t=0; t<15; ++t)
    for(i=0; i<3; ++i)
      num[t][0] = t+0+1;

  /* now print them out */
  for(t=0; t<15; ++t) {
    for(i=0; i<3; ++i)
      printf("%3d", num[t][0]);
9 Years
Discussion Span
Last Post by danzona

Here are a few hints:

Let's refer to a 2 dimensional array as a matrix. Let's say that in your example the matrix has 15 rows and 3 columns.

When you want to loop through a 15 x 3 matrix, you would use something like:

for(row = 0; row < 15; row++)
  for(column = 0; column < 3; column++)
    num[row][column] = x;

Notice that the first [] contains the row and the second [] contains the column. If you have a constant in the second [] (like num[t][0]) you will always be addressing the same column of data as you move down the rows. You won't be moving across the columns of the matrix.

You include <stdlib.h> to enable access to the rand() function, but you never call it.
x = rand()%15 would give you a random number between 0 and 14 (do you know why?).


no i dont know why?!but i need a random number between 0 and 2 so for the 2nd and 3rd column i need it to give either 0, 1 or 2 for the 2nd and the same for the 3rd column....


The policy here is to not do people's homework for them, but instead to help people with their problems.

Did you make any changes to your program after my first set of hints? If so, post the new code and indicate what you are stuck on now.

As another hint, I'll explain rand()%15.

The rand() function returns a random number between 0 and some enormous value.

% is the mod or modulus function. It returns the remainder from integer division.
For example in integer division,
8 / 5 = 1
8 % 5 = 3.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.