Solution for Exercise 10-13

ex1013

#include <stdio.h>

#define TRUE 1
#define FALSE 0

void limit(int stop);
int verify(int check);

int main()
{
    int x;

    printf("Enter a stopping value (0-100): ");
    scanf("%d",&x);
    if(verify(x))
    {
        limit(x);
    }
    else
    {
        printf("%d is out of range!\n",x);
    }
    return(0);
}

int verify(int check)
{
    if(check < 0 || check > 100)
        return FALSE;
    return TRUE;
}

void limit(int stop)
{
    int x;

    for(x=0;x<=100;x=x+1)
    {
        printf("%d ",x);
        if(x==stop)
        {
            puts("You won!");
            return;
        }
    }
    puts("I won!");
}

Notes

* The code defines the constants TRUE and FALSE at Lines 3 and 4.

* Why not just directly use 1 for TRUE and 0 for FALSE? Readability.

* Functions are prototyped at Lines 6 and 7.

* After receiving input at Line 14, an if-else structure determines whether input is valid. In Line 15, the verify() function is called with the value read by scanf(). The verify() function (at Lines 26 through 31) returns TRUE or FALSE depending on whether the value passed is within range. If so, the limit() function is called at Line 17. If not, Line 21 displays an error message and the program quits.

* The only way to allow the computer to win is to generate a random value and have the user guess a number less than that value. At that point the program becomes a simple guessing game and not the action-packed thriller it is as presented.