Home > Backend Development > C++ > body text

Write a function in C programming that returns 2 when the input is 1 and 1 when the input is 2

WBOY
Release: 2023-09-10 13:25:02
forward
1031 people have browsed it

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.

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</p><p>", reverseif(1));
   printf("%d</p><p>", reversesub(2));
   return 0;
}
Copy after login

Output

2
1
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template