Home > Article > Backend Development > Write a function in C programming that returns 2 when the input is 1 and 1 when the input is 2
You need to make a function that returns 2 for input 1 and returns 1 for input 2. This function can be made in various ways depending on the logic you use. The simplest way is to use a conditional statement, if the number is 1, return 2, otherwise return 1, other ways include using math operations (any kind will work) and XOR operations.
#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</p><p>", reverseif(1)); printf("%d</p><p>", reversesub(2)); return 0; }
2 1
The above is the detailed content of Write a function in C programming that returns 2 when the input is 1 and 1 when the input is 2. For more information, please follow other related articles on the PHP Chinese website!