Legit Logic: How To Use Conditional Statements for Beginners

How to declare a variable is often the first thing you learn in computer programming.  After that, a lot of courses and instructors see fit to let you know computers can do math, and ask you to do things like, “declare a variable and set its value to the outcome of 5 plus 8”.  It’s pretty boring, because unless you’ve been living under a rock for the past fifty years, you’ve heard of calculators and already know that computers are pretty decent at number-crunching.  Variables and mathematical operations are great and all, but as a beginner, it’s likely you’re itching to make the computer actually do something… which is where conditionals and loops come in. 

Unfortunately, conditionals and loops can also take some effort to fully get your head around.  Conceptually, they’re simple enough–some piece of behavior either happens or it doesn’t happen, or behavior repeats until it’s meant to stop.  Implementing these concepts, however, can be challenging for some students.  In this article, we’ll focus on conditional statements and how to use them.

What is a Conditional Statement? 

Photo by Pixabay

Conditional statements, sometimes known as control structures, are one of the fundamental ‘building blocks’ of computer programming.  These statements allow programmers to execute or skip certain pieces of code, based on defined conditions.

Take a moment and think about this scenario: you’re about to leave the house, and you need to know what kind of outerwear you need for the day.  Your decision is largely going to be based on the weather, so you check the forecast to see how warm it will be and whether or not it will rain.  If the forecast is fairly warm but calls for rain, you’ll put on your rain jacket; if it’s cold outside and might snow, you’ll opt for a winter coat instead.  If it’s cool and breezy, but dry, you might put on a light jacket, and if it’s going to be a beautiful, warm, sunny day, you might skip wearing a jacket entirely.  The outcome of this scenario (what type of outerwear you put on, and if you put on any at all) depends on certain conditions in the weather forecast. 

If Statements 

The two most commonly used types of conditional statements are if statements and switch statements.  An if statement has two parts: a condition, and a code block.  The statement evaluates its condition, and runs the code block only if the condition evaluates to true.  If statements are sometimes followed by an ‘else statement’, which will run if the condition in the if statement evaluates to false.  (Else statements are optional, and if statements can be used without them–for example, you can skip writing an else statement if you don’t want anything special to happen when the if condition evaluates to false.)

if(5 > 4) //this statement evaluates to 'true'
{
    Console.WriteLine("Five is greater than four!");
}
else 
{ 
    Console.WriteLine("If the condition in line 9 was false, this would print out instead."); 
}

Let’s revisit our decision-making scenario above.  If we were to translate this into code, we could assign the forecasted high temperature and whether or not it was likely to rain into a couple of variables, aptly named ‘temperatureinFahrenheit’ and ‘isGoingToRain’.  If it’s not going to rain, and the temperature is between 55 and 70 degrees Fahrenheit, we’ll want to wear a light jacket when we go outside.  The code for that decision may look something like this: 

bool isGoingToRain = false; 
int temperatureInFahrenheit = 71; 

if(temperatureInFahrenheit > 55 && temperatureInFahrenheit < 70 && !isGoingToRain){ 
    WearALightJacket(); 
}

The above example is written in C#; with the condition for the if statement in parenthesis, and the code block in curly brackets directly following the condition.

Logical Operators 

You may have noticed some interesting syntax in the condition!  The double-ampersand && represents the logical operator AND, and the bang (known as an exclamation mark, outside of a programming context) represents the logical operator NOT.  Using these operators, we can translate the condition into a sentence: if the temperature in Fahrenheit is greater than 55, AND the temperature in Fahrenheit is less than 70, AND [it is] NOT going to rain… then, we’ll wear a light jacket when we go outside.

In computer programming, ‘boolean’ means a result that can only have one of two values.  (Think of the boolean data type, which is always either true or false.) Conditional statements rely on boolean logic, which takes two code statements or expressions, and uses a logical operator to decide on whether the entire expression is true or false.

There are three common logical operators: 

OperatorSymbolSymbol NameBehavior
AND&&double-ampersandconditions on both sides of the AND operator need to evaluate to true for the statement to be true
OR|| pipesonly one condition on either side of the OR operator needs to evaluate to true for the statement to be true, although it is possible for both conditions to be true
NOT!bangconverts the boolean value directly following the operator to its opposite value (for example, !true evaluates to false) 

You can read through this ‘truth table’ to see the result of how logical operators evaluate expressions: 

if A is…and B is…A && BA || B!A
truetruetruetruefalse
truefalsefalsetruefalse
falsetruefalsetruetrue
falsefalsefalsefalsetrue

Else-If and Nested If Statements

If you need to check multiple conditions, you can you the ‘else if’ keyword combination, or a nested if statement (an if statement inside of another if statement).  Both of the examples below will result in the same output to the console!

Else if: 
if(age >= 18) { 
    Console.WriteLine("You are a legal adult!"); 
}
else if (age >= 18 && age < 21) { 
    Console.WriteLine("You are a legal adult, but can't purchase or consume alcohol in the United Sates!");
}
else { 
    Console.WriteLine("You are a minor!"); 
}
Nested if:
if(age >= 18) { 
    if(age > 21) { 
        Console.WriteLine("You are a legal adult, but can't purchase or consume alcohol in the United Sates!");
    }
    else {
    Console.WriteLine("You are a legal adult!"); 
    }
}
else { 
    Console.WriteLine("You are a minor!"); 
}

Switch Statements

Another kind of conditional statement is the ‘switch statement’.  Switch statements are a convenient way to perform different actions based on a single conditional expression.  Consider the below example, written in C#: 

int age = 19;

switch (age)
{
    case < 18:
        Console.WriteLine("You're a minor!");
        break;
    case >= 18:
        Console.WriteLine("You're an adult!”);
        break;
    default:
        Console.WriteLine($"You are {age} years old!");
        break;
}

In a switch statement, the expression for the switch is evaluated once, and the outcome of that evaluation is compared with the value of each ‘case’ statement.  If there is a match between the conditional outcome and the value of a case, the block of code associated with that case is executed.  In the above example, the expression is the value of ‘age’, which is 19.  This value matches the second case (under 21, when age is over 18), so “You’re an adult!” prints to the console. 

In a switch statement, only one case should execute, and it should be the first case which matches the outcome of the conditional expression.  The ‘break’ keyword is used to signify the end of code execution in the switch.  Once a case is matched and the code associated with the case has run, the ‘break’ keyword stops the execution of any further code inside of the switch statement, and normal programming flow resumes.

The ‘default’ keyword is used to define a catch-all case that will execute if no matching case is found in the switch. 

Conclusion

Understanding conditional statements is essential for any programmer, as they are one of the fundamental tools used in all computer programming.  Conditionals allow for dynamic decision-making, and by implementing them effectively, programmers can choose which code to execute based on specific conditions.  If you’re a new developer (which is likely, if you’re reading this article!), you should familiarize yourself with the syntax of if statements and switches in your chosen programming language, and practice them until you master the concept of conditional logic.  Like many things, it get easier the more you do it! 

Add a Comment