You are on page 1of 11

Iteration Structure Loop A section of code that repeats a few times.

while statement repeats a section of code until a certain condition becomes false. Format: while &expression' ( one or more statement) * where expression is the conditional expression which represents a relational, equality, or logical expression. Everytime C encounters a while statement, it .determines whether expression is true or false. !."f expression is true, then C executes statement and control passes bac# to the beginning of the while loop. "f expression is still true, then C executes statement again. $his process is repeated while the expression is true. %."f expression is initially false, then C ignores the remainder of the while statement. Flowchart:

T
count_emp <7

F exit loop

get data compute pay display pay increase count_emp by 1


Page 1

Example: count+emp , -) ./"nitiali0ation or loop control variable/. while &count+emp 1 2' ( ./$esting. 3oop repetition condition/. printf&45ours6 7') scanf&48d7, 9hours') printf&4:ate6 7') scanf&48lf7, 9rate') pay , hours / rate) printf&4;ay is <8=.!f>n7, pay') count+emp , count+emp ? ) ./@pdating. count+emp is updated./. * printf&4>nAll employees processed>n7') Infinite loops $he programmer must always ma#e sure that the conditional expression in a while loop must sooner or later become false. Atherwise, the program will enter in an infinite loop. "n other words, the loop will not terminate. $he body of the loop changes something in the condition so that eventually the condition become false and the program will continue with the statements that follow the while loop. Example: sum , -) counter , ) while &counter 1, -' ( sum ?, ) * sum , -) counter , ) while &counter 1, -' ( sum ?, ) counter ?, ) *
Page 2

"n this example, the conditional expression of the while loop &counter 1, -' will never become false since counter will always be equal to .

Nested while loops example i,-) while&i1, '( printf&4" am on the first loopB7') C,-) while&C1!'( printf&4" am on the second loopB7') C,C? ) * ./second while/. i,i? ) * ./first while/. Practice 1: i,-) C,-) while&i1, ' ( printf&4" am on the first loopB7') while&C1!' ( printf&4" am on the second loopB7') C,C? ) * ./second while/. i,i? ) * ./first while/. Practice 2: Dhat output values are displayed by the following while loop for a data value of EF of =F of 2F

Output: " am on the first loopB " am on the second loopB " am on the second loopB " am on the first loopB " am on the second loopB " am on the second loopB

printf&4Enter an integer 6 7') scanf&48d7, 9x') product , x) count , -) while &count 1 G'( printf&48d>n7, product') product /, x) count ?, ) *

Page 3

Practice 3: $he Hu :ipot company pays it salesmen on a commission basis it pays !-8 for sales exceeding ;!-,---.--, E8 for sales exceeding ; E,---.--, and %8 for sales below or equal ; E,---.--. Create a C program that will input unit price and quantity sold and then output the gross sales &unit price / quantity', and commission&sales / ;ercentage' based from the sales of each salesman. After computing a commission for a particular salesman, the program must prompt the user to compute for another commission. "f the user wants to stop processing the commission, output the sum of all gross pay otherwise continue to compute commission. break Statement $o interrupt the normal flow of control within a loop. $he break statement causes an exit from an enclosing loop. "n other words, encountering the break statement causes immediate termination of the loop. Example 1: a, ) b, ) while&a,, '( if&b,, '( printf&4All done J bye.>n7') brea#) * printf&4Kot yet done.>n7') * Example 2: Linclude 1stdio.h6 main & ' ( int x) while & ' ( printf &M>nNuess the secret number 6 M') scanf &48d7, 9x') if &x , , E' brea#) else printf &M>nOorryBBBM') * printf&M>n>nCongratulationsBBBM') *
Page 4

for Statement % loop control components I initiali0ation of the loop control variable

test of the loop repetition condition I change &update' of the loop control variable An important feature of the for statement in C is that it supplies a designated place for each of these three components.
I

Format 1: for &initiali0ation expression) loop repetition condition) update expression' statement ) statement!) for &initiali0ation expression) loop repetition condition) update expression'( statement ) statement!) * statement%) Format 2: Example total+pay , -.-) for &count+emp , -) ./ initiali0ation /. count+emp 1 2) ./ loop repetition condition /. count+emp ?, ' ( ./ update/. printf&45ours6 7') scanf&48d7, 9hours') printf&4:ate6 7') scanf&48lf7, 9rate') pay , hours / rate) printf&4;ay is <8=.!f>n7, pay') total+pay , total+pay ? pay) * printf&4>nAll employees processed>n7') printf&4$otal payroll is <8P.!f>n7, total+pay')

Practice
Page 5

. $race the execution of the loop that follows for n,P. Ohow values of odd and sum after the update of the loop counter for each iteration. !. sum , -) for multE , -) for &odd, ) odd1n) odd ?,!' multE 1 --) sum , sum ? odd) ?, is E) 8d.>n7, n, sum') printf&4Oum of positive odd numbers less multE than 8d printf&48d>n7, multE') errors do you see in the following fragmentF Correct the code so it displays all multiples of E from - through --. %. $race the following program fragment: G. Drite a program to display an inchesJtoJ centimeters conversion table. $he smallest and largest number of inches in the table are input values. Qour table should give conversion in =Jinch intervals. Ane inch D h a t

C , -) for &i , ) i1,E) i??'( printf&48d 8d>n7, ", C') C J, !) * equals !.EG cm.

E. Convert the following statement using the for statement and determine the output:

Endless for loop for & ) ) ' ( statement ) * or

ctr , ) while &ctr 1, -' ( printf&4Otill countingR7') printf&48d.>n7, ctr') ctr??) *

for&i,- ) ) ' ( statement ) statement!) *

for &C , ) ) ??C' printf &45elloB>n7')

Page 6

"n this example, the for statement does not have a test condition. $herefore, there is no condition for the loop to terminate. "n this example, the for statement does not have a loop operation. $herefore, the test condition will never become false.

for &C , ) C 1, -) ' printf &45elloB>n7')

do-while Statement Soth the for statement and the while statement evaluate a loop repetition condition before the first execution of the loop body. "n most cases, this pretest is desirable and prevents the loop from executing when there may be no data items to process or when the initial value of the loop control variable is outside the expected range. $here are some situations, generally involving interactive input, when we #now that a loop must execute at least one time. Format 1: do statement) while &loop repetition condition') total+pay , -.-) count+emp , -) ./ initiali0ation /. Format 2: do( do ( printf&45ours6 7') statement ) scanf&48d7, 9hours') statement!) printf&4:ate6 7') satementn) scanf&48lf7, 9rate') * while repetition condition') pay , hours&loop / rate) printf&4;ay is <8=.!f>n7, pay') count+emp ? , ) ./ update/. Example total+pay , total+pay ? pay) * while &count+emp 1 2') ./ loop repetition condition /. printf&4>nAll employees processed>n7') printf&4$otal payroll is <8P.!f>n7, total+pay')

Page 7

do while vs. while while continuation condition is tested at the beginning of the execution. do while continuation condition is tested at the end. while loop can be executed 0ero times do while must be executed at least once. Practice :ewrite the following code using a doJwhile statement with no decisions in the loop body: sum , -) for &odd, ) odd1n) odd ?,!' sum , sum ? odd) printf&4Oum of positive odd numbers less than 8d is 8d.>n7, n, sum')

continue Statement $o interrupt the normal flow of control within a loop, the programmer can use also continue statement.
Page 8

$he continue statement wor#s in a somewhat similar way to the break statement. Sut instead of forcing loop termination, continue forces the next iteration for the loop to ta#e place, s#ipping any code in between. Example a, ) b, ) while &a,, '( if&b,, '( printf&4All done J bye.7') continue) * printf&4Kot yet done.7') * Exercises: . Drite a program that guesses the userTs height. $he program ma#es a first guess and then as#s the user if it is too high, too low or correct. $he program continues to guess and as# the user for feedbac# until the user says the guess is correct or until three tries have been made, whichever comes first. !. Drite a program to list the numbers from - to !E, their cumulative sum, squares, third power and fourth power. $he output should be in a neat fiveJ column format. %. Drite a program that reads in a number n and then outputs the sum of the squares of the numbers from to n. "f the input is %, for example, the output should be G, because ! ? !! ? %! , ?G?U , G. $he program should allow the user to repeat this calculation as often as desired. G. Create a program that will count to J --, by !Ts and by %Ts. E. Vany ban#s and loan institutions compute interest on a daily basis. An a balance of ; --- with an interest rate of =8, the interest earned in one day is -.-= multiplied by ; ---and then divided by %=E, because it is only for one
Page 9

day of a %=E day year. $his yields ;-. = interest and so the resulting balance is ; ---. =. $he interest for the second day will be -.-= multiplied by ; ---. = and then divided by %=E. Drite a program that ta#es as input the amount of deposit, the interest rate and a duration in wee#s. $he program then calculates the account balance at the end of the duration specified. =. Enter a character and a number and print that number of copies of that character. Example: Enter a character: F Enter a number: G F F F F 2. Enter a list of numbers, print the number and continue until the number is greater than -. Example: Enter a number: E $he number is E Enter a number: % $he number is % Enter a number: 2 $he number is 2 Enter a number:

P. Enter a list of numbers, print out that number of asteris#s &/' on that line until the number entered is -. Example:
Page 10

Enter a number: E ///// Enter a number: / Enter a number: U. Enter a number between ! and !- and print a filled square with sides of that number of asteris#s &/'. Example: Enter a number: % /// /// /// -. Enter a number and print out its multiplication table from to -. Example: Enter a number: % times % , % ! times % , = . . - times % , %-. Enter your name and a number and print that number of copies of your name. Example: Enter your name: Fred Enter a number: G Fred Fred Fred Fred

Page 11

You might also like