Goto statement in C#
Dec 25, 2020 07:49 0 Comments C# (C-Sharp) PARTH

                     Goto statement in C#  

The goto statement is used to transfer the flow of the program directly to the statement mentioned against it. These statements move the control of the program to other parts of the program. The goto statement is also known as the Jump statement. One of the most common applications of the goto statement is to move the control of the program to a specific point in the switch statements.

Syntax:

goto statementname;

The syntax begins with declaring the goto keyword followed by the statement name. When in the program, whenever this line is to be executed, the program will jump on to the “statementname” specified against the goto statement.   Flow of goto statement  Let us understand the flow of goto statement with the help of a simple example (flowchart) – If we refer to the above flowchart, we can get the idea about the code flow of a program using the goto statement. We have three statements, statement 1, statement 2 and statement 3, and as the code moves ahead, it comes in contact with the goto statement in statement 3. And from statement 3, the code will jump to wherever the goto statement is pointing. In our example, we have our goto statement referring to statement 1 which means when the code comes on goto statement during the flow, it will check for condition and based on the result of the condition the code will continue moving forward, which means it will go to the end of the program or the goto statement will be executed and the code will make the jump.   Example - Let us see how to implement the goto statement in C# code using an example –

using System;

public class Program

{

public static void Main(string[] args)

{

passed: Console.WriteLine("You have passed the exam”);

Console.WriteLine("Enter your score");

int score = Convert.ToInt32(Console.ReadLine());

if (score >= 40)

{

goto passed;

}

else

{

Console.WriteLine("You have failed. Please try again.");

Console.ReadLine();

}

}

}

Output – You have passed the exam   Enter your score 45 You have passed the exam   Enter your score 39 You have failed. Please try again.

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect