#include // This program queries the user for a non-negative // integer 'n' and then calculates the integer square // root of that value. // // The integer square root of 'n' is the largest // non-negative integer 'isqrt' such that // // isqrt*isqrt <= n. // // For example, the integer square root of 20 is 4, // because // // 4*4 <= 20 // // but // // 5*5 > 20. // // If n < 0, simply return 0. // // Exercise: // // Eliminate the loop variable 'm'. Can you use // 'isqrt' itself as the loop variable? // Function declarations int main(); // Function definitions int main() { int n{}; std::cout << "Enter a non-negative integer: "; std::cin >> n; if ( n < 0 ) { return 0; } int isqrt{}; for ( int m{ 0 }; true; ++m ) { if ( m*m <= n ) { isqrt = m; } else { break; } } std::cout << "The integer square root of " << n << " is " << isqrt << "." << std::endl; std::cout << isqrt << "*" << isqrt << " = " << isqrt*isqrt << " <= " << n << " < " << (isqrt + 1) << "*" << (isqrt + 1) << " = " << (isqrt + 1)*(isqrt + 1) << std::endl; return 0; } // Hint: // // The variable 'm' starts at 0 and increases until // its square is greater than 'n'. // // At the end of each successful iteration, its value // is copied into 'isqrt'. // // Could 'isqrt' itself start at 0 and increase until // its square becomes greater than 'n'? // // If so, what must you do after the loop terminates? // Here is one solution: /* int main() { int n{}; std::cout << "Enter a non-negative integer: "; std::cin >> n; if ( n < 0 ) { return 0; } int isqrt{}; for ( ; isqrt*isqrt <= n; ++isqrt ) { // Do nothing. } --isqrt; std::cout << "The integer square root of " << n << " is " << isqrt << "." << std::endl; std::cout << isqrt << "*" << isqrt << " = " << isqrt*isqrt << " <= " << n << " < " << (isqrt + 1) << "*" << (isqrt + 1) << " = " << (isqrt + 1)*(isqrt + 1) << std::endl; return 0; } */