C program to find square and cube of a number using macro – #define SQUARE(x), #define CUBE(x)

Write a C program to find square and cube of a number using macro. How to find cube of a number using macro #define preprocessor directive in C program. Logic to find square and cube of a number using macro.

Till now we have covered basics of macro how to define, undefine and redefine a macro in C programming. In this post I will explain how to find square and sum of two numbers using macro,  #define preprocessor directive in C program.

Required knowledge

Basic C programming, Macros

How to find square and cube of a number using macros?

In previous post we learned how efficient macros are at transforming small functions with simple logic. We learned to create our own macro to calculate sum of two numbers.

We are already aware with macro definition syntax, if not I have added it below. So, let us define two macro which accept a argument and return square and cube of given number. 

Syntax:

#define MACRO_NAME(params) MACRO_BODY

Where MACRO_NAME is name of the macro. params is parameters passed to macro. MACRO_BODY is the body where we will write actual logic of macro.

Example:

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

Program to find square and cube of a number using macro

/**
 * C program to find square and cube of a number using macro
 */

#include <stdio.h>

// Define macro to find square and cube
#define SQUARE(x) (x * x)
#define CUBE(x) (x * x * x)

int main()
{
    int num;

    // Input a number from user
    printf("Enter any number to find square and cube: ");
    scanf("%d", &num);

    // Calculate and print square
    printf("SQUARE(%d) = %d\n", num, SQUARE(num));

    // Calculate and print cube
    printf("CUBE(%d) = %d\n", num, CUBE(num));

    return 0;
}

Output

Enter any number to find square and cube: 10
SQUARE(10) = 100
CUBE(10) = 1000

Happy coding 😉