if-else Statement

  • February 19, 2022
  • C
Matrix multiplication

As we have already seen that the if statement by itself will execute a single statement, or a group of statements when the expression following if evaluates to true, though it does nothing when the expression evaluates to false. Hence, for this distinct case, we need the else statement, which evaluates an expression when the condition is false.

Given below is the flowchart for the if-else statement:

The if block gets executed when the given condition is reached i.e., the condition is true, whereas, the else block is executed when the condition is false.

Key points:
  • The group of statements within the if curly braces (excluding the else) forms an if block.
  • The group of statements within the else curly braces creates an else block.
  • The else is written just below the if. The statements in the if block and those in the else block are indented to the right.
  • If there is only one statement in the else block to be executed, we could drop the pair of curly braces.
Example:
#include <stdio.h>

int main() {
    int age;
    printf("Enter Age: ");
    scanf("%d",&age);
    if(age>18)
    printf("Person is an adult for voting.");
    else
    printf("Person is underage for voting.");
    return 0;
}
Output:
Enter Age: 12
Person is underage for voting.
Enter Age: 34
Person is an adult for voting.
Nested if-else Statement:

The nested if-else means an if-else statement within an if or else block. Let’s take an example for better understanding:

#include <stdio.h>
int main() {
    int number1, number2;
    printf("Enter two integers: ");
    scanf("%d %d", &number1, &number2);

    if (number1 >= number2) {
      if (number1 == number2) {
        printf("Result: %d = %d",number1,number2);
           }
      else {
        printf("Result: %d > %d", number1, number2);
           }
    }
    else {
        printf("Result: %d < %d",number1, number2);
    }

    return 0;
}
output:
Enter two integers: 43 23
Result: 43 > 23

Note: also read about  Format specifiers in C & Decision-Making in C

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

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