How to use 'if...else' conditional statement in C

'if...else' Conditional Statement

In C, the 'if...else' conditional statement is used for conditional execution of a block of code out of two alternative blocks of code.

If the 'if' condition is true, the code block under 'if' condition will be executed. If the 'if' condition is false, the code block under 'else' condition will be executed.

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...else' condition

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

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

Create an 'if...else' conditional statement

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

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

Explanation of code:

  1. if (5 > 10): The line declares an 'if' conditional statement where the condition is '5 > 10'. We know that the condition is false as 5 is not greater than 10.
  2. printf("10 is greater than 5.");: The line is the code block under 'if' statement. In this case, this code block will not be executed as the 'if' condition is false.
  3. else is used to execute a block of code if the condition of 'if' statement is false. In this case, the 'else' code block will be executed as the condition is false.
  4. printf("5 is less than 10.");: The line is the code block under 'else' statement. In this case, this code block will be executed as the 'if' condition is false.

Live Code Playground

In the following C code editor, you can practice by creating more 'if...else' 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