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
Selected Reading
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 is to be made. This function can be made in many ways based on the logic you use. The easiest way to do this is to use a conditional statement that if the number is 1 then return 2 otherwise return 1 and ways include using mathematical operations (any will do) and XOR operation.
Example
#include <stdio.h>
// Method 1 using the if statement
int reverseif(int x) {
if (x == 1) return 2;
else return 1;
}
// Method 2 using the subtarction form sum of the two numbers (3 in this case)
int reversesub(int x){
return (3-x);
}
int main() {
printf("%d
", reverseif(1));
printf("%d
", reversesub(2));
return 0;
}
Output
2 1
Advertisements
