What Is a Condition in Coding

IF you clicked this article, THEN you are curious about conditional statements in programming! To give you the simplest possible explanation, a condition in coding is a chunk of code that will only be executed if certain criteria – defined by the programmer – are true.

I’m Jamie Lewis, and, for two decades now, one of my favorite hobbies has been writing computer programs. Some were basic scripts to assist in file management and backups. Others were more complex content management systems; in almost every scenario, though, I had to make good use of conditional statements in my code.

This article will look at what defines a conditional statement in coding, why they’re so important, and a few examples of how you can implement them in your code.

And with that said, there’s absolutely no reason for us to wait any longer – let’s get into conditions!

Conditional Statement Definition

Conditional statements (or “conditional expressions”) are instructions that direct the flow of computer code. Put simply, they tell a program to do several things depending on whether or not a condition has been met. Generally, they’ll be made up of at least two core components: IF and THEN.

To keep things simple, we’ll write our first example in pseudo-code. Let’s say you have a variable, ‘x,’ which is assigned a value of 0. Our program will simply test whether or not the value of ‘x’ is higher than 0; if it is, it will display a short text string.

    x has a value of 0

    IF x is more than 0 THEN:

    print “x has a value higher than 0”

That makes sense, right? Obviously, this code wouldn’t produce any visual result when executed, as it has only been instructed to print to the screen if x has a value of more than 0.

Types of Conditional Statements

While the IF..THEN structure might be the most basic example of a conditional statement; it’s far from the only one you should expect to use. Other popular conditional statement types include (but are not limited to):

  • IF,THEN,ELSE This is when things start to get interesting. An ‘IF,THEN,ELSE’ block allows you to provide two outcomes, depending on whether or not the conditions you set have been met. One will be executed if the condition is true. Otherwise, the alternative code will be executed.
  • IF,ELSE-IF,THEN Using the ELSE-IF statement, we can look for two – or more – specific conditions. This means we don’t need to rely on ELSE for every situation where our initial condition is not met. You can usually chain as many ELSE-IF statements together as you like, though it’s not considered great programming practice.
  • Nested IF Nested IF statements allow you to execute one IF statement within another (in other words, if the first condition is true, you can then test to see if a second condition is also true).
  • Switch statement A switch statement allows you to easily chain conditional statements based on checking for exact individual values. The benefit of switch statements is that C compilers typically use what’s called a “lookup table” when turning them into machine code; this often makes programs run significantly faster on users’ machines.
  • Nested Switch statement Nested switch statements are pretty advanced. Much like Nested IF checks, they allow you to check that one condition is true before checking another (rather than relying on “either-or” checks).

Conditional Statement Programming Examples

The best way to learn any programming concept is to practice using actual code. We’re going to demonstrate a few ways that you can use conditional statements in Java and C. Still, they should be easy enough to understand even if you’re using another language.

Conditional Statement Programming Java

Being one of the most popular and portable languages in the world, Java is an ideal candidate to demonstrate how a basic IF statement might be constructed:

    public class MyIfStatement {

   		public static void main(String args[]) {
   	   	int i = 1;

   	   	if(i<2) {
   	      	System.out.print("The current value of 'i' is less than 2!");
   	   	}
   		}
    }

(If you’re not a Java coder, just pay attention to the highlighted lines for the time being)

As you might already be able to tell, this basic program takes the value of an integer variable (‘i’) and compares it to a constant integer (2). As the condition is true (in other words, ‘i’ is less than 2), the string on the following line will then be printed to the screen.

Note: This is probably a good time to mention that, as shown in the above code block, the word ‘THEN’ doesn’t always need to be stated in conditional statements. This will vary according to the syntax of your chosen programming language!

Now, let’s elaborate a little further on this program and add an ELSE condition:

    public class NestedIfProgram {
    
   	public static void main(String args[]) {
      	int i = 4;
    
      	if(i<2) {
         	System.out.print("The current value of 'i' is less than 2!");
      	} else {
         	System.out.print("The current value of 'i' is actually higher than 2!");
      	}
   	}
    }

When this program is executed, the second string (“..higher than 2!”) will be displayed.

The program tests ‘i’ to see if its value is lower than 2, then – because that condition is untrue – it skips the first print instruction and moves immediately to the ELSE block. This block will be executed in any situation where ‘i’ is not less than 2!

Conditional Statements in C

It’s no surprise to see how closely an IF statement in C resembles its Java counterpart, seeing as both languages use very similar syntax.

    #include <stdio.h>

    int main () {
    
   	int i = 1;
         
   	if(i<2) {
      	printf("The variable 'i' has a value of less than 2\n" );
   	}
       
   	return 0;
    }

Let’s make things a little more interesting now. Here’s a Nested-IF statement in C.

	#include <stdio.h>
 
	int main () {
    
   	int i = 1;
    	 
   	if(i<3) {
          		printf("The variable 'i' has a value of less than 3\n" );
      	if (i==1){
              	printf("The variable 'i' has a value of 1\n");
      	}
   	}
  	 
   	return 0;
	}

While you could choose to write the above code as an IF-ELSE statement, it makes more sense here to only check if the value of ‘i’ is equal to 1 once we’ve already established that it’s less than 3. In other words, if the condition (i<3) is false, there’s no reason to check if it’s equal to 1 as that would be mathematically impossible. Feel free to set the value of ‘i’ to 2 here to see what happens when you run the code!

Both IF and ELSE statements can be nested within each other until your code is totally unreadable; this is typically considered awful programming practice, as there are far more eloquent solutions! In C, for example, we can use a switch statement to allow us to create a far greater number of outcomes without sacrificing the readability of our code.

Here’s a basic example of a switch statement:

    #include <stdio.h>
 
    int main () {
    
   	int i = 2;
    
   	switch(i) {
    	case 1 :
        	printf("i is set to 1\n" );
        	break;
    	case 2 :
        	printf("i is actually set to 2!\n");
        	break;
   	}
    
   	return 0;
    }

Importance of Conditional Statements in Programming

Computers would be limited to a very narrow range of applications without conditions. Essentially, they’d have to follow the exact same set of instructions any time a program was run. We can allow our programs to react according to user input with conditions.

Since the earliest computer programs and interactive games (such as Colossal Cave Adventure), conditional statements have been utilized to efficiently and quickly direct the flow of computer software according to the user’s needs.

Even the most basic tasks in today’s computers – moving a character in a video game, opening a text document, or playing an MP3 – all rely heavily on IF statements. Learning to use them efficiently is a valuable skill, and any aspiring programmer absolutely has to be able to use them competently.

Closing Thoughts

Conditional statements are chunks of code that allow us to execute certain instructions only when certain criteria are met. They’re a fundamental building block of software development and can appear in various forms (such as IF-ELSE statements, nested IF statements, switch statements, and more!).

Hopefully, this article has provided a solid primer on the topic, and we recommend experimenting with the code samples provided to ensure that you fully understand them!

Don’t forget to check back for more informative programming articles, and let us know your thoughts in the comments!

Leave a Reply

Your email address will not be published.