Break and Continue Statement in C++

In C++ programming, break and continue statements are used inside loops and switch statements to manipulate the normal execution of the loop and switch statements.

C++ Break Statement.

A break statement is used to bring the control of the program out of the loop. It is basically used to jump out of a running loop. 

syntax: break;


Flowchart of a break statement.

break statement flowchart
break statement Flowchart

Example:
//C++ Example of break statement
#include<iostream>
using namespace std;

int main(){

    cout<<"Print number using for loop"<<endl;
    for(int i = 0; i <= 10; i++){
        if(i == 5){
            break;
        }
        cout<<i<<" ";
    }

    int i = 1;
    
    cout<<"\nPrint number using while loop"<<endl;
    while(i <= 10){
        if(i == 4){
            break;
        }
        cout<<i<<" ";
        i++;
    }
    return 0;
}
Output:
Print number using for loop
1 2 3 4
Print number using while loop
1 2 3

Here in the above example, you can see that both the loop condition is written for printing value from 1 to 10 but both programs jump out of the loop as soon as the break condition is satisfied. 

C++ Continue statement.

The continue statement is used to skip the current iteration of the loop if the specified condition is true and continue with the next iteration of the loop. 
syntax: continue;

Flowchart of a continue statement.

continue flowchart
continue Flowchart
Example:
//C++ Example of continue statement
#include<iostream>
using namespace std;

int main(){

    for(int i = 1; i <= 10; i++){
        if(i == 5){
            continue;
        }
        cout<<i<<" ";
    }

    return 0;
}
Output:
1 2 3 4 6 7 8 9 10

Here, if you observe the output then you can see that value 5 is not printed by the loop because that condition is evaluated true for the continue statement so it skips the remaining part of the code and moves to the next iteration.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS