user3540944
user3540944

Reputation:

replace break line with another equivalent line in C#

I need to replace the break; line with another equivalent line without using goto, what is the possible solutions?

static void Main(string[] args)
{
    int Max = 100;

    for (int i = 0; i < Max; i++)
    {
       Console.Writeline(i);

        if (i == 50)
            break;
    }

    Console.ReadLine();
}

Upvotes: 1

Views: 112

Answers (6)

aloisdg
aloisdg

Reputation: 23521

If you dont have to keep the 'if' statement :

static void Main(string[] args)
{
    int Max = 100;

    for (int i = 0; i <= 50; i++) // stop when i > 50 
    {
       Console.WriteLine(i);
    }

    Console.ReadLine();
}

or

static void Main(string[] args)
{
    int Max = 50;

    for (int i = 0; i <= Max; i++)  // stop when i > Max
    {
       Console.WriteLine(i);
    }

    Console.ReadLine();
}

Demo DotNetFiddle

Upvotes: 1

Koen
Koen

Reputation: 644

 if (i == 50)
   return;

This should do the trick too

Upvotes: 0

DrKoch
DrKoch

Reputation: 9772

i = Max;

Explanation: It is perfectly legal to manipulate the loop variable (i) inside a for loop. At the end of the loop the for-chack is executed (i < Max) if it evaluates to false the loop terminates

In fact these two are equivalent:

for(int i=0; i < 3; i++)
{
    DoSomething(i);
}

Will transformed by the compiler to exactly:

  i=0;
start:
  if(i<3)
  {
    DoSomething(i);
    i++;
    goto start;
  }

Upvotes: 1

mybirthname
mybirthname

Reputation: 18127

I really love this stupid interview question: Is this valid ?

static void Main(string[] args)
{
    int Max = 100;

    for (int i = 0; i < Max; i++)
    {

       if(i >= 51)
          continue;

        Console.Writeline(i);

    }
    Console.ReadLine();
}

Upvotes: 1

Yasmin Endusa
Yasmin Endusa

Reputation: 63

Since you break at 50, which is then basically the maximum value that could be possibly achieved (using only the code you posted), why don't you simply set Max to 51 instead of 100? The outcome would be the same!

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Set i to Max

if (i == 50)
      i = Max;

This will stop the loop from running. It's not exactly same as break.Since it will execute the code after the if statement, you may need to use continue to skip it.

Upvotes: 3

Related Questions