Jump to content
  • Advertisement
Sign in to follow this  
darthstrife

Looping issue

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by darthstrife
Why 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 this post


Link to post
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 this post


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


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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!