C#- Booleans,If…Else , Switch, While & For Loops

C# Booleans

You will frequently need a data type in programming that can only contain one of two values, such as:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE
A bool data type in C# can accept the values true or false for this purpose.

Boolean Values

The bool keyword is used to declare a boolean type, which can only accept the values true or false :

Example

      bool isCSharpFun = true;
      bool isFishTasty = false;
      Console.WriteLine(isCSharpFun);   // Outputs True
      Console.WriteLine(isFishTasty);   // Outputs False
 
For conditional testing, it is more typical to return boolean values from boolean expressions (see below).

Boolean Expression

By comparing values or variables, a Boolean expression yields a Boolean value, either True or False .
 
This helps to develop reasoning and uncover solutions.
 
For instance, to determine whether an expression (or a variable) is true, you can use a comparison operator, such as the greater than (>) operator:

Example

      int x = 10;
      int y = 9;
      Console.WriteLine(x > y); // returns True, because 10 is higher than 9
 
 

Alternatively, even simpler:

Console.WriteLine(10 > 9); // returns True, because 10 is higher than 9
 
The equal to (==) operator is used in the following examples to evaluate an expression:

Example

      int x = 10;
      Console.WriteLine(x == 10); // returns True, because the value of x is equal to 10

Example

Console.WriteLine(10 == 15); // returns False, because 10 is not equal to 15
 

Real Life Example

Let’s consider a “real life example” in which determining a person’s voting age is necessary.

The following example shows how to use the >= comparison operator to determine whether the age of 25 is greater than
or equal to the 18-year-old voting age limit:

Example

int myAge = 25;
      int votingAge = 18;
      Console.WriteLine(myAge >= votingAge);
 
 
Nice, huh? Since we are currently winning, an even better strategy would be to enclose the aforementioned code in an if…else statement so that we can do different actions based on the outcome:
 

Example

If myAge is equal to or greater than 18, then output “Old enough to vote!” In the event when not, output “Not old enough to vote.”

      int myAge = 25;

      int votingAge = 18;

 

      if (myAge >= votingAge) 

      {

        Console.WriteLine(“Old enough to vote!”);

      } 

      else 

      {

 

        Console.WriteLine(“Not old enough to vote.”);

         }

All comparisons and conditions in C# are based on an expression’s boolean value. The following chapter will cover conditions (if…else).

C# Conditions and If Statements

The standard mathematical logical conditions are supported by C#:
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b
These circumstances can be used to carry out various actions for various choices.
Here are several conditional statements in C#:
  • Use if to declare a code block that will run if a given condition is met.
  • If the same condition is false, use else to designate a block of code to be run.
  • If the first condition is false, use else if to define a new condition to test.
  • To define numerous alternative code blocks to be performed, use the switch command.

if Statement

To indicate a block of C# code to be performed if a condition is True, use the if statement.
Syntax

if(condition)

{

     //block of  code to be executed if the given condition is true

}

Keep in mind that if is written in lowercase. If or IF in uppercase will result in an error.

We test two variables in the example below to see if 20 is bigger than 18. Print some text if the condition is true:

Example

if (20 > 18)
      {
        Console.WriteLine(“20 is greater than 18”);
      }
Additionally, we can test the following variables:

Example

 int x = 20;
 int y = 18;
  if (x > y)
      {
        Console.WriteLine(“x is greater than y”);
      }

An explanation of an example

In the example above, we use the > operator to test whether x is greater than y using two variables, y and x. We print “x is greater than y” on the screen since x is 20 and y is 18, and we know that 20 is greater than 18.

The else Statement

To indicate a block of code to be performed in the event that the condition is False, use the else statement.

Syntax

if(condition)

{

     //block of  code to be executed if the given condition is true

}

else

{

     //block of  code to be executed if the given condition is true

}

Example

      int time = 20;
      if (time < 18) 
      {
        Console.WriteLine(“Good day.”);
      } 
      else 
      {
        Console.WriteLine(“Good evening.”);
      }
// outputs “Good evening.”
 

An explanation of an example

The above example satisfies the criteria False since time (20) is greater than 18. We then go to the otherwise condition and print “Good evening” to the screen as a result. The program would print “Good day” if the time was less than 18.

else if Statement

Use the else if statement to express a new condition if the first condition is False .

Syntax

if(condition1)

{

//block of  code to be executed if the given condition is true

}

else if (condition2)

{

/  /block of  code to be executed if the given condition 1 is false and condition2 is True

}

else

{

// block of code to be executed if the condition1 is false and condition2 is False

}

Example

int time = 22;
      if (time < 10)
      {
        Console.WriteLine(“Good morning.”);
      }
      else if (time < 20)
      {
        Console.WriteLine(“Good day.”);
      }
      else
      {
        Console.WriteLine(“Good evening.”);
      }
    //   Outputs “Good evening.”
 

An explanation of an example

Because time (22) in the case above is larger than 10, the first condition is false. After determining that both conditions 1 and 2 in the else if statement are False, we proceed to the else condition and print “Good evening” on the screen.

That being said, our application would output “Good day” if the time was 14.

Short Hand If…Else (Ternary Operator)

Additionally, there is the shorthand if else, which is also referred to as the ternary operator due to its three operands. It can be applied to substitute one line of code for several lines of code. It frequently takes the place of basic if else statements:

Syntax

variable = (condition)expressiontrue:expressionfalse;
 

As an alternative to writing:

Example

      int time = 20;
      if (time < 18) 
      {
        Console.WriteLine(“Good day.”);
      } 
      else 
      {
        Console.WriteLine(“Good evening.”);
      }

You could just write:

Example

       int time = 20;
      string result = (time < 18) ? “Good day.” : “Good evening.”;
      Console.WriteLine(result);
 

C# Switch Statements

To choose which of several code blocks should be run, use the switch statement.

Syntax

switch(expression)
{
    case x:
       //code block
    break;
  case y:
       //code block
    break;
   default:
   //code block
    break;
}

Here’s how it functions:

  • One evaluation of the switch expression is performed.
  • The expression’s value is contrasted with each case‘s value.
  • The related block of code is run if there is a match.
  • Later in this chapter, the break and default keywords will be explained.
The weekday name is determined by using the weekday number in the following example:

Example

      int day = 4;
      switch (day) 
      {
        case 1:
          Console.WriteLine(“Monday”);
          break;
        case 2:
          Console.WriteLine(“Tuesday”);
          break;
        case 3:
          Console.WriteLine(“Wednesday”);
          break;
        case 4:
          Console.WriteLine(“Thursday”);
          break;
        case 5:
          Console.WriteLine(“Friday”);
          break;
        case 6:
          Console.WriteLine(“Saturday”);
          break;
        case 7:
          Console.WriteLine(“Sunday”);
          break;
      } 
     // Outputs “Thursday” (day 4)
 

break Keyword

C# exits the switch block when it encounters the break keyword.
 
This will put an end to case testing and additional code execution within the block.
 
After a match is made and the task is completed, a break is in order. Further testing is not required.
Because a break “ignores” the execution of the remaining code in the switch block, it can save a significant amount of execution time.

default Keyword

If a case match is not found, the default keyword, which is optional, indicates what code should be executed:

Example

      int day = 4;
      switch (day) 
      {
        case 6:
          Console.WriteLine(“Today is Saturday.”);
          break;
        case 7:
          Console.WriteLine(“Today is Sunday.”);
          break;
        default:
          Console.WriteLine(“Looking forward to the Weekend.”);
          break;
      }    
    / / Outputs “Looking forward to the Weekend.”

Loops

Loops can execute a block of code as long as a particular condition is reached.
 
Loops are useful because they eliminate errors, save time, and improve readability of programming.
 

C# While Loop

A block of code is iterated through by the while loop as long as a particular condition is met:

Syntax

while (condition)
{
   // code to be executed
}
In the example below, the code in the loop will repeat, over and over again, as long as a variable (i) is less than 5:

Example

      int i = 0;
      while (i < 5)
      {
        Console.WriteLine(i);
        i++;
      }
Note: The loop will never stop if you don’t increase the variable used in the condition!

Do/While Loop

The do/while loop is a version of the while loop. This loop will run the code block once, then check to see if the condition is true before repeating the loop indefinitely.

Syntax

do { //code to be executed } while(condition) A do/while loop is used in the example below. Because the code block runs before the condition is tested, the loop will always run at least once, even if the condition is false:

Example

int i = 0;
      do
      {
        Console.WriteLine(i);
        i++;
      }
      while (i < 5);

The loop will never stop if you don’t increase the variable used in the condition!

 For Loop

Use the for loop rather than the while loop when you are certain of the number of times you want to cycle through a block of code:

 

Syntax

for (statement 1; statement 2; statement 3)
{
   // code to be executed
}
 

Prior to the code block being performed, Statement 1 is run (once).

The requirement for carrying out the code block is specified in Statement 2.

Every time, statement 3 is run following the execution of the code block.

 The following example will display the digits 0 through 4:

Example

for (int i = 0; i < 5; i++) 
      {
        Console.WriteLine(i);
      }    

Example explained

Before the loop begins, Statement 1 sets a variable (int i = 0).


The requirement for the loop to execute ( i must be less than 5) is mentioned in Statement 2. The loop will restart if the condition is true and will finish if it is false.


After every execution of the loop’s code block, Statement 3 raises a value ( i++ ).
 

One more Example

 

The values in this example are limited to even numbers between 0 and 10.

Example

      for (int i = 0; i <= 10; i = i + 2)
      {
        Console.WriteLine(i);
      }    

Nested Loops

It’s also feasible to nest one loop inside of another. This is termed a nested loop.

For every time the “outer loop” iterates, the “inner loop” will run once:

Example

      // Outer loop
      for (int i = 1; i <= 2; ++i) 
      {
        Console.WriteLine(“Outer: ” + i);  // Executes 2 times
        
        // Inner loop
        for (int j = 1; j <= 3; j++) 
        {
          Console.WriteLine(” Inner: ” + j);  // Executes 6 times (2 * 3)
        }
 

foreach Loop

Additionally, there is a foreach loop that can only be used to iterate through the elements of an array or other data sets:  

Syntax  

foreach (type variableName in arrayName)
{
   //code to be executed
}

Using a foreach loop, the example that follows outputs every member in the vehicles array:

Example

string[] cars = {“Volvo”, “BMW”, “Ford”, “Mazda”};
      foreach (string i in cars) 
      {
        Console.WriteLine(i);
      } 

Note:If you don’t comprehend the above example, that’s okay. You will learn more about Arrays in the C# Arrays chapter.