# Problem with for and if loop

I am using the following code to calculate the square, cube and square root of numbers 1 through 12. I need a total of the square roots (but only if they are a perfect square). As the code is now, it prints all the information for all numbers, but the total of the Square roots stays at 1 when I believe it should really be 6.

If I move the closing brace for the If statement down below the Println statement, it only does all of the calculations for the first number and stops.

[code]// Calculate square, cube and square root of 1 to 12
class Numbers {
public static void main(String args[]) {
int n;
int s;
int c;
double sr;
double totSr=0;

for (n=1; n<=12; n++) {
s = n * n;
c = n * n * n;
sr = Math.sqrt(n);

if (n * n == sr) {
totSr = totSr + sr;
} // if
System.out.println("Num: " + n + " Square: " + s + " Cube: " + c + " Square Root: " + sr + " SqRt Total: " + totSr);

// System.out.println("Number is: " + n );
// System.out.println("Number Squared is: " + s);
// System.out.println("Number Cubed is: " + c);
// System.out.println("Square Root of Number is: "+ sr);
// System.out.println("Total of Square Roots is: " + totSr);
}//for
} // main
} // numbers [/code]

What am I doing wrong here?

Thanks,
Anne

• Look at this:
: [code]
: sr = Math.sqrt(n);
:
: if (n * n == sr) {
: totSr = totSr + sr;
[/code]
Is n*n == math.sqrt(n) ?
Do you see the error?

The one and only [b]Niklas Ulvinge[/b] [white]aka [b]IDK[/b][/white]

• : Look at this:
: : [code]
: : sr = Math.sqrt(n);
: :
: : if (n * n == sr) {
: : totSr = totSr + sr;
: [/code]
: Is n*n == math.sqrt(n) ?
: Do you see the error?
:
: The one and only [b]Niklas Ulvinge[/b] [white]aka [b]IDK[/b][/white]
:
:
No, I am sorry, I do not see the error.
Thanks,
• : : : [code]
: : : sr = Math.sqrt(n);
: : :
: : : if (n * n == sr) {
: : : totSr = totSr + sr;
: : [/code]

Math.sqrt(n) returns the square root of n and n*n is not equall to the square root of n.
But n is equall to the square root of n*n

The one and only [b]Niklas Ulvinge[/b] [white]aka [b]IDK[/b][/white]