***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Monday, April 26, 2021

goto statement, continue and break

Goto Statement

A goto statement provides an unconditional jump from the goto to a labeled statement in the same function.

NOTE: Use of goto statement is highly discouraged because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.

Syntax:

The syntax of a goto statement in C++ is:

goto label;

... .. ...

label:

statement;

Example program:

#include <iostream.h>

#include<conio.h>

void main ()

{

int num = 1;

STEP:

do

{

if( num = = 5)

{

num = num + 1;

goto STEP;

}

cout << "value of num : " <<num<<”\n”;

num = num + 1;

}while( num < 10 );

}

Out put:

value of num : 1

value of num : 2

value of num : 3

value of num : 4

value of num : 6

value of num : 7

value of num : 8

value of num : 9


Break Statement

The break statement has the following two usages in C++:

1. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.

2. It can be used to terminate a case in the switch statement.


Example program:

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int i=0;

while(i<=10)

{

if(i==5)

break;

cout<<"\n"<<i;

i++;

}

getch();

}

 

Output:

0

1

2

3

4

If i= =5 the control get out of the while loop, hence program will  print upto 4 only.


Continue Statement

The continue statement forces the next iteration of the loop to take place, skipping remaining code in between.

In the case of the for loop as soon as after the execution of continue statement, increment/decrement statement of the loop gets executed. After the execution of increment statement, condition will be checked.

In case of the while loop, continue statement will take control to the condition statement.

In case of the do..while loop, continue statement will take control to the condition statement specified in the while loop.


Example program:

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int i;

for(i=0;i<=10;i++)

{

if(i==5)

continue;

cout<<"\n"<<i;

}

getch();

}

 

Output:

0

1

2

3

4

6

7

8

9

10

If i= =5 , compiler stops the execution and controls goes to increment/decrement statement of the loop gets executed.

No comments:

Post a Comment