HOME HTML EDITOR C JAVA PHP

If...Else in c language

In C programming, the **If...Else** statement is used to execute a block of code only if a specified condition is met. It is the primary way to control the flow of a program. Without decision-making statements, a program would always run the same way, line by line, without reacting to user input or data changes.

1. The Basic 'if' Statement

The if statement is the simplest form of decision-making. If the condition inside the parentheses evaluates to **true** (non-zero), the code block inside the curly braces {} is executed.

[Image of if statement flowchart in C programming]
if (condition) {
    // block of code to be executed if the condition is true
}

Example: Checking if 20 is greater than 18.

if (20 > 18) {
    printf("20 is greater than 18");
}

2. The 'else' Statement

The else statement is used to specify a block of code that should run if the if condition is **false**. This creates a "fork in the road" for your program.

int time = 20;
if (time < 18) {
    printf("Good day.");
} else {
    printf("Good evening.");
}
// Output: "Good evening."

3. The 'else if' Statement

When you have more than two possible paths, you use else if. It allows you to check multiple conditions sequentially. The program will execute the code for the **first** condition that is true and skip the rest.

int score = 75;

if (score >= 90) {
    printf("Grade: A");
} else if (score >= 70) {
    printf("Grade: B");
} else {
    printf("Grade: C");
}

4. Nested If Statements

You can also place an if statement inside another if statement. This is known as **Nesting**. It is useful when one condition depends on the success of a previous condition.

int age = 25;
int weight = 60;

if (age >= 18) {
    if (weight >= 50) {
        printf("You are eligible to donate blood.");
    }
}

5. Short Hand If...Else (Ternary Operator)

C provides a compact way to write an if-else statement using the Ternary Operator. It consists of three operands and is often used to assign values based on a condition.

Syntax: variable = (condition) ? expressionTrue : expressionFalse;

int time = 20;
// If time is less than 18, result is "Good day", otherwise "Good evening"
char* result = (time < 18) ? "Good day." : "Good evening.";
printf("%s", result);

6. Comparison Table of Decision Statements

To choose the right statement for your logic, refer to this summary table:

Statement Purpose
if Executes code if one condition is true.
else Executes code if the same condition is false.
else if Tests a new condition if the first one is false.
switch Tests a variable against a list of constant values.

7. Common Mistakes to Avoid

Pro Tip: When writing complex nested if-else structures, keep an eye on your Indentation. Well-indented code is easier to debug and prevents the "Dangling Else" problem, where it's unclear which if an else belongs to.