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

C if Statement

What is an if Statement?

An if statement evaluates a condition and runs its block of code only when that condition is true -- if it's false, the block is skipped entirely and execution continues with whatever comes after it.

Example: What is an if Statement?

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

Simple Positive Check

You can use a single if statement to inspect a value and react to it, such as checking if (number > 0) to identify positive numbers, without needing an else branch when there's nothing specific to do for the false case.

Example: Simple Positive Check

c
#include <stdio.h>
int main() {
	int number = 5;
	if (number > 0) {
		printf("Positive");
	}
	return 0;
}

Checking Even Numbers

Combining the modulo operator with an if condition -- if (n % 2 == 0) -- lets a program detect even numbers by checking whether dividing by 2 leaves no remainder.

Example: Checking Even Numbers

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

Multiple Single if Checks

Writing several independent if statements in sequence means each condition is checked on its own, regardless of whether an earlier one was true -- unlike an else-if ladder, none of them are skipped just because a previous check already matched.

Example: Multiple Single if Checks

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

Nested if

An if statement placed inside another if's block only runs when both the outer and inner conditions are true, letting you build layered logic like first checking a number is positive, then separately checking if it's also even.

Example: Nested if

c
#include <stdio.h>
int main() {
	int n = 8;
	if (n > 0) {
		if (n % 2 == 0) {
			printf("Positive and even");
		}
	}
	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.