Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
While Loop | Introduction to Program Flow
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Introduction to Operators
3. Variables and Data Types
4. Introduction to Program Flow
5. Introduction to Functions

bookWhile 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.

h

while

copy
1234
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.

cpp

main

copy
12345678910111213141516
#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:

cpp

main

copy
1234567891011
#include <iostream> int main() { bool condition = true; while (condition) { std::cout << "Loop is infinite!" << std::endl; } }
Choose the correct version of the while loop.

Choose the correct version of the while loop.

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 4
We're sorry to hear that something went wrong. What happened?
some-alt