If...else Statements


C supports two types of selection statements: 'if' and 'switch'. In addition, the '?' operator is an alternative to 'if' in certain situations.

The general form of the if statement is

if(expression)
{
 //body of code
}
else
{
 //body of code
}

Where a statement can contain a statement, a block of statements, or nothing. The else section is optional.

If the expression is evaluated as true, then the statement or block that constitutes the goal of 'if' is executed; otherwise, the statement or block that is the target of the other will be executed if it is present. Remember, only the code related to 'if' or the code associated with the other executes, never both.

In C, the conditional statement 'if' must create a scalar result control a scalar is either an integer, character, pointer or floating-point type. Using a floating-point number to control conditional statements is rare because it speeds up the time it takes to execute.

Sample Program

Program
// find the max number
#include <stdio.h>

int main() {
  int a = 10, b = 20;
  if(a > b)
   printf("a is big number");
  else
   printf("b is big number");
  return 0;
}

In the example above, the big number is found inside two numbers. If this expression "a> b" is true then the code block inside the 'if' statement will run and if false then the code inside the else statement will run. See a flowchart of this program in the picture on the right.

if...else flow diagram