Hello,

I have generated a group of random numbers but I can not figure out how to display the numbers in groups of 4. Any suggestions?

srand ((unsigned int) time(NULL));
 int i, high, low, number;
 high = 47;
 low = 19;
 for (i=0; i<20; i++)
  
 {
      
      number = rand() % (high-low+1) + low;//
      cout << number << endl;
      
   }//end for i
   
  
       
 frz;
 return 0;
} // end of main function

There are two very simple ways of doing this:

  • To actually do the number=rand, cout stuff 4 times or..
  • To use another for loop.

I'll add another for loop to your code.

int main()
{
    srand ((unsigned int) time(NULL));
    int i, high, low, number;
    int j;        //added
    high = 47;
    low = 19;
    for (i=0; i<20; i++) {
        for(j=0; j<4; j++) {        //added
            number = rand() % (high-low+1) + low;
            cout << number << " ";      //changed
        }
        cout << endl;       //added
      }//end for i
  
  
      
    frz;
    return 0;
} // end of main function

This will output in the following manner:

42 30 20 28
21 38 45 25
23 21 39 35
 ...
and so on.

You just need to add a newline the moment you have displayed four randoms.

for(int i = 0; i < 100; ++i)
{
     if(i % 4 == 0)
         putchar('\n');
     cout << randomNumber;
}

Nick, I entered to code and my results were 4 colums of 20 #'s, not 5 columns of 4 #'s. Any suggestions?

Yep, I misread the question. ~s.o.s~'s suggestion to simply add a newline when n mod 4 is 0 (ie n is a multiple of 4) will work. This seems to be what your tutor suggested from the PM you sent me.

Thank You s.o.s & Fatnickc..........you guys are awesome!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.