Lesson 6.2

Goto Label in c# - with programming example


Objective

What is goto label keyword?
How it works?
Programming example of goto label keyword

What is goto label keyword?

Goto label is another kind of simple looping system in c# program. Goto keyword sends execution control to labeled statements. The goto keyword can send execution control to different case in a switch statements.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace goto_statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1, num2, result;
            //Label Created
            REPEAT:
            Console.WriteLine("Enter a number");
            num1=Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter second number");
            num2=Convert.ToInt32(Console.ReadLine());

            result = num1 + num2;
            Console.WriteLine("Add : " + result);

            Console.WriteLine("Do you want to add another value: press 1 for continue or press any key for exit");
            string option = Console.ReadLine();

            if (option == "1")
            {
                goto REPEAT; //Return program to label
            }
            else
            {
                Console.WriteLine("Press any key for Quit...");
                Console.ReadKey();
            }
        }
    }
}

Output

Enter a number
34
Enter second number
23
Add : 57

Do you want to add another value: press 1 for continue or press any key for exit
1

Enter a number
44
Enter second number
55
Add : 99

Do you want to add another value: press 1 for continue or press any key for exit
5

Press any key for Quit... __

Explanation:

In the above example, we created a label REPEAT which gets executed when goto keyword invoked. It is a simple program in which user enter two numbers for add. The program gives option to repeat process. If user wants to add another number the goto statement is invoked and send execution control to REPEAT label. If user presses any key the execution control goes to else block and program ends.

Summary

In this chapter you have learned how to use goto label in your program. The goto label is alternate loop control which works when goto statement is invoked. In the next chapter you will learn about break and continue keywords.

BackNext