Course Content
Programming in C
About Lesson

A more general form of if statements is shown below:

if (expression)
  statement
else if (expression)
  statement
else if (expression)
  statement
else
  statement

The expressions are evaluated in order and if any expression is true (non-zero value), the corresponding statements is executed, terminating the if-elseif-else chain.
else serves as the default case, when none of the other cases apply. else is optional and may be omitted.

We illustrate the use of if-elseif-else in the following binary search function:

int search(int arr[], int length, int num)
{
  int low = 0;
  int high = length - 1;
  int middle;
  while (low <= high) {
    middle = low + (high - low) / 2;
    if (num > arr[middle])
      low = middle + 1;
    else if (num < arr[middle])
      high = middle - 1;
    else
      return middle;
  }
  return -1; /* number not found */
}
Scroll to Top