Labs ICT
โญ Pro Login

If & Else

Life is full of decisions โ€” and so is code. You'll constantly need your program to pick a path based on conditions. That's where if, else if, and else come in.

The if Statement

The simplest form: if something is true, do this thing. If not, skip it.


#include 
int main() {
  int age = 18;
  if (age >= 18) {
    printf("You can vote!\n");
  }
  return 0;
}
    
Try it Yourself โ†’

Adding else if and else

When you need more than two branches, chain them with else if. The first matching condition wins, and the rest are skipped.


#include 
int main() {
  int score = 85;
  if (score >= 90) {
    printf("Grade A\n");
  } else if (score >= 75) {
    printf("Grade B\n");
  } else if (score >= 50) {
    printf("Grade C\n");
  } else {
    printf("Grade F\n");
  }
  return 0;
}
    
Try it Yourself โ†’

Nested if Statements

You can put an if inside another if. Handy when you need to check a second condition only after the first one passes.


#include 
int main() {
  int x = 10, y = 5;
  if (x > 0) {
    if (y > 0) {
      printf("Both are positive\n");
    }
  }
  return 0;
}
    
Try it Yourself โ†’

Truthy and Falsy in C

C doesn't have a boolean type by default. Instead, zero is false and anything non-zero is true. So if (1) always runs, and if (0) never does.


#include 
int main() {
  if (1) {
    printf("This always prints\n");
  }
  if (0) {
    printf("This never prints\n");
  }
  if (-1) {
    printf("Negative numbers are also true!\n");
  }
  return 0;
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which statement executes code when a condition is false?