Course Content
C++ Introduction
C++ Introduction
While Loop
Loops are programming constructs designed to repeatedly execute a block of code as long as a specified condition is met. They are essential for tasks that involve repetitive operations, such as iterating through data, performing calculations, or automating processes.
while
while (condition) { // If condition == true, then do_something; }
The program starts and checks the condition. If the condition is true, it executes the code inside the loop and then rechecks the condition. This process repeats until the condition becomes false, at which point the program exits the loop and stops.
main
#include <iostream> int main() { int currentBalance = 0; // Initial balance int monthlyDeposit = 500; // Fixed deposit amount int targetBalance = 5000; // Savings goal // Accumulate balance until it matches the target while (currentBalance < targetBalance) { currentBalance += monthlyDeposit; // Add deposit to balance } std::cout << "Final balance: $" << currentBalance << std::endl; }
The program starts with an initial balance, currentBalance
, set to 0
. A fixed deposit, monthlyDeposit
, is repeatedly added, increasing currentBalance
.
The loop runs until currentBalance
reaches or exceeds the target balance, targetBalance
. Once achieved, the loop ends, and a message confirms the savings goal. This demonstrates how consistent deposits can help achieve financial goals.
Note
The loop may not start if the condition is not satisfied.
It is crucial to make sure that the loop has an exit condition, that is, that the loop will not be infinite. The infinite loop example:
main
#include <iostream> int main() { bool condition = true; while (condition) { std::cout << "Loop is infinite!" << std::endl; } }
Thanks for your feedback!