C If-Else

A clear concept about if-else statement.

If-Else:

The 'if-else' statement is used to control the flow of a program based on a condition. It allows you to specify two different blocks of code to execute depending on whether a given condition is true or false. Here's the basic syntax of the if-else statement:

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

How it works?

1. The 'if' keyword is followed by a condition enclosed in parentheses. This condition is an expression that evaluates to either true or false.

2. If the condition is true, the code inside the curly braces immediately following the 'if' statement is executed.

3. If the condition is false, the code inside the 'else' block (the curly braces following 'else') is executed.

Here's an example to illustrate the usage of the 'if-else' statement:

c Copy Code
#include <stdio.h>

int main() {
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

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

    return 0;
}
Output:
Enter a number: 4
4 is even.

In this example, the program asks the user to input a number and then checks if the number is even or odd using the 'if-else' statement. If the condition '(number % 2 == 0)' is true, it prints that the number is even; otherwise, it prints that the number is odd.

Multiple If-Else:

You can also use multiple 'if-else' statements in a nested fashion to create more complex branching logic, for example:

c Copy Code
#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;
}
Output:
Enter your score: 85
Grade: B

The program takes a student's score as input and then uses multiple 'if-else' statements to determine the grade based on the score. The conditions are checked in order, and the first condition that is true will execute its corresponding block of code. If none of the conditions are true, the code inside the 'else' block will execute.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.