How to use 'if' conditional statement in C

'if' Conditional Statement

In C, the 'if' conditional statement is used for conditional execution of a block of code. The code will be executed if the condition is true.

The condition in an 'if' statement is evaluated in a boolean context (either 'True' or 'False').

These comparison operators ('==', '!=', '<', '>', '<=', '>=') and logical operators ('&&', '||', '!') are commonly used for comparison in the 'if' condition.

Syntax of 'if' condition

Simple syntax of 'if' condition is demonstrated in the following example:

  1. if (condition): In the line, 'if' is followed by a condition placed inside parentheses '()'.
  2. The block of code to be executed is placed inside curly braces '{}'. The code will be executed if the condition is true.

Create an 'if' conditional statement

An 'if' conditional statement has been created in the following example:

Example of 'if' conditional statement
Output of the above example
10 is greater than 5.

Explanation of code:

  1. if (10 > 5): The line declares an 'if' conditional statement where the condition is '10 > 5'. We know that the condition is true as 10 is greater than 5.
  2. printf("10 is greater than 5."); is the block of code which will be executed if the condition of 'if' is true. In this case, the code block will be executed as the 'if' condition is true.

'if' conditional statement with multiple conditions

An 'if' conditional statement with multiple conditions has been created in the following example:

Examples of 'if' conditional statement with multiple conditions
Output of the above example
10 is greater than 5 and 9 is smaller than 12.

Explanation of code:

  1. if (10 > 5 && 9 < 12): The line declares an 'if' conditional statement with two conditions '10 > 5' and '9 < 12' joined by logical AND (&&). We know that the both conditions are true.
  2. printf("10 is greater than 5 and 9 is smaller than 12."); is the code block which will be executed as the condition of 'if' is true. In this case, the code block will be executed as the 'if' condition is true.

Live Code Playground

In the following C code editor, you can practice by creating more 'if' conditional statements. Click the 'Execute Code' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output