Skip to main content

Conditional Branching

Description

You are given an integer n. Your task is to determine the relationship between n and the number 5, then print the appropriate message:

  • If n is greater than 5, print "Greater than 5"
  • If n is less than 5, print "Less than 5"
  • If n is equal to 5, print "Equal to 5"

This problem introduces the fundamental concept of conditional branching — the ability of a program to choose different paths of execution based on whether a condition is true or false. Conditional branching is one of the most important building blocks in programming because it allows your code to make decisions.

Without conditionals, a program would execute every line in order from top to bottom, unable to react to different inputs. With conditionals, your program becomes intelligent — it can respond differently depending on the data it receives.

In most programming languages, conditional branching is implemented using if, else if (or elif), and else statements. These constructs evaluate a boolean expression (something that is either true or false) and execute the corresponding block of code.

Examples

Example 1

Input:

n = 8

Output:

Greater than 5

Explanation: The value of n is 8. We compare 8 with 5. Since 8 > 5 is true, the program enters the first branch and prints "Greater than 5". The remaining conditions (less than 5, equal to 5) are never evaluated because the first matching condition short-circuits the decision chain.

Example 2

Input:

n = 4

Output:

Less than 5

Explanation: The value of n is 4. First, we check if 4 > 5 — this is false, so we skip the first branch. Next, we check if 4 < 5 — this is true, so the program enters the second branch and prints "Less than 5". The final else branch (equal to 5) is never reached.

Example 3

Input:

n = 5

Output:

Equal to 5

Explanation: The value of n is 5. First, we check if 5 > 5 — this is false (5 is not strictly greater than 5). Then we check if 5 < 5 — also false. Since neither the "greater" nor "less" condition matched, we fall through to the else branch, which handles the only remaining possibility: n equals 5. This demonstrates the exhaustive nature of if-else chains — every possible case is covered.

Constraints

  • 1 ≤ n ≤ 1000
  • n is a positive integer
  • Output must be exactly one of: "Greater than 5", "Less than 5", or "Equal to 5"
  • Do not print a newline after the result

Editorial

Brute Force

Intuition

The most natural way to think about this problem is exactly how a human would decide. Imagine you are standing at a fork in a road with three paths, each labeled with a sign:

  • Path 1: "Take this if the number is bigger than 5"
  • Path 2: "Take this if the number is smaller than 5"
  • Path 3: "Take this if the number is exactly 5"

You look at your number, read each sign one at a time from top to bottom, and take the first path whose condition matches. Once you take a path, you ignore the remaining signs.

This is precisely what an if-else if-else chain does in code. The computer evaluates conditions sequentially from top to bottom. The moment it finds a condition that evaluates to true, it executes that branch's code and skips all remaining branches.

In this brute force approach, we use three independent if statements — each one checks a separate condition. This works correctly but does not take advantage of the fact that the three conditions are mutually exclusive (if one is true, the others must be false). Every condition is evaluated regardless of whether a match was already found.

Step-by-Step Explanation

Let's trace through with n = 8:

Step 1: Read the input value n = 8. Store it in memory.

Step 2: Evaluate the first condition: n > 5. Substituting: 8 > 5. This is true.

Step 3: Since the condition is true, execute the body: print "Greater than 5".

Step 4: Even though we already found our answer, the program continues to the next if statement (because we are using independent if statements, not else if). Evaluate: n < 5. Substituting: 8 < 5. This is false. Skip this block.

Step 5: Continue to the third if statement. Evaluate: n == 5. Substituting: 8 == 5. This is false. Skip this block.

Step 6: All three conditions have been checked. The program produced the correct output "Greater than 5", but it wasted two unnecessary comparisons after already finding the answer.

Now let's trace with n = 5:

Step 7: Read n = 5. Evaluate n > 5: 5 > 5 is false. Skip.

Step 8: Evaluate n < 5: 5 < 5 is false. Skip.

Step 9: Evaluate n == 5: 5 == 5 is true. Print "Equal to 5".

Step 10: All three conditions checked. Correct output produced, but again all three comparisons were evaluated even though only the third matched.

Independent If Statements — Evaluating All Conditions — Watch how three separate if statements each evaluate their condition independently, even after a match is found.

Algorithm

  1. Read the integer n from input
  2. Check if n > 5 using a standalone if statement — if true, print "Greater than 5"
  3. Check if n < 5 using a second standalone if statement — if true, print "Less than 5"
  4. Check if n == 5 using a third standalone if statement — if true, print "Equal to 5"
  5. All three conditions are evaluated independently every time, regardless of matches

Code

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    
    // Three independent if statements — all are checked
    if (n > 5) {
        cout << "Greater than 5";
    }
    if (n < 5) {
        cout << "Less than 5";
    }
    if (n == 5) {
        cout << "Equal to 5";
    }
    
    return 0;
}
n = int(input())

# Three independent if statements — all are checked
if n > 5:
    print("Greater than 5", end="")
if n < 5:
    print("Less than 5", end="")
if n == 5:
    print("Equal to 5", end="")
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        // Three independent if statements — all are checked
        if (n > 5) {
            System.out.print("Greater than 5");
        }
        if (n < 5) {
            System.out.print("Less than 5");
        }
        if (n == 5) {
            System.out.print("Equal to 5");
        }
        
        sc.close();
    }
}

Complexity Analysis

Time Complexity: O(1)

We perform exactly 3 comparisons every time, regardless of the input value. While this is constant time, it is not the minimum number of comparisons needed — at most 2 comparisons suffice to determine which of the three cases applies.

Space Complexity: O(1)

We use only a single integer variable n. No additional data structures are needed.

Why This Approach Is Not Efficient

The brute force approach using three independent if statements has a subtle but important flaw: it always evaluates all three conditions, even after finding a match.

Consider n = 8:

  • The first if (n > 5) is true — we print the answer.
  • But the program still checks if (n < 5) and if (n == 5), both of which are guaranteed to be false.

In this toy problem with only 3 comparisons, the waste seems negligible. But this pattern reveals a deeper issue:

  1. Unnecessary computation: The three conditions are mutually exclusive — a number is either greater than, less than, or equal to 5. Once we know one is true, the others are definitively false. Checking them wastes CPU cycles.

  2. Bug risk: If the conditions were not perfectly mutually exclusive (a common mistake in more complex programs), multiple branches could execute, producing incorrect output. Using independent if statements does not enforce exclusivity.

  3. Scalability: Imagine extending this to 100 categories (grade ranges, tax brackets, etc.). Independent if statements would check all 100 conditions even if the first one matches. An if-else-if chain would stop at the first match.

A better approach uses the if-else if-else chain, which guarantees that the program stops evaluating conditions as soon as the first match is found.

Better Approach - If-Else If-Else Chain

Intuition

Instead of treating each condition as an independent question, we can link them together into a decision chain. Think of it as a series of gates:

  • Gate 1 asks: "Is n > 5?" If yes, you go through and are done. If no, you move to Gate 2.
  • Gate 2 asks: "Is n < 5?" If yes, you go through and are done. If no, you fall through to the default.
  • Default: If you reached here, the only remaining possibility is n == 5.

This is the if-else if-else pattern. The key insight is the else keyword, which means "only check this if ALL previous conditions were false." This creates a chain where:

  1. Conditions are evaluated top to bottom.
  2. The first true condition executes its block.
  3. All remaining conditions are skipped — they are never even evaluated.
  4. The final else acts as a catch-all for whatever remains.

This approach is more efficient because it performs at most 2 comparisons (worst case: n equals 5, both > and < fail) and as few as 1 comparison (best case: n > 5 matches immediately). It also makes the code's intent clearer — the three branches are explicitly mutually exclusive.

Step-by-Step Explanation

Let's trace through with n = 8:

Step 1: Read the input value n = 8.

Step 2: Evaluate the first condition in the chain: n > 5. Substituting: 8 > 5true.

Step 3: Since the condition is true, execute its block: print "Greater than 5". The entire if-else if-else chain is now done — we skip directly to the end, bypassing all remaining conditions.

Total comparisons: 1 (best case achieved).

Now let's trace with n = 4:

Step 4: Read n = 4. Evaluate n > 5: 4 > 5false. Skip this branch.

Step 5: Because the first condition was false, evaluate the else if condition: n < 5. Substituting: 4 < 5true.

Step 6: Print "Less than 5". Chain is done — skip the else block.

Total comparisons: 2.

Finally, let's trace with n = 5:

Step 7: Read n = 5. Evaluate n > 5: 5 > 5false. Skip.

Step 8: Evaluate n < 5: 5 < 5false. Skip.

Step 9: Both conditions failed, so the else block executes: print "Equal to 5". No additional comparison needed — the else branch is a logical guarantee that n must equal 5.

Total comparisons: 2 (worst case).

If-Else If-Else Chain — Short-Circuit Evaluation — Watch how the if-else if-else chain stops evaluating conditions as soon as the first match is found, skipping unnecessary comparisons.

Algorithm

  1. Read the integer n from input
  2. If n > 5, print "Greater than 5" and stop
  3. Else if n < 5 (only checked if Step 2 was false), print "Less than 5" and stop
  4. Else (only reached if both Steps 2 and 3 were false), print "Equal to 5"
  5. Maximum 2 comparisons, minimum 1 comparison

Code

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    
    // Linked if-else if-else chain
    // Only the first matching branch executes
    if (n > 5) {
        cout << "Greater than 5";
    }
    else if (n < 5) {
        cout << "Less than 5";
    }
    else {
        // n must be 5 — no comparison needed
        cout << "Equal to 5";
    }
    
    return 0;
}
n = int(input())

# Linked if-elif-else chain
# Python uses 'elif' instead of 'else if'
if n > 5:
    print("Greater than 5", end="")
elif n < 5:
    print("Less than 5", end="")
else:
    # n must be 5 — no comparison needed
    print("Equal to 5", end="")
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        // Linked if-else if-else chain
        if (n > 5) {
            System.out.print("Greater than 5");
        }
        else if (n < 5) {
            System.out.print("Less than 5");
        }
        else {
            // n must be 5 — no comparison needed
            System.out.print("Equal to 5");
        }
        
        sc.close();
    }
}

Complexity Analysis

Time Complexity: O(1)

We perform at most 2 comparisons and at minimum 1 comparison, regardless of the input value. This is strictly better than the brute force approach, which always performs 3 comparisons. In all cases, the number of operations is constant.

Space Complexity: O(1)

We use only a single integer variable n. No additional data structures are needed.

Why This Approach Is Not Efficient

The if-else if-else chain is already quite good for this specific problem. However, there are educational limitations worth addressing:

  1. Fixed threshold: The comparison value 5 is hardcoded in each condition. If the threshold changes, you need to update it in multiple places. A cleaner approach would store the threshold in a variable, making the code more maintainable.

  2. No function abstraction: The logic is written directly in main(). For real applications, decision-making logic should be encapsulated in a function that takes both the number and the threshold as parameters. This makes the code reusable, testable, and modular.

  3. Limited extensibility: What if we want to compare against multiple thresholds (e.g., grading: A, B, C, D, F)? The current approach would need manual extension. An optimal solution demonstrates function-based decision making that can be reused for any threshold.

The optimal approach wraps the decision logic in a reusable function, uses a parameterized threshold, and demonstrates clean, production-quality coding practices.

Optimal Approach - Function-Based Conditional with Parameterized Threshold

Intuition

In professional software development, logic that makes decisions should be encapsulated in functions. Instead of writing if-else chains directly in the main program, we create a function that:

  1. Takes parameters — both the value to check and the threshold to compare against.
  2. Returns a result — instead of printing directly, the function returns the appropriate string. The caller decides what to do with it (print it, store it, log it, etc.).
  3. Is reusable — the same function works for comparing any number against any threshold, not just n against 5.

Think of it like building a smart traffic light. Instead of hardcoding "turn red at 60 km/h", you build a speed checker that takes any speed and any limit as input, then returns whether the driver is over, under, or at the limit. The same checker works for a school zone (30 km/h), a highway (120 km/h), or a city road (50 km/h).

This approach also introduces the concept of separation of concerns: the decision logic is separate from the input/output logic. This is a fundamental principle of clean code that scales to large programs.

The conditional logic itself remains the same if-else if-else chain — the improvement is in how we organize and structure the code around it.

Step-by-Step Explanation

Let's trace through the function-based solution with n = 8 and threshold = 5:

Step 1: Read input n = 8. Define the threshold value as 5. These are our two parameters.

Step 2: Call the function compare(n, threshold)compare(8, 5). Control transfers into the function body.

Step 3: Inside the function, evaluate the first condition: value > threshold8 > 5true.

Step 4: Since the condition is true, the function prepares the return value: "Greater than 5". The function returns this string to the caller.

Step 5: Back in the main program, the returned string is received. Print it: "Greater than 5".

Now trace with n = 5 and threshold = 5:

Step 6: Call compare(5, 5). Inside the function, evaluate 5 > 5false. Move to else-if.

Step 7: Evaluate 5 < 5false. Move to else.

Step 8: The else block returns "Equal to 5". No comparison needed — it is the only remaining possibility.

Step 9: The main program prints the returned string: "Equal to 5".

Step 10: The function is reusable. We could call compare(100, 50) and it would return "Greater than 50". The logic is decoupled from the specific values 8 and 5.

Function-Based Decision Making — Parameterized Threshold — Watch how the decision logic is encapsulated in a reusable function that takes both value and threshold as parameters, making the code modular and clean.

Algorithm

  1. Define a function compare(value, threshold) that encapsulates the decision logic
  2. Inside the function, use an if-else if-else chain:
    • If value > threshold → return "Greater than {threshold}"
    • Else if value < threshold → return "Less than {threshold}"
    • Else → return "Equal to {threshold}"
  3. In the main program, read n and set threshold = 5
  4. Call compare(n, 5) and print the returned result
  5. The function is reusable for any value-threshold pair

Code

#include <iostream>
#include <string>
using namespace std;

// Function encapsulates the decision logic
// Takes value and threshold as parameters
string compare(int value, int threshold) {
    if (value > threshold) {
        return "Greater than " + to_string(threshold);
    }
    else if (value < threshold) {
        return "Less than " + to_string(threshold);
    }
    else {
        return "Equal to " + to_string(threshold);
    }
}

int main() {
    int n;
    cin >> n;
    
    // Clean separation: main handles I/O,
    // compare() handles logic
    cout << compare(n, 5);
    
    return 0;
}
def compare(value: int, threshold: int) -> str:
    """Compare value against threshold and return
    a descriptive string.
    
    Args:
        value: The number to evaluate
        threshold: The number to compare against
    
    Returns:
        A string describing the relationship
    """
    if value > threshold:
        return f"Greater than {threshold}"
    elif value < threshold:
        return f"Less than {threshold}"
    else:
        return f"Equal to {threshold}"


n = int(input())

# Clean separation: input/output here,
# decision logic in the function
print(compare(n, 5), end="")
import java.util.Scanner;

public class Solution {
    
    // Function encapsulates the decision logic
    static String compare(int value, int threshold) {
        if (value > threshold) {
            return "Greater than " + threshold;
        }
        else if (value < threshold) {
            return "Less than " + threshold;
        }
        else {
            return "Equal to " + threshold;
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        // Clean separation: main handles I/O,
        // compare() handles logic
        System.out.print(compare(n, 5));
        
        sc.close();
    }
}

Complexity Analysis

Time Complexity: O(1)

The function performs at most 2 comparisons (when n equals the threshold) and at minimum 1 comparison (when n is greater than the threshold). The function call overhead is negligible and constant. This matches the if-else if-else chain's efficiency while adding the benefits of modularity.

Space Complexity: O(1)

The function uses only its two parameters and a return string. No additional data structures are created. The string allocation is constant-sized (bounded by the length of the output message).