Tag Archives: operators

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#

Arithmetic and assignment operators in C#

Operators

Operators are symbols that are used to perform operations on data. The range of different operations you can perform can usually be placed in these four categories:

  • Arithmetic operators
  • Assignment operators
  • Equality operators
  • Logical operators

In this tutorial we will look at arithmetic and assignment operators used in the C# language. Later on in these tutorials we will also look at equality and logical operators when we work with conditional statements.

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used on number variables eg. int and float (although they can be used for other things too eg. the  + operator can be used to join two strings together).

Operator Name / description
+ Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together.
Subtraction – this operator is used to subtract one number from another.
* Multiplication – this operator is used to multiply two numbers together.
/ Division – this operator is used to divide one number by another.
% Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

<variable name> <assignment operator> <value>;

For example: x = 5; (or int x = 5; if the variable’s type has not already been declared).

The table below shows the different assignment operators available in C#.

Operator Description
= The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign.
+= , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5.
++ and — These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Watch the video below to see how arithmetic and assignment operators are used in the C# language and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f;
      float num2 = 4f;

      float result = num1 + num2 + 10f;

      result = num1 - num2;
      result = num1 * num2;
      result = num1 / num2;
      result = num1 % num2;

      int num3 = 30;
      num3--;

      Console.WriteLine(result);
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Comments

If statements in PHP

If statements (conditional statements) are used to make decisions in your programs. An if statement will test a condition and then run a section of code if the condition evaluates to true. There are a number of relational operators and logical operators you can use in if statements to test different conditions which are explained in the video below.

Relational operators

Relational operators are used for comparison such as checking if one variable’s value is greater than another. Eg. is x greater than y? (x>y). Here is a list of relational operators:

Operator Description
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
=== identical to (equal to AND of the same data type)
!= not equal to
!== not identical to (not equal to AND not of the same data type)

Logical operators

Logical operators are used to combine conditions. Eg. is x greater than both y and also less than z? Here is a list of logical operators:

Operator Description
&& AND
|| OR
and AND (same as &&)
or OR (same as ||)
xor Xor (if either one or the other is true, but not both)
! NOT (eg. !$x returns true if $x is not true)

Watch the video and then scroll down to see the sample code.

Sample if statement PHP code:

<?php
 
 $number = 5;
 
 if($number < 10)
 {
 echo $number , " is less than 10";
 }
 
// comparison operators include < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), == (equal to), != (not equal to), and === (identical to).
?>

Sample PHP code using AND operator used to test that both criteria are true (the AND operator is two && ampersands):

<?php
 
 $number = 5;
 
 if($number > 1 && $number < 10)
 {
 echo $number , " is greater than 1 and less than 10.";
 }
 
 // logical operators include && (and) and || (or)
?>

Sample PHP code using OR operator to test that at least one criteria is true. (the OR operator is two || bars):

<?php
 
 $number = 5;
 
 if($number < 10 || $number > 20)
 {
 echo $number , " is less than 10 or greater than 20.";
 }
 
 // logical operators include && (and) and || (or)
?>

PHP Manual references:

Operators in PHP

This tutorial explains the range of math and assignment operators available in the PHP programming language as well as operation precedence.

The main assignment and arithmetic operators you can use in PHP are:

  • = (equals is an assignment operator)
  • + (addition operator)
  • (subtraction operator)
  • * (multiplication operator)
  • / (division operator)
  • % (modulus, used for finding the remainder from a division)

Example: $total = $num1 + $num2

You can also assign a value from a calculation using these operators:

  • += (this means add and assign to eg. $total += 5 means to add 5 on to the value in the $total variable)
  • -= (subtract)
  • *= (multiply)
  • /= (divide)
  • %= (modulus)

Example: $total += $num3

Other operators include:

  • ++ (increment by 1)
  • — (decrement by 1)

Example: $total++

Watch the video below and then scroll down to see some of the sample code.

This video explains math and assignment operators. The next video explains comparison and logical operators.

Sample PHP code:

<?php
 
 $number = 5; // the assignment operator
 $number = $number + 4; // the addition operator
 $number = $number - 4; // the subtraction operator
 $number = $number * 4; // the multiplication operator
 $number = $number / 4; // the division operator
 $number = $number % 4; // the modulus operator
 
 $number += 4; // example of addition & assignment shortcut
 // other examples include -= , *= , /= , and %=
 
 $number ++; // increment
 $number --; // decrement
 
 $number = (2 + 4) * 3; // brackets used (example of operation precedence)
?>

PHP Manual references:

Operators in C#

Operators

Operators are symbols that are used to perform operations on data. The range of different operations you can perform can usually be placed in these four categories:

  • Arithmetic operators
  • Assignment operators
  • Equality operators
  • Logical operators

You will see how these operators can be used for conditional statements in the next tutorial but for now, you can watch the video below to learn about the different types of operators in the C# programming language.

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used number variables (although they can be used for other things too).

Operator Name / description
+ Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together.
Subtraction – this operator is used to subtract one number from another.
* Multiplication – this operator is used to multiply two numbers together.
/ Division – this operator is used to divide one number by another.
% Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

<variable name> <assignment operator> <value>;

For example: x = 5;

The table below shows the different assignment operators available in C#.

Operator Description
= The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign.
+= , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5.
++ and – These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Equality operators

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 equality 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.

 

Using And/Or Operators in If Statements

Using logical operators such as and/or allow a programmer to write complex if statements. For example, you can check if a number is greater than 10 AND is also less than 20 (both conditions have to evaluate to true for the code to run inside the if statement). Or, you can check if a number is less than 5 OR greater than 10 (only one condition has to evaluate to true for the code to run inside the if statement)

Logical operators:

  • The symbols && are used for the and operator in JavaScript
  • The || symbols are used for the or operator in JavaScript
  • A single exclamation mark ! can also be used as a not operator.

Check out the sample code below to see how these logical operators can be used to form complex if statements in JavaScript, and make sure you also watch the accompanying video here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 // This is a better way than using nested if statements
 // You can use and/or operators in JS (known as logical operators)
 // The AND operator is &&
 // The OR operator is ||
 
 var firstName = "John";
 var lastName = "Smith";
 
 if(firstName=="John" && lastName=="Smith"){
 document.write("Hello, John Smith!");
 // The message above will only be displayed if firstName is John AND lastName is Smith.
 // Try using || instead of && and change the value of one of the variables. What happens?
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Operators

If you have created your own variables and assigned them each a value (such as a string or integer), then you will already be familiar with the assignment operator which is a single = (equals sign).

There are other operators used for calculations though such as adding, subtracting, multiplying, dividing, increasing and decreasing values, etc. Take a look at the source code to see what is available.

Make sure you also watch the video about operators here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Operators</title>
 <script type="text/javascript">
 var x = 5, y = 10; //variables can be initialised on one line, separated by commas
 var z = x + y; // this is how variables can be added
 
 z++ //this increases the z variable value by 1
 
 z-- //this decreases the z variable value by 1
 
 // operators include + (plus) - (minus) * (multiply) / (divide) and % (modulus) which returns the remainder from division
 
 x+=y; //this is an example of compound addition. It is the equivalent of x = x + y
 // variables can be added using the compound addition += , compound subtraction -= , compound multiplication *= or compound addition /=
 
 document.write(z); // now let's see what the z variable displays after these modifications.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Using AND/OR operators in ‘If’ statements with JavaScript.

You can specify more than one condition in an IF statement. You can specify whether several conditions must evaluate to true for code to run or whether one of several possible conditions must evaluate to true for code to run. This involves using AND and OR operators. The AND operator in JavaScript is && and the OR operator in JavaScript is II. The NOT operator is a single ! (exclamation mark).

You can watch the video below or click here to view it on YouTube. Make sure you also have a look at the sample code further below and feel free to use and modify it.

So after watching the video, let’s recap what logical operators are all about. Using logical operators such as and/or allow a programmer to write complex if statements. For example, you can check if a number is greater than 10 AND is also less than 20 (both conditions have to evaluate to true for the code to run inside the if statement). Or, you can check if a number is less than 5 OR greater than 10 (only one condition has to evaluate to true for the code to run inside the if statement)

Logical operators:

  • The symbols && are used for the and operator in JavaScript
  • The || symbols are used for the or operator in JavaScript
  • A single exclamation mark ! can also be used as a not operator.

Check out the sample code below to see how these logical operators can be used to form complex if statements in JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 // This is a better way than using nested if statements
 // You can use and/or operators in JS (known as logical operators)
 // The AND operator is &&
 // The OR operator is ||
 
 var firstName = "John";
 var lastName = "Smith";
 
 if(firstName=="John" && lastName=="Smith"){
 document.write("Hello, John Smith!");
 // The message above will only be displayed if firstName is John AND lastName is Smith.
 // Try using || instead of && and change the value of one of the variables. What happens?
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Switch statements

Nested ‘If’ Statements in JavaScript

This tutorial explains how to create nested IF statements in JavaScript. A nested IF statement is an IF statement that is inside another IF statement. Also known as…ifception 😉 Using nested IF statements is not always the best way to code but it is handy to know them anyway. View the video below or click here to watch it on YouTube.

You can also view the previous tutorial on ‘if’ statements and see which operators can be used in JavaScript here.

The sample code below shows how to use if statements inside other if statements (nested if statements).

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 var age = 21;
 var maxAge = 30;
 var minAge = 18;
 
 // Below is an example of using if statements inside other if statements
 // This is called nested if statements.
 
 if(age>=minAge){
 if(age<=maxAge){
 document.write("You are within the accepted age range.");
 }
 else{
 document.write("You are above the accepted maximum age.");
 }
 }
 else{
 document.write("You are under the accepted minimum age.");
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Using and/or operators in a complex If statement

‘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

Operators in JavaScript

In this tutorial, you will learn how to use a range of operators in JavaScript to assign values, modify variables and make calculations.

If you have created your own variables and assigned them each a value (such as a string or integer), then you will already be familiar with the assignment operator which is a single = (equals sign).

Operators include:

Addition +
Subtraction
Division /
Multiplication *
Modulus %
Equals =

You can view the video below to see how to use these operators and scroll down to see the sample code.

 

The code below shows how you can use a range of operators when working variable assignments and calculations.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Operators</title>
 <script type="text/javascript">
 var x = 5, y = 10; //variables can be initialised on one line, separated by commas
 var z = x + y; // this is how variables can be added
 
 z++ //this increases the z variable value by 1
 
 z-- //this decreases the z variable value by 1
 
 // operators include + (plus) - (minus) * (multiply) / (divide) and % (modulus) which returns the remainder from division
 
 x+=y; //this is an example of compound addition. It is the equivalent of x = x + y
 // variables can be added using the compound addition += , compound subtraction -= , compound multiplication *= or compound addition /=
 
 document.write(z); // now let's see what the z variable displays after these modifications.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Next tutorial: Strings