0% found this document useful (0 votes)
12 views

06 Loop Statements

The document discusses different types of loops in C programming. It describes repetition structures called loops that repeat a block of code. The three main loop types in C are while loops, for loops, and do-while loops. While loops repeat as long as a condition is true. For loops allow initialization of a counter, condition test, and counter update to be specified in the loop header. Do-while loops execute the body first and then check the condition. Sentinel controlled loops repeat until a special end-of-data marker called a sentinel is encountered.

Uploaded by

Aditya Aditya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

06 Loop Statements

The document discusses different types of loops in C programming. It describes repetition structures called loops that repeat a block of code. The three main loop types in C are while loops, for loops, and do-while loops. While loops repeat as long as a condition is true. For loops allow initialization of a counter, condition test, and counter update to be specified in the loop header. Do-while loops execute the body first and then check the condition. Sentinel controlled loops repeat until a special end-of-data marker called a sentinel is encountered.

Uploaded by

Aditya Aditya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Data Structures and Algorithms

(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

Repetition (program control structure)


Loop : a control structure that repeats a group of steps in a
program.
Loop body : contains the statements to be repeated.
Three C loop control statements:
▶ while
▶ for
▶ do-while

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 2 / 35


Repetition in programs

Figure: Flow Diagram of loop choice process


(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 3 / 35
Repetition in programs

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 4 / 35


Loop type 1: Counting Loops

Counter controlled loop :


The repetition is managed by a loop control variable whose value
represents a count.
General format: Counter controlled loop
Set loop control variable to an initial value of 0.
while loop control variable < final value
. . .
Increase loop control variable by 1

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.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 5 / 35


The while Statement: syntax
Sample problem
Write a program to compute and display the gross pay for seven
employees.
Input : Number of Hrs worked and rate per hour.
Output: print a statement like “Pay is ...” for each of the employ-
ees.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 6 / 35


The while stmt
Loop repetition condition : the condition/expression following the reserve
keyword while that controls loop repetition.

Figure: Flowchart of the while loop

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 7 / 35


The while stmt: Syntax

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.”

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 8 / 35


Problems

Compute a sum in a loop


Extend the program to compute and display the gross pay for any
number of employees and display the Total payroll.

Multiplying a List of Numbers


Write a program to receive data items from the user until the
product of the received data items exceeds 10000. Display each
data item as it is entered into the system.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 9 / 35


Multiplying a List of Numbers

Pseudocode for general conditional loop

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 10 / 35


Compound Assignment Operators (additional C operators)

☞ For assignment operations of the form:

☞ C provides special assignment operators that enable a more concise


notation for statements of this type.
☞ For the operations +, -, *, /, and %, C defines the compound op =
assignment operators +=, -=, *=, /=, and %=. A statement of the form

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 11 / 35


Compund assignment statement

Convert:

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 12 / 35


While in ’C’: revisited (BACK TO WORK)

Figure: Three loop control components in addition to the loop body.

Initialization of the loop control variable ,


Test of the loop repetition condition , and
Change (update) of the loop control variable

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 13 / 35


The for statement

☞ An important feature of the for statement in C is that it supplies a


designated place for each of these three components.

☞ The for stmt allows us to specify three things about a loop in a single
line:

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 14 / 35


General syntax

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 15 / 35


Converting while into for

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 16 / 35


Flow chart

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;

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 17 / 35


Increment and Decrement Operators

☞ Side effect is a change in the value of a variable as a result of carrying


out an operation.
☞ The increment operator ++
a single variable as its operand.
The side effect : the value of its operand is incremented by one.
☞ The value of the expression in which the ++ operator is used de-
pends on the position of the operator.
Prefix increment : When the ++ is placed immediately in front of
its operand , the value of the expression is the variable’s value after
incrementing.
Postfix increment : When the ++ comes immediately after the
operand , the expression’s value is the value of the variable before it
is incremented.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 18 / 35


Problem

Function comp factorial computes the factorial of an integer


represented by the formal parameter n. Write a program to find
factorial using such a function.

WAP to implement following table using for loop:

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 19 / 35


LOOP TYPE 2: Conditional Loops
☞ In many programming situations, you will not be able to determine
the exact number of loop repetitions before loop execution begins.

Pseudocode for general conditional loop

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 20 / 35


Conditional Loops : a situation
You want to continue prompting the user for a data value as long as the
response is unreasonable

General format

C implementation

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 21 / 35


Sentinel-controlled loops

In the last program :


Input one/more additional data items each time the loop is executed.
Not known in advance : how many data items the loop should process.
Find some way: to stop reading and processing new data.
Sentinel
is an end marker that follows the 12,78,98,23,45,67,88,
34,67,78,45,54,56,66,
45,60,78,89,23,34,56,
42,75,89,25,54,65,82,
54,61,34,41,55,56,26,
65,67,56,86,23,54,76,
49,6,81,34,67,78,45,
52,36,96,45,60,78,89,
21,74,26,22,66,77,89,
22,66,77,89,03,56,45, 32,61,76,82,03,66,35, 43,96,35,66,78,56,67,
last item in a list of data. 66,78,56,67,74,43,33,
45,78,55,45,32,31,44,
76,73,57,61,74,43,73,
49,72,59,41,30,21,54,
64,13,53,45,78,55,45,
12,41,45,32,43,54,98,
32,43,54,98,67,76,56, 35,44,51,93,68,86,36, 27,56,26,68,99,01,11
... ... ...
is a unique data item and could
not normally occur as data. USP DOS TOC
General form

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 22 / 35


LOOP TYPE 3: Sentinel-controlled loops

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.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 23 / 35


Sentinel-controlled loops

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.

Implement using while statement.


Implement using for statement.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 24 / 35


Endfile-Controlled Loops

A data file is always terminated by an endfile character.


EOF can be detected by the scanf function.
Processing an arbitrary list of data (from files) does not require a
special sentinel value at the end of the data.
scanf function returns a result value:
▶ Same as the number of argument variables it has. The scanf was suc-
cessful (all values received).
▶ Less than the number of argument variables: scanf runs into difficulty
with invalid or insufficient data.
⋆ returns a value indicating the number of data items scanned before
encountering the error or running out of data.
▶ Value of standard constant EOF (A negative integer): when it detects
the endfile character before getting input data for any of its arguments.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 25 / 35


Using status value from the scanf to manage loop
repetition

Pseudocode: endfile-controlled loop

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 26 / 35


Infinite Loops on Faulty Data

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.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 27 / 35


Nested loops

Loops are either nested or disjoint.


Nested loops consist of an outer loop with one or more inner loops.
Syntax of Nested loop Example of Nested for loop

Outer loop for (initialization; condition; update)


{ {
Inner loop for (initialization; condition; update)
{ {
// inner loop statements. // inner loop statements.
} }
// outer loop statements. // outer loop statements.
} }

Each time the outer loop is repeated,


▶ the inner loops are reentered,
▶ their loop control expressions are reevaluated, and
▶ all required iterations are performed.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 28 / 35


Example

Tabulate/trace values of i and j variables


(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 29 / 35
Input validation loop using do-while Statement
Pseudocode for Input validation loop

C provides the do-while statement to implement such loops

Flow-diagram

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 30 / 35


Compare: do...while and for/while

for/while loop do...while loop


1 Evaluate a loop repetition condition Evaluates its condition at the bot-
before the first execution of the loop tom of the loop.
body
2 Entry controlled loops Exit controlled loop
3 No guarantee on the execution of The loop body is guaranteed to exe-
the loop body. cute at least one time.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 31 / 35


The Flag-Controlled Loops for Input Validation

In many cases, complex loop repetition condition may be simplified


by using a flag.

A flag is a type int variable used to represent whether or not a


certain event has occurred.

A flag has one of two values: 1 (true) and 0 (false)


Example problem
WAP that returns the first integer between n min and n max en-
tered as data.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 32 / 35


How to Debug and Test Programs

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.

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 33 / 35


Off-by-One Loop Errors

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

(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 34 / 35


(Ashish Kumar Gupta) Unit-I, C programming February 1, 2023 35 / 35

You might also like