Question:
How to use a loop to initialize each element of array to the value of its index squared?
2016-01-25 13:10:55 UTC
Write a program that declares a 10-element array of i nt , uses a loop to initialize each element to the value of its index squared, and then uses another loop to print the contents of the array, one integer per line.

What do they mean by index squared?
Three answers:
?
2016-01-25 13:29:51 UTC
Picture an array as a tall, narrow dresser or chest of drawers. It has many drawers, but only one thing can fit in each of them. To help you keep track, you assign them numbers (or indexes). You start at the top- so the topmost drawer is 0, the next one down is 1, next is 2, then 3, then 4, and so on. The drawer all the way at the bottom will be one less than the total number of drawers since you started the numbering at 0. For example, to have 10 drawers, they would be numbered 0 through 9.



At this point, you should draw a picture of what I described and make sure you are with me so far. Got it? Good, let's keep going because this is going to be a little more abstract.



Now, let's say that instead of putting objects inside of the drawers, you are just going to put little slips of paper with numbers written on them. This is exactly the same idea as having an array of integer values.



Are you familiar with the concept of a number squared? It just means a number multiplied by itself. 1 squared is 1 x 1, 2 squared is 2 x 2, and so on. This problem is asking for the index squared. Remember that the index is our name for each individual spot (or drawer) in the array. The first spot is 0, so 0 x 0 should go into it. The second spot is number 1, so 1 x 1 should go into it, the third spot is 2, so 2 x 2 should go into it.



Does that help?
husoski
2016-01-25 13:40:46 UTC
Don't use Math.pow() for squaring. It's ugly, slow and ugly. Did I mention that it's ugly?

If you need "x squared", use x*x.



Inside your first for loop, discard the line that's there. It doesn't store anything into the array anyway, and the assignment says to initialize the array...right?



Instead. the only line in the loop should be:

num[i] = i*i;



i is the index of the element being initialized, and i*i is the square of that index.



------------

PS: The time to use Math.pow() is when the exponent is a variable, or if it's not a small positive integer. Also use it when the base is an expression and it's uglier to create a temporary variable to hold that expression value, followed by a temp*temp*temp calculation or something like it.
wg0z
2016-01-25 13:14:07 UTC
array[x] = x*x, for x in range 0..9


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...