View Single Post
Old 04-04-2006, 11:37 PM   #13
tabacco
Friendly Server Admin
 
tabacco's Avatar
 
Join Date: Sep 2003
Location: Marin County, CA
Posts: 4,087
Default

Quote:
Originally Posted by SakSquash
What you said right there? All greek.
Okay, first the basic math...

The square of a number is that number times itself. So, the square of 2 is 4, the square of 6 is 36, the square of 10 is 100. Fair enough?

The cube is calculated just like the square, only you multiple by the same number once more. The cube of 2 is 8, or (2 * 2 * 2), the cube of 10 is 1000, or (10 * 10 * 10), etc.

Now onto the code...

Basically, all you need to do is count from 0 to 10, and print the square and cube of each number along the way, which is pretty much how you'd probablky do it on paper, right? So what you do is say "Ah, zero... well, the square of zero is zero, and the cube of zero is also zero" then you write that down, and move on to 1, and so on until you hit 10 and the homework's done, right?

Well, you just need to do the exact same thing with code. It just requires you to think a little more closely about the process than you woudl if you were doing it on paper.

Check out the for loop:
Code:
for(var number = 0; number <= 10; number = number + 1) { 
   foo
}
So as you can see, there are three parts to the loop statement, seperated by semicolons. The first one declares a variable called number, and sets the initial value to 0. Simple enough.

The second part is called the condition. Each time the loop runs, it will do whatever is where "foo" is in the code. It will keep doing "foo" over and over as long as the condition in the second part of the loop statement is true. So here it will keep looping as long as number is less than or equal to 10.

The third part is where the real magic happens. Each time the loop is run, this third part will be executed. So, after each time the loop runs here, number is going to be increased by one. That means that on the first run-through, number equals 0. The second time, it equals 1, and so on. Now, eventually it's going to get set to 11, at which point the second part will kick in and stop the loop from running again with 11 as the value.

So now you've got the code to count from 0-10 for you, right? That means all you have to do now is replace "foo" with the code to print those squares and cubes. To take the square of a number, you're going to use
Code:
Math.pow(number,2);
and to take the cube you're going to use
Code:
Math.pow(number,3);
Math.pow() is a function built into Javascript to take the power of a number (with the square being the second power, and a cube being the third). Basically the second argument to Math.pow() is the number of times the first argument should be multiplied by itself.

Does this help at all?
tabacco is offline