c
  1. c-if-else-statement

C if-else Statement

Syntax

if (expression) {
  // executed if the expression is true
} else {
  // executed if the expression is false
}

Example

#include <stdio.h>

int main() {
   int num = 5;

   if (num > 0) {
      printf("%d is a positive number.\n", num);
   } else {
      printf("%d is not a positive number.\n", num);
   }

   return 0;
}

Output

The output of the above example will be:

5 is a positive number.

Explanation

The if-else statement in C checks if a given condition is true or false and executes the appropriate code block based on the result of the evaluation. In the example above, the condition is num > 0, which evaluates to true since num is equal to 5. The statement in the if block is executed since the condition is true, and the printf statement outputs "5 is a positive number".

Use

The if-else statement is a fundamental programming construct used in decision-making and control flow in C programs. It can be used for tasks such as input validation, error checking, conditional execution of code blocks, and more.

Important Points

  • The if-else statement has two possible code blocks, one for if the condition in the if statement is true and one for if it is false.
  • The condition in the if statement must evaluate to a Boolean value (true or false).
  • If the condition is true, the code block in the if statement is executed. Otherwise, the code block in the else statement is executed.
  • Multiple else-if statements can be used to check for additional conditions if the first condition is false.

Summary

The if-else statement is a fundamental part of C programming that allows for conditional execution of code blocks based on the evaluation of a Boolean expression. It can be used for tasks such as input validation, error checking, control flow, and more. Understanding the syntax and use cases for if-else statements is essential to writing effective C programs.

Published on: