If Statement In C

Rcommended Topics Before You Continue :

  1. Variables And Data Types
  2. Basic I/O Functions*
I our day to day life we have to choose one of the alternative paths based on the result of some condition. Conditions are expressions which evaluate to either true or false. This is know as branching or decision making.

Forms of if and else constructs are:

  1. if statement
  2. if-else
  3. Nested if else

1. If Statement

Syntax:

if(condition)
{

statements;

}
Note: If there are more than one statements in the if or else part they have to be enclosed in { } braces. If there is only one statement in if or else part it is not necessary to enclose it in { } braces but it is a good practice to do so.

For Example:
We will check whether the given number is even or not and depending on that we will print even or odd.
#include<stdio.h>

void main()
{

int num; // Declared a variable to save integer

printf("\n Enter any number:- "); 
scanf("%d",&num); // Accepting and saving integer in 'num' variable

if(num%2==0) // Checking whether value in num is divisible by 2
printf("Given number is even \n");  // Note: I have not used { } braces as we have to execute single statement.


}

Explanation:
In statement if(num%2==0),if the expression num%2==0 evaluates to true (1) the next statement printf("Given number is even \n"); will get executed. The expression will become true only if num hold an even number. If it is holding a odd number then there will be no output of above code as the expression in if evaluates to false (0) and there is no code after if statement.

Prev - Variables and data types in C Next - Learn if-else in C