Slide 5
Slide 5
1
Example 1
2
Example 2
One solution is to copy and paste the necessary lines
of code. Consider the following modification:
3
Processing an arbitrary number of pairs
We might be willing to copy and paste to process a
small number of pairs of integers but
How about 1,000,000 pairs of integers?
The solution lies in mechanisms used to control the
flow of execution
In particular, the solution lies in the constructs that
allow us to instruct the computer to perform a task
repetitively
4
Repetition (Looping)
Use looping when you want to execute a block of code
several times
Block of code = Body of loop
C provides three types of loops
while statement
1 Most flexible
No ‘restrictions’
for statement
2 Natural ‘counting’ loop
do-while statement
3 Always executes body at least once
5
The while Repetition Structure
Repetition structure
Programmer specifies
Condition under which actions will be executed
Actions to be repeated
Psuedocode
While there are more items on my shopping list
Purchase next item and cross it off my list
6
The while Repetition Structure
• The condition is
tested false
condition
• If the condition is
true, the loop body
is executed and the true
condition is
loop body
retested.
• When the condition
is false, the loop is
exited. next stmt
7
1
The while Repetition Structure
Syntax:
while (expression)
basic block
8
Loop Control Variable (LCV)
The loop control variable is the variable whose value
controls loop repetition.
For a while loop to execute properly, the loop control
variable must be
declared
initialized
tested
updated in the body of the loop in such a way that the
expression/condition will become false
If not we will have an endless or infinite loop
9
Counter-Controlled Repetition
Requires:
1. Counter variable , LCV, initialized to beginning value
2. Condition that tests for the final value of the counter
(i.e., whether looping should continue)
3. Constant increment (or decrement) by which the
control variable is modified each time through the
loop
Definite repetition
Loop executes a specified number of times
Number of repetitions is known
10
Example 3
EXECUTION CHART
count count<5 repetition
1 true 1
2 true 2
3 true 3
4 true 4
5 true 5
6 false
11
Sentinel-Controlled Repetition
Requires:
1. Counter variable , LCV, initialized to beginning value
2. Condition that tests for the final value of the counter
(i.e., whether looping should continue)
Indefinite repetition
Used when number of repetitions not known
Sentinel value indicates "end of data"
12
Example 4
13
Loop Pitfalls
14
Loop Pitfalls: Misplaced semicolon
15
The for Repetition Structure
A natural 'counting' loop
Steps are built into for structure!
1. Initialization initialization
2. Loop condition test
3. Increment or decrement false
condition
true
loop body
…
increment
next stmt
16
17
18
Review: Pre-increment operator
Pre-increment operator: ++n
i) Stand alone: add 1 to n
If n equals 1, then after execution of the statement
19
Review: Post-increment operator
Post-increment operator: n++
i) Stand alone: add 1 to n
If n equals 1, then after execution of the statement
If n is initially 1, the above statement will print the value 1 and then
add 1 to n. After execution, n will have the value 2.
20
Pre- and Post-decrement operator
Pre- and post-decrement operators, --n, n-- ,
behave in a similar manner
Use caution when using in an expression
21
2
The for Repetition Structure
Syntax:
22
for Loop Example
23
for Loop Example
Bite 1 -- Yum!
Bite 2 -- Yum!
Bite 3 -- Yum!
24
25
26
Example 5
1 /* Loop Example:
2 Summation with for loop */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int sum = 0; /* initialize sum */
9 int number; /* number to be added to sum */
10
11 for ( number = 2; number <= 100; number += 2 ) {
12 sum += number; /* add number to sum */
Note that number has a different value
13 } /* end for */
14
each time this statement is executed
15 printf( "Sum is %d\n", sum ); /* output sum */
16
17 return 0; /* indicate program ended successfully */
18
19 } /* end function main */
Sum is 2550
The do-while Repetition Structure
The do-while repetition structure is similar to the
while structure
Condition for repetition tested after the body of the loop
is executed
loop body
true
condition
false
28
3
The do-while Repetition Structure
Syntax:
do {
statements
} while ( condition );
29
The do-while Repetition Structure
Example
30
The do-while Repetition Structure
Example
31
break and continue Statements
break
Causes immediate exit from a while, for, do…while or switch
statement
Program execution continues with the first statement after the structure
Common uses of the break statement
• Escape early from a loop
• Skip the remainder of a switch statement
Example 6
1 /* Example of
2 Using the break statement in a for statement */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int x; /* counter */
9
10 /* loop 10 times */
11 for ( x = 1; x <= 10; x++ ) {
12
13 /* if x is 5, terminate loop */
14 if ( x == 5 ) {
15 break; /* break loop only if x is 5 */
break immediately ends for loop
16 } /* end if */
17
18 printf( "%d ", x ); /* display value of x */
19 } /* end for */
20
21 printf( "\nBroke out of loop at x == %d\n", x );
22
23 return 0; /* indicate program ended successfully */
24
25 } /* end function main */
1 2 3 4
Broke out of loop at x == 5
break and continue Statements
continue
Skips the remaining statements in the body of a while, for or
do…while statement
• Proceeds with the next iteration of the loop
while and do…while
• Loop-continuation test is evaluated immediately after the
continue statement is executed
for
• Increment expression is executed, then the loop-continuation test
is evaluated
Example 7
1 /* Example of
2 Using the continue statement in a for statement */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int x; /* counter */
9
10 /* loop 10 times */
11 for ( x = 1; x <= 10; x++ ) {
12
13 /* if x is 5, continue with next iteration of loop */
14 if ( x == 5 ) {
15 continue; /* skip remaining code in loop body */
continue skips to end of for
16 } /* end if */
17
loop and performs next iteration
18 printf( "%d ", x ); /* display value of x */
19 } /* end for */
20
21 printf( "\nUsed continue to skip printing the value 5\n" );
22
23 return 0; /* indicate program ended successfully */
24
25 } /* end function main */
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
goto Statement
The goto statement is one of C’s unconditional jump, or branching,
statements.
Programmer can use goto to transfer execution both into and out of
loops, such as a for statement.
A goto statement and its target label must be located in the same
function, although they can be in different blocks.
Example 8
#include <stdio.h>
int main() {
int a = 5;
if (a < 10) {
goto less_than_ten;
} else {
goto greater_than_or_equal_to_ten;
}
less_than_ten:
printf("The number is less than ten.\n");
goto end;
greater_than_or_equal_to_ten:
printf("The number is greater than or equal to ten.\n");
goto end;
end:
printf("End of program.\n");
return 0;
}
THE END of Looping
38
Structured Programming
39
C’s single-entry/single-exit sequence, selection and
repetition statements
Structured Programming
Structured programming – why?
• Easier than unstructured programs to understand, test, debug and,
modify programs
Structured Programming
Structured Programming
• Simplest flowchart
44
Structured Programming
Repeatedly applying rule 2 to the simplest flowchart
45
Structured Programming
• Applying rule 3 to the simplest flowchart
46
Structured Programming
Structured Programming
• An unstructured flowchart
48
Structured Programming
Structured Programming Summary
All programs can be broken down into 3 controls
• Sequence – handled automatically by compiler
• Selection – if, if…else or switch
• Repetition – while, do…while or for
o Can only be combined in two ways
- Nesting (rule 3)
- Stacking (rule 2)
• Any selection can be rewritten as an if statement, and any repetition
can be rewritten as a while statement
Common Programming Error /
Error-Prevention Tip / Good
Programming Practice / Software
Engineering Observation /
Performance Tip
49
Common Programming Error
Because floating-point values may be approximate, controlling
counting loops with floating-point variables may result in
imprecise counter values and inaccurate tests for termination.
Error-Prevention Tip
Control counting loops with integer values.
Good Programming Practice
Indent the statements in the body of each control statement.
Good Programming Practice
Put a blank line before and after each control statement to make it
stand out in a program.
Good Programming Practice
Too many levels of nesting can make a program difficult to
understand. As a general rule, try to avoid using more than three
levels of nesting.
Good Programming Practice
The combination of vertical spacing before and after control
statements and indentation of the bodies of control statements
within the control-statement headers gives programs a two-
dimensional appearance that greatly improves program readability.
Common Programming Error
Using an incorrect relational operator or using an incorrect initial or
final value of a loop counter in the condition of a while or for
statement can cause off-by-one errors.
Error-Prevention Tip
Using the final value in the condition of a while or for statement and
using the <= relational operator will help avoid off-by-one errors. For a
loop used to print the values 1 to 10, for example, the loop-continuation
condition should be counter <= 10 rather than counter < 11 or
counter < 10.
Software Engineering Observation