Sunday, April 2, 2023

C macro for factorial

Macro in C for computing the factorial of a number:
#include <stdio.h>

#define FACT(n) ((n <= 1) ? 1 : n * FACT(n-1))

int main() {
    int n = 5;
    int result = FACT(n);
    printf("Factorial of %d is %d\n", n, result);
    return 0;

Factorial of 5 is 120

In this example, the FACT macro with an argument n is defined that calls itself recursively to compute the factorial of n.

The ternary operator is used to check whether n is less than or equal to 1. If so, it returns 1, which is the base case of the recursive algorithm. If n is greater than 1, the macro multiplies n by the result of FACTORIAL(n-1), which computes the factorial of n-1.

No comments:

Post a Comment