Hi there, we’re Harisystems
"Unlock your potential and soar to new heights with our exclusive online courses! Ignite your passion, acquire valuable skills, and embrace limitless possibilities. Don't miss out on our limited-time sale - invest in yourself today and embark on a journey of personal and professional growth. Enroll now and shape your future with knowledge that lasts a lifetime!".
For corporate trainings, projects, and real world experience reach us. We believe that education should be accessible to all, regardless of geographical location or background.
1C++ While Loop
In C++, the while loop provides a way to repeatedly execute a block of code as long as a specified condition is true. It allows you to automate repetitive tasks and control the flow of your program based on dynamic conditions. In this article, we will explore the usage of the while loop in C++ with examples.
1. Basic While Loop
The basic syntax of a while loop consists of the while keyword followed by a condition in parentheses. The code block within the while loop is executed as long as the condition evaluates to true. Here's an example:
#include <iostream>
int main() {
int count = 0;
while (count < 5) {
std::cout << "Count: " << count << std::endl;
count++;
}
return 0;
}
In the above code, the while loop continues to execute as long as the value of count
is less than 5. The variable count
is incremented within the loop, and the count value is displayed on the console.
2. Infinite Loop
You can create an infinite loop by omitting the condition or by using a condition that always evaluates to true. Here's an example of an infinite loop:
#include <iostream>
int main() {
while (true) {
std::cout << "This is an infinite loop." << std::endl;
}
return 0;
}
In the above code, the condition true
always evaluates to true, resulting in an infinite loop. To terminate an infinite loop, you can use a break statement or other control flow statements within the loop.
3. While Loop with User Input
The while loop is commonly used when reading user input until a specific condition is met. Here's an example:
#include <iostream>
#include <string>
int main() {
std::string password;
while (password != "secret") {
std::cout << "Enter the password: ";
std::cin >> password;
}
std::cout << "Access granted!" << std::endl;
return 0;
}
In the above code, the while loop continues to prompt the user to enter a password until the entered password matches the string "secret". Once the condition is met, the loop is terminated, and the message "Access granted!" is displayed.
The while loop is a powerful construct in C++ that allows you to repeat a block of code based on a specified condition. Use it to automate repetitive tasks, read user input, and perform actions as long as certain conditions are met. Exercise caution to avoid infinite loops by ensuring that the condition eventually becomes false.