1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: C++ Loops and Perfect Square

  1. Feb 12, 2012 #1
    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;

       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;
        int newRoot =1000;
        while (newRoot*newRoot < 1000 )
        cout<< newRoot*newRoot<<endl;

    Last edited: Feb 12, 2012
  2. jcsd
  3. Feb 12, 2012 #2
    I think it is because your while loop is never actually done because 1000*1000>1000

    not sure what your trying to do here
  4. Feb 12, 2012 #3
    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.
  5. Feb 12, 2012 #4
    hmm.... I think you might to try a do while loop and increase the number by 1 each time and check again
  6. Feb 12, 2012 #5

    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
  7. Feb 12, 2012 #6
    Thank-you, I see what I was doing wrong.

    We are required to use each std:: for our work, instead of loading the whole namespace.

    Thanks again :smile:
  8. Feb 12, 2012 #7
    As an aside, i.e. not homework, what if I wanted to write a square root function, that we allow you to set the given decimal points for stuff like the square of 7 or the square of 10.?

    I know C++ already has a sqrt function but could I use my code, clumsy though it may be or would I have to do something entirely different?
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook