← Back to C Course | Chapter 4: Control Flow | Lesson 2 of 11

C if-else Statement

What is if-else?

if-else covers exactly two possible outcomes for a condition: the if block runs when the condition is true, and the else block runs instead whenever it's false, so exactly one of the two paths always executes.

Example: What is if-else?

c
#include <stdio.h>
int main() {
	int age = 15;
	if (age >= 18) {
		printf("Adult");
	} else {
		printf("Minor");
	}
	return 0;
}

Pass or Fail Check

Comparing a score against a passing threshold with if-else -- if (score >= 50) ... else ... -- cleanly separates the pass and fail outcomes into two distinct, mutually exclusive code paths.

Example: Pass or Fail Check

c
#include <stdio.h>
int main() {
	int score = 40;
	if (score >= 50) {
		printf("Pass");
	} else {
		printf("Fail");
	}
	return 0;
}

Even or Odd Divider

Testing n % 2 == 0 inside an if-else lets a single conditional handle both the even and odd cases in one block, rather than needing two separate if statements to cover both outcomes.

Example: Even or Odd Divider

c
#include <stdio.h>
int main() {
	int n = 7;
	if (n % 2 == 0) {
		printf("Even");
	} else {
		printf("Odd");
	}
	return 0;
}

Voting Eligibility

if-else is a natural fit for eligibility checks, such as verifying if (age >= 18) ... else ... to separate users who qualify for something from those who don't, in a single readable comparison.

Example: Voting Eligibility

c
#include <stdio.h>
int main() {
	int age = 16;
	if (age >= 18) {
		printf("Can vote");
	} else {
		printf("Cannot vote");
	}
	return 0;
}

Nested if-else

Nesting an if-else inside either branch of an outer if-else lets you handle sub-decisions -- for example, once you know a number is positive, a nested if-else can further classify it as even or odd.

Example: Nested if-else

c
#include <stdio.h>
int main() {
	int n = 8;
	if (n > 0) {
		if (n % 2 == 0) {
			printf("Positive even");
		} else {
			printf("Positive odd");
		}
	} else {
		printf("Not positive");
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.