C If Statement

In this lesson, you will learn about Conditional Statements in C, particularly the if statement, and its usage, along with examples to better understand the topic.

What is a Conditional Statement?

A  conditional statement is a code block that determines a program’s execution route based on the set condition’s value. Code implementation can be divided into categories as shown below:

  • Sequential – this includes executing all the codes from top to bottom.
  • Decision – this one contains choosing several alternatives. The performed code relies on the condition’s value.

Like most programming languages, C enables you to write code based on the outcomes of a logical or comparative test condition at runtime that executes distinct activities. This implies that in the form of phrases that evaluate either true or false, you can generate test circumstances, and, based on these outcomes, you can execute specific activities.

This lesson will focus on the if conditional statement and its usage.

C If Statement

The if statement executes a code block based on a condition. The condition must be true. Otherwise, the compiler will not execute the code inside the statement.

Syntax of if statement

if(condition is true or false){
// Code to be processed here based on condition
}

Flowchart of if statement

Example of the “if Statment”

#include <stdio.h>

int main() {
  int
  var;
  printf("Enter an integer: ");
  scanf("%d", &var); // takes the input
  // true if input is divisible by 2
  if ((var % 2) == 0) {
    printf("The number you entered if dividable by 2 %d.\n",
      var);
  }
  return 0;
}

Output

Enter an integer: 8
Come in this block if you are divisible by 8

Program explanation

The program above takes the user input and checks if that input is dividable by 2. If the statement (var % 2) == 0, which is the modulus of var, is true, then the condition is met, and the code inside the if statement will be executed. Else, the program skips the code inside the if statement and reaches the end by executing the return 0.

In the next lesson, you will learn about another conditional statement in C, the if-else statement.