How to write 6 different functions that accept 5 or 7 and return the other number, without using if,switch in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

/*
    Six different functions that accept 5 or 7
    and return the other number, without using if/switch.
*/

/* 1. Arithmetic sum trick: 5 + 7 = 12 */
int flip_sum(int x) {
    return 12 - x;
}

/* 2. Product trick: 5 * 7 = 35 */
int flip_product(int x) {
    return 35 / x;
}

/* 3. XOR trick: 5 ^ 7 = 2
      x ^ 2 flips 5 ↔ 7 */
int flip_xor(int x) {
    return x ^ 2;
}

/* 4. Modulo-based trick using divisibility:
      x % 7 == 0 → x is 7
      x % 5 == 0 → x is 5
   These expressions evaluate to 1 or 0 in arithmetic. */
int flip_mod(int x) {
    return 5 * (x % 7 == 0) + 7 * (x % 5 == 0);
}

/* 5. Absolute-value trick: |x - 12| flips 5 ↔ 7 */
int flip_abs(int x) {
    return abs(x - 12);
}

/* 6. Array lookup using boolean indexing */
int flip_array(int x) {
    static const int table[2] = {7, 5};
    return table[x == 5];  /* x==5 → 1 → 5; x==7 → 0 → 7 */
}

int main(void) {
    printf("flip_sum(5) = %d\n", flip_sum(5));
    printf("flip_sum(7) = %d\n\n", flip_sum(7));

    printf("flip_product(5) = %d\n", flip_product(5));
    printf("flip_product(7) = %d\n\n", flip_product(7));

    printf("flip_xor(5) = %d\n", flip_xor(5));
    printf("flip_xor(7) = %d\n\n", flip_xor(7));

    printf("flip_mod(5) = %d\n", flip_mod(5));
    printf("flip_mod(7) = %d\n\n", flip_mod(7));

    printf("flip_abs(5) = %d\n", flip_abs(5));
    printf("flip_abs(7) = %d\n\n", flip_abs(7));

    printf("flip_array(5) = %d\n", flip_array(5));
    printf("flip_array(7) = %d\n", flip_array(7));

    return 0;
}



/*
OUTPUT:

flip_sum(5) = 7
flip_sum(7) = 5

flip_product(5) = 7
flip_product(7) = 5

flip_xor(5) = 7
flip_xor(7) = 5

flip_mod(5) = 7
flip_mod(7) = 5

flip_abs(5) = 7
flip_abs(7) = 5

flip_array(5) = 5
flip_array(7) = 7

*/

 



answered Mar 31 by avibootz

Related questions

...