For working professionals
For fresh graduates
More
4. C++ Variable
10. C++ for Loop
12. C++ Lambda
13. Loop in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
33. Iterators in C++
34. Queue in C++
36. Stack in C++
37. ifstream in C++
40. Templates in C++
43. Namespace in C++
46. Recursion in C++
48. C++ Shell
49. Setw in C++
51. Atoi in C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
68. C++ Comments
72. Sorting in C++
Repetition is often the key to solving problems efficiently. C++ offers us a versatile tool for this purpose, the while loop. This control structure empowers us to execute a block of code repeatedly as long as a specific condition holds true.
Unlike its for loop counterpart, the while loop in C++ is ideal for scenarios where the exact number of iterations isn't known in advance. In this tutorial, we will explore the core mechanics of the while loop as well as its syntax and usage. We will also discover how to wield it effectively to solve a variety of programming challenges in this guide.
The while loop in C++ allows us to create dynamic and responsive programs that react to changing conditions and user interactions. It is a very important type of loop in C++ programming that we always find ourselves using time and time again.
Unlike its loop companions (for, do-while, range-based for), the while loop thrives in scenarios where the exact number of repetitions is uncertain. We can think of it as a repetition that continues until any of its conditions are met.
The while loop in C++ continues executing its code block until the specified condition becomes false, making it ideal for tasks that require repetition until a particular goal is achieved or a certain state is reached.
Unlike the for loop, which often relies on a counter variable to dictate a fixed number of iterations, the while loop is more adaptable. It repeats a block of code as long as a given condition remains true. This makes it perfect for tasks like reading data from a file (continue until the end of the file) or handling user input (keep asking until valid input is received).
It is also very important to know that the while loop in C++ is a "pre-test" loop, meaning it checks the condition before each iteration. If the condition is initially false, the loop's body won't even execute once. This is like a detective who won't start investigating if there's no initial evidence to follow.
However, once it does start investigating, the loop will not stop until the case is closed.
The while loop has a straightforward structure:
while (condition) {
// Code block to be executed
}
Let's dissect each part of the structure:
+----------------+
| Condition |
+-------+--------+
|
v
|
+-------+--------+
| Code Block |
+-------+--------+
|
v
|
| Yes (true)
+---------------------+
| |
| No (false) |
| |
v |
+-----------------------------+
The condition part of a while loop is a boolean expression. These expressions can use a variety of operators:
Examples:
x < 10 (true if the value of x is less than 10)
isDone == false (true if the boolean variable isDone is false)
(age >= 18) && (hasLicense == true) (true if both conditions are met)
The curly braces {} are crucial for defining the scope of the while loop in C++. Any code within the braces is considered part of the loop's body and will be repeated.
If your while loop contains only a single statement, you can technically omit the curly braces. However, this is generally discouraged as it can lead to errors if you later add more statements to the loop.
Example:
while (x < 10)
x++; // Only this statement is part of the loop
y = x * 2; // This is outside the loop
When your C++ code is compiled, the while loop is translated into lower-level instructions, either assembly code for direct machine execution or bytecode for execution by a virtual machine (like the JVM or Java Virtual Machine).
Here's a simplified example of how a while loop might translate into assembly-like instructions:
; Initialization (Before the loop)
mov eax, 0 ; Initialize counter to 0
; Loop start
loop_start:
cmp eax, 5 ; Compare counter to 5
jge loop_end ; Jump to loop_end if counter >= 5
; Loop body
; (Instructions to print the counter and increment it)
inc eax ; Increment counter
jmp loop_start ; Jump back to loop_start
; Loop end
loop_end:
; (Rest of the program continues here)
The instruction pointer (IP) is a register within the CPU that keeps track of the memory address of the next instruction to be executed. In a while loop:
Now that we have explored what is looping in C++ with the while loop, let us look at some practical applications of the while loop in C++.
The while loop is our best friend when it comes to ensuring users provide valid input:
#include <iostream>
#include <limits>
int main() {
int age = 0;
while (true) {
std::cout << "Enter your age (0-120): ";
std::cin >> age;
if (std::cin.fail() || age < 0 || age > 120) {
std::cerr << "Invalid age. Please enter a number between 0 and 120.\n";
std::cin.clear(); // Clear error state
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Discard invalid input
} else {
break; // Valid input, exit loop
}
}
std::cout << "Your age is: " << age << std::endl;
}
This while loop in C++ example not only checks if the input is within a valid range but also handles cases where the user types in letters or symbols by using std::cin.fail(), std::cin.clear(), and std::cin.ignore().
If you wish to learn how to code in C++, you can check out upGrad’s software engineering courses.
Processing files line by line is a classic use case for while loops:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream myFile("data.txt");
std::string line;
while (std::getline(myFile, line)) { // Read until end of file (EOF)
// ... process each 'line' here ...
}
myFile.close();
}
Here, the while loop in cpp continues until getline() fails to read another line (reaching the end of the file).
Create a user-friendly menu with a C++ do while loop:
#include <iostream>
int main() {
int choice;
do {
std::cout << "\nMenu:\n1. Option 1\n2. Option 2\n0. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;
// ... handle the user's choice (switch statement or if-else chain) ...
} while (choice != 0);
}
In the above C++ do while example, we create an interactive menu with the help of the while loop.
Game engines use while loops to keep the game running until the player quits or some condition is met:
while (gameIsRunning) {
// Process input
// Update game state
// Render graphics
}
Infinite loops are a common pitfall with while loops. They occur when the loop's condition never becomes false, causing the code to repeat endlessly.
We should always ensure that something within the loop's body can eventually change the condition to false. If we want to intentionally create an infinite loop, we can use break with a well-defined exit condition. Be cautious with nested loops, as they can easily become infinite if not structured properly.
Forgetting to update the condition variable: Imagine a loop intended to count to 10. If you forget to increment the counter variable (i++), it will always remain at its initial value, leading to an infinite loop.
Incorrectly Structured Conditional Expressions
A simple typo in the comparison operator (e.g., using = instead of ==) can drastically change the loop's behavior. Complex logical conditions might have unintended side effects, keeping the condition perpetually true.
Here are two debugging strategies:
Nested while Loops
Nested loops involve one while loop placed inside the body of another. This allows you to handle more complex iterative tasks.
Structure and logic:
while (outerCondition) {
// ... outer loop code ...
while (innerCondition) {
// ... inner loop code ...
}
// ... more outer loop code ...
}
The inner loop completes its full set of iterations for each single iteration of the outer loop.
Examples:
Here are two real-world applications:
The while loop is one of the essential loops in C++ programming, enabling us to craft dynamic and responsive code. By understanding its syntax, behavior, and best practices, you've added a powerful tool to your programming arsenal.
Finally, we should always remember that careful condition management is crucial to avoid infinite loops, and employing techniques like nested loops or intentional infinite loops with break statements can further enhance the flexibility of your code. You can also explore the combination of C++ for while loop as well.
Now you should be well-equipped to harness the full potential of while loops to write elegant and efficient C++ programs. If you wish to learn programming languages such as C++, you can check out upGrad’s computer science programs such as the Master’s in Computer Science Program.
A while loop is a repetitive control structure that executes a block of code as long as a given condition remains true.
First, initialize a control variable, then use the while keyword followed by a condition in parentheses, and finally, the code block to be repeatedly enclosed in curly braces.
The loop's body will not execute even once.
Yes, if the condition never becomes false, the loop will run indefinitely.
You can exit a while loop either by making the condition false or using the break statement inside the loop.
Yes, you can have a while loop inside another while loop (nested loops).
Here is the while statement C++:
while (condition) {
// Code block to be executed repeatedly
}
Yes, C++ offers other loops like for loops (for known iterations) and do-while loops (execute at least once). You can also use recursion or standard library algorithms in some cases.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.