# I am new to Java and wish to print the square of numbers from 1 to 10. thanks

• July 23rd, 2011, 01:27 PM
I am new to Java and wish to print the square of numbers from 1 to 10. thanks
import java.math.*;

public class Loops {
public static void main(String[]args)
{
int count=0,result=0,number = 1;
while(count<10)
{
result=(int)(Math.pow(number, 2));
result = result + count;
System.out.println(result);
count++;
}

}

}
• July 23rd, 2011, 03:30 PM
dlorde
Re: I am new to Java and wish to print the square of numbers from 1 to 10. thanks
What's the problem? and why are you adding 'count' to the result?

BTW using Math.pow(..) is fine, but it's simpler just to multiply the number by itself...
• July 23rd, 2011, 04:29 PM
Staticity
Re: I am new to Java and wish to print the square of numbers from 1 to 10. thanks
You don't want to add the count to the result....... Doing so changes the value of the result. What you meant to do is "number = number + counter".. But if you did that, you would get the squares of 0, 2, 4, 6, 8, etc.... This is because 0 + 0 = 0, then 1 + 1 = 2, etc... A simpler way to increase the value of number by 1 is to use "number++;" the same way you allowed the loop to stop by changing the counter in increments of 1.