C++ Repetition and Looping Structures Study Guide
REPETITION (LOOPING)
Repetition or looping is a programming technique used to avoid redundant code when a specific task needs to be performed multiple times.
Why Use Looping?
Consider a scenario where the word "UPSI" needs to appear on the screen once. The code would be:
#include <iostream.h>
void main() {
cout << ‘‘UPSI’’ << endl;
}
If we want the word "UPSI" to appear 3 times, we could write:
#include <iostream.h>
void main() {
cout << ‘‘UPSI’’ << endl;
cout << ‘‘UPSI’’ << endl;
cout << ‘‘UPSI’’ << endl;
}
However, C++ provides a more efficient way to code repetitive actions using the following statements:
- looping with
while - looping with
for - looping with
do..while
Three Main Rules in Writing Repetition
To use repetition statements correctly, one must follow three main rules involving the Control Variable (CV). The CV is the variable that controls the looping process, determining how many times the loop will execute.
- Initial value of Control Variable (CV): Setting the starting point for the variable.
- Condition: The logical expression that determines if the loop continues or stops.
- Increment or Decrement: Updating the CV (e.g.,
or) so that the loop eventually reaches the exit condition.
Syntax and Implementation of Loops
(a) The while Loop
The while loop is a pre-test loop, meaning the condition is tested before the statements inside the loop are executed.
Syntax:
while (condition){sttm;sttm;increment;}
Example:
#include <iostream.h>
void main() {
int counter = 1; // CV – counter, initial value = 1
while (counter < 4) // condition
{
cout << ‘‘UPSI’’ << endl;
counter++; // increment
}
}
(b) The for Loop
The for loop also acts as a pre-test loop. It combines the initialization, condition, and increment into a single line.
Syntax:
for (initial value of CV; condition; increment){sttm;sttm;}
Example:
#include <iostream.h>
void main() {
for (int counter = 1; counter < 4; counter++)
{
cout << ‘‘UPSI’’ << endl;
}
}
(c) The do..while Loop
The do..while loop is a post-test loop. It executes the statements first and checks the condition at the end. This guarantees the loop body runs at least once.
Syntax:
do{sttm;sttm;increment;}while (condition);
Example:
#include <iostream.h>
void main() {
int counter = 1; // CV – counter, initial value = 1
do
{
cout << ‘‘UPSI’’ << endl;
counter++; // increment
}
while (counter < 4); // condition
}
Classifications and Hints
Pre-test vs. Post-test Loops
- Pre-test loop (
whileandfor): The condition is tested first before executing the statements. - Post-test loop (
do..while): The condition is tested last, after the statements have been executed.
HINT: Place the while statement in the program at the exact location of the statements that need to be repeated.
Types of Control Variables (CV)
- Counter: Used when we can count exactly how many times the loop should run.
- Signal: Used when the number of repetitions depends on user input or specific conditions. There are two types of signals:
- Flag: Uses a specific value (often yes or no) to control the loop.
- Sentinel: Uses a specific value, often a negative number (e.g., ), to stop the looping.
Deciding When to Use Specific CVs and Statements
Usage Guidelines for CVs
- Counter: Use when the exact number of repetitions is known in advance.
- Signal: Use when the number of repetitions is unknown and depends on the user during runtime.
Selection Matrix for Looping Statements
- Known iterations (Counter CV): Use
fororwhileloops. - Unknown iterations (Signal CV): Use
whileordo..whileloops. - Versatility of
while: Thewhilestatement is highly flexible and can be used in both situations (known or unknown iterations) depending on the requirements of the problem.
Code Examples by CV Type
Example: Flag Signal
#include <iostream.h>
void main() // flag CV
{
char response = 'Y'; // initial value of CV
while (response == 'Y' || response == 'y') // condition
{
cout << "UPSI";
cout << "Enter your response";
cin >> response; // increment (update CV)
}
}
Example: Counter CV
#include <iostream.h>
void main() {
int counter = 1; // CV – counter, initial value = 1
while (counter < 4) // condition
{
cout << ‘‘UPSI’’ << endl;
counter++; // increment
}
}
Example: Sentinel Signal
#include <iostream.h>
void main() {
int response = 0; // initial value of CV
while (response != -999)
{
cout << "UPSI" << endl;
cout << "Enter the response";
cin >> response; // increment (update CV)
}
}
Exercises and Solutions
Exercise 1
Write a simple C++ program to code the word "FSKIK" three times using the while statement. Experiment by dropping one of the repetition rules and observe the behavior (e.g., infinite loops if increment is missing).
Exercise 2: Average of Three Numbers
Calculate the average of three numbers entered by a user via keyboard using both while and for statements.
Solution using for loop:
#include <iostream.h>
void main() {
int number, total = 0, average;
for (int counter = 1; counter <= 3; counter++)
{
cout << "Enter the numbers";
cin >> number;
total = total + number;
}
average = total / 3;
cout << "the average of numbers is" << average;
}
Exercise 3: Sum and Average of Positive Numbers
Write a program that accepts positive numbers and calculates their total and average. The loop must stop when a negative number is entered.
Solution using while and Sentinel:
#include <iostream.h>
void main() {
int number, total = 0, average, counter = 0;
int response = 1;
while (response != -999)
{
cout << "Enter the number" << endl;
cin >> number;
if (number >= 0)
{
total = total + number;
counter++;
}
else
{
cout << "Enter the larger number or equal to zero";
}
cout << "any number (press -999 to stop)";
cin >> response;
}
cout << "TOTAL NUMBER POSITIVE THAT HAVE BEEN ENTERED IS" << total << endl;
if (counter > 0) {
average = total / counter;
cout << "AVERAGE OF NUMBERS IS" << average;
}
}