Home  >  Article  >  Backend Development  >  In C++, 'for' and 'while' have different uses

In C++, 'for' and 'while' have different uses

王林
王林forward
2023-08-28 13:01:14803browse

In C++, for and while have different uses

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.

For 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.

Syntax

for(initisation; condition; update){
   …code to be repeated
}

While loop

While loop is an entry control loop that allows the user to repeatedly execute a given statement until a given condition is true.

Grammar

while(condition){
   …code to be repeated
}

The difference between For loop and While loop

  • 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.

    Example

    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;
    }

    Output

    Displaying for loop working with continue statement
    loop count 0
    loop count 1
    loop count 2
    loop count 4

    Example

    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;
    }

    Output

    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!

    Statement:
    This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete