C Tutorial menu

C If...Else and Switch

Conditions let a C program take different paths depending on values.

The if Statement

Example

c
#include <stdio.h>

int main(void) {
  int temperature = 40;
  if (temperature > 35) {
    printf("It is very hot today. Drink water!\n");
  }
  return 0;
}
Output
It is very hot today. Drink water!

if, else if and else

C checks each condition from top to bottom and runs the first block that is true:

Example

c
#include <stdio.h>

int main(void) {
  int units = 250;   // electricity units used

  if (units <= 100) {
    printf("Low usage\n");
  } else if (units <= 300) {
    printf("Normal usage\n");
  } else {
    printf("High usage\n");
  }
  return 0;
}
Output
Normal usage

True and False in C

C has no separate boolean type in older code. Any non-zero number counts as true, and 0 counts as false. Since C99 you can include <stdbool.h> and use bool, true and false:

Example

c
#include <stdio.h>
#include <stdbool.h>

int main(void) {
  bool isMember = true;
  if (isMember) {
    printf("You get a 10%% discount\n");
  }
  return 0;
}
Output
You get a 10% discount

To print a % sign with printf, write %%.

The Ternary Operator

A short form of if...else that picks one of two values:

Example

c
int n = 7;
printf("%s\n", (n % 2 == 0) ? "Even" : "Odd");
Output
Odd

The switch Statement

switch compares one whole number (or a char) with a list of fixed values:

Example

c
#include <stdio.h>

int main(void) {
  char choice = 'b';

  switch (choice) {
    case 'a':
      printf("Biryani\n");
      break;
    case 'b':
      printf("Nihari\n");
      break;
    case 'c':
      printf("Haleem\n");
      break;
    default:
      printf("Invalid choice\n");
  }
  return 0;
}
Output
Nihari
PartPurpose
caseOne value to match
breakLeaves the switch
defaultRuns when nothing matches

Without break, C continues into the next case. Sometimes this is useful, but usually it is a bug.

A Common Mistake

Writing = instead of == inside a condition sets the value instead of comparing it:

Example

c
int x = 5;
if (x = 0) {      // wrong: x becomes 0, and 0 is false
  printf("zero\n");
}

Always use == to compare.

Exercise

Exercise

In C, which value is treated as false in a condition?

Learn C with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp