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;
}

Result:
Factorial of 5 is 120

Explanation:
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.


























Saturday, April 1, 2023

macro programming in C


Macro programming in C involves the use of preprocessor directives to define macros, which are essentially short pieces of code that can be used to simplify the programming process. Here's an example of how to use macros in C:

#include <stdio.h>

#define SQUARE(x) ((x) * (x))

int main()
{
    int num = 5;
    int square = SQUARE(num);

    printf("The square of %d is %d\n", num, square);

    return 0;
}
In this example, we define a macro called SQUARE, which takes a single argument x and returns the square of x. We then use the macro in our main function to calculate the square of the variable num, and store the result in a new variable called square.

video demonstration

Also we surround the entire macro definition with parentheses to ensure that the order of operations is correct, and surround the argument x with parentheses within the macro itself to prevent any unexpected behavior when the macro is used.

When we compile and run this program, we should see the following output:


The square of 6 is 36

This is because the macro SQUARE has replaced the expression SQUARE(num) with ((num) * (num)), which evaluates to 25 in this case.