Sie sind auf Seite 1von 2

Homework 1

CSPP50101
due Monday July 22, midnight
For each problem below, write a single main program stored in a single
file, one file per question. Name the files p1_1.c, p1_2.c, p1_3.c,
p1_4.c, and p1_5.c.
Also, unless otherwise specified, you may assume that the user input
is correct (ie you do not need to check for incorrect input).
Write programs to do each of the following:
1. Echo an integer input by the user.
ex.
prompt> ./my_echo
Enter any integer: 32
You typed 32
(program ends)
2. Echo any integer greater than 0 and less than 100, otherwise give
an error statement.
ex.
prompt> ./my_echo2
Enter any integer between 0 and 100: 103
Error: this integer is out of range
(program ends)
3. Redo 1 but give the user the option of continuing, rather than
ending the program after the first echo.
ex.
prompt> ./my_echo3
Enter any integer: 100
You typed 100.
Continue? (y or n) y
Enter another integer: 22
You typed 22.
Continue? (y or n) n
bye ...
(program ends)
hint: careful using scanf("%c", &whatever). Unlike scanf with %d,
%c does not ignore the newline character. A simple workaround is:
scanf("%c%c", &whatever, &dummy), and simply ignore the '\n'
stored in dummy.
4. Write a program that prompts the user to guess a value between 0
and 100. The program reports on whether each guess is too high or
too low and lets the user try again. This process continues until
the right number is guessed. When the user gets the right number, the
program reports how many guesses were required to get the number.
hint: the following sequence can (roughly) be used to generate a
pseudo-random number from 0 to 100. This requires including the
time.h and stdlib.h libraries.
int ran
srand(time(NULL));

ran = (int) ((float) rand()/RAND_MAX * 100.);


ex.
prompt> ./user_guess
I'm thinking of a number from 0 to 100.
Enter guess: 50
too low.
Enter guess: 60
too hi.
Enter guess: 55
Got it in 3 tries!
(program ends)
5. Write a program that guesses the value that the user is thinking
between 0 and 100. After each guess, the computer will ask the user
to state whether the guess is correct (y), too low (l), or too high
(h). You can assume that the user is using the program correctly -ie that they don't make a mistake and say 'l' when they meant 'h',
etc. Upon ending, the program should list the number of guesses
required to get the number.
ex.
prompt> ./computer_guess
Think of a number between
Is your number 50? (y, l,
Is your number 75? (y, l,
Is your number 62? (y, l,
I guessed in 3 tries!
(program ends)

0 and 100 and press return to start program


h) h
h) l
h) y

Das könnte Ihnen auch gefallen