### Perfect square prgram

Hey Guys,
I just dont get the result that I want, this is a perfect square program but any number that is given to the program it returns not a perfect square, and i dont know why?
 ``1234567891011121314151617181920212223242526272829303132333435363738394041`` `````` #include using namespace std; int perfect_square(int); int main() { int result; int num=0; cout<<"enter a number: "; cin>>num; result = perfect_square(num); if (result=='1') { cout<<"perferct square"<=n; i++) { sqr = i*i; counter++; } if(sqr==n) { return '1'; } else { return '2'; } }``````
@moreme

You have a few problems.
1. You declared your function as int, but returning a char. Same with the variable, result

2. Your for loop in the function.
`for(int i=1; sqr>=n; i++)`
sqr should be an i. And it's <=, not >=

3. The checking in your program, should be checking the int value, not a char value

4. Your going through the entire number checking in the for loop, before you check it sqr was equal. ( Assuming that the loop was correct to begin with)
You should check after each multiplication, for equals.

Here's the program, corrected.

 ``123456789101112131415161718192021222324252627282930313233343536`` ``````// Perfect Square.cpp : main project file #include #include using namespace std; int perfect_square(int); int main() { int result; int num=0; cout<<"enter a number: "; cin>>num; result = perfect_square(num); if (result==1) { cout<<"perfect square"<
closed account (iAk3T05o)
Why are you using a char with a with an int. It's 1 not '1' and 2 not '2'
Take a look at the condition on line 28:

`for(int i=1; sqr>=n; i++)`

What is the initial value of sqr and what is the initial value of any n you pass to the function?

Also you don't want this for-loop to run past the value of n (Or do you?)

EDIT:
@Nathan2222, this should not matter seeing as chars have an integer value as well and OP seems to be checking for the same char value in main
http://www.asciitable.com/
Last edited on
 this should not matter seeing as chars have an integer value
Well yes, but the code looks odd. Using an appropriate type makes the code easier to read and understand. In this case I'd say the most suitable type would be `bool` rather than `int` or `char` as the function `perfect_square()` returns a yes/no that is `true` or `false` result.
Thanks guys all of your ideas were so useful.
Topic archived. No new replies allowed.