How to use goto to break out from for loop in C#

2 Answers

0 votes
using System;

class Program
{
    static void Main() {
        int[] arr = { 6, 8, 2, 1, 0 };
        
        foreach (int n in arr) {
            if (n == 2)
                goto Found;
        }
        
        Console.WriteLine("Not found");
        goto Finish;

    Found:
        Console.WriteLine("Found");

    Finish:
        Console.WriteLine("End of program");
    }
}



/*
run:

Found
End of program

*/

 



answered Nov 25, 2020 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        int[] arr = { 6, 8, 2, 1, 0 };
        
        foreach (int n in arr) {
            if (n == 99)
                goto Found;
        }
        
        Console.WriteLine("Not found");
        goto Finish;

    Found:
        Console.WriteLine("Found");

    Finish:
        Console.WriteLine("End of program");
    }
}



/*
run:

Not found
End of program

*/

 



answered Nov 25, 2020 by avibootz

Related questions

2 answers 214 views
1 answer 134 views
3 answers 216 views
216 views asked Sep 7, 2022 by avibootz
1 answer 109 views
109 views asked Nov 22, 2020 by avibootz
1 answer 232 views
1 answer 157 views
157 views asked May 16, 2015 by avibootz
...