C if Statement
In this page:
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?
#include <stdio.h>
int main() {
int age = 20;
if (age >= 18) {
printf("Adult");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int number = 5;
if (number > 0) {
printf("Positive");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int n = 8;
if (n % 2 == 0) {
printf("Even");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int n = 8;
if (n > 0) {
printf("Positive ");
}
if (n % 2 == 0) {
printf("Even");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int main() {
int n = 8;
if (n > 0) {
if (n % 2 == 0) {
printf("Positive and even");
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: