Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda While Loop | Loops
Introduction to C++ | Mobile-Friendly

book
While Loop

What is a loop in C++? It’s a cycle which repeats until the certain condition is true.

For example, one of the most popular loops is while:

python
while (condition) {
// Code here will be executed while the condition is true
}

As long as the specified condition is true we repeat doing the code in the while cycle. When the condition becomes false, the program starts to execute the line that follows this loop. An example of the while loop:

int i = 0;
while (i < 3) {
&nbsp;&nbsp;&nbsp;&nbsp; i ++;
&nbsp;&nbsp;&nbsp;&nbsp; cout << i << endl;
}
12345
int i = 0; while (i < 3) { &nbsp;&nbsp;&nbsp;&nbsp; i ++; &nbsp;&nbsp;&nbsp;&nbsp; cout << i << endl; }
copy

Initially, we declare the variable i as 0. Then the while loop checks the condition (i < 3) by each iteration and if the statement is true, we increment the variable i and print it. By the third iteration, i becomes 3 and the program doesn’t execute the code in the while loop again since the condition is false.

You can also use the while loop to interact with the user’s input or do something certain number of times. For example, calculate the sum of 3 user’s inputs:

python
// Declare variables
int i = 0;
int sumInputs = 0;
int number;

// Calculate the sum
while (i < 3){
cout << "Enter the number:";
cin >> number;
sumInputs += number;
i++;
}

// Print the result
cout << "The sum of your numbers is " << sumInputs;

By each iteration we add the user’s input number to the variable sumInputs - our sum and increment i since to execute the code in the block 3 times.

Be careful writing the loops! Increase/decrease the value in the condition or your loop will never end!

question mark

In the while loop we repeat doing the code during the time...

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 1

Pergunte à IA

expand
ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

We use cookies to make your experience better!
some-alt