# C++ Loops and Perfect Square

1. Feb 12, 2012

### mr.me

Heres my problem, step one I've solved. Step two only ever returns the original newRoot*newRoo and I don't understand how to correct it

To demonstrate event controlled loops use arithmetic to create:
1.Create a sequence to determine the next largest perfect square
2.Create another sequence to determine the next smallest perfect square for a value less than 1000

My code:

Code (Text):

#include <iostream>
#include <math.h>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;

main()
{
cout << "Enter a number for which to find the next largest perfect square: ";
int number;
cin >> number;
int sqRoot = 1;
while (sqRoot*sqRoot < number)  // sqRoot is too small
sqRoot++;                 //  try the next number
cout << sqRoot*sqRoot << endl;

cout<< "Enter a number for which to find the next smallest perfect square: ";
int newNumber;
cin>>newNumber;
int newRoot =1000;
while (newRoot*newRoot < 1000 )
newRoot-+newRoot;
cout<< newRoot*newRoot<<endl;

}

Last edited: Feb 12, 2012
2. Feb 12, 2012

### Punkyc7

I think it is because your while loop is never actually done because 1000*1000>1000

not sure what your trying to do here
newRoot-+newRoot

3. Feb 12, 2012

### mr.me

I guess that was an obvious mistake :tongue2:

Still I am not sure how to construct my loop for the problem in question

With the second loop I wanted to check each iteration until a got a value less-than the user entered value...

So if I entered 6 I wanted it to return a 4 because that is the first perfect square less than 6

Im not sure how to do this on paper or with the while loop.

4. Feb 12, 2012

### Punkyc7

hmm.... I think you might to try a do while loop and increase the number by 1 each time and check again

5. Feb 12, 2012

### Punkyc7

x=1
y=0
while(y<input)
{
if(x*x>input)
break
y=x*x;
x++
}

cout <<y

I think that might do it

you could say "using namespace std" instead of saying all the using at the top

Last edited: Feb 12, 2012
6. Feb 12, 2012

### mr.me

Thank-you, I see what I was doing wrong.