Utilizor
Contact Us
HomeC TutorialC If...Else

CC If...Else

Conditional statements.

C Conditions and If Statements

C supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to: a == b
  • Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

C has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

Examples

If Statement

c example

Executing code if condition is true.

#include <stdio.h>

int main() {
  if (20 > 18) {
    printf("20 is greater than 18");
  }
  return 0;
}

Else Statement

c example

Executing code if condition is false.

#include <stdio.h>

int main() {
  int time = 20;
  if (time < 18) {
    printf("Good day.");
  } else {
    printf("Good evening.");
  }
  return 0;
}

Else If Statement

c example

Testing multiple conditions.

#include <stdio.h>

int main() {
  int time = 22;
  if (time < 10) {
    printf("Good morning.");
  } else if (time < 20) {
    printf("Good day.");
  } else {
    printf("Good evening.");
  }
  return 0;
}

Short Hand If...Else

c example

Using the ternary operator.

#include <stdio.h>

int main() {
  int time = 20;
  (time < 18) ? printf("Good day.") : printf("Good evening.");
  return 0;
}

Test Your Knowledge

1. Which keyword is used to test a condition?

2. What is the correct syntax for a short hand if...else?