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. Variables and Data Types
3. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions

bookWhile Loop

We used if...else, switch-case to compare our variables with other values. But what if we need to do something a hundred times? A thousand times? A million times?

Loops are designed for just such cases! It allows you to loop your program under certain conditions. Structure of while loop:

cpp

main

copy
1234567891011121314151617
#include <iostream> int main() { //x + y = result int x = 0; //root of equation int y = 8; int result = 1000; //increase x, until it satisfies the equation while (y + x != result) { x += 1; //x = x + 1 } std::cout << "Root of the equation: " << x; }

We have summed up (x+=1) 992 times in this case. The loop ran while x + y was not equal to result (1000).

As soon as the expression x + y became equal to result, the loop ended, and we got the root of the equation (х).

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
some-alt