C if else Statement

Summary: in this tutorial, you will learn how to use C if else statement to control flow of the program based on a given condition.

C if statement

The if statement allows you to control the execution of code based on a  particular condition. The syntax of the if statement is as follows:

The body of the if statement only executes if the expression evaluates to non-zero value or true. If the expression evaluates to false, the statements inside the body of the if statement will be ignored.

The following flowchart illustrates the if statement:

c if statement flowchart

Let’s take a look at the following example:

The program asked users to enter a number. If the number is greater than zero, it displays a message showing that, otherwise it does nothing.

C if else statement

Sometimes you want to execute a piece of code in case the expression in the if statement evaluates to false. You can use the second form of the if statement which is known as if else statement. The following illustrates the syntax of the if else statement:

The following example demonstrates how to use the if else statement:

This program asks users to enter a number. It displays the corresponding message based on the input value.

C else if statement

If  you want to use more than one condition, you can use if else-if statement. The syntax of the if else if statement is as follows:

The else-if statement is used to make multiway decisions. The conditions in the corresponding if and else if branch evaluate in sequence from top to bottom. If a condition evaluates to true, the statements associated with it executes and terminates the whole chain.

The following flowchart illustrate the if else statement:

c if else statement flowchart

You can have as many branches as you want but it is not recommended because the code look less readable and difficult to maintain.

The following example compares the input number with zero (0) and displays corresponding message:

Putting it all together

We will use the if else statement to develop a simple currency conversion program.

How it works.

  • First, we define some popular exchange rates using constants such as USD to Euro, USD to Yen….
  • Second, we ask users to input USD amount and choose the corresponding currency.
  • Third, based on the user choice from menu from 1 to 5, we calculate the foreign currency amount. If users entered unknown currency, the program asks user to enter the exchange rate before doing calculation.

In this tutorial, we have shown you how to use various forms of the C if else statement to control flow of the program based on a given condition.