Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a function that returns 2 for input 1 and returns 1 for 2 in C programming
A function that returns 2 for input 1 and 1 for input 2 can be implemented using various approaches. This is a common programming exercise that demonstrates different logical and mathematical techniques for value swapping between two specific numbers.
Syntax
int functionName(int x);
Method 1: Using Conditional Statement
The simplest approach uses an if-else statement to check the input value and return the corresponding output −
#include <stdio.h>
int reverseif(int x) {
if (x == 1)
return 2;
else
return 1;
}
int main() {
printf("Input 1, Output: %d<br>", reverseif(1));
printf("Input 2, Output: %d<br>", reverseif(2));
return 0;
}
Input 1, Output: 2 Input 2, Output: 1
Method 2: Using Mathematical Operation
This method uses subtraction from the sum of both numbers (1 + 2 = 3). Subtracting the input from 3 gives the desired result −
#include <stdio.h>
int reversesub(int x) {
return (3 - x);
}
int main() {
printf("Input 1, Output: %d<br>", reversesub(1));
printf("Input 2, Output: %d<br>", reversesub(2));
return 0;
}
Input 1, Output: 2 Input 2, Output: 1
Method 3: Using XOR Operation
The XOR operation provides an elegant bitwise solution. Since 1 XOR 3 = 2 and 2 XOR 3 = 1, we can use 3 as the XOR key −
#include <stdio.h>
int reversexor(int x) {
return (x ^ 3);
}
int main() {
printf("Input 1, Output: %d<br>", reversexor(1));
printf("Input 2, Output: %d<br>", reversexor(2));
return 0;
}
Input 1, Output: 2 Input 2, Output: 1
Comparison
| Method | Logic | Pros | Cons |
|---|---|---|---|
| Conditional | if-else statement | Easy to understand | More verbose |
| Mathematical | 3 - x | Concise, elegant | Less readable for beginners |
| XOR | x ^ 3 | Bitwise operation, efficient | Requires understanding of XOR |
Conclusion
All three methods effectively swap values between 1 and 2. The mathematical approach (3-x) is the most concise, while the conditional method is the most readable. The XOR method demonstrates bitwise manipulation techniques.
