Sunday 22 October 2017

Jump Statement:Break,Go To and Continue statement

JUMP STATEMENTS

Jump statements are used to interrupt the normal flow of the program or you can say that the jump statements are used to jump a particular statement or piece of code.

Types of jump statements:-
  • Break
  • Continue 
  • GoTo
BREAK STATEMENT:-

The break statement is used inside the loop or switch case.It is used to come out from the loop or switch case.When we use break statement it terminates the loop or switch case and shows the result.

Syntax:-
.....
.....
break;
To check how break statement works?click here

CONTINUE STATEMENT:-

Continue statement is used inside the loop.This statement is used to skip a particular part of the code and resume the loop.

Syntax:-
while(test Expression) //you can use for loop and do while loop 
{
//codes
if(condition for continue)
{
 continue;
}
//codes
}
Program to print reverse numbers from 10 to 1 except 5:-
#include<iostream>
using namespace std;

 int  main()
{
    for(int n=10;n>=1;n--)
   {
        if(n==5) continue;
        cout<<"\n"<<n;
    }
    return 0;
}
Output:
10
9
8
7
6
4
3
2
1

The above program print numbers from 10 to 1 except 5 because we use continue statement when n==5 that means it will skip 5 and print remaining numbers.

GO TO STATEMENT:-

GoTo statement is another type of jump statement. it can be used to jump from anywhere to anywhere within in the function, sometimes it is also referred as an unconditional jump statement.

Syntax:-
goto label;
.
.
.
label:

Or
label:
.
.
.
goto label;
The label is an identifier.When goto statement is encountered, control of the program jumps to label: and start executing the code.

Program to print the square of positive numbers:-

#include<iostream>
#include<conio.h>
using namespace std;

int main ()
{
    int n;
    float result;
start:
    cout<<"Enter any no:";
    cin>>n;
    if(n<=0)
    {
        goto start;
    }
    else
    {    
        result =n*n;
        cout<<"Square is :"<<result;
   }
    return 0;
}
Output:-
Enter any no:-1
Enter any no:0
Enter any no:2
Square is :4
In the above program, whenever the number is less or equal to zero, it will jump to start statement and ask to enter the number again when the number is greater than zero, it shows the result. 

NOTE: Avoid use of GoTo Statement because it makes the program logic very complex and difficult to modify.

you can use continue and break statement instead of GoTO statement.

Whether you use GoTO statement or not....
If the use of GoTo statement makes your program simpler than you should use it else avoid it.

KEEP CODING....





1 comment: