If Else Conditional Statements in C

Get Certified in C Programming and Take Your Skills to the Next Level

Conditional statements are the bedrock of programming, enabling your code to make informed decisions and respond dynamically. Among these, the if-else-if ladder stands out as a powerful construct for intricate decision-making. In this comprehensive guide, we will deeply explore if-else-if ladders and delve into various facets of conditional statements in C/C++ programming, with a special focus on beginners.

Understanding If-Else Statements

Conditional statements, like the if-else construct, allow your program to choose between different paths based on specific conditions.

In C/C++, an if-else statement is structured like this:

if (condition) {
    // Code 
} else {
    // Code 
}

The condition within the parentheses is evaluated. If true, the code within the first set of curly braces is executed. If false, the code within the else block is executed.

Single If Statements

The building block of conditional programming is the single if statement. It lets you execute code only when a particular condition is met. Consider a temperature check:

#include <stdio.h>

int main() {
    int temperature = 32;

    if (temperature > 30) {
        printf("It's a hot day!\n");
    }

    return 0;
}

Output:

if else output

In this example, if the temperature is above 30 degrees, the message “It’s a hot day!” will be displayed.

single if else output

Simple If-Else Statements

When dealing with two distinct outcomes, a simple if-else statement shines. For instance:

#include <stdio.h>

int main() {
    int score = 85;

    if (score >= 90) {
        printf("Grade: A\n");
    } else {
        printf("Grade: B or below\n");
    }

    return 0;
}

Output:

simple if else output

simple if else

This code snippet determines whether a student’s score deserves an A or not.

Else If Statements

For scenarios with multiple potential outcomes, the else-if statement comes into play. It enables testing a sequence of conditions.

Imagine a grading system:

#include <stdio.h>

int main() {
    int evaluation = 78;

    if (evaluation >= 90) {
        printf("Assessment: Outstanding\n");
    } else if (evaluation >= 80) {
        printf("Assessment: Commendable\n");
    } else if (evaluation >= 70) {
        printf("Assessment: Satisfactory\n");
    } else {
        printf("Assessment: Needs Improvement\n");
    }

    return 0;
}

Output:

else if output

Here, the program evaluates conditions sequentially and assigns a corresponding grade.

else if

Nested If-Else Statements

In addition to the if-else-if ladder, nested if-else statements handle even more complexity:

#include <stdio.h>

int main() {
    int x = 5;
    int y = 7;

    if (x > 0) {
        if (y > 0) {
            printf("Both x and y are positive.\n");
        } else {
            printf("Only x is positive.\n");
        }
    } else {
        printf("Neither x nor y is positive.\n");
    }

    return 0;
}

Output:

nested if else output

This code snippet categorizes the relationship between x and y.

nested if else

If else-if ladder

The if-else-if ladder handles various conditions by executing specific blocks of code for each case. If a condition is true, its associated code runs. If none match, the else block’s code executes. This is similar to a switch-case setup, where the else block is like the default case.

if (condition1) {
    // Code executed when condition1 is met
} else if (condition2) {
    // Code executed when condition2 is met
} else if (condition3) {
    // Code executed when condition3 is met
}
// ...
else {
    // Code executed if none of the conditions are met
}

#include <stdio.h>

int main() {
    int temperature = 27;
    if (temperature <= 0) {
        printf("It's freezing out there!\n");
    } else if (temperature > 0 && temperature <= 15) {
        printf("The weather is quite chilly.\n");
    } else if (temperature > 15 && temperature <= 25) {
        printf("It's a comfortable day.\n");
    } else if (temperature > 25 && temperature <= 35) {
        printf("It's getting hot.\n");
    } else {
        printf("It's scorching hot!\n");
    }

    return 0;
}

Output:

It’s getting hot.

else if ladder

Conditional Expressions

Conditional expressions, often referred to as ternary expressions, offer a concise method for making decisions in programming. They evaluate a given condition and return one of two values based on whether the condition is true or false. This enables the creation of succinct, one-line expressions that select between different values or outcomes.

#include <stdio.h>

int main() {
    int years = 21;
    
    // Utilizing a conditional statement to ascertain voting capability
    const char* status = (years >= 18) ? "able to participate in voting" : "not eligible to vote";
    
    printf("At %d years old, you are %s.\n", years, status);

    return 0;
}

Output:

At 21 years old, you are able to participate in voting.

In this adapted example, the term “conditional expression” is used to describe the concise decision-making process. The condition (age >= 18) is evaluated, and depending on the result, the expression after? (“eligible to vote”) or after : (“not eligible to vote”) is assigned to the votingStatus variable. The program then prints a personalized message based on the person’s age. The use of the conditional expression simplifies decision-making in a compact manner.

Combining Logical Operators with If-Else

Logical operators like AND (&&) and OR (||) amplify the power of if-else statements. For instance:

#include <stdio.h>

int main() {
    int personAge = 20;
    int hasValidID = 1; // 1 indicates true

    if (personAge >= 18 && hasValidID) {
        printf("Welcome aboard! You've got the green light.\n");
    } else {
        printf("Oops! Looks like this journey isn't ready for you just yet.\n");
    }

    return 0;
}

Output:

combining logical operator with if else

Here, both age and having an ID are required for club entry.

Relational Operators

Relational operators are fundamental elements in programming, and computer science used to establish relationships and comparisons between values or expressions. These operators help determine the interactions and order between different data types, aiding in decision-making processes within algorithms and logical operations. They return Boolean values, either “true” or “false,” indicating whether a given relationship or condition is satisfied.

Here are some commonly used relational operators:

  • Equal to (==): This operator compares two values for equality and returns “true” if they are equal and “false” otherwise.
  • Not equal to (!=): This operator checks if two values are not equal and returns “true” if they are not equal and “false” if they are equal.
  • Greater than (>): This operator compares if the value on the left is greater than the value on the right. It provides a “true” outcome when the condition is satisfied and yields “false” otherwise.
  • Less than (<): This operator checks if the value on the left is less than the value on the right. It returns “true” if the condition is satisfied; otherwise, it returns “false.”
  • Greater than or equal to (>=): This operator determines if the value on the left is greater than or equal to the value on the right. It yields “true” if the condition holds true; otherwise, it yields “false.”
  • Less than or equal to (<=): This operator establishes whether the value on the left is less than or equal to the value on the right. It provides “true” if the condition is met; otherwise, it provides “false.”

Example:

#include <stdio.h>

int main() {
    int score = 87;
    score = score + 13;

    if (score == 100) {
       printf("Congratulations, you've reached a perfect score!");
    }

    return 0;
}

Output:

Congratulations, you’ve reached a perfect score!

Real-World Examples

  • Bank Loan Approval: Using if-else statements, a bank’s software can decide whether to approve a loan based on credit score, income, and other factors.
  • Weather Forecast: A weather app can display different recommendations using if-else statements, depending on the current weather conditions.
  • Online Shopping: E-commerce websites use if-else statements to display customized recommendations and discounts to users based on their browsing history.

Best Practices for Writing If-Else Statements

  • Readable Formatting: Employ proper indentation to enhance code readability.
  • Descriptive Variable Names: Clearly named variables illuminate code intentions.
  • Comments: Add comments to elucidate complex conditions or logic.
  • Modularization: Break complex conditions into functions for better code organization.

Conclusion

A solid grasp of if-else-if ladders and conditional statements is vital for programmers. These tools empower your programs to adapt to diverse scenarios. By understanding the basics, utilizing single-if statements, grasping simple if-else statements, mastering else-if statements, and harnessing the potential of the if-else-if ladder, you’ll be equipped to tackle a wide array of programming challenges.

Remember, mastery comes through practice. Experiment with conditions, nesting, and logical operators to reinforce your comprehension. Happy coding!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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