Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to break out of nested for loops in C#

3 Answers

0 votes
using System;

class Program
{
    static void Main() {
        bool stop = false;
        
        for (int i = 1; i <= 30 && !stop; i++) {
            for (int j = 0; j < 5; j++) {
                if (i == 4) {
                    stop = true;
                    break;
                }
                Console.Write(j + " ");
            }
            Console.WriteLine();
        }
 
        Console.WriteLine("After loops");
    }
}



/*
run:

0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 

After loops

*/

 



answered Sep 7, 2022 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        for (int i = 1; i <= 30; i++) {
            for (int j = 0; j < 5; j++) {
                if (i == 4) {
                    goto ENDLOOPS;
                }
                Console.Write(j + " ");
            }
            Console.WriteLine();
        }
 
  ENDLOOPS:
        Console.WriteLine("\nAfter loops");
    }
}



/*
run:

0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 

After loops

*/

 



answered Sep 7, 2022 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        try {
            for (int i = 1; i <= 30; i++) {
                for (int j = 0; j <= 5 - 1; j++) {
                    if (i == 4)
                        throw new Exception("");
                    Console.Write(j + " ");
                }

                Console.WriteLine();
            }
        }
        catch {
            Console.WriteLine("");
        }
        
        Console.WriteLine("After loops");
    }
}





/*
run:

0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 

After loops

*/

 



answered Sep 7, 2022 by avibootz

Related questions

3 answers 215 views
3 answers 173 views
3 answers 185 views
2 answers 175 views
4 answers 231 views
2 answers 154 views
2 answers 153 views
...