Easy Tutorial
❮ C Exercise Example52 C Function Fputs ❯

Decision Making

Decision structures require programmers to specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is false.

In C, any non-zero and non-null values are considered true, and zero or null is considered false.

Here is the general form of a typical decision structure found in most programming languages:

Decision Statements

C provides the following types of decision statements. Click on the links to see details of each statement.

Statement Description
if statement An if statement consists of a boolean expression followed by one or more statements.
if...else statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
nested if statements You can use one if or else if statement inside another if or else if statement.
switch statement A switch statement allows a variable to be tested for equality against a list of values.
nested switch statements You can use one switch statement inside another switch statement.

? : Operator (Ternary Operator)

We have covered the conditional operator ? : in the previous chapter, which can be used to replace if...else statements. Its general form is as follows:

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Note the use and placement of the colon.

The value of a ? expression is determined by Exp1. If Exp1 is true, then Exp2 is evaluated and becomes the value of the entire expression. If Exp1 is false, then Exp3 is evaluated and becomes the value of the entire expression.

Example

The following example checks whether a number is odd or even by inputting a number.

Example

#include<stdio.h>

int main()
{
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    (num % 2 == 0) ? printf("Even") : printf("Odd");
}
❮ C Exercise Example52 C Function Fputs ❯