Loops in programming are used to calculate a piece of code multiple times. Here, we will see the difference between two types of loops in the program, For loop and While loop.
The For loop is a repetitive control loop that allows the user to loop through a given block of code a specific number of times.
for(initisation; condition; update){ …code to be repeated }
While loop is an entry control loop that allows the user to repeatedly execute a given statement until a given condition is true.
while(condition){ …code to be repeated }
For loop is a controlled loop, while while loop is a conditional loop
Control loop.
The conditional statement of the for loop allows the user to add an update statement in it, while in the while condition there is only control The expression can be written as.
In a for loop, the test condition is usually an integer comparison, whereas in a while loop, the test condition can be any other expression that evaluates to a Boolean value.
Case in which two loops in the code can provide different solutions
One situation is when the loop body contains a In while loop, continue statement before update statement, but in for loop The update statement already exists in initialization.
Procedural example to illustrate how our solution works: (for loop)
#include<iostream> using namespace std; int main(){ cout<<"Displaying for loop working with continue statement\n"; for(int i = 0; i < 5; i++){ if(i == 3) continue; cout<<"loop count "<<i<<endl; } return 0; }
Displaying for loop working with continue statement loop count 0 loop count 1 loop count 2 loop count 4
Program to demonstrate how our solution works: (while loop)
#include<iostream> using namespace std; int main(){ cout<<"Displaying for loop working with continue statement"; int i = 0; while(i < 5){ if(i == 3) continue; cout<<"loop count "<<i<<endl; i++; } return 0; }
Displaying for loop working with continue statementloop count 0 loop count 1 loop count 2
The above is the detailed content of In C++, 'for' and 'while' have different uses. For more information, please follow other related articles on the PHP Chinese website!