Loop Syntax
A loop repeatedly executes a set of statements until a specific condition is met.
In C++, the while loop: as long as the condition is true, the while loop will repeatedly execute a set of statements until a certain specific condition is satisfied.
Syntax:
while (condition) { // Loop body, statements to be repeated}
The loop continues to execute while the condition is true.
When the condition is false, the statements inside the while loop are not executed.
while Loop
The loop body is the block of statements within the braces.
For example:
int num = 1;while (num < 6) { // Loop block cout << "Number: " << num << endl; num = num + 1;}
The above example declares a variable equal to 1 (int num = 1).
The while loop checks the condition (num < 6) and executes the statements in its body, incrementing the value of num by 1 each time the loop runs.
After the 5th iteration, num becomes 6, the condition evaluates to false, and the loop stops running.
For example:
Print the value of variable x to the screen 5 times.
int x = 1;while (x <= 5) { cout << "value is " << x << endl; x = x + 1;}
while Loop
Note that the variable values in the condition expression can change.
If changed, the number of times the loop runs will also change.
#include <iostream>using namespace std;int main(){ int num = 1; // Condition variable num while (num < 6) { cout << "Number: " << num << endl; // Increment num by 3 in the loop body num = num + 3; } return 0;}
If the loop condition remains true, the loop will continue indefinitely.
For example:
The given program outputs all numbers from 0 to 20.
Please modify the code to output only the multiples of 3.
Note, do not output 0.
#include <iostream>using namespace std;int main(){ int num = 1; while(num <= 20){ if(num % 3 == 0){ cout <<num <<endl; } num+=1; } return 0;}
For example:
Increment the value of variable bacon by 2 each loop and output it, stopping when it equals 20.
int bacon = 0;while (bacon <= 20) { cout << "bacon is " << bacon << endl; bacon = bacon + 2;}