Priniting numbers using break and continue in C++


By using break,you can force immediate termination of a loop, bypassing the conditional expression and any remaininh code in the body of the loop.When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.

The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop.

This C++ program uses a for loop to iterate from 0 to 9 (inclusive) and print the values of the loop variable i, except when i equals 4. When i equals 4, the loop is exited prematurely using the break statement. Here's a breakdown of the program's logic:

  • The program starts executing from the main() function.
  • A for loop is used to iterate from 0 to 9 (inclusive).
  • For each iteration of the loop, the value of the loop variable i is printed to the console using cout.
  • If the value of i equals 4, the loop is exited prematurely using the break statement.
  • After the loop is exited, the program returns 0 to indicate successful completion.

Source Code

#include<iostream>
using namespace std;
int main()
{
    for(int i=0;i<10;i++)
    {
        if (i==4)
        {
            break;
        }
        cout<<i<<"\n";
    }
    return 0;
}
To download raw file Click Here

Output

0
1
2
3


Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples