0% found this document useful (0 votes)
13 views79 pages

Chapter 5 PF Lecture Slides

Chapter 3 covers control structures in programming, focusing on repetition through loops in C++. It explains the types of loops (while, for, do-while), their syntax, and when to use each type, along with examples and best practices for designing loops. Additionally, it discusses the use of break and continue statements, nested loops, and the importance of debugging to avoid software patches.
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)
13 views79 pages

Chapter 5 PF Lecture Slides

Chapter 3 covers control structures in programming, focusing on repetition through loops in C++. It explains the types of loops (while, for, do-while), their syntax, and when to use each type, along with examples and best practices for designing loops. Additionally, it discusses the use of break and continue statements, nested loops, and the importance of debugging to avoid software patches.
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/ 79

Chapter 3:

Control Structures II (Repetition)


CS 111: PROGRAMING FUNDAMENTALS
DR. ASMA SAJJAD, IIUI, DOC
Why Is Repetition Needed?
Why Is Repetition Needed?
• The original program declares separate variables for each day's calorie
count, which is inefficient for larger datasets.
• Instead of declaring multiple variables, a loop can be used to repeatedly
take input and sum the values.
• A looping structure allows for flexibility in handling any number of days
without modifying the program.
• Three types of loops in C++:
o while loop
o for loop
o do-while loop
while Looping (Repetition) Structure
• A while loop is a control structure that allows repeating a block of
code as long as a condition remains true.
• It is useful when the number of iterations is not known beforehand.
• The syntax of a while loop:
while Looping (Repetition) Structure
• How It Works:
o The condition is evaluated first.
o If the condition is true, the loop executes the statements inside
the block.
o The condition is checked again, and the loop continues until the
condition becomes false.
o If the condition is false initially, the loop will not execute at all.
while Looping (Repetition) Structure
while Looping (Repetition) Structure
while Looping (Repetition) Structure
while Looping (Repetition) Structure
while Looping (Repetition) Structure
while Looping (Repetition) Structure
• If you put a semicolon at the end of the while loop (after the logical
expression), then the action statement of the while loop is empty or
null. For example, the action statement of the following while loop
is empty.

• The statements within the braces do not form the body of the while
loop.
Designing while Loops
• A while loop executes as long as its condition evaluates to true.
• The loop control variable (LCV) is a variable that determines when
the loop should stop.
• Steps to properly design a while loop:
o Initialize the LCV before the loop starts.
o Write a condition in the while statement that checks the LCV.
o Update the LCV inside the loop so the condition eventually
becomes false, preventing an infinite loop.
Designing while Loops
Case 1: Counter-Controlled while Loops
• A counter-controlled while loop runs a fixed number of times.
• The loop control variable (LCV) acts as a counter to track iterations.
• It is used when you know exactly how many times a loop should
execute.
Case 1: Counter-Controlled while Loops
Case 1: Counter-Controlled while Loops
Case 1: Counter-Controlled while Loops
Case 2: Sentinel-Controlled while Loops
• Used when the number of inputs is unknown.
• A sentinel value signals when to stop taking input.
• The first input is taken before the loop starts.
• The loop runs until the sentinel value is encountered.
Case 2: Sentinel-Controlled while Loops
Case 2: Sentinel-Controlled while Loops
Case 2: Sentinel-Controlled while Loops
Case 2: Sentinel-Controlled while Loops
Telephone Digit Example
Case 2: Sentinel-Controlled while Loops
Telephone Digit Example
Case 2: Sentinel-Controlled while Loops
Telephone Digit Example
Case 3: Flag-Controlled while Loops
• Uses a bool flag variable to control the loop.
• The loop continues until the flag variable is set to true.
• The flag is updated inside the loop based on a condition.
• The flag name describes the condition (e.g., isFound, isFull).
Case 3: Flag-Controlled while Loops
Number Guessing Game Example
• Random Number Generation: The program generates a random
number between 0 and 99 using rand() and srand(time(0)) to
ensure different outputs each time.
• User Interaction & Looping: The program continuously asks the user
to guess the number using a flag-controlled while loop until they
guess correctly.
• Conditional Checks & Feedback: Based on the user's guess, the
program provides feedback if the guess is too high or too low and
prompts them to try again until they get the correct number.
Case 3: Flag-Controlled while Loops
Number Guessing Game Example
Case 3: Flag-Controlled while Loops
Number Guessing Game Example
Case 4: EOF-Controlled while Loops
• EOF-Controlled While Loops: Used when reading data from a file
without relying on a sentinel value. The loop continues reading until
it reaches the end of the file.
• Input Stream Behavior: The cin or file input stream returns false
when it reaches the end of the file or encounters an invalid input,
which helps control the loop.
Case 4: EOF-Controlled while Loops
• eof() Function: Used to explicitly check if a file stream has reached the
end of the file, commonly used when processing text files.
• Example Applications:
o Summing Numbers: Reads a set of numbers and sums them up until
EOF is reached.
o Processing Student Grades: Reads student names and test scores,
assigns grades, and calculates the class average using an EOF-
controlled loop.
• File Handling & Error Checking: Ensures files are opened correctly,
processes data line by line, and closes files properly to prevent data loss
or corruption.
Case 4: EOF-Controlled while Loops
Case 4: EOF-Controlled while Loops
Case 4: EOF-Controlled while Loops
Case 4: EOF-Controlled while Loops
More on Expressions in while Statements
• Unlike simple loops controlled by a single variable, some while
loops use multiple conditions.
• Logical operators (&&, ||, !) can be used to combine multiple
conditions.
More on Expressions in while Statements
Two Content Layout with Table
• First bullet point here Class Group 1 Group 2
• Second bullet point here Class 1 82 95
• Third bullet point here Class 2 76 88
Class 3 84 90
For Looping (Repetition) Structure
• for loop is a specialized form of while loop.
• Used for counter-controlled repetition.
• The syntax of a while loop:
For Looping (Repetition) Structure
• Execution:
• Run init.
• Check condition.
• If true: run body, then update.
• Repeat until condition is false.
• for is a reserved keyword in C++.
For Looping (Repetition) Structure
For Looping (Repetition) Structure
For Looping (Repetition) Structure
For Looping (Repetition) Structure
For Looping (Repetition) Structure
For Looping (Repetition) Structure
For Looping (Repetition) Structure
For Looping (Repetition) Structure
do while Looping (Repetition) Structure
• do...while is the third type of loop in C++.
• Syntax:
do while Looping (Repetition) Structure
• Loop body runs at least once.
• Executes the statement first, then checks the expression.
• If expression is true, repeats the loop.
• Use braces {} for compound statements.
• Avoid infinite loops by ensuring expression becomes false.
• do is a reserved keyword in C++.
Do while Looping (Repetition) Structure
Do while Looping (Repetition) Structure
do while Looping (Repetition) Structure
• Divisibility Test by 3 and 9:
• If m divides n, then n = m × t for some integer t.
• An integer is divisible by 3 or 9 if the sum of its digits is divisible by
3 or 9.
• Example:
• n = 27193257, digit sum s = 2+7+1+9+3+2+5+7 = 36
• Since 36 is divisible by both 3 and 9 → 27193257 is divisible by
both.
do while Looping (Repetition) Structure
• To extract digits:
• num % 10 → gives last digit.
• num / 10 → removes last digit.
• Use a do...while loop to find digit sum:

• Use this digit sum to check divisibility by 3 and 9.


Do while Looping (Repetition) Structure
Choosing the Right Looping Structure
• Use for loop: when the number of repetitions is known.
• Use while loop: when repetitions are unknown and could be 0.
• Use do...while loop: when repetitions are unknown but at least 1.
break and continue Statements
• break Statement:
• Used to exit immediately from a loop (for, while, do...while) or a switch
structure.
• Common uses:
• Exit early from a loop.
• Skip the rest of a switch case.
• After break, control moves to the first statement after the loop or switch.
• Can simplify code by eliminating flag variables.
• Use sparingly to avoid hard-to-read “spaghetti code.”
break and continue Statements
• Example break Statement:
break and continue Statements
• continue Statement:
• Skips the rest of the current loop iteration and moves to the next.
• In while and do...while: loop condition is re-evaluated after
continue.
• In for: the update expression runs, then the condition is rechecked.
break and continue Statements
• Example continue Statement:
Nested Control Structures
• A loop inside another loop
• Commonly used for:
•Matrix operations
•Pattern generation
•Multi-level iterations
• Syntax:
for (int i = 0; i < outerLimit; i++)
{
for (int j = 0; j < innerLimit; j++)
{ // code }
}
Nested Control Structures
Example 5-23

• To process the data in Example 5-23,


where each line of numbers is followed
by the sentinel value -999, we can use a
loop to read and sum the values of
each line. Here's a shortened and
optimized version of the code based on
description in the book
Example 5-24
• Here’s a short and clean
version of the code for
Example 5-23 with unspecified
number of lines, using an EOF-
controlled loop
Example 5-25

• Here’s a short and clean version


of the code for Example 5-25,
using an EOF-controlled loop to
process candidate data from a file
of unknown size:
Avoiding Bugs by Avoiding Patches
• Debugging helps identify and fix syntax and logical errors.
• A software patch is extra code added to fix a bug without fixing the
real cause.
• Instead of patching, it's better to understand the problem fully and
correct the original logic.
• This leads to cleaner, more reliable code.
Avoiding Bugs by Avoiding Patches
Avoiding Bugs by Avoiding Patches
• Problem with the Program
• The input file has 3 lines, but the program prints 4 lines.
• The last line repeats numbers, showing a bug.
• The error is due to the loop running one time too many a classic off-
by-one error.
• Beginners might fix this by adding a software patch (e.g., skipping
the extra output manually).
• But this only hides the symptom, not the real cause.
Avoiding Bugs by Avoiding Patches
Exercise Questions
Exercise Questions
Exercise Questions
Exercise Questions
Exercise Questions
Exercise Questions
Exercise Questions
Exercise Questions
Exercise Questions
Exercise Questions
Exercise Questions

You might also like