Tag Archives: else

Making comparisons in C# (if, else if, and else statements)

In this tutorial you will learn how to make comparisons in C# using the following conditional statements:

  • if
  • else if
  • else

We can check, for example, if a number is less than, greater than, less than or equal to, greater than or equal to, equal to, or not equal to another number. We can also check if a string variable is equal to another string value (for example, checking if a password is correct). To make comparisons, we will need to be familiar with comparison operators.

Comparison operators

Comparison (or equality) operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the comparison operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Watch the video below which shows how to make comparisons using if, else if, and else statements (scroll down for the sample code).

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int x = 11;

      if (x > 10)
      {
        Console.WriteLine("x is greater than 10");
      }
      else if (x < 10)
      {
        Console.WriteLine("x is less than 10");
      }
      else{
        Console.WriteLine("x is equal to 10");
      }
    }
  }
}

Logical operators

We can also check if multiple conditions evaluate to true or if at least one of multiple conditions evaluate to true in a single if statement using logical operators. Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Here is an example of using the && logical operator to display a message only if a user’s first name is “Joe” AND their last name is also “Bloggs”.

if (firstName == "Joe" && lastName == "Bloggs")
{
   Console.WriteLine("Hello Joe Bloggs.");
}
else
{
   Console.WriteLine("I don't know you.");
}

Watch the video below to see how you can use logical operators in conditional statements and then scroll down for the sample code.

Sample code using logical OR operator

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string firstName = "Joe";
      string lastName = "Smith";

      if (firstName == "Joe" || lastName == "Bloggs")
      {
        Console.WriteLine("Hi Joe.");
      }
      else{
        Console.WriteLine("I don't know you.");
      }
    }
  }
}

Sample code using logical AND operator

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string firstName = "Joe";
      string lastName = "Bloggs";

      if (firstName == "Joe" && lastName == "Bloggs")
      {
        Console.WriteLine("Hi Joe.");
      }
      else{
        Console.WriteLine("I don't know you.");
      }
    }
  }
}

Next tutorial: Switch statements in C#

Conditional programming in C#

Conditional statements are used so that your program can make decisions based on different conditions. For example, a game might display a message to the player if their score is higher than a certain number. Or an app might provide different content based on its user’s age. When your program has a range of conditions, you can build powerful algorithms.

Watch the video below and then scroll down to view the sample code.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10)
{
   Console.WriteLine("Hello World");
}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if statements allow you to specify what action will occur when a condition is met and else statements can be used to run another piece of code if the condition is not met. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18)
{
   Console.WriteLine("You are old enough to vote");
}
else
{
   Console.WriteLine("You are not old enough to vote");
}

else if statement

The limitation of using just if and else statements is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the else if statement comes in.

Using else if statements allows you to test multiple conditions. You can have several else if statements that each test a different condition. The else part is optional when using if and else if statements but is handy if you want something to happen if none of the specified conditions are met.

Here is some sample code for the ifelse if and else statements:

if(age>=18)
{
   Console.WriteLine("You are old enough to vote");
}
else if(age==17)
{
   Console.WriteLine("You can vote after your next birthday");
}
else
{
   Console.Writeline("You are not old enough to vote");
}

Sample C# code

Here is the sample C# code used in the video. Comments have been added to the code to explain each part of the code.

using System;

namespace MyCSharpApp
{
  class MainClass

  {
    public static void Main (string[] args)
    {
      // Ask the user to select an option (type of calculation)
      // \n will create a new line
      Console.WriteLine ("Select from one of the following options: \n1 - Add\n2 - Subtract\n3 - Multiply\n4 - Divide");

      // Store the selected option in a variable as an integer value (1, 2, 3, or 4)
      int option = int.Parse (Console.ReadLine ());

      // Ask the user to enter two numbers
      Console.WriteLine ("Enter two numbers...");

      // Store the first number in a variable as a float value
      float num1 = float.Parse(Console.ReadLine ());

      // Ask the user to enter the first of the two numbers
      Console.WriteLine ("Enter the first number:");

      // Ask the user to enter the second of the two numbers
      Console.WriteLine ("Enter the second number:");

      // Store the second number in a variable as a float value
      float num2 = float.Parse(Console.ReadLine ());

      // check the option selected and display the result of the relevant calculation

      // if option 1 (add) was selected...
      if (option == 1) {
        Console.WriteLine ("The answer is: " + (num1 + num2));
      }

      // if option 2 (subtract) was selected...
      else if (option == 2) {
        Console.WriteLine ("The answer is: " + (num1 - num2));
      }

      // if option 3 (multiply) was selected...
      else if (option == 3) {
        Console.WriteLine ("The answer is: " + (num1 * num2));
      }

      // if option 4 (divide) was selected...
      else if (option == 4) {
        Console.WriteLine ("The answer is: " + (num1 / num2));
      } 

      // if no option was selected...
      else {
        Console.WriteLine ("Option is not recognised");
      }
    }
  }
}

Comparison operators

Comparison (or equality) operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the comparison operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Logical operators

Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Here is an example of using the && logical operator to display a message only if a user’s firstname is “Joe” AND their last name is also “Bloggs”.

if (first_name == "Joe" && last_name == "Bloggs")
{
   Console.WriteLine("Hello Joe Bloggs.");
}
else
{
   Console.WriteLine("I don't know you.");
}

Next tutorial: While loops in C#

Else and else if statements in PHP

In the previous tutorial we looked at if statements in PHP. In this tutorial we will look at how to specify more conditions by using the else and else if statements. If you are testing multiple conditions you can use an if statement along with else if and else statements. You can also place an if statement inside another if statement – this is known as a nested if statement.

The basic structure of if, else if and else statements looks like this:

if(condition){
  // do something
}
else if(another condition){
  // do something else
}
else{
  // do something completely different if the
  // other two conditions are not met
}

The basic structure of a nested if statement looks like this:

if(condition){
  if(another condition){
     //do something
  }
}

Make sure you use the correct brackets for conditions and statements inside if statements, and also make sure that you have matching closing brackets.

Watch the video below to see how to use if, else if, and else statements in PHP and then scroll down to see the sample code.

Sample PHP code:

<?php
 
 $age = 20;
 
 if($age >= 18){
 echo "You are old enough to vote";
 }
 
 else if($age == 17){
 echo "You can vote on your next birthday";
 }
 
 else{
 echo "You are not old enough to vote";
 }
 
?>

PHP Manual references:

Conditional statements in C#

Conditional statements

Conditional statements are used so that your program can make decisions. When your program has a range of conditions, you can build powerful algorithms. In this tutorial, you will learn about if statements, if/else statements, and if/else if statements. Watch the video below and then scroll down to see the sample code.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10)
{
 print("Hello World");
}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

if/else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if/else statements allow you to specify what action will occur when a condition evaluates to true and also what will occur if the condition evaluates to false. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18)
{
 print("You are old enough to vote");
}
else
{
 print("You are not old enough to vote");
}

if/else if statement

The limitation of the if/else statement is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the if/else if statement comes in.

The if/else if statement provides more options than the if/else statement. It is set up in the same way but it has more than one condition. The else part is optional in an if/else if statement.

Here is some sample code for the if/else if statement:

if(age>=18)
{
 print("You are old enough to vote");
}
else if(age==17)
{
 print("You can vote after your next birthday");
}
else
{
 print("You are not old enough to vote");
}

‘If’ Statements in JavaScript

This tutorial explains how to use IF statements for conditional programming in JavaScript. An IF statement can be used to make decisions based on whether a condition evaluates to true or false. Watch the video below or click here to view it on YouTube.

An ‘if statement’ is used to test a condition. If the test condition evaluates to true (Eg. x is less than y), then the code inside the if statement will run. If the test condition evaluates to false, then the code inside the if statement won’t run and the program will continue on.

Operators that you can use in JavaScript to make comparisons include:

Equal to ==
Not equal to !=
Greater than >
Less than <
Greater than or equal to >=
Less than or equal to <=

Take a look at the sample code of an if statement below.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - If Statements</title>
 <script type="text/javascript">
 
 /* For an 'if' statement, the syntax should look like:
 
 if(condition to be tested){
 //run code here
 }
 
 */
 
 var age = 20 // declare the variable age
 
 if(age>=18){
 document.write("You are old enough to vote."); // this message only displays if age is greater than or equal to 18
 }
 
 /* Operators you can use include:
 == equal to
 != not equal to
 > greater than
 < less than
 >= greater than or equal to
 <= less than or equal to
 */
 
 </script>
 
</head>
<body>
 
</body>
</html>

Often when using if statements, you will want to test more than just one condition. The sample code below explains how to do this.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - If Else Statements</title>
 <script type="text/javascript">
 
 // You can have a single if statement (tests one condition)...
 // However, you can also have an IF statement that tests multiple conditions
 // Eg. You can have an if and an else statement (tests two conditions)
 // You can have an if statement, else if statements, and an else statement (tests several conditions)
 
 // if - is the first condition to test
 // else if - is used to test other conditions
 // else - will run a piece of code only if none of the other condition tests have evaluated to true
 
 var age = 16
 
 if(age>=18){
 document.write("You are old enough to vote.");
 }
 else if(age==17){
 document.write("You can vote after your next birthday.");
 }
 else{
 document.write("You cannot vote yet.");
 }
 
 // Make sure you don't confuse the = sign (used for assigning values to variables) for == (used for comparisons)
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Nested if statements