patterncModerate
Find whether a given number is a perfect square or not
Viewed 0 times
numbersquareperfectfindwhethergivennot
Problem
I am trying to find whether a given number is a perfect square or not by using just addition and subtraction.
Please review my code.
Please review my code.
#include
int check(int);
main()
{
int N;
printf("\n Enter the N:");
scanf("%d",&N);
if(check(N))
{
printf("\n[%d] Perfect Square:\n",N);
}
else
{
printf("\nNot perfect Square\n");
}
}
int check(int n)
{
int i=1;
while(n>0)
{
n-=i;
printf("[%d]",n);
i+=2;
}
if(n==0)
return 1;
return 0;
}Solution
Presentation
I have re-indented your code, I do not know how your code is on your side but you should definitly indent it properly.
Also, you should remove useless lines.
Naming
Documentation
Is it a good habit to add some documentation telling what your code is supposed to do. In your case, it could be nice to also tell the reader how it works.
The expression for the nth square number is n2. This is also equal to the sum of the first n odd numbers.
Types
You can use the bool type in C++.
I have re-indented your code, I do not know how your code is on your side but you should definitly indent it properly.
Also, you should remove useless lines.
Naming
check is not a good function name. isPerfectSquare would probably be easier for everyone to understand.Documentation
Is it a good habit to add some documentation telling what your code is supposed to do. In your case, it could be nice to also tell the reader how it works.
The expression for the nth square number is n2. This is also equal to the sum of the first n odd numbers.
Types
You can use the bool type in C++.
Context
StackExchange Code Review Q#41333, answer score: 14
Revisions (0)
No revisions yet.