The Wayback Machine - https://web.archive.org/web/20221004052720/https://www.geeksforgeeks.org/c-if-else-statement/
Skip to content
Related Articles

Related Articles

C – if…else Statement

View Discussion
Improve Article
Save Article
  • Last Updated : 12 Sep, 2022
View Discussion
Improve Article
Save Article

In the C programming language, the if-else statement is used for decision-making. If the given condition is true, then the code inside if block is executed, otherwise else block code is executed. Any non-zero and non-null values are assumed as true, and zero or null, values are assumed as false values. 

Syntax:

if(conition) {
        // execute statement of if block when
          // condition is true
    }
      else {
        // execute statement of else block when
          // condition is false
    }

C




// C Program to show the if...else statement
#include <stdio.h>
  
int main()
{
    int a = 10;
    if (a < 20) {
        printf("Given Value is less than 20\n");
    }
    else {
        printf("Given Value is greater than 20");
    }
    return 0;
}

Output

Given Value is less than 20
if else in C

 

Advantages:

  • The if-else statement helps us to make decisions in programming and execute the right code.
  • It also helps in debugging code.

Disadvantages:

  • if-else statements increase the number of code paths to be tested.
  • If there are a lot of if statements the code sometimes becomes unreadable and complex.

Example 1:  Check whether a number is odd or even

C++




// C Program to find the 
// odd and even number using 
// if else statement
#include <stdio.h>
  
int main()
{
    int num = 5;
    if (num % 2 == 0) 
    {
        // if number is a multiple of 2 then
        // the remainder will be 0
        printf("%d is even number", num);
    }
    else 
    {
        // else the remainder will be odd
        printf("%d is a odd number", num);
    }
    return 0;
}

Output

5 is a odd number

Note: when we only have one line of code inside id or else we can skip the curly braces.

Example 2. Check whether the person is above 20 or not

C




// C Program to Demonstrate
// the example of if
// else statement
#include <stdio.h>
  
int main()
{
    int age = 25;
    if (age < 20)
        printf("Age less than 20");
    else
        printf("Age greater than 20");
    return 0;
}

Output

Age greater than 20

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!