You are on page 1of 17

Introduction to Programming

FSC1331/FDN1120
Topic 7 : Repetition (Looping)

Topic’s / Unit’s Learning Outcome:


1. The Iteration structure
2. Accumulating and Counting
3. Counter-Controlled Loop
4. Nested Loops
5. Sample Programs

17/01/2016 1
7.1 The Iteration structure
• The Iteration Structure is also known as loop or repetition.
• In C, a loop enables certain operations/tasks/instructions to be
repeated.
• Those operations/tasks/instructions are repeated base on
condition(s) outcome – true or false.
• There are two types of loops in C known as pretest and posttest
loops.
• A pretest test loop evaluates the outcome of condition(s) prior to
tasks/operations.
while(condition==true || condition!=sentinel value ie. -1)
• In contrast a posttest loop would enable tasks/operations to be
performed at least once prior to the condition(s) evaluation.
do{….}while(condition!=true)
17/01/2016 2
7.1.1 Pretest Loops
• A pretest loop begins with the keyword while.
• Condition is enclosed in parenthesis; each statement in the block is
indented one level and ends with a semicolon; and there is no
semicolon after the block’s closing brace.

17/01/2016 3
7.1.2 Posttest Loops
• The body in posttest loop would be executed once no matter what.
• The posttest loops begins with a do.
• There is semicolon at the end of condition.

17/01/2016 4
7.2 Accumulating and Counting
• Accumulating adds or multiplies few values together.
• Accumulating is quite common in loops especially in finding out
total value for a range of values entered.
• Counting keeps track of number of times certain operations or
instruction executed.
• A counter variable is normally declared to count by adding 1 each
time the operation is performed.

17/01/2016 5
7.2 Accumulating and Counting

17/01/2016 6
7.3 Counter-Controlled Loops
• A counter-controlled loop allows some operations to be executed
for a fix number of times continuously without any interruption.
• In a counter-controlled loop there are 5 essential elements such as
i. initialization,
ii. test/condition,
iii. body,
iv. counter
v. the end part.

17/01/2016 7
7.4 Nested Loops
• A loop within another is known as nested loop.
• When there is any nested loops the inner one would always be
executed (until test proven) followed by outer after.

17/01/2016 8
7.5 Sample Programs
repeat

Pre/ Post Test?

17/01/2016 9
7.5 Sample Programs

Pre / Post Test?

17/01/2016 10
7.5 Sample Programs

17/01/2016 11
7.5 Sample Programs

17/01/2016 12
7.5 Sample Programs

17/01/2016 13
7.5 Sample Programs

17/01/2016 14
7.5 Sample Programs

17/01/2016 15
7.5 Sample Programs

17/01/2016 16
7.5 Sample Programs

17/01/2016 17

You might also like