If Statement in C | C Programming Tutorials

C if statement is a conditional statement in C programming language. It is used to when branching is required. In this C tutorial, you are going to learn what is if statement in C programming and how to use in C program.

C Tutorials

  1. Variables And Data Types
  2. Basic I/O Functions*
In 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 statement
  3. Nested if else statement

If Statement in C

If statement in C programming is used to control if a program enters a section of code or not based on whether the condition is true or false.

If statement is used when program needs do specific actions based on user input.

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.

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
}

Output

 Enter any number: 10 
 Given number is even 

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 - C Variables and data types Next - C if...else Statement