goto Example in C#

Here, we are going to learn about the goto statement and its C# implementation. By Nidhi Last updated : April 15, 2023

goto Statement

The goto statement is used to transfer the control of the program from the current position to the specific label.

C# program to demonstrate the example goto statement

The source code to demonstrate the goto statement is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the goto statement.
using System;

public class Program
{
    public static void Main(string[] args)
    {
        int number=0;
        int power=0;
        int result = 0;
        int choice = 0;
    LOOP_LABEL:

        Console.Write("Enter number: ");
        number = int.Parse(Console.ReadLine());

        Console.Write("Enter power: ");
        power  = int.Parse(Console.ReadLine());

        result = (int)Math.Pow(number, power);

        Console.WriteLine("Result : " + result);

        Console.WriteLine("Do you want to calculate power again?? Press 1 for Yes, Press 2 for No: ");
        choice = int.Parse(Console.ReadLine());

        if (choice == 1)
            goto LOOP_LABEL;
       
    }
}

Output

Enter number: 4
Enter power: 3
Result : 64
Do you want to calculate power again?? Press 1 for Yes, Press 2 for No:
1
Enter number: 2
Enter power: 3
Result : 8
Do you want to calculate power again?? Press 1 for Yes, Press 2 for No:
2
Press any key to continue . . .

Explanation

In the above program, we created a Program class that contains the Main() method. In the Main() method we created some local variables and we defined a label LOOP_LABEL.  Then read the value of the variable number and power and then calculated the power.

After that we asked to question to the user to execute the same block of code again, if the user pressed 1 then we transferred the control of the program from the current position to the labeled position. If the user pressed a value other than 1 then the program gets terminated.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.