Search code examples
cperfect-square

Square using define directive not working


I implemented a squaring define directive as this :

#include <stdio.h>

#define SQR(y) ((y)*(y))

int main() {
    int a;
    printf("Enter : ");
    scanf("%d",&a);
    a = SQR(a);
    printf("The square is: %d\n",SQR(a));
    return 0;
}

But when I execute it, I don't get any error, but it is giving wrong answer every time.

Why is it giving 4th power instead of second power of input?


Solution

  • You are squaring it twice.

    In your code:

    a = SQR(a);
    printf("The square is: %d\n",SQR(a));
    
    1. this first makes a = a*a

    2. Now you print SQR((a*a)*(a*a)), or a*a*a*a

    You can replace SQR(a) in printf with a, or remove the a = SQR(a)

    Try this :

    #include <stdio.h>
    #define SQR(y) ((y)*(y))
    
    int main() {
        int a;
        printf("Enter : ");
        scanf("%d",&a);
        printf("The square is: %d\n",SQR(a));
        return 0;
    }