Assignment Chef icon Assignment Chef
All English tutorials

Programming lesson

Mastering Loops in C++: While, Do-While, For, and Nested Loops Explained with Real-World Examples (2026)

Learn how to use while, do-while, for, and nested loops in C++ with practical examples from vehicle distance, penny doubling, and rainfall calculations. Perfect for CS 1081 students.

C++ loops tutorial while loop C++ do-while loop C++ for loop C++ nested loops C++ input validation C++ distance calculation C++ penny doubling C++ rainfall average C++ CS 1081 assignment 5 computer science 1081 C++ programming help loop examples C++ C++ for beginners C++ assignment help 2026 C++ trends

Why Loops Matter in Programming (and in Your Daily Life)

Imagine you're tracking your daily steps for a month using a fitness app like Fitbit or Apple Health (May 2026 trend). Instead of writing 30 separate lines of code to log each day, you'd use a loop. Loops let you repeat a block of code efficiently. In computer science 1081 – assignment #05, you'll master four loop types: while, do-while, for, and nested loops. Let's break them down with examples you can actually use.

Program #1: Using a While Loop for Input Validation and Distance Calculation

The while loop checks a condition before executing the loop body. It's perfect when you might not need to run the loop at all. In Program #1, you ask for speed and time, validate input, then display distance traveled each hour.

Example: Vehicle Distance Tracker

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double speed;
    int hours;

    cout << "What is the speed of the vehicle in mph? ";
    cin >> speed;
    while (speed < 0) {
        cout << "Speed cannot be negative. Re-enter: ";
        cin >> speed;
    }

    cout << "How many hours has it traveled? ";
    cin >> hours;
    while (hours < 1) {
        cout << "Hours must be at least 1. Re-enter: ";
        cin >> hours;
    }

    cout << "Hour\tDistance Traveled" << endl;
    cout << "------------------------" << endl;
    int hour = 1;
    while (hour <= hours) {
        double distance = speed * hour;
        cout << hour << "\t" << distance << endl;
        hour++;
    }
    return 0;
}

This validates input using while loops and displays a table. Notice how the loop repeats until the user enters correct data. This is input validation in action.

Program #2: Do-While Loop – Guaranteed Execution

A do-while loop executes the body at least once before checking the condition. Use it when you want to prompt the user at least once.

Example: Same Vehicle Distance with Do-While

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double speed;
    int hours;

    do {
        cout << "What is the speed of the vehicle in mph? ";
        cin >> speed;
        if (speed < 0) cout << "Speed cannot be negative.\n";
    } while (speed < 0);

    do {
        cout << "How many hours has it traveled? ";
        cin >> hours;
        if (hours < 1) cout << "Hours must be at least 1.\n";
    } while (hours < 1);

    cout << "Hour\tDistance Traveled" << endl;
    cout << "------------------------" << endl;
    int hour = 1;
    do {
        double distance = speed * hour;
        cout << hour << "\t" << distance << endl;
        hour++;
    } while (hour <= hours);
    return 0;
}

This do-while loop ensures the user sees the prompt at least once. It's great for menus or repeated input.

Program #3: For Loop with Penny Doubling – A Viral TikTok Challenge Analogy

The for loop is ideal when you know exactly how many times to iterate. In Program #3, salary doubles each day starting from $0.01. This is like the viral penny doubling challenge on TikTok (still trending in 2026) where people see how fast money grows.

Example: Penny Doubling Pay

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    int days;
    do {
        cout << "For how many days will the pay double? ";
        cin >> days;
        if (days < 1) cout << "Days must be at least 1.\n";
    } while (days < 1);

    double total = 0.0;
    double pay = 0.01;
    cout << "Day\tTotal Pay" << endl;
    cout << "---------------" << endl;
    for (int day = 1; day <= days; day++) {
        cout << day << "\t$" << fixed << setprecision(2) << pay << endl;
        total += pay;
        pay *= 2;
    }
    cout << "---------------" << endl;
    cout << "Total $" << total << endl;
    return 0;
}

Notice how the for loop neatly increments day and doubles pay. The do-while handles input validation.

Program #4: Nested Loops for Rainfall Average – Like Tracking Weather for a Gaming Marathon

Nested loops are loops inside loops. In Program #4, you collect rainfall data for each month over multiple years. Think of it like tracking your screen time across months for a gaming marathon (e.g., Fortnite or Roblox).

Example: Average Rainfall Calculator

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    const int MONTHS = 12;
    int years;
    double totalRain = 0;
    int totalMonths = 0;

    cout << "This program will calculate average rainfall over a period of years.\n";
    cout << "How many years do you wish to average? ";
    cin >> years;
    while (years < 1) {
        cout << "Years must be at least 1. Re-enter: ";
        cin >> years;
    }

    for (int year = 1; year <= years; year++) {
        cout << "Year " << year << endl;
        for (int month = 1; month <= MONTHS; month++) {
            double rain;
            cout << "Number of inches of rain for month " << month << "? ";
            cin >> rain;
            while (rain < 0) {
                cout << "Rainfall cannot be negative. Re-enter: ";
                cin >> rain;
            }
            totalRain += rain;
            totalMonths++;
        }
    }

    double average = totalRain / totalMonths;
    cout << "Over a period of " << totalMonths << " months, " << totalRain << " inches of rain fell.\n";
    cout << "Average monthly rainfall for the period is " << average << " inches.\n";
    return 0;
}

The outer loop runs for each year, the inner loop runs for each month. This nested loop structure is common in data processing.

Common Mistakes and Pro Tips

  • Infinite loops: Always update your loop variable. Forgetting hour++ in a while loop can crash your program.
  • Off-by-one errors: Use <= when you want to include the last value. For example, hour <= hours includes the final hour.
  • Input validation: Always check for invalid input before using the value. Use while or do-while to reprompt.
  • Formatting output: Use <iomanip> for neat tables. In the real world, clean output matters for reports.

Connecting to Real-World Trends

In May 2026, AI coding assistants like GitHub Copilot are everywhere, but they still generate loops wrong sometimes. Knowing how loops work helps you debug. Also, financial apps like Robinhood or YNAB use loops to calculate compound interest—just like the penny doubling problem. And if you're into gaming, think of loops as the game loop: update player position, check collisions, render frame, repeat.

Summary

You've seen four loop types: while (check first), do-while (do first), for (count-controlled), and nested loops (loop within loop). Practice by modifying the examples: change the constant in Program #4 to 4 months for quicker testing. Master these, and you'll ace computer science 1081.