06 Loop Statements
06 Loop Statements
(UCS540)
Problem solving in C
Repetition and Loop statements
February 1, 2023
(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 1 / 35
Repetition in programs
When to use : known prior to loop execution exactly how many loop
repetitions will be needed to solve the problem.
The known number should appear as the final value in the while
condition.
The loop control variable is a variable whose value controls loop repe-
tition.
The loop control variable (count emp) must go through the following
steps for the loop to execute properly.
▶ Initialization. Set loop control variable to an initial value (initialized to
0) before the while statement is reached.
▶ Testing. Test initial control varible before the start of each loop repeti-
tion (called an iteration or a pass).
▶ Updating. update loop control variable during each iteration.
Infinite loop : If the loop control variable is not updated, the loop will
execute “forever.”
Convert:
☞ The for stmt allows us to specify three things about a loop in a single
line:
Start
count_emp=0 is
count_emp False
count_emp= < num_emp
count_emp +1
True
print total_pay
Input
hours, rate
exit
pay = hours * rate
Print pay
total_pay =
total_pay + pay;
General format
C implementation
Problem statement
Write a program to calculate the average score for a subject from a
collection of exam scores for that subject in a class. If the class is
large, the instructor may not know the exact number of students who
took the exam being graded. The program should work regardless
of class size.
Problem statement
Write a program to calculate the average score for a subject from a
collection of exam scores for that subject in a class. If the class is
large, the instructor may not know the exact number of students who
took the exam being graded. The program should work regardless
of class size.
Score average problem using sentinels: it does not use return status
from the scanf statement to control loop repetition.
Score average problem using EOF: uses return status from scanf stmt,
still open to enter Infinite loop due to faulty data.
How to modify endfile-controlled loop to exit when encountered the
EOF or faulty data ?
Observation: On a faulty input such as 4o, scanf function would return
a status of 0 on second iteration.
Flow-diagram
A debugger program
allows single-step execution.
helps you to trace your program’s execution and observe the effect of
each C statement on variables you select.
assists in validate loop control variables and other important variables
(e.g., accumulators)
to check if the input variables contain the correct data after each scan
operation.
Debugging without a debugger: insert extra diagnostic calls to printf
that display intermediate results at critical points in your program.
A fairly common logic error in programs with loops is a loop that executes
one more time or one less time than required.
Sentinel controlled loop
Counting loops