The goto statement in C++ programming is used to change the normal sequence of program execution by transferring control to another part of the program.
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
The label seems to be an identifier in the above-given syntax. When the command goto label; is encountered, the program's control jumps to label: and will execute the code given below it.
The fig shows the working of goto in C++
let us write a program that will calculate the average of numbers that is entered by the user.
suppose If the user enters a number that is negative, it will surely ignore the number and will calculate the average number which was entered before 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;
}
Output:
Average = -nanMaximum number of inputs: 3 Enter n1: 1 Enter n2: 2 Enter n3: 3 Average = 2
Goto statements are optional in C++ programming, and it is generally recommended to avoid using them.