Given an integer value, check the given input is divisible by 3. If it is divisible print the message "The number is divisible by 3". If it is not divisible print the message "The number is not divisible by 3 and gives a remainder _".
else if
allows you to check multiple conditions in sequence.
Syntax:
if (condition1) { /* block 1 */ }
else if (condition2) { /* block 2 */ }
else { /* block 3 */ }
How it works:
condition1
is checkedcondition2
condition2
is TRUE → Execute block 2else
block✅ Only ONE block will execute (the first condition that's true).
Multiple if statements (independent):
if (a > 0) { /* runs if true */ }
if (a > 10) { /* also runs if true */ }
❌ Both conditions are checked, and both blocks can run.
Else-if ladder (mutually exclusive):
if (a > 10) { /* runs if true */ }
else if (a > 0) { /* only runs if first is false */ }
✅ Only one block executes. Once a condition is true, the rest are skipped.
💡 Use else-if when: You have mutually exclusive conditions (only one should execute).
💡 Use separate if when: You want to check independent conditions that can both be true.
To check if a number is divisible by 3:
if (a % 3 == 0)
→ Number is divisible (remainder is 0)
if (a % 3 != 0)
→ Number is NOT divisible (remainder is 1 or 2)
Getting the remainder:
long long remain = a % 3;
Examples:
9 % 3 = 0
→ Divisible ✅10 % 3 = 1
→ Not divisible, remainder 125 % 3 = 1
→ Not divisible, remainder 154653 % 3 = 2
→ Not divisible, remainder 2Step-by-step with a = 25:
a = 25
if (25 % 3 == 0)
→ 25 % 3 = 1
, so 1 == 0
is FALSEelse if
else if (25 % 3 != 0)
→ 1 != 0
is TRUElong long remain = 25 % 3;
→ remain = 1
"The number is not divisible by 3 and gives a remainder 1"
Step-by-step with a = 9:
a = 9
if (9 % 3 == 0)
→ 9 % 3 = 0
, so 0 == 0
is TRUE"The number is divisible by 3"
Notice in this code we mix both styles:
Without braces (single statement):
if (a % 3 == 0)
cout << "The number is divisible by 3";
With braces (multiple statements):
else if (a % 3 != 0) {
long long remain = a % 3;
cout << "..." << remain;
}
✅ This is perfectly valid! The first block has ONE statement (no braces needed), but the second block has TWO statements (braces required).
💡 Key rule: You can mix styles in the same if-else chain. Each block follows its own rule based on statement count.
💡 Tip: Use else-if when checking mutually exclusive conditions to make your code more efficient!
#include <iostream>
using namespace std;
int main() {
long long a;
cin >> a;
if (a % 3 == 0)
cout << "The number is divisible by 3";
else if (a % 3 != 0) {
long long remain = a % 3;
cout << "The number is not divisible by 3 and gives a remainder " << remain;
}
return 0;
}