
Originally Posted by
jwxie518
Hi. Here is the code
Code:
#include <iostream>
#include <iomanip>
#include <stdlib>
int main()
{
for ( int i = 1; i <= 20; i++ )
{
cout << setw( 10 ) << ( 1 + rand() % 6 );
if ( i % 5 == 0 )
cout << endl;
}
return 0;
}
The for-loop will allow all actions within to occur 20 times. I think you've worked that bit out.
Code:
cout << setw( 10 ) << ( 1 + rand() % 6 );
This code allows a line to contain a width of 10 characters and prints the pseudo-random value determined by 1 + rand() % 6 with possible values {1, 2, 3, 4, 5, 6}.
Code:
if ( i % 5 == 0 )
cout << endl;
This will start a new line of text when the variable 'i' incremented by the loop is divisible by 5 exactly. Now to your questions:

Originally Posted by
jwxie518
I don't understand a few things here:
1. for the rand() function, the book said rand() % 6 would produce integers in the range 0 to 5. Then why don't we just do rand() % 7? Is it because we want to ignore the zero therefore we do 1 + rand() % 6?
Because by adding one to are preventing a value of zero being produced and a maximum value of 6. rand() % 7 will allow the values {0,1, 2, 3, 4, 5, 6}, so we guarantee not producing a value of zero for your code as presented.

Originally Posted by
jwxie518
2. the % as the book explained is "we use the modulus operator in conjunction with rand". I don't get it.
It's this part of the code:

Originally Posted by
jwxie518
3. for i % 5 == 0, I am having trouble understanding it. I know if you want to know whether a number is odd or even you could do i % 2 == 0. But I don't get the use of it here. It seems like it's being use to "go to the next line" because in the book it shows:
5 5 3 5 5
2 4 2 5 5
5 3 2 2 1
5 1 4 6 4
Thank you.
As said, a new line is started once the variable 'i' is exactly divisible by 5.
Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum