Accept a number as input which will be 1 or 2, If it is 1, print 2. If it is 2, print 1.
(without using conditional statement)
The Challenge: No if-else Allowed!
This problem is a mind-bending puzzle. Usually, we'd use an if-else statement to swap 1↔2. But what if conditionals don't exist? Welcome to the world of mathematical logic where clever arithmetic replaces branching!
int a;
cin >> a;
// ❌ This would work BUT uses conditional!
if (a == 1) {
cout << 2;
} else {
cout << 1;
}
Let's analyze the problem:
Input (a) | Output | Relationship? |
---|---|---|
1 | 2 | 🤔 |
2 | 1 | 🤔 |
What pattern can we find?
Notice that: 1 + 2 = 3 and 2 + 1 = 3
So if we have one number, the other is: 3 - number
// If input is 1: 3 - 1 = 2 ✓
// If input is 2: 3 - 2 = 1 ✓
int a;
cin >> a;
cout << 3 - a; // One line solves it all!
3 - a
)
replaces an entire conditional structure! This is the elegance of mathematical thinking.
// Example 1: Input = 2
a = 2
Output = 3 - 2 = 1 ✓
// Example 2: Input = 1
a = 1
Output = 3 - 1 = 2 ✓
// Why does this work?
// Because we're finding the "complement" in the set {1, 2}
// The sum of both numbers is always 3
// So: other_number = total - current_number
There are multiple ways to solve this without conditionals:
cout << 3 - a; // Simplest and most readable
cout << (a ^ 3); // Bitwise magic!
// 1 ^ 3 = 2 (binary: 01 ^ 11 = 10)
// 2 ^ 3 = 1 (binary: 10 ^ 11 = 01)
cout << (a % 2) + 1; // Toggle between 1 and 2
// 1 % 2 = 1, then +1 = 2
// 2 % 2 = 0, then +1 = 1
cout << -a + 3; // Same as 3 - a
int lookup[] = {0, 2, 1}; // index 0 unused, 1→2, 2→1
cout << lookup[a];
Method | Formula | Readability | Performance |
---|---|---|---|
Subtraction | 3 - a |
⭐⭐⭐⭐⭐ | ⚡ Fastest |
XOR | a ^ 3 |
⭐⭐⭐ | ⚡ Fastest |
Modulo | (a % 2) + 1 |
⭐⭐⭐⭐ | ⚡ Fast |
Array Lookup | lookup[a] |
⭐⭐⭐ | ⚡ Fast |
What if we had different numbers?
// To toggle between two numbers X and Y:
// Formula: (X + Y) - current
// Toggle between 5 and 10:
Output = (5 + 10) - a; // = 15 - a
// If a=5: 15-5=10 ✓
// If a=10: 15-10=5 ✓
// Toggle between 0 and 1 (common in binary):
Output = 1 - a; // or use: a ^ 1
This technique appears in many contexts:
3 - a
avoid branches
entirely, leading to:
This problem teaches a crucial programming skill: recognizing patterns. When you can't use the "obvious" solution, step back and look for mathematical relationships. Often, the most elegant solution is the simplest one!
3 - a
!
#include <iostream>
using namespace std;
int main() {
int a;
cin >> a;
cout << 3 - a;
return 0;
}