Category: CSharp Tutorial

  • Loops in C#

    A situation may arise during coding where you need to repeat the block of code for some number of times then the loops present in C# will come into play.

    Loops allow us to execute a block of code or statement or group of statements as many times according to the user’s need. The condition is checked every time the loop is repeated. It is done by evaluating a given condition for true and false.

    If true, the loop statement are repeated, if false then the loop is skipped.

    Loops in C programming
    Loops in Programming

    Two Types of Loops in C Programming.

    1. Entry controlled loop:

    In entry control loops, the conditional is checked first and then the block of code is executed. It is also called a pre-checking loop.

    There are two types of entry control loop:

    • for loop. 
    • while loop.

    2. Exit controlled loop:

    In exit control loop the block of code is executed first and then the condition is checked. It is also called a post-checking loop.

    There is only one type loop in the exit control loop.

    • do-while loop.

    C# While Loop

    A while loop is an entry-control loop that evaluates the condition before executing the block of the loop. If the condition is true then the body of the loop is executed else the loop will be skipped. The loop continues until the condition stated found to be false.

    The syntax for while loop in C#:

    while(condition)
    {  
       //block of code to be executed  
    } 

    You should use a while loop, where the exact number of iterations is not known but the loop termination condition, is known.

    For example and flowchart of while loop, click here


    C# do…while loop

    As we know from the above loop that if the condition is found false then the loop will not be executed but what if we want the loop to execute once (like the menu drive program) even if the condition is found to be false. So in this kind of situation do-while loop comes into play.

    It is the same as the while loop where the loop is terminated on the basis of the test condition. The main difference is that the do-while loop checks the condition at the end of the loop which allows the do-while to execute the loop at least once.

    The syntax for do-while loop in C#:

    do{
        //statements..
     }while (condition);

    You should use do while loop if the code needs to be executed at least once.

    For example and flowchart of do-while loop, click here


    C# for Loop

    The for loop is an entry-control loop as the condition is initially checked. It has the most efficient structure than the other two loops. The loop allows the programmer to write the execution steps together in a single line and also the specific number of times the execution is to be iterated.

    It has three computing steps as shown in the syntax below.

    • initialization: The first step is the initialization of the variable and is executed only once. And need to end with a semicolon(;).
    • condition: Second is condition check, it checks for a boolean expression. If true then enter the block and if false exit the loop. And need to end with a semicolon(;).
    • Increment or Decrement: The third one is the increment or decrement of the variable for the next iteration. Here, we do not need to use the semicolon at the end.

    The syntax for for loop in C#:

    for(initialization; condition; Increment/Decrement) 
    {
       // Statements
    } 

    You should use for a loop when the number of iterations is known beforehand, i.e. when the number of times the loop body is needed to be executed is known.

    For example and flowchart of for loop, click here


    C# Nested Loops

    A combination of loops where one loop is inside the other loop is called a nested loop. C# allow nesting any of the above loops.

    Syntax:

    The syntax for a nested for loop statement in C#:

    for (initialization1; condition1; increment/decrement) 
    {
       for (initialization2; condition2; increment/decrement) 
       {
          //inner statement
       }
    
       //outer statement
    }

    The syntax for a nested while loop statement in C#:

    while(condition1) 
    {
       while(condition2) 
       {
          //inner statement
       }
       
       //outer statement
    }

    The syntax for a nested do-while loop statement in C#:

    do {
       //outer statement
       do {
          //inner statement
       }
       while(condition1);
    }
    while(condition2);

    You can use loops inside another for any number of times as required. You can also use any type of loop inside any other type of loops. For example, you can use while loop inside for loop or vice versa.

    Example of C# nested loop

    We will see an example of use of nested for loop in C# to print a star pattern.

    using System;
    
    namespace Loops
    {
       class NestedLoopProgram
       {
          public static void Main(string[] args)
          {
             for (int i = 1; i <= 5; i++)
             {
                for (int j = 1; j <= i; j++)
                {
                   Console.Write("* ");
                }
    
                Console.WriteLine();
             }
          }
       }
    }

    Output:

    * 
    * * 
    * * * 
    * * * * 
    * * * * * 

    The Infinite Loop

    As the name suggests, the infinite loop is a forever executing loop. The infinite loop repeats indefinitely and the condition never becomes false. It is also known as an indefinite loop or an endless loop.

    We can use one of the Loops in C# to turn it into infinite loop.

    infinite ‘for’ loop

    for(; ;)  
    {  
      //body of the loop  
    }

    Example: of infinite for loop in C#

    using System;
    
    namespace Loops 
    {
       class InfiniteLoop 
       {
          static void Main(string[] args) 
          {
             for (; ; ) 
             {
                Console.WriteLine("Executed Forever.");
             }
          }
       }
    } 

    The above program will run forever. The compiler assumes the condition to be true if the condition is absent in the loop.


  • C# for Loop

    The for loop is an entry-control loop as the condition is initially checked. It has the most efficient structure than the other two loops. The loop allows the programmer to write the execution steps together in a single line and also the specific number of times the execution is to be iterated.

    for loop Flowchart:

    for loop

    It has three computing steps as shown in the syntax below.

    • initialization: The first step is the initialization of the variable and is executed only once. And need to end with a semicolon(;).
    • condition: Second is condition check, it checks for a boolean expression. If true then enter the block and if false exit the loop. And need to end with a semicolon(;).
    • Increment or Decrement: The third one is the increment or decrement of the variable for the next iteration. Here, we do not need to use the semicolon at the end.

    The syntax for for loop in C#:

    for(initialization; condition; Increment/Decrement) 
    {
       // Statements
    } 

    You should use for a loop when the number of iterations is known beforehand, i.e. when the number of times the loop body is needed to be executed is known.


    Example of C# for Loop

    using System;
    
    namespace Loops
    {
       class ForProgram
       {
          static void Main(string[] args)
          {
             //f or loop execution
             for (int i = 1; i <= 10; i++)
             {
                Console.WriteLine("Value of i: {0}", i);
             }
          }
       }
    }

    Output:

    Value of i: 1
    Value of i: 2
    Value of i: 3
    Value of i: 4
    Value of i: 5
    Value of i: 6
    Value of i: 7
    Value of i: 8
    Value of i: 9
    Value of i: 10

  • C# do-while loop

    As we know from the above loop that if the condition is found false then the loop will not be executed but what if we want the loop to execute once (like the menu drive program) even if the condition is found to be false. So in this kind of situation do-while loop comes into play.

    It is the same as the while loop where the loop is terminated on the basis of the test condition. The main difference is that the do-while loop checks the condition at the end of the loop which allows the do-while to execute the loop at least once.

    do-while Flowchart:

    do-while loop

    The syntax for do-while loop in C#:

    do{
        //statements..
     }while (condition);

    You should use do while loop if the code needs to be executed at least once.


    Example of C# do-while loop

    using System;
    
    namespace Loops
    {
       class DoWhileProgram
       {
          static void Main(string[] args)
          {
             int i = 1;
    
             //do loop execution
             do {
                Console.WriteLine("value of i: {0}", i);
                i += 1;
             }
    
             while (i <= 10);
          }
       }
    }

    Output:

    value of i: 1
    value of i: 2
    value of i: 3
    value of i: 4
    value of i: 5
    value of i: 6
    value of i: 7
    value of i: 8
    value of i: 9
    value of i: 10

  • C# While Loop

    A while loop is an entry-control loop that evaluates the condition before executing the block of the loop. If the condition is true then the body of the loop is executed else the loop will be skipped. The loop continues until the condition stated found to be false.

    while loop Flowchart:

    While Loop

    The syntax for while loop in C#:

    while(condition)
    {  
       //block of code to be executed  
    } 

    You should use a while loop, where the exact number of iterations is not known but the loop termination condition, is known.


    Example of C# While Loop

    using System;
    
    namespace Loops
    {
       class WhileProgram
       {
          static void Main(string[] args)
          {
             int i = 1;
    
             //while loop execution
             while (i <= 10)
             {
                Console.WriteLine("value of i: {0}", i);
                i++;
             }
          }
       }
    }

    Output:

    value of i: 1
    value of i: 2
    value of i: 3
    value of i: 4
    value of i: 5
    value of i: 6
    value of i: 7
    value of i: 8
    value of i: 9
    value of i: 10

  • C# Decision Making Statements

    During coding, you tackle most of the situations where your next move depends on your decisions. Now to make such a decision in programming, we use the decision-making statement provided by the programming language.

    Decision-Making statements are used when a user wants a certain block to be executed under certain conditions. The condition to be checked is determined by true or false value.

    C# programming language provides the following types of decision-making statements:

    • if statement 
    • if-else statement 
    • nested-if statement 
    • if-else-if ladder statement 
    • switch-case statement 

    The above decision making statements determines the direction of flow of the program execution.


    C# if statement

    An if statement consists of a Boolean expression followed by a block of codes. If the Boolean expression is true, the block of code inside the if statement will be executed else if statement will be skipped. This is the simplest one of all the decision-making statements.

    The syntax of the if statement in C#:

    if (condition) 
    {
       //block of statement
    }

    Note: If the curly brackets { } are not used with if statement or any other decision statements then the statement just next to it will only be executed and others will not be considered as a part of the decision statements.

    For example and flowchart of C# if statement, click here


    C# if…else statement

    This statement contains two-part and depends on the boolean value evaluated by the condition checked. If the condition is true then the code inside the if statement is executed or if it is false then the code inside else statement will be executed.

    The syntax of the if..else statement in C#:

     if (condition) 
     {
      //code executed if condition true 
     }
     else
     {
      //code executed if condition false 
     }

    For example and flowchart C# if…else statement, click here


    C# nested if statement

    In this type of statement the if block contains another if block within it. And the inner if statement is executed only if the outer if statement’s condition is true.

    The syntax of the nested if statement in C#:

    if(condition1)
    {    
       //block of code to be executed    
       if(condition2)
       {  
         //block of code to be executed    
       }    
    } 

    For example and flowchart C# nested if statement, click here


    C# if-else-if ladder statement

    This statement allows the user to have multiple options to check for different conditions. Here, if one of the if or else-if condition is true then that part of the code will be executed and the rest will be skipped. if none of the conditions are true then the final else statement present at the end will be executed.

    The syntax of the if-else-if ladder statement in C#:

     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
     {  
        //final else if all the above condition are false 
     }

    For example and flowchart C# if-else-if ladder statement, click here


    C# switch statement

    A switch statement allows a variable to be tested for equality against multiple values and each of those values is called a case. It can be used instead of nested if...else..if ladder.

    There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.

    Switch expression and case value must be of the same type. Each of these case is exited by break keyword which brings the execution out of the switch statement.

    The syntax of the switch statement statement in C#:

    switch (expression)
    {
        case value1:    
               //code to be executed;    
               break;  //optional  
        case value2:    
                //code to be executed;    
                break;  //optional  
        .
        .
        .
        .    
        case valueN:    
                //code to be executed;    
                break;  //optional 
            
        default:     
               code to be executed if all cases are not matched;    
    }

    The expression is evaluated once and compared with the values of each case label.

    • If the expression and case value are matched then the corresponding code present within that particular case will be executed and a break statement is used to come out of the switch statement by skipping all of the other cases.
    • If the values of expression and case do not match, the code within default: is executed.

    For example and flowchart C# switch statement statement, click here


    The ? : Operator

    ? : This operator is called a conditional operator or ternary operator. The execution of this operator depends on the result of the binary condition.

    Ternary Operator can also be used instead of if...else statement as it does follow the same algorithm and the only difference is ternary operator takes less space and it’s the short version of if...else statement.

    ? : Operator is also called Ternary Operator because it takes three operands to operate, as shown in the syntax below.

    Syntax of Ternary Operator:

    variable = Condition ? Expression1 : Expression1

    Here, the condition that is the binary condition is to be evaluated. And if the binary condition is true then Expression1 is executed and if it is false then Expression2 is executed. And both of them return the results.

    Click here to learn about ternary operator with an example.


  • C# switch statement

    A switch statement allows a variable to be tested for equality against multiple values and each of those values is called a case. It can be used instead of nested if...else..if ladder.

    There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.

    Switch expression and case value must be of the same type. Each of these case is exited by break keyword which brings the execution out of the switch statement.

    The syntax of the switch statement statement in C#:

    switch (expression)
    {
        case value1:    
               //code to be executed;    
               break;  //optional  
        case value2:    
                //code to be executed;    
                break;  //optional  
        .
        .
        .
        .    
        case valueN:    
                //code to be executed;    
                break;  //optional 
            
        default:     
               code to be executed if all cases are not matched;    
    }

    Switch statement Flowchart:

    switch statement

    Example of C# switch statement

    using System;
    
    namespace DecisionStatement
    {
       class SwitchStatement
       {
          static void Main(string[] args)
          {
             char grade_choice = 'D';
    
             switch (grade_choice)
             {
                case 'A':
                   Console.WriteLine("Excellent!");
                   break;
    
                case 'B':
                   Console.WriteLine("Very Good!");
                   break;
    
                case 'C':
                   Console.WriteLine("Well done");
                   break;
    
                case 'D':
                   Console.WriteLine("You passed");
                   break;
    
                case 'F':
                   Console.WriteLine("Failed! Better Luck Next time");
                   break;
    
                default:
                   Console.WriteLine("Invalid grade");
                   break;
             }
          }
       }
    }

    Output:

    You passed

  • C# if-else-if ladder statement

    This statement allows the user to have multiple options to check for different conditions. Here, if one of the if or else-if condition is true then that part of the code will be executed and the rest will be skipped. if none of the conditions are true then the final else statement present at the end will be executed.

    The syntax of the if-else-if ladder statement in C#:

     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
     {  
        //final else if all the above condition are false 
     }

    Flowchart diagram for if-else if statement:

    if elseif statement

    Example of C# if-elseif ladder statement

    using System;
    
    namespace DecisionStatement
    {
       class IfElseIfLadder
       {
          static void Main(string[] args)
          {
             int x = 50;
    
             if (x > 70)
                Console.WriteLine("True, x > 700");
             else if (x < 100)
                Console.WriteLine("True, x < 100");
             else if (x == 20)
                Console.WriteLine("True, x == 20");
             else
                Console.WriteLine("x is not present");
          }
       }
    }

    Output:

    True, x < 100

  • C# nested if statement

    In this type of statement the if block contains another if block within it. And the inner if statement is executed only if the outer if statement’s condition is true.

    The syntax of the nested if statement in C#:

    if(condition1)
    {    
       //block of code to be executed    
       if(condition2)
       {  
         //block of code to be executed    
       }    
    } 

    nested if statement Flowchart:

    nested if

    Example of nested if statement in C#

    using System;
    
    namespace DecisionStatement
    {
       class NestedIfStatement
       {
          static void Main(string[] args)
          {
             int a = 300;
             int b = 600;
    
             /*check the boolean condition */
             if (a > 100)
             {
                Console.WriteLine("This is outer if statement");
                if (b > 200)
                   Console.WriteLine("a is greater than 100 and b is  greater than 200");
             }
          }
       }
    }

    Output:

    This is outer if statement
    a is greater than 100 and b is  greater than 200

  • C# if…else statement

    This statement contains two-part and depends on the boolean value evaluated by the condition checked. If the condition is true then the code inside the if statement is executed or if it is false then the code inside else statement will be executed.

    The syntax of the if..else statement in C#:

     if (condition) 
     {
       //code executed if condition true 
     }
     else
     {
       //code executed if condition false 
     }

    if..else statement Flowchart:

    if…else

    Example of if…else statement in C#

    using System;
    
    namespace DecisionStatement
    {
       class IfElseStatement
       {
          static void Main(string[] args)
          {
             int x = 50;
    
             // check condition
             if (x < 30)
             {
                Console.WriteLine("True, x is less than 30");
             }
             else
             {
                Console.WriteLine("False, x is greater than 30");
             }
          }
       }
    }

    Output:

    False, x is greater than 30

  • C# if statement

    An if statement consists of a Boolean expression followed by a block of codes. If the Boolean expression is true, the block of code inside the if statement will be executed else if statement will be skipped. This is the simplest one of all the decision-making statements.

    The syntax of the if statement in C#:

    if (condition) 
    {
       //block of statement
    }

    Note: If the curly brackets { } are not used with the if statement then the statement just next to it will only be executed and others will not be considered as a part of the statement.


    if statement Flowchart:

    if statement

    Example of C# if statement:

    using System;
    
    namespace DecisionStatement
    {
       class IfStatement
       {
          static void Main(string[] args)
          {
             int x = 50;
    
             // check condition
             if (x < 100)
             {
                Console.WriteLine("True, x is less than 100");
             }
          }
       }
    }

    Output:

    True, x is less than 100