tagsexponentialflowgorithm

What does for i = 1 ; i <= power ; 1 += 1) { mean?


Sorry for pretty basic question.

Just starting out. Using flowgorithm to write code that gives out a calculation of exponential numbers.

The code to do it is:

function exponential(base, power) {
    var answer;
    answer = 1;
    var i;
    for (i = 1 ; i <= power ; i+= 1) {
        answer = answer * base;
        }
    return answer;
    f

then it loops up to the number of power. And i just understand that in the flowgorithm chart but i dont understand the code for it. what does each section of the for statement mean? i = 1 to power, i just need help understanding how it is written? What is the 1+= 1 bit?

Thanks.


Solution

  • The exponential function will take in 2 parameters, base and power. You can create this function and call (fire) it when ever it is needed like so exponential(2,4). The for (i = 1; 1 <= power; i+=1) is somewhat of an ugly for loop. for loops traditionaly take three parameters. The first parameter in this case i =1 is the assignment parameter, the next one 1 <= power is the valadation parameter. So if we call the function like so...exponential(2,4) is i less than 4? The next parameter is an increment/decrement parameter. but this doesnt get executed until the code inside the for loop gets executed. Once the code inside the for loop is executed then this variable i adds 1 to itself so it is now 2. This is usefull because once i is no longer less than or equal to power it will exit the for loop. So in the case of exponential(2,4) once the code inside this for loop is ran 5 times it will exit the for loop because 6 > 5.

    So if we look at a variable answer, we can see that before this for loop was called answer was equal to 1. After the first iteration of this for loop answer = answer times base. In the case of exponential(2,4) then answer equals 1 times 2, now answer =2. But we have only looped through the foor loop once , and like i said a for loop goes like (assignment, validator, "code inside the foor loop". then back up to increment/decrement). So since we to loop through this for loop 5 times in the case of exponential(2,4) it will look like so.

    exponential(2,4)

    answer = 1 * 2
    now answer = 2
    
    answer = 2 * 2
    now answer = 4
    
    answer = 4 * 2
    now answer = 8
    
    answer = 8 * 2
    now answer = 16
    

    answer = 16 * 2 now answer = 32

    So if we could say... var int ans = exponential(2,4) Then ans would equal 32 hence, the return answer; at the last line of your code.