Break-Statement-In-C++ .

In this session i have discussed break statement in C++ .


The break is a keyword in C++ which is used to break the loop . It is also used in switch case to break the case . If you will use the break in inner loop then it will terminate the inner loop only .

Example : Write a program that will demonstrate the break statement in loop .

    #include<iostream>
    using namespace std;  
    int main()
    {          
            int i;
            for(i=1;i<10;i++)
            {
                cout<<i;
                cout<<" ";
                if(i==6)
                {
                    break;
                }
            }
            cout<<"Out of loop i="<<i;
            return 0;
    }
    
    OUTPUT : 1 2 3 4 5 Out of loop i=6
    

Example : Write a program that will demonstrate the break statement in nested loop .

    #include<iostream>
    using namespace std;  
    int main()
    {          
        int i=1,j=1;
        for(i=1;i<=3;i++)
        {
            for(j=1;j<=3;j++)
            {
                cout<<"\n"<<i<<j;
                if(i==2 && j==2)
                {
                    break;//will break inner loop  only
                }
            }//end of for loop
        }
        return 0;
    }
    
    OUTPUT : 1 1
             1 2
             1 3
             2 1
             2 2
             3 1 
             3 2
             3 3
    


Example : Write a program that will demonstrate the break statement in switch .

    #include<iostream>
    using namespace std;  
    int main()
    {          
            int i ,x,y,result;
            i=2;
            switch(i)
            {
                case 1:
                {
                    cout<<"Enter the value for x :";
                    cin>>x;
                    cout<<"Enter the value for y :";
                    cin>>y;
                    int sum=x+y;
                    cout<<"Sum="<<sum;
                    break;
                }
                case 2:
                {
                    cout<<"Enter the value for x :";
                    cin>>x;
                    cout<<"Enter the value for y :";
                    cin>>y;
                    int sub=x-y;
                    cout<<"Sub="<<sub;
                    break;
                }
                case 3:
                {
                    cout<<"Enter the value for x :";
                    cin>>x;
                    cout<<"Enter the value for y :";
                    cin>>y;
                    int mul=x*y;
                    cout<<"Mul="<<mul;
                    break;
                }
                default :
                {
                    cout<<"Invalid number";
                    break;
                }
            }
            return 0;
    }
    
    OUTPUT : Enter the value for x : 20
             Enter the value for y : 10
             Sub=10
    

Welcome to AndroidATPoint.

back image                     next image