Chapter: 2 Control Statements

By Haitomns G

2.1    Introduce the control statements

When a program breaks the sequential flow and jumps to another part of the code, it is called branching. When the branching is based on a particular condition, it is known as conditional branching. If branching takes place without any decision, it is known as unconditional branching.

C# language possesses such decision-making capabilities and supports the following statements known as control or decision-making statements.

  1. if statement
  2. if else statement
  3. if else if else statement
  4. switch statement

2.2    Demonstrate if, if else and if else ladder and compute it

  1. if statement

The if statement checks the given condition. If the condition evaluates to be true then the block of code/statements will execute otherwise not.

Syntax:

if(condition)

{

                //statements

}

Code:

        using System;

public class GFG {

    public static void Main(string[] args)

    {

        string name = “Sam”;

        if (name == “Sam”) {

            Console.WriteLine(“If statement executed.”);

        }

    }

}

Output:

If statement executed.

  • if else statement

The if statement evaluates the code if the condition is true but what if the condition is not true, here comes the else statement. It tells the code what to do when the if condition is false.

Syntax:

    if(condition)

    { 

      // code if condition is true  

    }

    else

    { 

      // code if condition is false 

    } 

Code:

using System;

public class GFG {

    public static void Main(string[] args)

    {

        string name = “Sam”;

        if (name == “Sam”) {

            Console.WriteLine(“If statement executed.”);

        }

        else {

            Console.WriteLine(“Else statement executed.”);

        }

    }

}

Output:

        Else statement executed.

  • if else if else statement

The if-else-if ladder statement executes one condition from multiple statements. The execution starts from top and checked for each if condition. The statement of if block will be executed which evaluates to be true. If none of the if condition evaluates to be true then the last else block is evaluated.

Syntax:

        if(condition1)

        { 

            // code to be executed if condition1 is true 

        }

        else if(condition2)

        { 

            // code to be executed if condition2 is true 

        } 

        else if(condition3)

        { 

            // code to be executed if condition3 is true 

        } 

        …

        else

        {

            // code to be executed if all the conditions are false 

        } 

Code:

        using System;

class GFG {

    public static void Main(String[] args)

    {

        int i = 20;

        if (i == 10)

            Console.WriteLine(“i is 10”);

        else if (i == 15)

            Console.WriteLine(“i is 15”);

        else if (i == 20)

            Console.WriteLine(“i is 20”);

        else

            Console.WriteLine(“i is not present”);

    }

}

Output:

        i is 20

2.3   Demonstrate the switch statement and its functions

  • Switch Statement

A switch statement allows a variable to be tested for equality against a list of values. There is default case (optional) at the end of switch, if none of the case matches then default case is executed.

It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression.

Syntax:

switch (expression)

 {

case value1: // statement sequence

             break;

case value2: // statement sequence

             break;

.

.

.

case valueN: // statement sequence

             break;

default: // default statement sequence

}

Code:

using System;

public class GFG

{

    public static void Main(String[] args)

    {

        int number = 30;

        switch(number)

        {

        case 10: Console.WriteLine(“case 10”);

                 break;

        case 20: Console.WriteLine(“case 20”);

                 break;

        case 30: Console.WriteLine(“case 30”);

                 break;

        default: Console.WriteLine(“None matches”);

                 break;

        }

    }

}

Output:

        case 30

2.4    Illustrate the for loop and deduce its usage

The process of repeatedly executing a block of statements is known as looping. The statements in the block may be executed any number of times, from zero to an infinite number. Loops are of two types:

  1. Entry Control Loop:

The loops in which condition to be tested is present in beginning of loop body are known as Entry Controlled Loops.

  1. For Loop
  2. While Loop
  3. For Each Loop
  • Exit Control Loop

The loops in which the testing condition is present at the end of loop body are termed as Exit Controlled Loops.

  • Do while Loop
  1. For Loop

for loop has similar functionality as while loop but with different syntax. The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is done in one line in for loop thereby providing a shorter, easy to debug structure of looping.

  • Initialization of loop variable: The expression / variable controlling the loop is initialized here. It is the starting point of for loop.
  • Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value true or false.
  • Increment / Decrement: The loop variable is incremented/decremented according to the requirement and the control then shifts to the testing condition again.

Syntax:

for (loop variable initialization ; testing condition; increment / decrement)

{   

    // statements to be executed

}

Code:

        using System;

class forLoopDemo

{

    public static void Main()

    {

        // for loop begins when x=1

        // and runs till x <=4

        for (int x = 1; x <= 4; x++)

            Console.WriteLine(“Sam {0}”, x);

    }

}

Output:

        Sam 1

        Sam 2

        Sam 3

        Sam 4

2.5    Illustrate the do while loop and deduce its usage.

  • While Loop:

The test condition is given in the beginning of the loop and all statements are executed till the given boolean condition satisfies when the condition becomes false, the control will be out from the while loop.

Syntax:

        while (boolean condition)

{

   loop statements…

}

Code:

        using System;

class whileLoopDemo

{

    public static void Main()

    {

        int x = 1;

        // Exit when x becomes greater than 4

        while (x <= 4)

        {

            Console.WriteLine(“Sam {0}”, x);

            x++;

        }

    }

}

Output:

        Sam 1

        Sam 2

        Sam 3

        Sam 4

  • For each

C# provides an easy to use and more readable alternative to for loop, the foreach loop when working with arrays and collections to iterate through the items of arrays/collections. The foreach loop iterates through each item, hence called foreach loop.

Syntax:

foreach(data_type var_name in collection_variable)

{

     // statements to be executed

}

Code:

using System;

class GFG {

    // Main Method

    static public void Main()

    {

        Console.WriteLine(“Print array:”);

        int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };

        foreach(int items in a_array)

        {

            Console.WriteLine(items);

        }

    }

}

Output:

Print array:

1

2

3

4

5

6

7

2.6    Illustrate the while loop and deduce its usage

  1. Do while Loop

do while loop is similar to while loop with the only difference that it checks the condition after executing the statements, i.e. it will execute the loop body one time for sure because it checks the condition after executing the statements.

Syntax:

do

{

    statements..

} while (condition);

Code:

using System;

class dowhileloopDemo

{

    public static void Main()

    {

        int x = 21;

        do

        {

            // The line will be printed even

            // if the condition is false

            Console.WriteLine(“Sam”);

            x++;

        }

        while (x < 20);

    }

}

Output:

        Sam

2.7    Classify loop control statements and compare its feature

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C# provides the following control statements.

  • break statement

Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

Syntax:

        break;

Code:

        using System;

namespace Loops {

   class Program {

      static void Main(string[] args) {

         /* local variable definition */

         int a = 10;

         /* while loop execution */

         while (a < 20) {

            Console.WriteLine(“value of a: {0}”, a);

            a++;

            if (a > 15) {

               /* terminate the loop using break statement */

               break;

            }

         }

         Console.ReadLine();

      }

   }

}

Output:

        value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

  • continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Syntax:

        continue;

Code:

        using System;

namespace Loops {

   class Program {

      static void Main(string[] args) {

         /* local variable definition */

         int a = 10;

         /* do loop execution */

         do {

            if (a == 15) {

               /* skip the iteration */

               a = a + 1;

               continue;

            }

            Console.WriteLine(“value of a: {0}”, a);

            a++;

         }

         while (a < 20);

         Console.ReadLine();

      }

   }

}

Output:

        value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

  • goto statement

The C# goto statement is also known jump statement. It is used to transfer control to the other part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from deeply nested loop or switch case label.

Currently, it is avoided to use goto statement in C# because it makes the program complex.

Code:

        using System; 

public class GotoExample 

    { 

      public static void Main(string[] args) 

      { 

      ineligible: 

          Console.WriteLine(“You are not eligible to vote!”); 

      Console.WriteLine(“Enter your age:\n”); 

      int age = Convert.ToInt32(Console.ReadLine()); 

      if (age < 18){ 

              goto ineligible; 

      } 

      else 

      { 

              Console.WriteLine(“You are eligible to vote!”);  

      } 

      } 

   } 

Output:

You are not eligible to vote!

Enter your age:

11

You are not eligible to vote!

Enter your age:

5

You are not eligible to vote!

Enter your age:

26 You are eligible to vote!

Haitomns G. is a desktop, android, and web developer based in Nepal. He has worked on building several websites, apps, and softwares for clients and independent projects. He is experienced in C, C++, C#, Java, Python, SQL, HTML, CSS, PHP, and JavaScript.

1 thought on “Chapter: 2 Control Statements”

  1. Hi, Neat post. There’s a problem with your website in internet explorer, would check this… IE still is the market leader and a huge portion of people will miss your magnificent writing due to this problem.

    Reply

Leave a Comment

Slide to prove you're not a bot/spammer *