Anda di halaman 1dari 12

2/7/2011

INTRODUCTION

• The for loop generally is used when the loop


will iterate a fixed number of times.
• However, sometimes the number of times a
loop will iterate is unpredictable, depending
on user input during runtime.
• While the total number of loop iterations may
be unpredictable, there often are situations in
which the loop will iterate at least once.

THE WHILE LOOP THE WHILE LOOP


• The while loop is similar to a for loop in that both • By contrast, the parentheses following the
have the typical characteristics of a loop: the
while keyword consists only of the condition,
code inside each continues to iterate until a
condition becomes false. any initialization and update can be elsewhere
in the code.
• The difference between them is in the #include <iostream.h>
parentheses following the for and while main()
keywords. {
for (int num = 1; num <= 10; num++)
• The parentheses following the for keyword cout << num << “ “;
consists of three expressions, initialization, return 0;
condition, and update. }

1
2/7/2011

THE WHILE LOOP THE WHILE LOOP


#include <iostream.h>
main() • With the while loop, the variable had to be
{ declared and initialized before the loop since
int num = 1;
while (num <= 10) this cannot be done inside the parentheses
{ following the while keyword.
cout << num << “ “;
num++; • Further, variable was updated inside the code
} of the loop using the increment operator. This
return 0;
} update also can be done inside the
Note: The two statements in the body of the while loop could have been
combined into one statement, cout << num++.
parentheses following the while keyword.

THE WHILE LOOP THE WHILE LOOP


while (num <= 10)
– The update of the variable is particularly {
important with the while loop. Without that cout << num << “ “;
num++;
update, the loop would be infinite. }
int num = 1; • The update could also be done within the
while (num <= 10) condition itself.
cout << num << “ “; #include <iostream.h>
main()
• If more than one statement belongs to the { int num = 0;
while (num++ < 10)
while loop, then the statements must be cout << num << “ “;
contained within curly braces. }
return 0;

2
2/7/2011

THE WHILE LOOP THE WHILE LOOP


– Updating the counter within the condition
requires two changes. as that would be interpreted as an empty
• The value of the variable has to be initialized to 0 statement.
instead of to 1 because the increment inside the
while (num <= 10);
parentheses during the first iteration of the loop would
change the variable’s value to 1. cout << num++ << “ “;
• The relational operator in the condition is changed.
• As with the for loop, the statement or
statements following the while keyword and
parentheses will not execute if the
parentheses is followed by a semicolon,

THE WHILE LOOP THE WHILE LOOP


#include <iostream.h>
int main () • Comparison of for and while Loops
{
int n;
– The practical difference between the for and while
cout << "Enter the starting number > "; loops is not apparent in a program with a
cin >> n; predictable number of iterations.
while (n>0)
{ – A while loop is a superior choice to a for loop in a
cout << n << ", ";
--n; program where the number of iterations is
} unpredictable, depending on user input during
cout << "FIRE!";
return 0;
runtime.
}

3
2/7/2011

THE WHILE LOOP THE WHILE LOOP


#include <iostream.h>
main()
• Using the break Keyword
{ – While the user should be required to enter good data
int num; if they are going to enter any data at all, they should
cout << “Enter a positive number: “;
cin >> num;
have the option, when told the data entered was not
while (num <= 0) valid, of quitting the data entry.
{ #include <iostream.h>
cout << “Number must be positive; please main()
retry: “;
{
cin >> num;
int num;
}
cout << “The number you entered is “ << num << “ “; char choice;
return 0; cout << “Enter a positive number: “;
} cin >> num;

THE WHILE LOOP THE WHILE LOOP


while (num <= 0)
{ • Flags
cout << “Number must be positive; try again
(Y/N): “; – Ideally, we would want to output the data if it
cin >> choice;
if (choice == ‘Y’) were valid. If the data were not valid, then we
{
cout << “Enter number: “;
would want to output the fact instead.
}
cin >> num; – Use the break keyword sparingly because it create
else multiple exit points for the while loop, making the
break;
} code more difficult to understand and increasing
cout << “The number you entered is “ << num << “ “; the possibility of logic errors.
return 0;
} • As an alternative, use a logical operator.

4
2/7/2011

THE WHILE LOOP THE WHILE LOOP


#include <iostream.h> if (choice == ‘Y’)
main() {
{ cout << “Enter number: “;
cin >> num;
int num;
}
char choice; else
bool quit = false; quit = true;
cout << “Enter a positive number: “; }
cin >> num; if (quit == false)
while (num <= 0 && quit == false) cout << “The number you entered is “ << num
<< “ “;
{ else
cout << “Number must be positive; try again cout << “You did not enter a positive number”;
(Y/N): “; return 0;
cin >> choice; }

THE WHILE LOOP THE WHILE LOOP


– A flag is a Boolean variable whose value indicates • While (true)
whether a condition exists. – Programmers sometimes make the condition of the
Note: A common programming mistake in a while condition using a logical
while loop always true, such as while (true) or while
operator is to use && when you should use || or vice versa.
(1), and break out of the while loop with the break
keyword.
– The use of the while (true) syntax has the
disadvantage of making the code less readable
because the condition that stops the loop cannot be
discerned from the parentheses following the while
keyword.
– The do while loop avoids this disadvantage and would
be a preferable choice.

5
2/7/2011

THE WHILE LOOP THE WHILE LOOP


cout << “Number must be positive; try
#include <iostream.h>
again (Y/N): “;
main()
cin >> choice;
{
int num; if (choice != ‘Y’)
char choice; {
bool quit = false; quit = true;
while (true) break;
{ }
cout << “Enter a positive number: “; }
cin >> num; }
if (num > 0) if (quit == false)
break;
cout << “The number you entered is “ << num
else << “ “;
{
else

THE WHILE LOOP THE WHILE LOOP


cout << “You did not enter a positive number“;
• The continue Keyword
return 0;
} – Can use the continue keyword in a while loop just
as it can be use in a for loop.
– The continue keyword, like the break keyword, is
used within the code of a loop, commonly within
an if/ else structure.
– If the continue statement is reached, the current
iteration of the loop ends, and the next iteration
of the loop begins.

6
2/7/2011

THE WHILE LOOP THE WHILE LOOP


#include <iostream.h>
main() – Use continue keyword sparingly. Normally, each
{
int num, counter = 0, total = 0;
iteration of a for loop has one end point. However,
cout << “How many items do you want to buy: “; when you use a continue statement, each
cin >> num;
while (counter++ < num)
iteration has multiple end points. This makes the
{ code more difficult to understand, and can result
if (counter % 13 == 0)
continue;
in logic errors.
total += 3; – Could use the logical ! (Not) operator as an
}
cout << “Total for “ << num << “ items is $” << total; alternative to using the continue keyword.
return 0;
}

THE WHILE LOOP THE WHILE LOOP


#include <iostream.h>
main() • Nesting While Loops
{
int num, counter = 0, total = 0;
– Can nest one while loop inside another.
cout << “How many items do you want to buy: “; – Also can nest a while loop inside of a for loop, or a
cin >> num;
while (counter++ < num) for loop inside of a while loop.
{
if (!(counter % 13 == 0))
total += 3;
}
cout << “Total for “ << num << “ items is $” << total;
return 0;
}

7
2/7/2011

THE WHILE LOOP THE DO WHILE LOOP


#include <iostream.h>
main() • The do while loop is similar to the while loop.
{
int x = 0; • The primary difference is that with a do while
while (x++ < 5) loop the condition is tested at the bottom of
{
int y = 0;
the loop, unlike a while loop where the
while (y++ < 5) condition is tested at the top.
cout << “X”;
cout << “\n”; • A do while loop will always execute at least
} once, whereas a while loop may never execute
return 0;
} at all if its condition is false at the outset.

THE DO WHILE LOOP THE DO WHILE LOOP


• Syntax
• A Do While Loop Example
do { #include <iostream.h>
statement(s); main()
} while (condition); {
int num;
– The do keyword starts the loop. char choice;
– The statement or statements belonging to the bool quit = false;
loop are enclosed in curly braces. do {
cout << “Enter a positive number: “;
– After the close curly braces, the while keyword cin >> num;
appears, followed by the condition in parentheses, if (num <= 0)
terminated by a semicolon. {

8
2/7/2011

THE DO WHILE LOOP THE DO WHILE LOOP


cout << “Number must be positive; try
again (Y/N): “; #include <iostream.h>
cin >> choice; int main ()
if (choice != ‘Y’) {
quit = true; unsigned long n;
} do {
} while (num <= 0 && quit == false);
cout << "Enter number (0 to end): ";
if (quit == false)
cout << “The number you entered is “ << num cin >> n;
<< “ “; cout << "You entered: " << n << "\n";
else } while (n != 0);
cout << “You did not enter a positive number“; return 0;
return 0;
}
}

THE DO WHILE LOOP THE DO WHILE LOOP


• Scope
• Comparison of the Do While and While Loop
– With a do while loop, it is important that a variable
– Prefer a do while loop over a while loop in used in the condition following the while keyword not
situations in which the loop must execute at least be declared inside the loop.
once before a condition may be tested, simply int num;
char choice;
because under these circumstances it seems bool quit = false;
illogical to test the condition prematurely on the do {
first iteration of the loop. // statements
} while (num <= 0 && quit == false);
– A do while loop normally is preferable to a while – Variables could not be declared inside the do while
loop when choosing a loop to display a menu. loop because the code would not compile.

9
2/7/2011

THE DO WHILE LOOP THE DO WHILE LOOP


• The parentheses following the while keyword is highlighted, • Variables have been declared in main, just after the open
and the compiler error is that variables are undeclared curly brace which begins the body of the main function. This
identifiers. give the variables scope until the close curly brace, which
char choice; ends the body of the main function.
do {
• The area between an open and close curly brace is referred
int num;
to as a block.
bool quit = false;
// more statements • This issue arises far more often with the do while loop than
} while (num <= 0 && quit == false); with the for or while loops.
• The reason is the variable scope. • With for or while loops, the condition precedes the body of
• A variable must be declared before it can be referred to in the loop, so any variables used in the condition necessarily
code. Once a variable is declared, it may be referred to would be declared before the loop or, in case of the for loop,
wherever in the code it has scope. within the parentheses following the for keyword.

THE DO WHILE LOOP JUMP STATEMENTS


• By contrast, since the condition of a do while loop • In addition to the sequences, repetition and
comes after the body of the loop, it is an easy mistake selection constructs, C++ also provides jump
to declare the variables used in the condition before it,
in the body of the loop.
statements.
• It allow program control to be transferred
from one part of the program to another
unconditionally.
• C++ has four jump statements.
– break – goto
– continue – return

10
2/7/2011

JUMP STATEMENTS JUMP STATEMENTS


• The break Statement
• The continue Statement
– If executed, it terminates the structure that contains
it. – The continue statement can only be used inside a
– A general rule is, a break terminates the nearest loop and not a switch.
enclosing switch or loop. – When executed, it transfers control to the test
for (sum = 0, count = 0; ; count++)
condition in a while or a do-while loop, and to the
{
cout << “\n Enter a positive number (1 to terminate) ”; increment expression in a for loop.
cin >> data; – It forces the next iteration to take place
if (data < 0) break;
sum = sum + data; immediately, skipping any instructions that may
} follow it.

JUMP STATEMENTS JUMP STATEMENTS


– Unlike the break statement, continue does not • The goto Statement
force the termination of a loop, it merely transfers – The goto statement has the form:
control to the next iteration. goto label:
for (I = 1, sum = 0; i<100; i++) where label is any valid C++ identifier followed by
{ a colon (:) and must be placed in the same
if (i % 2) continue;
function.
sum = sum + 1;
sum = 0;
}
i = 0;
next:
i++;

11
2/7/2011

JUMP STATEMENTS JUMP STATEMENTS


cout << “\n Enter next number: “;
• The return Statement
cin >> data;
sum += data; – The return statement has the form:
if (i < 20) goto next;
return expression:
cout << “\nSum = “ << sum;
– The frequent use of the goto statement is usually – The effect of executing a return statement is to
not recommended because its use could result in terminate execution of the current function and
‘spaghetti’ codes that will be difficult to debug. pass the return value contained in the expression
– However, it could be very useful in certain (if any) to the function that invoked it.
situations such as exiting from a deeply nested • The value returned must be of the same type or
loop. convertible to the same type as the function.

JUMP STATEMENTS JUMP STATEMENTS


– If necessary, more than one return statements cout << “\nThe average = “ <<avgy;
may be placed in a function. return 0;
• The execution of the first return statement in the }
function automatically terminates the function. float avg(float x1, float x2)
# include <iostream.h> {
main() float avgx;
{ avgx = (x1 + x2)/2;
float y1, y2, avgy; return avgx;
float avg(float, float); }
y1 = 5.0;
y2 = 7.0;
– The execution of the first return statement in the
avgy = avg(y1, y2); function automatically terminates the function.

12

Anda mungkin juga menyukai