If/Elseif/Else Statements

If/else type keywords allow for selective execution of instructions. When the first condition (following the if keyword) evaluates to false, then the next condition (following the elseif keyword) will be checked. Additional elseif statements can be added when needed. The else statement, which can be omitted, will "catch" situations where all of the other conditionals evaluated to false. Elseif keywords can also be omitted when only the if and else keywords are desired.

Syntax

  1. if(condition)
    1. Instruction;
  2. elseif(condition)
    1. Instruction;
  3. else
    1. Instruction;

--or--

  1. if(condition)
  2. {
    1. Instruction Block
  3. }
  4. elseif(condition)
  5. {
    1. Instruction Block
  6. }
  7. else
  8. {
    1. Instruction Block
  9. }

Example

  1. void main()
  2. {
    1. int a = 3;
    2. if(a<=2)
    3. {
      1. printf("\nSince A=3, this won't be printed");
    4. }
    5. elseif(a>=3)
    6. {
      1. printf("\nSince A=3, this will be printed");
    7. }
    8. else
    9. {
      1. printf("\nSince the previous elseif evaluated to true, this will not be printed");
    10. }
  3. }