To find square of a number

This program is to find the square of a number.

Logic:

  • for even number: 4 * (n/2)^2
  • for odd number: 4 * (n/2)^2 + 4 * (n/2) + 1

(n/2) = (n >> 1)

#include <stdio.h>

int square(int num)
{
    if (num ==1)
      return 1;
    else if (num ==0)
      return 0;
    else if (num%2 ==0)
      return (4 * square(num >> 1));
    else
    return (4 * square(num >>1) + 4 * (num >>1) +1);    
}

int main()
{
  int num;
  printf("\n Enter the number: ");
  scanf("%d", &num);
  printf("\n The square of the number is: %d", square(num));
  
  return 0;
}

Output:

Enter the number: 4
The square of the number is: 16


Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: