Public Group

# Looping issue

This topic is 4478 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Why won't this loop end when a non-perfect square is entered?
#include <stdio.h>

int main(void)
{
int N, root = 0, perfect = 0;
printf("Enter an integer: ");
scanf("%d", &N);
while(perfect != 1 || N > root * root)
{
if(N == root * root)
{
perfect = 1;
printf("The perfect square of %d is %d.\n", N, root);
}
else
root++;
}

system("PAUSE");
return 0;
}


##### Share on other sites
i thought that || should be an &&...although this messes up the cases where the number has a perfect square for some reason

##### Share on other sites
while(perfect != 1 && N >= root * root)

##### Share on other sites
thanks, i knew it was something stupid I was missing.

##### Share on other sites
Quote:
 Original post by darthstrifeWhy won't this loop end when a non-perfect square is entered?*** Source Snippet Removed ***

Your loop would be simpler if you only test for the one thing:
while (root*root < N){  ++root;}if (root*root == N){  // whoosiiiii!}

Obviously, that doesn't explain why your loop is not working :)

The loop is not working because either perfect!=1 or N>root*root is true when you enter a non perfect square. When N<root*root, perfect has to be 1, but it is never the case since you are not processing a perfect square.
So... see my simpler loop above :)

Regards,

##### Share on other sites
yeah i know it would be simpler but i need the perfect in there....i simplified the code here for clarity but in the actual program i was using pointers and perfect served a purpose...thanks everyone

##### Share on other sites
Quote:
 Original post by darthstrifein the actual program i was using pointers and perfect served a purpose...thanks everyone

No, it didn't. :) (Hint: just 'break' from the loop)

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 9
• 34
• 16
• 11
• 10
• ### Forum Statistics

• Total Topics
634122
• Total Posts
3015644
×