If-Else Statements in C

If-Else Statements in C: Making Decisions in Your Code



(toc)

If-Else Statements in C


An if-else statement is a control flow statement used to execute different code blocks based on a specified condition. It allows you to make decisions and perform different actions depending on the outcome of a logical expression.


Syntax:


if (condition) {
    // Code to be executed if the condition is true
} else {
    // Code to be executed if the condition is false
}
  • condition: An expression that evaluates to either true or false.
  • if block: The code block to be executed if the condition is true.
  • else block: The code block to be executed if the condition is false (optional).

Example:


int number = 10;

if (number > 0) {
    printf("The number is positive.\n");
} else {
    printf("The number is negative or zero.\n");
}

In this example, the if statement checks if number is greater than 0. If it is, the first printf statement is executed. If not, the else block is executed.


Nested If-Else Statements:

You can nest if-else statements within each other to create more complex decision-making structures.


int grade = 85;

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

Key Points:

  • The if statement is used to execute code conditionally.
  • The else block is optional and is executed if the condition is false.
  • Nested if-else statements can be used for more complex decision-making.
  • Use indentation to improve code readability.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!