Repetition

advertisement
Principles of Programming (C Lab)
Structured Programming - Repetition
WORKSHOP OBJECTIVES:
By the end of this lab session, you should be able to:
1. Apply input validation to the program
2. Solve and write C programs using repetition control structure.
Exercises (Please do ALL):
1. Using any repetition structure of your choice, write a program that will print the countdown
from 5 to 0.
Output sample:
5
4
3
2
1
0
Boomm!!
2. Modify the above program so that instead of printing the countdown of 5, your program will
print the countdown of any number (n) given by the user. For example:
Output sample:
Please enter a number: 8
8
7
6
5
4
3
2
1
Boomm!!
3. Write a program that reads a positive integer n and then computes and prints the sum of all
integers between 1 and n.
4. Modify answer for Q1, this time around, calculate and print the sum of all integers between 1
and n that is divisible by 3. Include appropriate input validation in your program.
5. Write a program that reads the exam marks for ten students and prints the number of passes
and failures (marks more than 40 is a pass).
1
Principles of Programming (C Lab)
6. Write a program that reads positive floating point numbers using repetition control-structure
until the user terminates the program by entering zero. Your program should determine and
print the smallest and largest of the supplied numbers. Please include appropriate input
validation in your program.
Sample output:
7. Write a program that reads two positive integers corresponding to two year values, ensures
that the first year value is less than the second, and then determines and outputs all year
values for leap years. A leap year is a year that can be evenly divided by 4, unless it is a
centennial, in which case it must be evenly divided by 400. For example, 1600 and 1992 are
leap years, whereas 1700 and 1998 are not (because 1700 even if it can be evenly divided
by 4, it can not be evenly divided by 400).
Sample Output:
2
Principles of Programming (C Lab)
Brain teaser……. try this one. It will be fun and
you’ll learn a lot once you got it..
Write a ‘Guessing Game’ program. The program is to generate one random number between 0 –
20. The user is then given 5 tries to guess the generated number. For each guesses, the program
will tell whether the number is greater than, less than or equal to the random number. If the user
has not guessed the number by the fifth try, the program will display the generated number.
To generate a random number, you need to include <stdlib.h>, <time.h> in your program. You
must also include the following code at the start of your program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int number;
srand(time(NULL)); /* seed random function */
number = rand() % 21; /* generating random number between 0 -20 */
...
}
Sample solutions:
Successful guessing:
3
Principles of Programming (C Lab)
Unsuccessful guessing:
Good luck!!!!
4
Download