While loop, a fundamental construct for flow control within a C++ program, is also one that many programmers and developers struggle with in its efficient usage and theoretical understanding. Here, we are going to explore the syntax of the while loop and the most common parts, as well as give examples of the implementation to ensure that the loops are being implemented properly. By mastering the while loop, you’ll enhance your ability to write optimized and effective C++ code.
Table of Contents:
What is a While loop in C++?
A while loop is a control structure in C++ that loops through a block of code as long as the condition given is true. It tests the condition before executing the work in the loop. This, in turn, means that if the condition is false at first, none of the code in the loop body will be executed. It’s great for when you don’t know the number of iterations in advance, and the loop should be based purely on a condition.
Syntax of While Loop
while (condition) {
// loop body
}
Here, the condition specifies the Boolean expression; if the condition is true, it executes the loop body and terminates the loop if it is false.
Working of While Loop
Working steps of the while-loop:
- The condition is evaluated.
- If that is true, then the body of the loop is executed.
- After the loop body is executed, the condition is then checked again.
- This is repeated until the expression is false.
Flow Diagram of While Loop
The flow diagram is drawn such that the test condition is evaluated before the loop body. If that condition happens to be false initially, the loop is skipped.
Parts of the While Loop
There are 3 parts of a while loop they are:
1. Test Expression
The test expression is checked every time through the loop to determine whether the loop will execute or not. If it returns true, the loop goes on, otherwise, it stops.
while (i <= 5) // i is the test expression
2. Loop Body
This is the code block that is executed when the condition is true. It can be composed of one or more statements.
while (i <= 5) // i is the test expression
3. Update Expression
The update statement adjusts the loop control variable so it eventually fails the test expression and ends the infinite loop.
cout << i << " ";
Examples of While Loop in C++
Below are some examples for the while loop in C++:
1. Printing Numbers from 1 to 5
This example demonstrates how to use a loop to print numbers sequentially from 1 to 5. It showcases basic loop control with a start value, end condition, and increment. Such loops are foundational in iteration and number-based tasks in programming.
Example:
Output:
The loop prints numbers from 1 to 5 by increasing the value of i by 1, and then stops since the condition i <= 5 is met.
2. Calculating the Sum of Natural Numbers
It adds all the numbers up from 1 to the specified limit. It’s a good example of using a running total (accumulator) and conditional looping. It’s a standard technique for problems involving a cumulative total or series.
Example:
Output:
This code adds the first 5 natural numbers using a while loop. It sets sum to 0, loops from 1 to n (5 in this case), and adds the values of i to sum. At the end of the loop, it displays the result, which is 15.
Get 100% Hike!
Master Most in Demand Skills Now!
3. Print a Square Pattern Using Nested Loops
Here, we show how you can print a square pattern using a nested loop. The outer one counts the rows, the inner one checks the symbols to add to each row. It’s an easy way to produce all sorts of “grid-based” things when you’re programming.
Example:
Output:
Below is a C++ program to print a square pattern of 3*3 in a while loop. The outer loop is for the rows, and the inner loop will print three * symbols on each row. The program makes a shift to the next line after each row with the help of endl.
4. Infinite While Loop
An infinite while loop is a loop that executes indefinitely when the condition never returns false. This sort of loop is nice to have when you need monitoring or repeated operations of some kind, but it must always have some way to get out of it (i.e., a break clause or ability for another outside thing to interrupt it).
Example:
Output:
Because the condition is true, an infinite loop runs until a break is used to exit.
5. Program to Reverse a Number Using a While Loop
In this example, you will learn to write a program to reverse a number using a while loop. The loop extracts the last digit of the number (which is simply the remainder when divided by 10) over and over and builds the reversed number by multiplying the existing reversed value by ten and adding the extracted digit. The procedure is repeated until the number becomes 0.
Example:
Output:
The loop goes through and pulls out each digit of num, and in the opposite order, multiplies the reversed number so far by 10 and adds the new digit to the reversed number.
6. Displaying the Elements of an Array Using a While Loop
The following code illustrates how to print the contents of an array in a while loop. The while loop loops through the array by introducing an index to access the array elements, and prints the value at the index. Finishes when all elements have been displayed, and serves as an output.
Example:
Output:
This example uses a while loop to print the elements of an integer array. It begins with the index i = 0 and continues to print the elements from position arr[i] through i < 5, which is the size of the array. The output will be: 10 20 30 40 50.
Password Strength Checker
In this program, we prompt the user to enter their password. The password must also conform to certain strength rules, such as:
- At least 8 characters long
- Contains at least one digit (0-9)
- Should include at least one uppercase letter (A to Z)
We repeatedly keep asking the user to enter a new password until it meets all conditions.
Example:
Output:
The above code is used to determine if a particular password is strong, meaning it has 8 or more characters, at least one digit, and at least one uppercase character. It is using a while(true) loop that will ask for a password over and over until a strong enough password is entered, checking the strength of the password with isStrongPassword, and the components of a string with isdigit() and isupper(); both functions are doing a character check.
Generate Fibonacci Sequence (Using While Loop)
This is a program to print the Fibonacci series of a number n. When we do that, we will be using while until we get a number greater than or equal to n. Each number generated sums the two numbers before it.
Example:
Output:
We add 0 and 1, then add 1 and 1, then 1 and 2, and keep going with the last two to find the next Fibonacci number. The while loop prints numbers until the Fibonacci number after the current one exceeds 20.
Conclusion
The while loop in C++ is a control statement that is used to execute a block of code repeatedly as long as the condition specified is true. It tests the condition before each loop iteration, so the loop body executes only if the condition is true. It’s particularly useful when you do not know in advance the number of iterations, e.g., User input, Processing Data Stream, Waiting for an event. In this guide, we’ve gone through the mechanics of while loops, including their syntax and their different parts, such as the test expression, the loop body, and the update expression.
C++ While Loops – FAQs
Q1. What is a while loop in C++?
A while loop executes a block of code as long as the condition is true.
Q2. When does a while loop terminate?
A while loop is executed as long as a condition is true.
Q3. Can a while loop run zero times?
Yes, when the initial condition is false, it will loop zero times.
Q4. How is a while loop different from a do-while loop?
A while loop verifies the condition; if the condition is true the first time, then the loop will be executed. A do-while loop checks the condition after the statements are processed.
Q5. Can you create an infinite while loop?
Yes, by setting the condition as always true, e.g, while(true).