The programming code listed below can demonstrates you about the rand() function of the C++ language :
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int iScrt, iGss;
srand ( time(NULL) );
iScrt = rand() % 10 + 1;
do
{
printf ("Guess the number (1 to 10): ");
scanf ("%d",&iGss);
if (iScrt<iGss) puts ("The secret number is lower");
else if (iScrt>iGss) puts ("The secret number is higher");
} while (iScrt!=iGss);
puts ("Congratulations!");
return 0;
}
Output of the above code can be as follows :
Code:
Guess the number (1 to 10): 5
The secret number is higher
Guess the number (1 to 10): 8
The secret number is lower
Guess the number (1 to 10): 7
Congratulations!
In the above example, the random seed can be initialized to a value that can be representing the second in which the program can be executed. The time can be defined in the header file <ctime>. In this way to initialize the seed can be generally a good option for most of the random needs.
Bookmarks