C++Tutorials

C++ goto control statement

In this article, we will learn about c++ goto control statement, want’s to know about the control statement click here.

Before moving forward I want to recap that control statement has two types-:

  1. Conditional Statement
  2. Unconditional Statement

If you want to know what is a conditional statement, click here .

The C++ goto statement is also known as the jump statement. It is used to transfer control to the other part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from the deeply nested loop or switch case label.

Syntax of goto Statement

goto label;
... .. ...
... .. ...
... .. ...
label: 
statement;
... .. ...

C++ Goto Statement Example

Let’s see the simple example of goto statement in C++.

#include <iostream>  
using namespace std;  
int main()  
{  
ineligible:    
         cout<<"You are not eligible to vote!\n";    
      cout<<"Enter your age:\n";    
      int age;  
      cin>>age;  
      if (age < 18){    
              goto ineligible;    
      }    
      else    
      {    
              cout<<"You are eligible to vote!";     
      }         
}  

Output:

You are not eligible to vote!
Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!

Another example of goto statement to check number is evern or not

// C++ program to check if a number is 
// even or not using goto statement 
#include <iostream> 
using namespace std; 
  
// function to check even or not 
void checkEvenOrNot(int num) 
{ 
    if (num % 2 == 0) 
    // jump to even 
        goto even;  
    else
    // jump to odd 
        goto odd;  
  
even: 
    cout << num << " is even"; 
    // return if even 
    return;  
odd: 
    cout << num << " is odd"; 
} 
  
// Driver program to test above function 
int main() 
{ 
    int num = 26; 
    checkEvenOrNot(num); 
    return 0; 
} 

Output:

26 is even

Program to print number from 1 to 10 using goto statement

// C++ program to print numbers 
// from 1 to 10 using goto statement 
#include <iostream> 
using namespace std; 
  
// function to print numbers from 1 to 10 
void printNumbers() 
{ 
    int n = 1; 
label: 
    cout << n << " "; 
    n++; 
    if (n <= 10) 
        goto label; 
} 
  
// Driver program to test above function 
int main() 
{ 
    printNumbers(); 
    return 0; 
} 

Output

1 2 3 4 5 6 7 8 9 10

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button