C# if, else if, else, switch, for, and while loops

We learned about the reference types in the previous article. Before I have another tutorial on arrays, string builders, and collections, I want to give you a brief about loops like if, else, else if, while, do-while, switch statement, and for loops.

If, else-if and else statement

if else statement is used when we want to choose a set of statements when some particular condition is met. The syntax is as follows.

if(condition)
{
   // do task 1
}
else if(condition)
{
    //do task 2
}
else
{
    //do task 3
}

The if requires a condition that will result in a Boolean of true or false. The same happens in the case of else-if. Else is executed when neither if nor else-if conditions were not met. One can have nested if, else or if, else-if, else loops inside.

For instance, I have a number and I will check if the number is in the range 0 to 15 then adds the number with 2. Else-If the given number is in the range between 15 to 50 then it adds 10 to the number. Neither if nor else-if is valid then the program flow goes to the else part where the result is just the number. Notice that I have used && operator which is a logical AND operation to make sure multiple conditions are true in order for the control to go inside the if or else if statement. You can use Logical OR( || ) will check if one of the conditions is true.

namespace TelestreakTutorial
{
    class Program
    {
        static int StatementsLoopsTutorial(int number)
        {
            int result = 0;
            if ((number < 15) && (number > 0))// 1-14 included 
            {
                result = number + 2;
            }
            else if ((number > 15) && (number < 50))
            {
                result = number + 10;
            }
            else
            {
                result = number;
            }
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(StatementsLoopsTutorial(23));
        }
    }
}

****************
OUTPUT
33

Switch statement

The switch is used when we want to select one statement based on which case matched the pattern of the switch condition. I have an example to demonstrate a switch case.

namespace TelestreakTutorial
{
    class Program
    {
        static void SwitchTutorial(int selection)
        {
            switch (selection)
            {
                case 0: Console.WriteLine("Case 0"); break;
                case 1: Console.WriteLine("Case 1"); break;
                default: Console.WriteLine("No Case Selected"); break;
            }
            return;
        }

        static void Main(string[] args)
        {
            SwitchTutorial(1);
            SwitchTutorial(45);
        }
    }
}
************************************
OUTPUT
Case 1
No Case Selected

The switch statement will allow the control to flow to the case according to the selection. When I pass 1 to the switch it prints out case 1. When 45 is given to the switch, it says “no case selected” because there is no case 45. if there is no case to address the selection it falls back to the default case.

for loop

for loop executes a set of statements when a condition holds good by incrementing the counter a particular number of times.

Syntax and example
for( initialize; condition ; increment)
{
    //statements
}
/********EXAMPLE*****/
for (int i=0;i<10; i++)
{
    Console.WriteLine(i);
}

for(;;)
{
    //statements 
}

We have to follow the syntax I mentioned earlier for constructing a for loop. The initialize declares a local variable, the condition checks if true before the control enters the for loop again. When the condition is false then the for loop stops executing. The increment is also called iteration where we can post-increment or decrement the variable. A for loop with 2 semicolons is infinite for loop. C++ also has the same syntax to use the ‘for’ loop. The example above demonstrates an infinite loop. A break can be added to come out on a certain condition.

while loop

while loop executes the statements until the condition evaluates to true.

Syntax and Example
while(condition)
{
    //statements
}
/*************Example****/
int i = 10; 
while(i >=0)
{
    Console.WriteLine(i);
    i--;
}
******************
OUTPUT
10
9
8
7
6
5
4
3
2
1
0

For instance, in the example, I am printing the numbers in reverse order from 10 to 0. Each time I check for the condition if it is still greater than or equal to 0. When the control flows inside the while loop I print the number and decrement the number.

Conclusion

We have learned about the iterative loops and conditional statements used in C#. There is one more type of loop called foreach which I will explain in another article as it requires some pre-requisite to array or list or any other type of collection. I will be explaining about arrays in the next article. Hope you enjoyed this post.

Have fun programming.

Prev: Reference types

Next: Coming Soon