Lokang 

C++ and MySQL

loops

In C++, loops are essential for repeating a block of code multiple times based on a condition. The while loop is one of the simplest and most common loops used in programming. Unlike the for loop, which is typically used when the number of iterations is known beforehand, the while loop is ideal when the number of iterations depends on a condition being true or false.

The Structure of a while Loop

The basic syntax of a while loop in C++ is as follows:

while (condition) {
   // Code to execute as long as condition is true
}
  • condition: This is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the loop body executes. If false, the loop terminates.
  • The loop body contains the code that you want to repeat as long as the condition remains true.

Example 1: Basic while Loop

Let’s start with a simple example where a while loop is used to print numbers from 1 to 5.

#include <iostream>
using namespace std;
int main() {
   int i = 1;
   while (i <= 5) {
       cout << i << endl;
       i++;
   }
   return 0;
}

Explanation:

  • The loop starts with i equal to 1.
  • The condition i <= 5 is checked before each iteration.
  • As long as i is less than or equal to 5, the loop prints the value of i and then increments it.
  • When i becomes 6, the condition is false, and the loop terminates.

Example 2: while Loop for User Input Validation

A common use of the while loop is to repeatedly prompt the user for input until a valid value is provided.

#include <iostream>
using namespace std;
int main() {
   int number;
   cout << "Enter a positive number: ";
   cin >> number;
   while (number <= 0) {
       cout << "Invalid input. Please enter a positive number: ";
       cin >> number;
   }
   cout << "You entered: " << number << endl;
   return 0;
}

Explanation:

  • The program prompts the user to enter a positive number.
  • If the user enters a number less than or equal to 0, the loop repeats, asking for a valid input.
  • The loop exits only when the user provides a positive number.

Example 3: Infinite Loops

A while loop can run indefinitely if the condition never becomes false. This is known as an infinite loop and should generally be avoided unless specifically required (e.g., in servers).

#include <iostream>
using namespace std;
int main() {
   while (true) {
       cout << "This loop will run forever!" << endl;
   }
   return 0;
}

Explanation:

  • The condition true is always true, so the loop never terminates on its own.
  • Use this carefully, typically with a break statement or an external condition to exit the loop.

Example 4: Exiting a Loop Early with break

You can use the break statement to exit a while loop before the condition becomes false.

#include <iostream>
using namespace std;
int main() {
   int i = 1;
   while (i <= 10) {
       cout << i << endl;
       if (i == 5) {
           break; // Exit the loop when i is 5
       }
       i++;
   }
   return 0;
}

Explanation:

  • The loop prints numbers from 1 to 5.
  • When i becomes 5, the break statement terminates the loop early.

Example 5: Skipping Iterations with continue

The continue statement can be used to skip the rest of the current iteration and move on to the next one.

#include <iostream>
using namespace std;
int main() {
   int i = 0;
   while (i < 5) {
       i++;
       if (i == 3) {
           continue; // Skip the rest of the loop when i is 3
       }
       cout << i << endl;
   }
   return 0;
}

Explanation:

  • The loop prints the numbers 1, 2, 4, and 5.
  • When i becomes 3, the continue statement skips the cout statement, so 3 is not printed.

When to Use a while Loop

  • Unknown Number of Iterations: When you don’t know in advance how many times you want to loop, and the loop should continue until a condition is met.
  • Waiting for a Condition: When you need to keep checking a condition and act only when it becomes true or false.
  • User Input Validation: When you need to repeatedly prompt the user for correct input until they provide a valid response.

Comparison with Other Loops

  • for loop: Use when you know the number of iterations ahead of time, as it allows you to initialize, check the condition, and update the loop control variable in one place.
  • do-while loop: Use when you need the loop body to execute at least once before checking the condition.

Summary

  • The while loop is a flexible control structure that repeats a block of code as long as a specified condition remains true.
  • It is best used when the number of iterations is not known beforehand and depends on dynamic conditions.
  • The loop continues as long as the condition is true, and terminates when the condition becomes false.

 

This content provides a comprehensive explanation of the while loop in C++, including examples, best use cases, and practice problems to help reinforce the understanding of this essential loop structure.