878850. The Else Statement

Basic

The Else Statement

Summary

The else statement is a fundamental concept in programming that allows us to execute a block of code when a certain condition is not met. In this problem, we will explore how to use the else statement effectively in various programming languages.

Detailed Explanation

The else statement is used in conjunction with if-else statements or switch statements. It provides an alternative code path to be executed when the original condition is not satisfied. The general syntax for using the else statement is as follows:

if (condition) {
    // code to execute when condition is true
} else {
    // code to execute when condition is false
}

Here, if the condition is met, the code inside the if block will be executed. If not, the code in the else block will be executed.

For example, let's say we have a program that takes an integer as input and checks if it's even or odd. We can use the else statement to handle the case when the number is neither even nor odd (which would mean it's an invalid input).

int num;
scanf("%d", &num);

if (num % 2 == 0) {
    printf("The number is even.\n");
} else {
    printf("The number is odd.\n");
}

In this example, if the num is even, the code inside the if block will be executed. If not, the code in the else block will be executed.

Optimized Solutions

Java

View on GeeksforGeeks
public class ElseStatement {
    public static void main(String[] args) {
        int num = 5; // invalid input - neither even nor odd

        if (num % 2 == 0) {
            System.out.println("The number is even.");
        } else {
            System.out.println("The number is odd.");
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.