Structure and Nesting
Think of a numberNow we write the following program: 'It thinks of a number in the range 0 to 99 and then asks the user to guess it'. This sounds complicated, especially the 'thinks of a number' part, but all you need to know is that the statement:
r = rand()will store a random number in the integer variable r. The standard library function rand() randomly picks a number within the range 0 to 32767, but this might vary from machine to machine. Look upon rand() as being a large dice.
The rand() function will produce numbers such as:
2567134
20678
15789
32001
15987
etc...
If we look at the last two digits of all of these numbers they would form our random set! To select just these numbers we can use an arithmetic calculation of the following form:
r = rand() % 100For example:
#includemain()
{
int target;
int guess;
int again;
printf("\n Do you want to guess a number 1 =Yes, 0=No ");
scanf("%d",&again);
while (again)
{
target = rand() % 100;
guess = target + l;
while(target!=guess)
{
printf('\n What is your guess ? ");
scanf("%d",&guess);
if (target>guess) printf("Too low");
else printf("Too high");
}
printf("\n Well done you got it! \n");
printf("\nDo you want to guess a number 1=Yes, 0=No");
scanf("%d".&again);
}
}
This looks like a very long and complicated program, but it isn't. Essentially it used two loops and an if/else which in English could be summarised as:
while(again){
think of a number
while (user hasn't guessed it)
{
get users guess.
if (target < guess) tell the user the guess is low
else
tell the user the guess is high
}
}
The integer variable again is used to indicate that the user wants to carry on playing. If it is 0 then the loop stops so 0 = No, and 1, or any other non-zero value, = Yes. If the user guesses the correct value the program still tells the user that the guess is too high and then congratulates them that they have the correct value. Such problems with how loops end are common and you have to pay attention to details such as this. There are a number of possible solutions, but the most straight forward is to change the inner loop so that the first guess is asked for before the loop begins. This shifts the test for the loop to stop to before the test for a high or low guess:
#includemain()
{
int target;
int guess;
int again;
printf("\n Do you want to guess a number 1 =Yes, 0=No ");
scanf("%d",&again);
while (again)
{
target = rand() % 100;
printf('\n What is your guess ? ");
scanf("%d",&guess);
while(target!=guess)
{
if (target>guess) printf("Too low");
else printf("Too high");
printf('\n What is your guess ? ");
scanf("%d",&guess);
}
printf("\n Well done you got it! \n");
printf("\n Do you want to guess a number 1=Yes, 0=No");
scanf("%d".&again);
}
}