Home / C Sharp / Archive by category 'C# Flow Control'

C# Flow Control

csharp-flow-control

How to use continue statement to exit a for statement iteration

using System;
 
public class ContinueBreakIterate
{
   public static void Main( string[] args )
   {
      for ( int count = 1; count <= 10; count++ ) // loop 10 times
      {
         if ( count == 5 ) // if count is 5, 
            continue; // skip remaining code in loop
 
         Console.Write( "{0} ", count );
      } // end for
 
      Console.WriteLine( "\nUsed continue to skip displaying 5" );
   } // end Main
} // end class ContinueBreakIterate

How to use break statement to exit a for statement

using System;
 
public class ExitBreakFor
{
   public static void Main( string[] args )
   {
      int count; // control variable also used after loop terminates
 
      for ( count = 1; count <= 10; count++ ) // loop 10 times
      {
         if ( count == 5 ) // if count is 5, 
            break; // terminate loop
 
         Console.Write( "{0} ", count );
      } // end for
 
      Console.WriteLine( "\nBroke out of loop at count = {0}", count );
   } // end Main
} // end class ExitBreakFor

Do While in C#

using System;
 
public class DoWhileExample
{
   public static void Main( string[] args )
   {
      int counter = 1; // initialize counter
 
      do
      {
         Console.Write( "{0}  ", counter );
         ++counter;
      } while ( counter <= 10 ); // end do...while 
 
      Console.WriteLine(); // outputs a newline
   } // end Main
} // end class DoWhileExample

Flow control in C# : Part 1 – Conditional statements IF-ELSE

The if-else statement is inherited from C and C++. The if-else statement is also known as a conditional statement. The ‘if’ statement block is executed when the condition is true; if it’s false, control goes to the else statement block. You can have a nested if-else statement with one of more else blocks. You can also apply conditional or ( || ) and conditional and (&&) operators to combine more then one condition.

IF-ELSE syntax:

1
2
3
4
if (condition)
     statement;
else 
    statement;

example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
public class SampleClass 
{
 public static void Main()
   {
      int num1 = 61;
           int num2 = 231;
        int res = num1 + num2;
      if (res > 252)
        {
           res = res - 50;
             Console.WriteLine("Result is more then 252");
          }
      else
           {
           res = 252;
             Console.WriteLine("Result is less then 252");
       }
 
       bool b = true;
         if (res > 252 || b)
            Console.WriteLine("Res > 252 or b is true");
     else if ( (res>252) && !b )
         Console.WriteLine("Res > 252 and b is false");
           else
        Console.WriteLine("else condition");
     }
}