Introduction

To stop a program from running normally, use a jump statement. 4 Types of Jump statements are:

  1. goto
  2. break
  3. continue
  4. return

Let's examine each of them individually.

goto statement

A control statement called a "goto" is used to move the focus of a program's attention from one location to another without imposing any conditions. The goto statement's syntax is as follows:

goto label;

..

label: statement;

An identifier is a label in the previous syntax. The program's control goes to label: and runs the code there when the goto label; is encountered

C++ script that uses the goto instruction to compute the average of two values.

#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;
}

Output

Maximum number of inputs: 5

Enter n1: 10

Enter n2: 20

Enter n3: -2 Average = 15

write your code here: Coding Playground

The average of the user-inputted integers is determined in the above code snippet. The average of the entered numbers is disregarded if the user submits a negative value. up until a calculation of that moment.

Break statement

A break statement, also known as a jump statement, stops the execution of a loop and transfers control so that the loop's body may continue normally.

N number count in C++ using break statement

#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;
}

Output

Count : 0

Count : 1

Count : 2

Count : 3

Count : 4

Count : 5

write your code here: Coding Playground

In the aforementioned example, the loop will cycle 20 times under the while condition, but the break statement will force the loop to end once the count hits 5.

Continue statement

Similar to how the break statement functions, the continue statement also does. The continue statement compels the loop to continue or carry out the subsequent iteration as opposed to ending it (the break statement does that). The code inside the loop that comes after the continue statement is skipped whenever the continue statement is used in a loop, and the subsequent iteration of the loop then starts.

C++ script using continue statement to display numbers upto 10 except 6

#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i<= 10; i++) {
if (i == 6)
continue;
else
cout<<i<< " ";
}
return 0;
}


Output

1 2 3 4 5 7 8 9 10


write your code here: Coding Playground

The loop iterates 10 times in the example above, but due to the continue expression, if i reaches 6, control is passed to the for loop.

To check out similar topics and questions, do visit our Discussion Forum.