In programming, loops are used to repeatedly execute the same block of code multiple times as long as the given condition is true. In C++, we have three types of loops and these are:
- while loop
- do...while loop
- for loop
Here in this post, we are going to discuss while loop in detail.
C++ While Loop.
While loop is used to execute the same block of code repeatedly as long as the specified condition is true. While loop is an entry control loop which means it checks the condition each time before entering the loop.
While loops are used when we don't know the exact count of how many times the loop is going to run. (alert-passed)
while loop syntax:
while (condition){ //code block }
Here the while loop evaluates the specified condition and if the condition is true then it will execute the block of code present inside the body of the while loop. While the loop will check the condition each time before executing the code block and this process continues until the condition become false. (alert-success)
![]() |
Flowchart of while loop in C++ |
C++ Example: Program to print the first five natural numbers.
//C++ Example of while loop to print 5 number #include<iostream> using namespace std; int main(){ int i = 1; //while loop while(i <= 5){ cout<<i<<" "; i++; } return 0; }
1 2 3 4 5
Here in this program, we are executing the code block and printing natural numbers as long as the value of variable i is less than or equal to 5.
Warning: Never write a condition for your loop that will be always evaluated as true else your loop will keep on running for infinite times until your memory gets full. (alert-warning)
Few example programs:
No comments:
Post a Comment