C - The if-else Statement

Hello, aspiring programmers! Today, we're going to dive into one of the most fundamental concepts in programming: the if-else statement. As your friendly neighborhood computer science teacher, I'm excited to guide you through this journey. So, grab your favorite beverage, get comfortable, and let's embark on this coding adventure together!

C - if...else statement

What is an if-else Statement?

Before we jump into the nitty-gritty, let's start with a real-life analogy. Imagine you're standing at a crossroads. You need to decide which path to take based on a specific condition. If it's sunny, you'll take the scenic route. Otherwise, you'll take the shorter path. This decision-making process is exactly what an if-else statement does in programming!

An if-else statement allows your program to make decisions based on certain conditions. It's like giving your code a brain to think and act accordingly.

Syntax of if-else Statement

Now, let's look at how we write an if-else statement in C. Don't worry if it looks a bit strange at first – we'll break it down step by step!

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Let's dissect this syntax:

  1. The if keyword starts the statement.
  2. The condition is placed inside parentheses (). This is what we're checking.
  3. If the condition is true, the code inside the first set of curly braces {} is executed.
  4. If the condition is false, the code after the else keyword (inside its curly braces) is executed.

Flowchart of if-else Statement

To visualize how an if-else statement works, let's look at a flowchart:

       +-------------+
       |   Start     |
       +-------------+
              |
              v
       +-------------+
       | Condition   |
       |   Check     |
       +-------------+
              |
          +---+---+
         /         \
    Yes /           \ No
       /             \
      v               v
+-------------+ +-------------+
|  Execute    | |  Execute    |
| 'if' block  | | 'else' block|
+-------------+ +-------------+
      |               |
      |               |
      +-------+-------+
              |
              v
       +-------------+
       |    End      |
       +-------------+

This flowchart shows how the program decides which block of code to execute based on whether the condition is true or false.

C if-else Statement Examples

Let's dive into some practical examples to see how if-else statements work in action!

Example 1: Checking if a number is positive or negative

#include <stdio.h>

int main() {
    int number = 10;

    if (number > 0) {
        printf("The number is positive.\n");
    } else {
        printf("The number is non-positive.\n");
    }

    return 0;
}

In this example:

  • We have a variable number with the value 10.
  • The condition number > 0 checks if the number is greater than zero.
  • Since 10 is indeed greater than 0, the condition is true.
  • Therefore, the program will print "The number is positive."

Let's try changing the value of number to -5:

int number = -5;

Now, the condition number > 0 is false, so the program will print "The number is non-positive."

Example 2: Determining if a person can vote

#include <stdio.h>

int main() {
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    if (age >= 18) {
        printf("You are eligible to vote!\n");
    } else {
        printf("Sorry, you are not eligible to vote yet.\n");
    }

    return 0;
}

This program:

  1. Asks the user to input their age.
  2. Checks if the age is 18 or above.
  3. If true, it informs the user they can vote.
  4. If false, it tells the user they're not eligible yet.

Try running this program with different ages and see how it responds!

The else-if Statement in C

Sometimes, we need to check multiple conditions. This is where the else if statement comes in handy. It's like adding more crossroads to our initial analogy.

Here's the syntax:

if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition1 is false and condition2 is true
} else if (condition3) {
    // Code to execute if condition1 and condition2 are false, and condition3 is true
} else {
    // Code to execute if all conditions are false
}

Let's see an example:

#include <stdio.h>

int main() {
    int score;

    printf("Enter your score: ");
    scanf("%d", &score);

    if (score >= 90) {
        printf("Grade: A\n");
    } else if (score >= 80) {
        printf("Grade: B\n");
    } else if (score >= 70) {
        printf("Grade: C\n");
    } else if (score >= 60) {
        printf("Grade: D\n");
    } else {
        printf("Grade: F\n");
    }

    return 0;
}

This program assigns a grade based on the score entered:

  • 90 or above: A
  • 80-89: B
  • 70-79: C
  • 60-69: D
  • Below 60: F

Try running this program with different scores and see what grade you get!

Conclusion

Congratulations! You've just learned about one of the most powerful tools in a programmer's toolkit: the if-else statement. With this knowledge, your programs can now make decisions, just like you do in real life.

Remember, practice makes perfect. Try creating your own programs using if-else statements. Maybe a program that decides what clothes to wear based on the weather, or one that recommends a movie genre based on your mood?

Keep coding, keep exploring, and most importantly, keep having fun! Until next time, happy programming!

Credits: Image by storyset