Search code examples
variablesintegerprintfscanfperfect-square

Squares from Integer Variables in C


How do you make squares from integer variables?

Here is my code:

#include <stdio.h>

int main(){

   int n, p1, p2, p3, p4;
   printf("Enter 4 numbers:")
   scanf("%d %d %d %d", &n, &p1, &p2, &p3);
   printf("%d %d %d %d\n", n, p1, p2, p3);
   return 0;

}

Edit 1: Thanks for all your answers guys! I would request for this thread to be closed.


Solution

  • There are different ways of squaring a number. You will find four different ones below:

    #include <stdio.h>
    
    int main()
    {
       int p1, p2, p3, p4;
       int p3s;
    
       printf("Enter 4 numbers:"); /* 
       scanf("%d %d %d %d", &p1, &p2, &p3, &p4);
    
       p1 = p1 * p1; /* square p1 value */
    
       p2 *= p2; /* square p2 value */
    
       p3s = p3 * p3; /* square p3 value */
    
       printf("%d %d %d %d\n", p1, p2, p3s, p4 * p4 /* square p4 value*/);
    
       return 0;
    }
    

    For (very) large numbers, the squares can overflow.