Goto statement:
The goto statement is a control statement that is used to transfer the control from one place to another place without any condition in a program.
Flow chart:
Example of goto statements:
C++ Code
#include<iostream>
using namespace std;
void goto_statement() {
cout << "ONE" << '\n';
goto label;
cout << "TWO" << '\n';
cout << "THREE" << '\n';
label:
cout << "FOUR" << '\n';
}
int main() {
goto_statement();
return 0;
}
Output:-
ONE
FOUR
Explanation:- In the above program, the first cout statement(ONE) has been executed and after that line goto statement tells the compiler to go to the statement marked as a label in this way control is transferred label statement.
Problem statement:- program to display the first 5 odd numbers using the goto statement in c++
Code:
C++ Code
# include <iostream>
using namespace std;
void goto_statement() {
int n = 1;
cout << "first 5 odd numbers are:- ";
jump: {
if (n < 10) {
// Control of the program move to jump:
cout << n << " ";
n += 2;
goto jump;
}
}
}
int main() {
goto_statement();
return 0;
}
Output:- first 5 odd numbers are:- 1 3 5 7 9
Explanation:- In the above program the first 5 odd numbers are displayed. if n is less than 10 goto statement transfers the control to the jump statement. If n is greater than 10 the control comes out of the loop.
Disadvantages of goto statement:-
- If we increase the goto statement in a program the tracing becomes difficult.
- Since goto is an unconditional statement, the efficiency of the program reduces by moving the control from one point to another unconditionally.
- By using break and continue statements we can reduce the usage of goto statements.
Special thanks to JAIGANESH R S for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article