0% found this document useful (0 votes)
4 views73 pages

Slide 5

The document discusses repetition and looping in programming, focusing on various loop structures such as while, for, and do-while loops. It explains the importance of loop control variables and provides examples of counter-controlled and sentinel-controlled repetition. Additionally, it highlights common pitfalls, best practices, and structured programming principles to enhance code readability and maintainability.

Uploaded by

vectormr1999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views73 pages

Slide 5

The document discusses repetition and looping in programming, focusing on various loop structures such as while, for, and do-while loops. It explains the importance of loop control variables and provides examples of counter-controlled and sentinel-controlled repetition. Additionally, it highlights common pitfalls, best practices, and structured programming principles to enhance code readability and maintainability.

Uploaded by

vectormr1999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Repetition/Looping

1
Example 1

 What if we want to process


three different pairs of integers?

2
Example 2
 One solution is to copy and paste the necessary lines
of code. Consider the following modification:

 What if you wanted to process four sets?


Five? Six? ….

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

 while loop repeated


 As long as condition is true
 Until condition becomes false

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

 Expression = Condition to be tested


 Resolves to true or false
 Basic Block = Loop Body
 Reminder – Basic Block:
 Single statement or
 Multiple statements enclosed in braces

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

Enter value or zero to end: 2


……………????
Enter value or zero to end: 0
……………???

13
Loop Pitfalls

Enter value or zero to end: 2

What is wrong with my


program? It just sits there!

14
Loop Pitfalls: Misplaced semicolon

 Notice the ‘;’ after the while condition!


 Body of loop is between ) and ;
 Result here: INFINITE LOOP!
Ctrl-c = Kill foreground process

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

Flowcharting a typical for repetition statement


with an example
Review: Assignment Operators
 Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;

 Examples of assignment operators:


a += 5 (a = a + 5)
a -= 4 (a = a - 4)
b *= 5 (b = b * 5)
c /= 3 (c = c / 3)
d %= 9 (d = d % 9)

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

the value of n will be 2.


ii) In an expression:
Add 1 to n and then use the new value of n in the expression.

If n is initially 1, the above statement will print the value 2.


After execution of printf, n will have the value 2.

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

the value of n will be 2.


ii) In an expression:
Use the value of n in the expression and then add 1 to n.

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

 Do not use unless you know what you are doing!

21
2
The for Repetition Structure
 Syntax:

for (initialization; test; increment)


basic block

22
for Loop Example

How many times does loop body execute?

23
for Loop Example

How many times does loop body execute?

Bite 1 -- Yum!
Bite 2 -- Yum!
Bite 3 -- Yum!

24
25

for Loop Statement


 For loops can usually be rewritten as while loops:
initialization;
while ( loopContinuationTest ) {
statement;
increment;
}

 Initialization and increment: Can be comma-separated lists


Example:
for (int i = 0, j = 0; j + i <= 10; j++, i++)
printf( "%d\n", j + i );
for loop example
 Prints the integers from one to ten

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

 Prints the integers from 1 to 10

30
The do-while Repetition Structure
 Example

 Makes sure that the user enters a valid weight

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.

 When program execution reaches a goto statement, execution


immediately jumps, or branches, to the location specified by the goto
statement.

 The statement is unconditional because execution always branches


when a goto statement is encountered, the branch does not depend on
any program condition.

 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

Rules for Forming Structured Programs

1) Begin with the “simplest flowchart”.


2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence.
3) Any rectangle (action) can be replaced by any control statement (sequence, if,
if...else, switch, while, do...while or for).
4) Rules 2 and 3 may be applied as often as you like and in any order.
43

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

• Stacked, nested, and overlapped building blocks


47

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

Place only expressions involving the control variables in the


initialization and increment sections of a for statement.
Manipulations of other variables should appear either before the
loop (if they execute only once, like initialization statements) or in
the loop body (if they execute once per repetition, like
incrementing or decrementing statements).
Common Programming Error
Using commas instead of semicolons in a for header is a syntax
error.
Common Programming Error
Placing a semicolon immediately to the right of a for header
makes the body of that for statement an empty statement. This
is normally a logic error.
Error-Prevention Tip
Although the value of the control variable can be changed in the
body of a for loop, this can lead to subtle errors. It is best not to
change it.
Good Programming Practice
Although statements preceding a for and statements in the body
of a for can often be merged into the for header, avoid doing so
because it makes the program more difficult to read.
Good Programming Practice
Limit the size of control-statement headers to a single line if
possible.
Good Programming Practice
Some programmers always include braces in a do...while
statement even if the braces are not necessary. This helps eliminate
ambiguity between the do...while statement containing one
statement and the while statement.
Common Programming Error
Infinite loops are caused when the loop-continuation
condition in a while, for or do...while statement
never becomes false. To prevent this, make sure there is
not a semicolon immediately after the header of a
while or for statement. In a counter-controlled loop,
make sure the control variable is incremented (or
decremented) in the loop. In a sentinel-controlled loop,
make sure the sentinel value is eventually input.
Software Engineering Observation

Some programmers feel that break and continue violate the


norms of structured programming. Because the effects of these
statements can be achieved by structured programming
techniques, these programmers do not use break and
continue.
Performance Tip
The break and continue statements, when used properly,
perform faster than the corresponding structured techniques.
Software Engineering Observation

There is a tension between achieving quality software engineering


and achieving the best-performing software. Often one of these
goals is achieved at the expense of the other.
Performance Tip
In expressions using operator &&, make the condition that is most
likely to be false the leftmost condition. In expressions using
operator ||, make the condition that is most likely to be true the
leftmost condition. This can reduce a program’s execution time.
Common Programming Error
Using operator == for assignment or using operator = for equality
is a logic error.
Good Programming Practice

When an equality expression has a variable and a


constant, as in x == 1, some programmers prefer
to write the expression with the constant on the
left and the variable name on the right (e.g. 1 == x
as protection against the logic error that occurs
when you accidentally replace operator == with =.
Error-Prevention Tip
After you write a program, text search it for every = and check that
it is being used properly.
Good Programming Practice

It is strongly recommended that a goto statement


not be used anywhere in a program. It isn’t
needed. Always use other C/C++ branching
statements. Furthermore, when program
execution branches with a goto statement, no
record is kept of where the execution came from.

You might also like