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

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: An");
} else if (grade >= 80) {
    printf("Grade: Bn");
} else if (grade >= 70) {
    printf("Grade: Cn");
} else {
    printf("Grade: Fn");
}

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.

In C programming, an if-else statement is a control statement that allows for conditional execution of code. It provides the ability to specify different blocks of code to be executed based on the evaluation of a condition. In this syntax, the condition is an expression that is evaluated to be either true or false.

If we want our programs to execute a different set of instructions when the condition is false, then we can use an else statement.

Key points about if-else statements:
  • Structure:
    • “if” block: Contains the code that will be executed if the condition is true.
    • “else” block: Contains the code that will be executed if the condition is false.
  • How it works:
    • The program evaluates the condition within the “if” statement.
    • If the condition is true, the code inside the “if” block is executed.
    • If the condition is false, the code inside the “else” block is executed (if present).

Related Posts

Leave a Reply