Conditional Statements in C

M4-R5.1 · Chapter 4: Building IoT applications · 3 min read

Conditional Statements

Conditional statements are used to perform different actions based on different conditions. Very often when you write code, you want to perform different actions for different decisions.

In C programming we have the following conditional statements:

  1. If statement
  2. If else statement
  3. If else if statement
  4. Nested If statement
  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false

The if Statement

Use the if statement to specify a block of C code to be executed if a condition is true.

Syntax

if (condition) {

// block of code to be executed if the condition is true

}

Example: -

#include <stdio.h>
int main() {
    int marks = 75;

    if (marks >= 50) {
        printf("You passed the exam!");
    }
    
    return 0;
}

Output: You passed the exam!

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax -

if (condition) {

// block of code to be executed if the condition is true

}

else {

// block of code to be executed if the condition is false

}

Example :-

#include <stdio.h>

int main() {
    int age = 16;

    if (age >= 18) {
        printf("Eligible to vote.");
    } else {
        printf("Not eligible to vote.");
    }
    
    return 0;
}

 Output: Not eligible to vote.

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {

// block of code to be executed if condition1 is true

}

else if (condition2) {

// block of code to be executed if the condition1 is false and condition2 is true

}

else {

// block of code to be executed if the condition1 is false and condition2 is false

}

Example:-

#include <stdio.h>
int main() {
    int marks = 72;

    if (marks >= 90) {
        printf("Grade: A\n");
    } else if (marks >= 75) {
        printf("Grade: B\n");
    } else if (marks >= 60) {
        printf("Grade: C\n");
    } else {
        printf("Grade: F\n");
    }
    
    return 0;
}

Output: Grade: C