Anda di halaman 1dari 10

Going round in loops

Going round in loops About the while statement For statement Do while statement

Learn

6.1 Repetitive tasks

Fig 6.1 Let C do repetitive tasks You can make C to repeat certain tasks repeat certain tasks repeat certain tasks repeat certain tasks repeat certain tasks repeat certain tasks repeat certain tasks repeat certain tasks repeat certain tasks repeat certain tasks repeat certain tasks . . . . . . . . . . .. !i " #or a #i$ed number o# times !ii" as long as a condition is true !non %ero" &hen a program is doing repetitive tasks we sa' that it has gone into a loop. (ome o# the most common constructs #or looping are ) the while statement the for statement the do..while statement.

6.2 The while statement Let us start our discussion with the while statement. *t has the #ormat shown below)
while (conditional expression) { statements } -his block o# statements marked b' curl' brackets.../ is e$ecuted repeatedl' as long as the conditional e$pression is true.

+,

Going round in loops

Let us illustrate the use o# the while loop in the program below. -he program prints the message 01e2s a 3oll' good #ellow.4 ten times.
/*Program 6-1 */ /* Programs prints Hes a oll! good "ellow# ten times */ $incl%de&stdio'h( main() -his block o# statements enclosed conditional e$pression { in brackets ./ is repeated when the int co%nt)*+ conditional e$pression n >16 is true. while(co%nt&1*) { print" (Hes a oll! good "ellow',n#)+ co%nt--+ } }

-he screen will displa' the results as shown.


Hes Hes Hes Hes Hes Hes Hes Hes Hes Hes a a a a a a a a a a oll! oll! oll! oll! oll! oll! oll! oll! oll! oll! good good good good good good good good good good "ellow' "ellow' "ellow' "ellow' "ellow' "ellow' "ellow' "ellow' "ellow' "ellow'

-he program e$ecution can be illustrated in the #low chart in Fig 6.5. A brie# description o# the program #low is given below. &hen the program is #irst run co%nt is assigned as initial value o# %ero. co%nt)*. -he program then #lows into the while loop and co%nt is tested i# it is less than 16 which o# course will produce -789 !or Y9(" response . -he statements in the while loop are e$ecuted) prints message and increment co%nt b' 1. :ow co%nt ) 1. -he program loops back to the testing stage again and i# the condition is still true step -wo is repeated. (teps 5 and , is count is increased to 16. !count ;16" &hen count ; 16 the test condition will produce a FAL(9 !:<" value as count now is not less than 16. -he e$ecution o# the while loop is then terminated.

+=

Going round in loops

main!"

while loop count ;6

Y9( count > 16 H

prints messageD count @@

:< Fig 6.5 9nd -he above while loop ma' be written in a shorthand #orm as shown. *t is supposed to make the program look more elegant and impressive. ?ut i# that con#uses 'ou stick to the elementar'. while !count@@ >16" . print# !A1eBs a 3oll' good #ellowCnA"D /
count is increment here As this is reduced to a single statement the curl' brackets are not necessar'. Gut here to make program more readable.

Another e$ample. -his programs produces a table o# the sEuare and cube o# 6 to 15.
/* Program 6-. */ $incl%de &stdio'h( main() { int /)*+ print"(/,t,t01%are o" /,t,t2%3e o" /,n)+ while (/ & 14) { print" (5d,t,t5d,t,t,t5d,n#6/6/*/6/*/*/)+ /--+ } print"(,n,n7hats all "ol/s 8,n#)+ }

+F

Going round in loops

/ * 1 . 4 = A 6 @ > ? 1* 11 1.

01%are o" / * 1 = ? 16 .A 46 =? 6= >1 1** 1.1 1==

2%3e o" / * 1 > .@ 6= 1.A .16 4=4 A1. @.? 1*** 1441 1@.>

7hats all "ol/s 8

Your turn 1 7e write the while loop in Grogram 6I5 in shorthand #orm.

5 9$amine the program below. -he program prompts the use #or a number and then goes into a while loop. *# the conditional e$pression is -789 !non %ero" the message 01ello there.4 is printed #or a certain number o# times which is a #unction o# the number entered.
/*Program 6-4 */ $incl%de &stdio'h( main() { int n%m + print" (9:nter a n%m3er ;9)+ scan"(95d96<n%m)+ while (n%m & 1*) { print"(9Hello6 there,n9)+ n%m--+ } }

!a" *# the number entered is 6 how man' times is the message A1ello there.A printed H !b" *# the number entered is J how man' times is the message printed H !c" *# the number entered is 16 how man' times is the message printed H

+6

Going round in loops

!d" *# the number entered is 1, how man' times is the message printedH ,

&rite a program to print a table o# the Fahrenheit temperatures and their Celsius
eEuivalents #or Fahrentheit temperature 6 to ,66oF with a step o# 56oF. 8se the #ormula
C= F ( F ,5 ) K

Your table should look similar to this) F 6 56 =6 .. .. 5+6 ,66 = C I1J.+ I6.J I=.= .. .. 1,J.+ 1=+.K

&hat does this program printH


/*Program 6-= */ $incl%de&stdio'h( $de"ine 7:B 1* main() { int /)*+ while (/-- & 7:B) print"(5Ad#6/)+ print"(,n,n5d,n#6/)+

-he #ollowing are part o# a program what does it printH a. int x)*+
while (--x &4) print"(5=d#6x)+

b. int x)1**+
while (x-- &1*4) print"(5=d,n#6x)+ print" (5=d,n#6x)+

c. char ch ) Ca
while (ch 8) Ch) { print"(5c#6ch)+ ch --+ } print" (,n5c,n#6ch)+

$$ +J

Going round in loops

6.3 The for statement Another commonl' used control construct is the for statement. Like the while statement the for statement is used to repeat actions or tasks #or a #i$ed number o# times. For e$ample the codes below prints the message 01ello there4 ten times.
int /+ "or (/)1+ /&)1*+ /--) { print"(Hello6 there,n#)+ }

-he #or statement has the #ollowing #orm)


initialise D condition D update

-his block o# codes is e$ecuted ten times. :ote) -his block contains onl' one statement so curl' brackets are not necessar'.

"or (/)1+ /&)1*+ /--) { print"(Hello6 there,n#)+ }

:ote the semicolon seperators

For the for statement 'ou need to speci#' i. ii. iii. an initial value #or the counter e.g k;6 k;16 the conditional e$pression e.g. k ; ; 16 k L;=6 update procedureD 'ou can increment or decrement the counter b' 1 or b' a certain interval #or e$ample a step o# 56. k @;56D

++

Going round in loops

Your turn 1 Describe the output generated b' these programs


/*Program 6-A */ $incl%de &stdio'h( main() { int i)*6 )*+ "or (i)1+ i&1*+ i -).) { --+ print"(5d,n#6 )+ } print"(5d,n#6i)+

b.

/*Program 6-6 */ $incl%de &stdio'h( main() { int i)*6 )*6/)*+ "or (i)1+i&1*+i--) { i" (i5.))*) -).*+ else /--+ } print"( )5d,n#6 )+ print"(/)5d,n#6/)+ }

7eIwrite the program to print a table o# the sEuare and cube o# 6 to 15


o# the for statement.

making use

7eIwrite the temperature conversion program

making use o# the for statement.

$$

6.4 The do..while statement -he while and the for statements test the conditions be#ore ! at beginning" iteration o# the loop. -he do..while statement tests the condition at the end o# the loop. -he #ormat o# the do..while statement is shown below.
do { statement(s)+ } while (conditional expression)+ -est condition at the end

*t can be seen that the statement!s" is #irst e$ecuted then the conditional e$pression is tested. *# it is true !non%ero" the control is passed back to the beginning o# the loop. -he prcoess is repeated until the conditional e$pression is tested #alse !%ero".

+K

Going round in loops

-he do.. while loop can be represented in the #low chart below in Fig 6.,

do statement!s"

conditional e$pression true H

-789MY9(

FAL(9M:<

Fig 6.,

-he e$ample below shows how the do.. while statement is used. -his program prints the number 1 to 16.
/*Program 6-@ */ /*Prints 1 to 1* */ $incl%de&stdio'h( main() { int n%m3er )1+ do {

print"(5d,n#6n%m3er)+ n%m3er --+ } while (n%m3er &)1*)+ print"(,nDoop terminated when n%m3er is 5d#6n%m3er)+ }

A shorthand to the do''while loop is shown below.


do { print"(5d,n#6n%m3er)+ } while (--n%m3er &)1*)+

*ncrement n%m3er b' 1 #irst be#ore testing is done.

K6

Going round in loops

Your turn 1 &hat does the #ollowing program printH


/*Program 6-> */ $incl%de&stdio'h( main() { int co%nt ) *+ do { print" (5d,t5d,5d,n#6 co%nt6 .*co%nt6 1.*co%nt)+ co%nt--+ } while(co%nt &)1.)+ }

5 ,

9nter the program to -C and run it. Does it produce the e$pected resultsH Nodi#' the above program b' incorporating the command) co%nt-- into the
conditional e$pression (co%nt &)1.)

&rite a program to print the message 01e2s a 3oll' good #ellowL4 until a ke' is pressed.
!1int) use the kbhit !"

$$ 6." #ndless loop A program ma' unintentionall' got stuck inside a loop and is unable to break out o# it. &e sa' the program has gone into an endless loop. -his occurs when the conditional e$pression is alwa's true. (o care must be taken to ensure that the value o# the conditional e$pression is modi#iable with a loop. *# 'ou #ind that 'ou program has go into an endless loop press the CtrlIC ke' to halt program e$ecution. &e however sometimes would deliberatel' put an endless loop in a program. -his can be achieved b' putting the value 1 as the conditional e$pression as shown below. while (1) { E' E' }

K1

Going round in loops

or do { E' E' } while(1)+ -he value 1 is alwa's 0true4. 1ence the while loop and the dowhile loop come endless loops. *n #act putting a non %ero value as the conditional e$pression will cause the loop to repeat endlessl'. Your turn 1

&rite a program to print the phrase 09ndless loop.4 repeatedl'. 8se the value 1 as the
conditional e$pression #or the while or do..while loop.

7epeat 9$ercise 1 with some other non %ero values !#or e$ample =
conditional e$pression.

I5 etc" #or the

$$

K5

Anda mungkin juga menyukai