C++ Jump Statements

Jump statements unconditionally transfer the program control within a function. C++ has various statements that unconditionally branch i.e goto, break, and continue.

C++ Break

Break is a jump statement that is used to omit a part of the code. The break statement is used to terminate the smallest enclosure. It is used to jump out of a loop (for, while, do-while).

Example :

for (int i = 0; i < 5; i++)
{
if (i == 4)
{
break;
}
cout << i << "\n";
}


Output :

0
1
2
3

C++ Continue

Continue is another jump statement, it is used to skip a part of the code. The Continue statement is used to skip one iteration.

This example skips when the value of i is 3:

Example :

for (int i = 0; i < 5; i++)
{
if (i == 3)
{
continue;
}
cout << i << "\n";
}


Output :

0
1
2
4

C++ Goto

A goto statement is used to transfer control of the program to anywhere in the program. The target destination is marked by a label. The syntax of goto statement is:

Syntax :

goto label;
.
.
.
label:


where label is a user supplied identifer.

Example :

a=0;
start:
cout<<"\n"<<++a;
if(a<50)goto start;


This will print number from 1 to 50.

Exercise:-

1. Which keyword is used to come out of a loop only for that iteration?

A. break
B. continue
C. return
D. none of the mentioned

View Answer


2. Which one is not a jump statement?

A. for
B. goto
C. continue
D. break

View Answer



Program :-

A program to add the factors of a number

#include <iostream>
using namespace std;
int main ( )
{
int x=0, y, sum=0;
cout«"Enter a number: ";
cin>>y;
while(l)
{
x++;
if (x>y)
break;
if(y%x!=0)
continue;
sum=sum+x;
}
Cout<<"\n Sum of factors: "<< sum;
return 0;
}


Output :

Enter a number: 8
Sum of factors: 15





Visit :


Discussion



* You must be logged in to add comment.