05 Iteration

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 46

ITERATION

UCCD1004 Programming Concepts and Practices


Content Overview
Structure of C++ Programs

Statements Control Control


String and
and Structures Structures Functions Structs Pointers
Array
Expressions (Selection) (Iteration)

Input & Pass-by-


Data Types FileIO Classes
Output reference
Introduction
Find the average of five numbers:-

How about if we want to find the average of 100000 numbers?


Introduction
• Repetition is one thing that computer can do very well.
Introduction
• There are many situations in which it is necessary to repeat a set of
statements.

• For example:-
• Lookup for a student in a list
• Find minimum / maximum in a list
• Count the number of items in a list
• many more …
Iteration in C++
• There are 3 common ways to perform iteration in
C++.

• While Loop
• Do.. While Loop
• For Loop
• For each Loop
Last week
Introduction to Loops: if(choice == 1){
}
The while Loop
• Loop: part of program that may execute > 1 time (i.e., it repeats)
• while loop format:
while (condition)
{ statement(s); No ; here

}
• The {} can be omitted if there is only one statement in the body of
the loop

5-8
while Loop is a Pretest Loop
• while is a pretest loop (condition is evaluated before the
loop executes)

• If the condition is initially false, the statement(s) in the body of


the loop are never executed

• If the condition is initially true, the statement(s) in the body


continue to be executed until the condition becomes false

5-9
While Loop
While Loop
While Loop
Exiting the Loop
• The loop must contain code to allow condition to eventually
become false so the loop can be exited
• Otherwise, you have an infinite loop (i.e., a loop that does not
stop)
• Example infinite loop:
x = 5;
    while (x > 0)    // infinite loop
because
        cout << x;    // x is always > 0

5-13
While Loop (Sentinel Controlled)
While Loop
While Loop (Flag-Controlled)
For example:-
While Loop (EOF)
For example
Common Error
Common Errors
• Don’t forget the { } :
int numEntries = 1;
while (numEntries <=3)
cout << "Still working … ";
numEntries++; // not in the loop body

• Don’t use = when you mean to use ==

while (numEntries = 3)  // always true


{
    cout << "Still working … ";
    numEntries++;
}
5-21
For Loop
The for Loop
• Pretest loop that executes zero or more times
• Useful for counter-controlled loop

Required ;
• Format:

for( initialization; test; update )


{   1 or more statements;
}
No ; goes here

5-23
For Loop
For Loop
For example
Common Error
Custom update statement
Using For Loop
While Loop vs. For Loop
The do-while Loop
• do-while: a post test loop (condition is evaluated after the
loop executes)
• Format:
do
{   1 or more statements;
} while (condition);
Notice the

required ;

5-31
Do… While Loop
Different between while and do..while loop
For example
For example
do-while Loop Notes
• Loop always executes at least once
• Execution continues as long as condition is true; the loop is
exited when condition becomes false
• Useful in menu-driven programs to bring user back to menu to
make another choice

5-36
// This program averages 3 test scores. It uses a do-while loop
// that allows the code to repeat as many times as the user wishes.
#include <iostream>
using namespace std;

int main()
{
    int score1, score2, score3;   // Three test scores
    double average;               // Average test score
    char again;                   // Loop again? Y or N
    
    do
    {   // Get three test scores
        cout << "\nEnter 3 scores and I will average them: ";
        cin  >> score1 >> score2 >> score3;
        
        // Calculate and display the average
        average = (score1 + score2 + score3) / 3.0;
        cout << "The average is " << average << ".\n";
        
        // Does the user want to average another set?
        cout << "Do you want to average another set? (Y/N) ";
        cin  >> again;
    } while ((again == 'Y') || (again == 'y'));
    return 0;
}
5-37
    do
    {  // Display the menu and get the user's choice
        cout << "\n   Health Club Membership Menu\n\n";
        cout << "1. Standard Adult Membership\n";
        cout << "2. Child Membership\n";
        cout << "3. Senior Citizen Membership\n";
        cout << "4. Quit the Program\n\n";
        cout << "Enter your choice: ";
        cin  >> choice;
        
        // Validate the menu selection
        while ((choice < 1) || (choice > 4))
        {
            cout << "Please enter 1, 2, 3, or 4: ";
            cin  >> choice;
        }
        // Process the user's choice
        if (choice != 4)
        {   cout << "For how many months? ";
            cin  >> months;
            
            // Compute charges based on user input
            switch (choice)
            {
                case 1: charges = months * ADULT_RATE;
                    break;
                case 2: charges = months * CHILD_RATE;
                    break;
                case 3: charges = months * SENIOR_RATE;
            }
            // Display the monthly charges
            cout << fixed << showpoint << setprecision(2);
            cout << "The total charges are $" << charges << endl;
        }
        } while (choice != 4); // Loop again if the user did not   select  choice 4 to quit.
5-38
Do... While Loop Usage

• Do…while loop often used for input validation.


Break

• The break statement, when executed in a switch structure,


provides an immediate exit from the switch structure.

• Similarly, the break statement in while, for, and do. . .while


loops provides an immediate exit from the loop structure.
For Example
Continue

• The continue statement is used in while, for, and do. . .while


structures. When the continue statement is executed in a loop,
it skips the remaining statements in the loop and proceeds with
the next iteration of the loop.
For example
Nested Control Structures
• All the aforementioned structures can be nested to solve more
complex problems.
Deciding Which Loop to Use
• The while loop is a conditional pretest loop
• Iterates as long as a certain condition exits
• Validating input
• Reading lists of data terminated by a sentinel

• The do-while loop is a conditional posttest loop


• Always iterates at least once
• Repeating a menu

• The for loop is a pretest loop


• Built-in expressions for initializing, testing, and updating
• Situations where the exact number of iterations is known
5-45
Programming Practices: Avoid Patching
Codes
• Very often novice programmers like to patch their codes after
observe certain bugs without have complete understanding of
the code.

• Patching codes will only introduce more bugs and make


program more difficult to maintain in long run.

You might also like