Objectives

advertisement
King Saud University
College of Computer & Information Science
CSC111 – Tutorial06
Loops
All Sections
-------------------------------------------------------------------
Objectives:
Student should learn how to:
1- Follow the loop design strategy to develop loops.
2- Control a loop with a sentinel value.
3- Write loops using for statements
Exercise 1
1) Analyze the following code. Is count < 100 always true, always false,
or sometimes true or sometimes false at Point A, Point B, and Point
C?
2) How many times are the following loop bodies repeated? What is the
output of each loop?
3) Suppose the input is 2 3 5 4 0. What is the output of the following code?
Explain what it does.
4) Convert the following while loop into a do-while loop.
5)
Suppose the input is 2 3 4 5 0. What is the output of the following code?
Solution
1)
Count < 100 is:
Always true at Point A
Sometimes true sometimes false at Point B (when is it false?)
Always false at Point C
2)
a will repeat forever (infinite number of times)
b will repeat forever (infinite number of times)
c will repeat 9 times
3)
max is 5
number 0
This program finds maximum number among input numbers.
4)
5)
sum is 14
count is 5
Exercise 2
Write a program using for loop that prompts the user to enter two
integers x and y. Then program prints numbers between x and y (excluding
x and y) that are either divisible by x or divide y in reverse (from largest to
smallest).
Here are is a sample run:
Enter two integers: 10 50
40 30 25 20
Enter two integers: 5 1
Solution
↵
↵
Exercise 3
Solve exercise 2 using while loop and without using logical operators
|| and &&. (Note: there is no relation between while and ||, &&. This is
just to train you on different equivalent ways of writing loops and
conditional statements)
Done…
Download