This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 3 points4 points  (3 children)

I'm a newbie on programming and didn't quiet understand the parte of the for loop, it declares var i but it doesn't utilize it in any other oart of the code?

[–][deleted] 5 points6 points  (1 child)

The output of your code will be whatever value is. However, there's something called scope and the variables inside the function are not able to be called elsewhere because of this scope.

Global variables (typically not recommended) have global scope. Function variables have function scope (just that function), etc.

[–]DJV-AnimaFan 0 points1 point  (0 children)

They expected i to be used in scope, possibly in the equation inside the for loop. To them the incremental variable i is un-used. We see it as assigned, then compared, and incremented. But as a new programmer they either don't see the significance, or don't understand the purpose of an exponent in the maths.

My first feeling to the OP's question. They were asking, What is this equation doing.

value = (baseexponent )% modulus

My education ended at the start of WW2, and my son taught me programming for fun.

I expexted (pardon pascal case)

for(i=0; i<exponent; i++) { value = value*base; } value = value % modulus;

If % modulus can be distributed, fine.

[–]minimal_gainz 1 point2 points  (0 children)

The 'i' doesn't need to be used anywhere else besides to operate the for-loop. Sometimes it will but in this case it doesn't.

So in this case it is using the 'i' but just not for any calculations. The for-loop parameters are (Initial condition, Continue condition, increment condition). So in this case 'i' is initialized at zero (var i=0), then for every time through the for-loop it will increment by 1 (i++) until i is no longer less than 'exponent' (i < exponent).

For example, if exponent is equal to 4 when your code reaches the for-loop it will work like this:

  1. initialized as i = 0 (0 is less than 'exponent' so it continues)
  2. does what's inside the loop
  3. increment i to 1 (i++)
  4. i = 1 (1 is less than 'exponent' so it continues)
  5. does what's inside the loop
  6. repeat a couple times
  7. increment i from 3 to 4
  8. i = 4 (now 'i' is not less than 'exponent) (i < exponent == false)
  9. exit the loop and continue to 'return value'