UNIT-II Repetition in Programs
UNIT-II Repetition in Programs
CHAPTER OBJECTIVES
• To understand why repetition is an important control
structure in programming
5
• To learn about loop control variables and the three steps
needed to control loop repetition
• To learn how to use the C for, while, and do-while
statements for writing loops and when to use each
statement type
• To learn how to accumulate a sum or a product within a
loop body
• To learn common loop patterns such as counting loops,
sentinel-controlled loops, and flag-controlled loops
• To understand nested loops and how the outer loop con-
trol variable and inner loop control variable are changed
in a nested loop
• To learn how to debug programs using a debugger
• To learn how to debug programs by adding diagnostic
output statements
I n your programs so far, the statements in the program body execute only once.
However, in most commercial software that you use, you can repeat a process many
times. For example, when using an editor program or a word processor, you can move
the cursor to a program line and perform as many edit operations as you need to.
Repetition, you’ll recall, is the third type of program control structure
(sequence, selection, repetition), and the repetition of steps in a program is called a
loop a control loop. In this chapter we describe three C loop control statements: while, for, and
structure that repeats do-while. In addition to describing how to write loops using each statement, we
a group of steps in a
program describe the advantages of each and explain when it is best to use each one. Like if
statements, loops can be nested, and the chapter demonstrates how to write and use
nested loops in your programs.
FIGURE 5.1
Flow Diagram
of Loop Choice
Process Any steps No No loop
repeated? required
Yes
Yes
Use a counting
loop
Self-Check
1. Choose an appropriate kind of loop from Table 5.1 for solving
each of the fol- lowing problems.
a. Calculate the sum of the test scores of a class of 35
students. (Hint: Initialize sum to zero before
entering loop.)
b. Print weekly paychecks for a list of employees. The
following data are to be entered interactively for each
employee: ID, hours worked, and hourly pay rate. An ID of
zero marks the end of the data.
c. Process a data file of Celsius temperatures. Count how
many are above 100°C.