Java TOPIC 19 – WHILE LOOPS – Part 1 LESSON WORK QUESTION 1 How many
iterations will there be for each of the following programs? In other words, how many times will the
following programs say “Hi” to you?
QUESTION 2 – SEQUENCES Write the
program that will use while loops to output each of the sequences seen below
with all numbers separated by a comma. You should use one while loop per sequence. a)
1,2,3,4,5,6,7,8,9,10, b)
10,20,30,40,50,60,70,80,90,100 c)
20,19,18,17,16,15,14,13,12,11,10 d)
1,4,9,16,25,36,49,64,81,100 e)
1,2,4,8,16,32,64,128,256,512,1024 QUESTION 3 – USER
DECIDES Write a
program that asks the user for a low number and a high number. It will then output all numbers between the
two provided numbers. Sample
output: Enter a number: 10 Enter another
number: 14 Your numbers are: 10 11 12 13 14 Extra:
Can you also make the program deal with the situation of the two
numbers being entered in the wrong order?
So the user would enter the larger number first and then smaller
number next. QUESTION 4 – COLLATZ
SEQUENCE Background In the 1930s,
a mathematician named Lothar Collatz
looked at a special sequence of numbers.
In the sequence, when a number is even, then the next number will be
half of that number. When a number is
odd, then the next number will be 3 times than number plus 1. Here is an example for the sequence that
starts with 10. 10,5,16,8,4,2,1,4,2,1,4,2,1,… Because of
the cycle that begins when we hit 1, we usually stop the sequence at 1. So the Collatz
sequence starting with 10 is: 10,5,16,8,2,1, Collatz made an interesting observation. No matter what number we start with, we
seem to always get to 1. However,
despite many many efforts, nobody has ever proven
this to be true. So it is possible
that we find a number that will not lead to the value 1. Work Write the
program that asks the user for a positive integer that will the starting
point for the Collatz sequence. Use a while loop that will output the
entire sequence ending at 1. Hint You need to
loop until the value of the sequence is equal to 1. So that should be your condition. |
|
|