Iteration in C
Iteration Overview
Iteration allows programs to repeat code segments, enhancing functionality and readability.
There are three types of iteration (loops) in C.
Two case studies are used to explore these loops.
Case Study 1: Lisa's Apples
Lisa buys apples at "First Bite" restaurant.
She orders and eats apples until she's no longer hungry.
Initial,naive solution involves repeating code:
Reading lines of input.
Converting input.
Using
ifstatements.Incrementing a counter.
Problem With Copy-Pasting
Copying and pasting code leads to confusion and update difficulties.
Example:
Code starts by setting default variable values.
Asks if Lisa wants an apple (true/false).
Increments apple count if true, otherwise, count remains zero.
Outputs the number of apples eaten.
The code works for one apple, but requires repetition for more apples.
Code becomes increasingly long and inflexible.
Hard to adapt to different customer needs (e.g., wanting two apples, five apples, or 10 apples.)
Changing input/output statements across all copies is tedious and error-prone (e.g., fixing a typo).
Case Study 2: Steven's Apples
Steven, the owner of "First Bite", wants to track daily apple sales.
We can declare variables, set defaults, input sales, and output data.
Problem with scaling
Calculating sales for two days involves copy-pasting.
Extending to three or four days makes the code even longer.
Calculating sales over a week, month, or year would result in unmanageable code.
Potential for errors when copy-pasting (e.g., calculating 364 days instead of 365).
The code is difficult to modify even though it only repeats a simple code block.
Steven might get frustrated because of the increase in manual labor.
Iterations (Loops) to the Rescue
Iterations (loops) are similar to
ifstatements but repeat multiple times.
Types of Loops
Two categories of loops:
While Loops and Do-While Loops:
Use a Boolean expression to control repetition.
Suitable when the number of iterations is unknown.
For Loops:
Also use a Boolean expression.
Use a numeric condition to define iteration boundaries.
Ideal when the number of iterations is known in advance.