Anda di halaman 1dari 13

LAB H AN DOUT FOR LOOP

T h e f or ma t of a f or l oop i s:

for(initializing expressions) { statements; // what the loop will do }

Prior to the for loop, declare a variable, such as an integer. This variable will be used for the three initializing conditions of the for loop: Telling the compiler at which value to begin Telling the compiler at which value to stop Incrementing or decrementing the loop (makes the loop move to the next value for code processing)

WRITE THE FOLLOWING CODE

#include<iostream.h> void main() { // declare a variable int i; for(i= 0; i < 11; i++) cout << i << endl; } /* This opens the comment: This is the generated output: 0 1 2 3 4 5 6 7 8 9 10 */ This closes the comment i= 0 told the compiler you are starting at 0. i < 11 told the compiler where to stop the loop i++ means i = i + 1 (which increments the loop, moves the loop the next i value).

to

Count ing backwar ds wit h a f or Loop


T ell t he compi l e r wh e r e to st a r t T ell t he compi l e r wh e n to st op D e cr e me nt t h e l oop: j = j - 1 i n i t s sh or t e r f or m i s j - -

#include<iostream.h>

void main() { // declare a variable before starting int i; for(i=10; i > - 1; i--) { if(i == 0) cout << "Blast Off!" << endl; else cout << i << endl; } }

Shor t cut s f or coding incr ement s and decr ement s


j = j + 2 ca n b e wr i t t e n j + = 2 ; ( a d d s 2 t o t h e va l ue of j )

j = j of

2 ca n b e wr i t t e n j - = 2 ; ( sub t r a ct s 2 f r om t h e va l ue j)

k = k + 1 ca n b e wr i t t e n k + + ;

( a d d s 1 t o t h e va l ue of k )

k = k va l ue

ca n b e wr i t t e n k - - ; of

( sub t r a ct s 1

f r om t h e k

m = m + 5 ca n b e wr i t t e n m+ = 5 m) A na l y z e T h i s Loop:

( a d d s 5 t o t h e va l ue of

int k; for (k = 0; k < 51; k +=10) cout << k << endl;

Review Exer cises ( Re f e r to t he cod e a b ove in t he sh a d e d b ox . . . ) At wh a t va l ue of k d oe s t h e f or l oop b e gi n? W h a t i s l a st va l ue of k t h e f or l oop wi l l out put ? By wh a t va l ue of k d oe s t h e f or l oop i ncr e me nt e a ch st e p? W r it e t he out put of t he f or l oop.

- W r i t e t h e O ut put of t h e F ol l owi ng Cod e :

int n; int stop = 3; int start = 8; cout << "start on 8" << endl; for(n = (start- 1); n >= stop; n--) { if(n=stop) cout << "stop on " << n << endl; else cout << "down to " << n << endl; }

Compiler Er r or s, I nf init e Loops T y pi ca l e r r or s i n t h e f or l oop st r uct ur e a r e not put t i ng i n t h e pr ope r se mi col on ( ; ) a f t e r t h e f i r st a nd se cond cond i t i ons, i nsi d e t h e pa r e nt h e se s or a cci d e nt a l l y r e ve r si ng t h e < or > sy mb ol s W h e n a l oop i s count i ng f or wa r d , i t ma k e s se nse t h a t t h e l oop sh oul d st op some wh e r e l e ss t h a n some va l ue , or i t wi l l count f or e ve r a n i nf i ni t e l oop. F or e x a mpl e ,

Count from 20 to 45 by 5's: int k = 0; for(k = 20; k < 50; k+=5) cout << k << endl;

Ea ch numb e r wi l l b e on a se pa r a t e l i ne b e ca use of t h e e nd l [ e nd l i ne ] st a t e me nt . cout < < e nd l ; i s a n e mpt y l i ne b ut cout < < k < < e nd l ; i s t h e out put of t h e va l ue of k , t h e n a ne wl i ne . T h i nk of e nd l ; a s a l i ne b r e a k . N ot h i ng come s a f t e r i t on t h a t l i ne so a ny ot h e r ne w out put must b e on a not h e r l i ne . I f b y a cci d e nt , a st ud e nt h a d cod e d :

for(k = 20; k > 50; k+=5)

W he r e woul d t he l oop st op? I t b e gi ns a t 2 0 , a d d s 5 so k = 2 5 , a nd ne x t t i me k = 3 0 , t h e n k = 3 5 a nd wh e n k = 5 0 t h e st oppi ng pl a ce i s k "gr e a t e r t h a n" 5 0 , so k ge t s 5 mor e a d d e d t o i t . . . f or e ve r . ( T h i s i s ca l l e d a n i nf i ni t e l oop. )

T h e e nd

This document was created with Win2PDF available at http://www.win2pdf.com. The unregistered version of Win2PDF is for evaluation or non-commercial use only. This page will not be added after purchasing Win2PDF.

The while loop Its format is: while (test expression) { //statement } and its functionality is simply to repeat statement while the condition set in expression is true. For example, we are going to make a program to countdown using a while-loop:
// custom countdown using while #include <iostream.h> int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!\n"; return 0;

}
Enter the starting number > 8

8, 7, 6, 5, 4, 3, 2, 1, FIRE

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if

the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true. The whole process of the previous program can be interpreted according to the following script (beginning in main): 1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two posibilities: * condition is true: statement is executed (to step 3) * condition is false: ignore statement and continue after it (to step 5) 3. Execute statement: cout << n << ", "; --n; (prints the value of n on the screen and decreases n by 1) 4. End of block. Return automatically to step 2 5. Continue the program right after the block: print FIRE! and end program. When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever (infinite loop ). In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end.

Of course this is such a simple action for our computer that the whole countdown is performed instantly without any practical delay between numbers. The do- while loop Its format is: do { //statement } while (test expression); Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. For example, the following example program echoes any number you enter until you enter 0.

// number echoer #include <iostream.h> int main () { int n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0; }

Enter number You entered: Enter number You entered: Enter number

(0 to end): 12345 12345 (0 to end): 160277 160277 (0 to end): 0

You entered: 0

The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. In fact if you never enter the value 0 in the previous example you will be prompted for more numbers forever.

Exercise Use a while loop to calculate the sum of the integers from 1 to 10. Create a program that loops 30 times, but only outputs numbers that are not divisible by 3 or 5. use while loop and use an if statement inside it. Create a program that uses a do while loop to count the number of characters (not including white space i.e. space bar) entered by the user. The count should end when it first encounters a # character in the input. (use getch() ) Optional Write a program using while loop that inputs a number till you press zero and shows the sum of the numbers that have been input by the user.

This document was created with Win2PDF available at http://www.win2pdf.com. The unregistered version of Win2PDF is for evaluation or non-commercial use only. This page will not be added after purchasing Win2PDF.

Anda mungkin juga menyukai