-6

The program creates a two-dimensional array (named "table") and fills the array with random numbers (-1, 0 or 1).

int main() {
    srand(time(0));  
    const int ROWS=3;
    const int COLS=4;

    int table[ROWS][COLS];

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

    for (int i = 0; i < ROWS; i ++)  {
        for (int j = 0; j < COLS; j++)
            cout << setw(3) << table[i][j];

        cout << endl;
    }

    return 0;
}
Gaslan
  • 808
  • 1
  • 20
  • 27
  • hint `% operator`... – Marcin Orlowski Aug 16 '17 at 09:20
  • 2
    I recommend you pick up [one or two beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and read about the arithmetic operators. Or do a search for *modulo operator*. Reading about [`std::rand`](http://en.cppreference.com/w/cpp/numeric/random/rand) might be helpful as well. – Some programmer dude Aug 16 '17 at 09:21
  • 2
    which part you dont understand? If the array is filled with random (-1, 0 or 1) then probably that expression generates random numbers between -1 and 1.... – 463035818_is_not_an_ai Aug 16 '17 at 09:22
  • x%y returns what remains after you divide x by y. So for x%3 that can only return 0 or 1 or 2. Now sustract 1 from that and guess what you can get from a random integer. % is the [modulo operator](https://en.wikipedia.org/wiki/Modulo_operation). – LukStorms Aug 16 '17 at 09:34
  • ohhh now I understand. I was confused on the part "3-1" but I understand it now. Thank you! – ExploringCoding Aug 16 '17 at 09:54
  • You dont understand the % operator. It will return any value between 0 .. MAX-1. So 5%2 will return 1. Why? What is the biggest number that can be divided by two that is smaller then 5. It is 4, so 5-4 = 1. The idea there is, if you use %3 it will return anything from 0 up to 2. But if you do -1 it will return anything from -1 up to 1 – Lefsler Aug 16 '17 at 10:01
  • Makes more sense now. Thanks buddy :) – ExploringCoding Aug 16 '17 at 10:28

1 Answers1

-3

rand() % 3 give a number in the range 0 --> 2

zurricanjeep
  • 38
  • 1
  • 6