Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Loop Controls in C#
2.1.
Goto 
2.2.
Break
2.3.
Continue 
2.4.
Return
2.5.
Throw
3.
FAQs
4.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Loop Controls in C#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Control statements are another important concept in programming, and the various jump statements assist us in doing so. These statements aid in the transfer of control from one point to another. Another concept that aids in jumping from one logic to another within a program is positioning the execution based on a specific requirement. This blog will help you learn about C# control statements.

Loop Controls in C#

C# offers five different types of loop control statements to programmers, which are listed below:

  • goto
  • break
  • continue
  • return
  • throw

Goto 

In C,# the goto statement is also known as the jump statement. As the name implies, goto is used to move program control to a predefined label. The goto statement can be used to repeat a code section for a specific condition. The goto statement unconditionally branches from one point in the block to another. Put another way, and the goto statement moves execution to another label within the statement block.

A label is required for the goto to identify where the branch is to be made. A label can be any valid identifier that is followed by a colon. The label is placed directly before the statement to which control is transferred. The goto statement can move control to any point in a program.

In the below example, the program transfers execution to the "display" label:

using System;
namespace ConsoleApplication
{
class CN
{ 
    static void Main(string[] args)
    {
        Console.WriteLine("Goto Example");
        // as we have used goto display, control is transferred to display
        goto display;
        Console.WriteLine("skipped line");
        display:
        {
            Console.WriteLine("displayed line");
        }            
        Console.Read();
    }
}
}

Output:

Goto Example

displayed line

Break

This statement is used to end any iteration or statement associated with it. When the break is encountered, the program execution is passed to the following statement in the iteration.

Example:

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
 
namespace loopControl_break
{
    class CN
    {
        static void Main(string[] args)
        {
            int num = 0;
 
            while (num < 100)
            {
                Console.WriteLine(num);
                if (num == 20)
                {
                    Console.WriteLine("breaking the loop using break loop control ...");
                    break;
                }
                num++;
            }
            Console.ReadLine();
        }
    }
}

Output:

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

breaking the loop using break loop control ...

Continue 

It is used to move the program control to the start of the loop. It continues until a specific condition is met; in other words, the continue statement skips the remaining code in the loop and returns the pointer to the start of the loop. The continue statement instructs the compiler to ignore the following statements and proceed to the next iteration.

For example, we want to print an iteration of numbers from 1 to 10, and we don't want to print till 4. So we skip till the number reaches 5.

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
 
namespace loopControl_continue
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 0;
            while (num < 10)
            {
                num++;
                if (num < 5)
                {
                    continue;
                }
                Console.WriteLine(num);
            }
            Console.ReadLine();
        }
    }
}

Output:

5

6

7

8

9

10

Return

The return statement ends the execution of the method that contains it and returns control to the calling method. The returned value can be used for whatever purpose the calling method intended. When the method is executed and returns a value, we can assume that C# stores this value in the location where the method was called. 

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace loopControl_return
{
    class Program
    {
        public int addition(int a, int b)
        {
            // returns the addition of a of b
            return a + b;
        }
        
        static void Main(string[] args)
        {
            Program p = new Program();
            int sum;
            // calling the function addition that will return addition of the given two numbers
            sum = p.addition(7, 3);
            Console.WriteLine(sum);
 
            Console.ReadLine();
        }
    }
}

Output:

10

Throw

A throw is a keyword in C#, and it is helpful to throw an exception manually during program execution, and we can handle those thrown exceptions using try-catch blocks based on our needs. The throw keyword will raise only exceptions derived from the Exception base class.

The syntax is:

throw [e];

where e is an instance of a System-derived class

Example:

using System; 
class CN
 { 
    static string s = null;  
    static void display(string s1) 
    { 
        if (s1  == null) 
            throw new NullReferenceException("Exception Found.");              
    }    
static void Main(string[] args) 
{  
    try
    { 
        display(s); 
    }  
    catch(Exception exp) 
    { 
        Console.WriteLine( exp.Message ); 
    }                      
} 
}

Output:

Exception Found.

Also see,  Ienumerable vs Iqueryable

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

FAQs

  1. Why are Loop Control statements used?
    Loop Control statements to aid in transferring control from one point to another. 
  2. What are the Loop Controls available in C#?
    C# offers five different types of loop control statements to programmers, which are goto, break, continue, return and throw
  3. What is the use of the break statement?
    The break statement is used to end any iteration or statement associated. When the break is encountered, the program execution is passed to the following statement in the iteration.
  4. Does the throw statement break the loop?
    No, the code fails because the exception isn't handled. If you put a try/catch block inside your loop, you can continue the iteration.
  5. How do you continue after throwing an exception?
    If you catch the exception, you're throwing, your code will continue after the try-catch block. If an exception is missed, it usually exits the calling function.

Key Takeaways

In this article, we have extensively discussed loop controls in C# and have seen its various types with their syntax and examples.

We hope that this blog has helped you enhance your knowledge regarding Loop Controls in C# and if you would like to learn more, check out our articles in the code studio library. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass