Jump
statements
Jump
statements are used to interrupt the normal flow of program. Types of Jump
Statements are
•
goto statement
•
break statement
•
continue statement
The
goto statement is a control statement which is used to transfer the control
from one place to another place without any condition in a program.
The
syntax of the goto statement is;
In
the syntax above, label is an identifier. When goto label; is encountered, the
control of program jumps to label: and executes the code below it.
#include <iostream>
using namespace std;
int main()
{
float num, average, sum = 0.0;
int i, n;
cout<< "Maximum number of inputs: ";
cin>> n;
for(i = 1; i<= n; ++i)
{
cout<< "Enter n" <<i<< ":
";
cin>>num;
if(num< 0.0)
{
// Control of the program move to jump: goto jump;
}
sum += num;
}
jump:
average = sum / (i - 1);
cout<< "\nAverage = " << average; return
0;
}
Maximum number of inputs: 5
Enter n1: 10
Enter n2: 20
Enter n3: -2 Average = 15
In the above program the average of numbers entered by the
user is calculated. If the user enters a negative number, it is ignored the
average of numbers entered. Until that point is calculated.
A
break statement is a jump statement which terminates the execution of loop and
the control is transferred to resume normal execution after the body of the
loop. The following Figure. shows the working of break statement with looping
statements;
#include <iostream>
Using namespace std;
int main ()
{
int count = 0;
do
{
cout<< "Count : " << count <<endl;
count++;
if( count > 5)
{
break;
}
}while( count < 20 );
return 0;
}
Count : 0
Count : 1
Count : 2
Count : 3
Count : 4
Count : 5
In
the above example, while condition specified the loop will iterate 20 times
but, as soon as the count reaches 5, the loop is terminated, because of the
break statement.
The
continue statement works quite similar to the break statement. Instead of
terminating the loop (break statement), continue statement forces the loop to
continue or execute the next iteration. When the continue statement is executed
in the loop, the code inside the loop following the continue statement will be
skipped and next iteration of the loop will begin.
The
following Figure describes the working flow of the continue statement
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i<= 10; i++) {
if (i == 6)
continue;
else
cout<<i<< " ";
}
return 0;
}
1 2 3 4 5 7 8 9 10
In
the above example, the loop will iterate 10 times but, if i reaches 6, then the
control is transferred to for loop, because of the continue statement.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.