While’s – The Basic Idea. Set of operations is repeated as long as (while) some condition is true. First Year Lifestyle: go to the pub while (you are thirsty) buy a beer drink it end while throw up go home - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Set of operations is repeated as long as (while) some condition is true.
First Year Lifestyle:
go to the pubwhile (you are thirsty) buy a beer drink itend whilethrow upgo home
This is a “pre-test” loop. The test is performed before any actions are performed. If you are not thirsty when you arrive at the pub, you will not buy any beer at all.
Actions to be repeated as long as the condition is true.
while (boolean expression) { any number of statements }
The while statement as shown above is actually the combination of the fundamental C++ while statement (which allows only one statement in the “body” of the loop) and the C++ block statement.
If the boolean expression evaluates to true, all of the statements in the body of the loop are exacuted before the condition is tested again. We DO NOT somehow break out out the loop is the condition becomes false part way through the execution of these statements.
We want a program which reads in ten values and computes their average.
Pseudo-code:
values_read = 0 sum = 0 while values_read is less than 10 read a value sum = sum + value just read values_read = values_read + 1 end while output sum divided by values_read
This is an example of a “counting loop”. We loop until a counter reaches some value.
We want a program which reads in values until –999 is entered and computes the average of the values entered (excluding the –999).
values_read = 0 sum = 0 read a value while value just read is not -999 sum = sum + value just read values_read = values_read + 1 read a value end while if values_read is zero output “no values entered” else output sum divided by values_read endif
This is a “sentinal controlled” loop. We loop until some “sentinal value” is entered.
Given an initial investment ($) and an interest rate (%), we want to know how many years it will take for our investment to reach some target amount ($). Interest is paid anually.
Pseudo Code:
read investment, interest rate, and target years = 0 while investment is less than the target value // do another year’s worth of calculations compute interest investment = investment + interest years = year + 1 end while output years and final investment value
So far output lists have involved just three possibilities: a message (“”), an expression, and endl. The last of these is an example of a “manipulator”. Other possibilities exist.
The following two manipulators control the output of floating point values.
setprecision (integer expression)
- specifies the number of digits to be output after the decimal point
setiosflags (ios::fixed | ios::showpoint)
- forces fixed point (as opposed to scientific) notation and specifies that the decimal point is to be displayed even if the fractional part is zero.
The basic C++ statement consists of an expression followed by a semi-colon. This means “evaluate the expression and then throw away the final result”. Because “=“ is an operator, the “assignment statement” is just a special case of this general form.
a = b; // an expression and a semi-colon
a + b; // legal but useless – results in // “code has no effect” warning
The “=“ operator is right associative. This allows assignments of the form shown below.
a = b = c = d = 0; // all variables get 0
“d = 0” is performed first, the result of this operation (the value assigned, zero) is then assigned to “c”, and so on.
The “for loop” is a bit of a luxury in that in doesn’t allow us to do anything that can’t be done almost as easily with a while loop.
for (i = 0; i < 10; i++) { // statements }
is entirely equivalent to
i = 0; while (i < 10) { // statements i++; }
It can be somewhat more convenient, and does bring all of the key looping information together (e.g. we can see at a glance that the above loop counts from 0 to 9).
for (expr 1; expr 2; expr 3) { any number of statements}
The above is entirely equivalent to:
expr 1;while (expr 2) { any number of statements expr 3;}
Usually expr 1 initializes some variable, expr 2 (which should produce a bool result) tests this variable, and expr 2 somehow modifies it.
As usual, the fundamental C++ “for” only allows one statement in the loop body, and the above is actually the combination of the “for” and a block statement.
The variable used to control a for loop may be declared within the loop as shown below
for (int i = 0; i < 10; i++) { any number of statements}// i doesn’t exist here
In this case the variable only exists while the loop is being executed, and it cannot be tested or otherwise accessed afterwards.
Can be particularily confusing if we’ve already declared a variable with the same name. In this case references inside the loop access the loop variable, and references outside the loop access the other variable.
This feature is best avoided unless one really understands what is going on.
Imagine that we want a program which determines whether values are prime numbers (divisible only by themselves and one). We want this program to continue accepting and processing values until –1 is entered.
Sample run:
Enter a value (-1 to terminate): 46 46 is not prime – divisible by 2 Enter a value (-1 to terminate): 17 17 is prime Enter a value (-1 to terminate) –1
cout << “Enter a value (-1 to terminate): “; cin >> number; while (number > 0) { // work out whether the number is prime // and output an appropriate message. // code to do this to be inserted here cout << “Enter a value (-1 to terminate): “; cin >> number; }
This is the standard pattern for a “sentinal controlled” loop.
Junk values (such as –2, etc.) are treated as being equivalent to -1. This is very reasonable and means that, in writing the processing code, we need not worry about negative values.
try dividing by 2, 3, 4, and so on if the number is divisible by the test value then the number isn’t prime – stop if the test value > square root of number then the number is prime - stop Note:
if the number is divisible, at least one of the divisors must be less than or equal to the square root of the number.
Proof:
if both of the divisors were greater than the square root of the number, their product would be greater than the number.
int number, test;bool still_looking; // our first ever bool variable. . . still_looking = true; // no answer so far test = 2; // our initial test value do { if (test * test > number) { // test > sqrt(number) cout << number << “ is prime” << endl; still_looking = false; } else if ((number % test) == 0) { cout << number << “ is not prime (divisible by “ << test << “)” << endl; still_looking = false; } else { // advance to next test value test++; // still_looking remains true } } while (still_looking); // a boolean expression!!
The break doesn’t have to be within an “if” but normally will be – an unconditional break doesn’t make much sense (if we’re always going to break out of it, why have a loop in the first place?).
Execution of the break transfers control to the statement after the loop.