Lab 3: Input validation with “if” statements; use loops to

advertisement
Lab 3: Input validation with “if”
statements; use loops to
execute code repeatedly
Part I: Input validation with “if - else” statements
“Input validations” means to check if the user’s input is legal or not. For example, if you want
user to enter two numbers and calculate a / b, then user should not enter a 0 for b.
In this lab, you will make some improvements to your simple calculator from the last lab to make
it more “robust.”
First, run your simple calculator program. Enter 10 for a and 0 for b. You should see the result of
a / b is “inf.”
Now modify your code. If user enters 0 for b, do not print the line “a / b = inf”. Instead, print
“Error: a divided by 0.”
Example:
Please enter a: 10
Please enter b: 0
a + b = 10
a - b = 10
a * b = 0
Error: a divided by 0
Part II: Average calculator
In this part of the lab, write a program to ask user to enter numbers repeatedly. When the user
enters a -1, stop and print the average of all the numbers entered (excluding the -1).
Example:
please enter a number
please enter a number
please enter a number
please enter a number
please enter a number
The average is: 25
(-1
(-1
(-1
(-1
(-1
to
to
to
to
to
stop):10
stop):20
stop):30
stop):40
stop):-1
Hints:
1. Be careful with scopes. Your program need to use a variable to record the sum of the
numbers seen so far. That sum variable needs to be declared before you enter the loop.
2. Your loop should run forever, unless the user enters a -1. Make sure you use the right break
condition so the loop stops at the right time.
3. Average = Sum / Count. You probably need another variable to keep the count of numbers.
Every time a user enters a new number that is not -1, Count is incremented by 1.
4. Be careful with types. Do you want to use integers or doubles?
Part III: Printing a pattern (optional)
This part of the lab is optional, and will not be graded. Please do not upload your solution to this
part.
Try to use loops to print the following pattern:
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
Hint: you need two nested loops to solve this problem - one for each row and one for each
column.
Download