if..else construction

1
(1)

The if...else Construction is a fundamental control flow statement in programming. It allows your code to make decisions by executing specific blocks of code only when certain conditions are met.

At its simplest, it evaluates a condition as either True or False.

Basic Structure

The syntax varies slightly by language, but the logic remains the same:

  1. if: Executes the code block if the condition is True.

  2. else: Provides an alternative path if the if condition is False.

Conceptual Example (Pseudocode)

Plaintext

if (it is raining) {
    take an umbrella
} else {
    wear sunglasses
}

Expanding the Logic

When you have more than two possibilities, you use else if (or elif in languages like Python) to test multiple conditions in sequence.

StatementPurpose
ifThe initial condition to check.
else ifAdditional conditions to check if the previous ones were False.
elseThe “catch-all” block if no previous conditions were True.

Implementation in Python

Python

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

Best Practices

  • Order Matters: Conditions are evaluated from top to bottom. Once one condition is met, the program executes that block and skips the rest of the chain. Always place your most specific conditions at the top.

  • Keep it Readable: If you find yourself nesting if statements too deeply (e.g., an if inside an if inside an if), consider using a switch or match statement, or breaking your logic into smaller functions.

  • Boolean Logic: You can combine multiple conditions using logical operators:

    • and: Both conditions must be True.

    • or: At least one condition must be True.

    • not: Reverses the boolean value.

 

Here are the following examples in the  if..else construction for different programming languages

C

C++

C#

Common Lisp

Dart

F#

Go

Java

JavaScript

Kotlin

Python

Rust

C
int n = 21;

if (n > 22) 
{
    printf("n > 22 \n");
} 
else if (n < 22) 
{
    printf("n < 22 \n");
} 
else 
{
    printf("n == 22 \n");
}

C++

#include <iostream>

int main()
{
    int n {21};
    if (n > 22)
    {
        std::cout << "n > 22" << std::endl;
    }
    else if (n < 22)
    {
        std::cout << "n < 22" << std::endl;
    }
    else
    {
        std::cout << "n == 22" << std::endl;
    }

    // if-else with variable initialization
    int a {5};
    int b {3};
    if(int c {a - b}; a > b)
    {
        std::cout << "a + b = " << c << std::endl;
    }
    else
    {
        std::cout << "a - b = " << c << std::endl;
    }
}

C#

C#

int n = 21;
     
if(n > 22)
{
    Console.WriteLine("n > 22");
}
else if (n < 22)
{
    Console.WriteLine("n < 22");
}
else
{
    Console.WriteLine("n = 22");
}

Common Lisp

Lisp

(let ((n 21))
    (if (> n 22)
        (format t "n > 22")
        (if (< n 22)
            (format t "n < 22")
            (format t "n = 22"))))

If the if block must have several expressions, which are formatted using the progn operator:

Lisp

(let ((n 21))
    (if (< n 22)
        (progn
            (format t "n < 22~%")
            (format t "n != 22~%"))))

To test the truth of a condition, you can also use the when macro, which is similar to if..then:

Lisp

(let ((n 21))
    (when (< n 22)
        (format t "n < 22~%")
        (format t "n != 22~%")))

The unless macro is equivalent to an else expression and tests the opposite condition:

Lisp

(let ((n 22))
    (when (< n 22)
        (format t "n < 22~%")
        (format t "n != 22~%"))
    (unless (< n 22)
        (format t "n >= 22~%")))

Dart

Dart

void main() {
    int n = 21;
    if(n > 22){
        print("n > 22");
    }
    else if(n < 22){
        print("n < 22");
    }
    else{
        print("n = 22");
    }
}

F#

F#

let n = 21
     
if n > 22 then
    printfn "n > 22"
elif n < 22 then
    printfn "n < 22"
else
    printfn "n = 22"

Getting the result from if..then

F#

let a = 21
let b = 22
let res = if(a > b) then 1 elif(a < b) then -1 else 0
printfn "%d" res

Go

Go

package main
import "fmt"
 
func main() {
    n := 21
     
    if n > 22 {
        fmt.Println("n > 22")
    } else if n < 22{
        fmt.Println("n < 22")
    } else{
        fmt.Println("n == 22")
    }
}

Java

Java

class Program {
    public static void main(String[] args) {  
        int n = 21;
     
        if(n > 22)
        {
            System.out.println("n > 22");
        }
        else if (n < 22)
        {
            System.out.println("n < 22");
        }
        else
        {
            System.out.println("n = 22");
        }
    }
}

JavaScript

JavaScript

let n = 21;
     
if(n > 22) {
    console.log("n > 22");
}
else if (n < 22){
    console.log("n < 22");
}
else{
    console.log("n == 22");
}

Kotlin

Kotlin

fun main() {
    val n = 21
    if(n > 22) {
        println("n > 22")
    }
    else if(n < 22){
        println("n < 22")
    }
    else{
        println("n = 22")
    }
}

Getting the result from if..else

Kotlin

fun main() {
    val a = 21
    val b = 22
    val res = if(a > b) 1 else if(a < b) -1 else 0
    println(res) // -1
}

Python

Python

n = 21
if n > 22:
    print("n > 22")
elif n < 22:
    print("n < 22")
else:
    print("n = 22")

Getting the result from if..else

Python

a = 21
b = 22
res = 1 if(a > b) else -1
print(res)

Rust

Rust

fn main(){
    let n = 21;
    if n > 22 {
        println!("n > 22")
    }
    else if n < 22 {
        println!("n < 22")
    }
    else{
        println!("n = 22")
    }
}

Getting the result from if..else

Rust       

fn main(){
    let a = 21;
    let b = 22;
    let res = if a > b {1} else {-1};
    println!("{}", res);
}



Next

How useful was this post?

Click on a star to rate it!

Average rating 1 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?


Explore More IT Terms


Share this term: Facebook X LinkedIn WhatsApp Email

Leave a Reply

Your email address will not be published. Required fields are marked *