Dear All members.

I'm a very freshy member and just register today. Programming is very new for me. Please advice how to how to put the random integer between 1-100 into the 2 dimensions array (5x5 metrix).

What me just know the function rand() can be used to generate a sequence of pseudo-random numbers and the srand(time(0)) will initialize it. The array(5,5) is the space to store those random numbers.

Anyhow, as I am a starter of C++ programming, please also advice the link to any effective tutorial.

Best regards,
Mixsir

The easiest way to get a random integer within a range is to take the remainder of division by the high value of the range and add by the low value. So to get a random number from 1 to 10:

rand() % 10 + 1

rand() % 10 gives you a value in the range of 0 to 9, so adding 1 fits the range properly. Now, using modulus with rand() is hit or miss because it uses the low order bits of the random number, and certain common random number algorithms used for the implementation of rand() have exceptionally non-random low order bits. However, implementations have gotten better over the years, so this isn't as much of an issue as it used to be.

Two nested loops allow you to go through all elements of a two dimensional array:

#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
  int matrix[5][5];

  srand ( static_cast<unsigned> ( time ( 0 ) ) );

  for ( int i = 0; i < 5; i++ ) {
    for ( int j = 0; j < 5; j++ )
      matrix[i][j] = rand() % 100 + 1;
  }

  //...
}

yea thats a great piece of code! Im a newbie as well!. How would you go about generating the numbers and then putting them in a 9x9 matrix and then printing that on screen?
thanks
r.rizbaf

Space for threads isn't a sparse resource. If you have a new question, start a new thread rather than resurrect a year old thread. We won't get mad, I promise.

Wouldn't it be nice if you could just change the value of two variables and be able to use the same code for any 2 dimensional array? Well, you're in luck. Just change the value of the two const ints declared in main() in the minor variation of Narue's original and you can do just that.

#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
  const int ROWS = 5;
  const int COLS = 5;
  int matrix[ROWS][COLS];

  srand ( static_cast<unsigned> ( time ( 0 ) ) );

  for ( int i = 0; i < ROWS; i++ ) {
    for ( int j = 0; j < COLS; j++ )
      matrix[i][j] = rand() % 100 + 1;
  }

  //...
}

yea thats cool but how do i print them out on screen?
[thanks the previous code was coolio! :)]

This article has been dead for over six months. Start a new discussion instead.