C# program to demonstrate the example goto statement

Here, we are going to learn about the goto statement and its C# implementation.
Submitted by Nidhi, on September 10, 2020

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

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.