if statement in C – free C programming tutorial

In this tutorial, you will be familiarize with one type of conditional statement that is if statement available for C programming language, along with its syntax and example of if-statements.

Conditional statements : 

Conditional statements are those code which allows you to control the program’s flow of the execution centred on a condition.
It means that the statements in the program are not executed in sequence.
Rather, one group of statements is executed, depending on how the condition is evaluated.


if statement:

Syntax :

if (condition)
 {
   statement;
   statement;
 }

Working of if-statement:

  1. If condition written in brackets() is true, then single statement or multiple statements inside the curly braces executes, otherwise skipped.
  2. Numerical values other than zero is considered true while zero is false.

Diagram which illustrates the working or compiling of if-statement :

if statement


Example consisting single if statement:

C code for determining which of the two numbers is lesser among the two given numbers i.e variable x = 10 and y = 20:

// header file
#include <stdio.h>
   
int main()    // compiling of program starts from main function
{

// Declaration of local variables
    int x = 10;
    int y = 20;

// if statement
// (x<y) is condition
// if condition written in brackets is true then inner body is executed 
    if (x<y)
      {
        printf("Variable x is less than y");
      }

// if condition written in brackets is false then inner body is skipped
// control of program reach to below statement
    return 0;
}

Output:

Variable x is less than y


Example consisting multiple if statements :

C code for determining which of the two numbers is greater or lesser among the two given numbers i.e variable x= 20 and y= 10:

// header file
#include <stdio.h>
int main()  // compiling of program starts from main function
{
// Declaration of local variables
    int x = 20;  
    int y = 10;
// if statements
// (x<y) is condition 
// if condition (x<y) is true then inner body is executed otherwise skipped
    if (x<y)
      {
        printf("Variable x is less than y");
      }
// if statements
// (x>y) is condition 
// if condition (x>y) is true then inner body is executed otherwise skipped
    if (x>y) 
      { 
        printf("Variable x is more than y"); 
      }
    return 0;
}

Output:

Variable x is more than y

This is all about the one type of conditional statement that is if statement available for C programming language, along with its syntax and example of if-else.
If you have any query please comment below.

Leave a Comment

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