Ch1 - Output . Ch2 - Sequence . Ch3 - Variables . Ch4 - Input
We use the concept of repeating a task as long as a certain condition remains true. Here is an example: the program asks for a series of numbers. It squares each one, and stops when a negative one is entered.
the above as a flowchart is:
Note:
- 'while' means 'as long as'
- the printLine and the n =getInt(...) are obeyed again and again, as long as it is true that the number is >= 0. When this condition becomes false, the program continues with the statement immediately below the closing }.
- the condition for going through the loop is tested at the top of the loop. In our example, note the sequence of instructions: the use of getInt is immediately followed by the test of the condition. This ensures that we never square a negative number.
- for readability, we indent the tasks in the middle (i.e. the 'body') of the loop.
The general form of repetition is:
while (some condition) { body of loop }As in 'if', brackets ( ) must surround the condition.
To summarise: the condition is tested at the top of the loop. As long as it is true, the statements in the middle of the loop are obeyed once, and the condition is tested again. As soon as the condition is found to be false, the loop terminates, and the next statement in the program is obeyed. Remember - 'while' means 'as long as'.
Study the example carefully:
In the following, sum acts as a running total - observe its value in the top right, as you run the program.
1. Write a program which displays 5 alerts, with your name in each one.
2. Write a program to display the numbers 6 down to 1 inclusive.
3. Write a program to process a series of exam marks, ended by -999(i.e. an unusual mark, called a 'rogue value'). The output is to consist of 3 numbers:
- the average mark, the number of marks below 40, and the number of students.
4. Write a program to add up 10 (always 10) numbers. Do not use a rougue value.
5. Write a program which adds up a list of numbers. Its first task is to ask the user how many numbers they have. Do not use a rogue value.
6. Write a program to display the biggest number in a list of 10 numbers. Assume they are all positive.
Here is how a human might find the largest number in a massive list of numbers: they have a sheet of paper with 'biggest so far' written on it. They write '0' on it, to start with. They scan each number, one-by-one. When they find a number biggest than the one written on the sheet, they replace that number with the new biggest. You will need a loop with an 'if' nested inside it.
Ch1 - Output . Ch2 - Sequence . Ch3 - Variables . Ch4 - Input