Search code examples
javafor-loopcomputer-science

for loop, misunderstanding


just to note, i am new CS student, so i barely understand whats going on

The question at hand is to find totA and totB, now i know the answer is 10 and 5. But i dont understand how it gets this answer. When i try to do this my self the answer i get is totA = 12, and totB = 6

I got totA by adding 6 first, then adding the 4 after the second loop and finally get 12 as the answer. for totB, i assume do to there being two ++, with i++ and totB++, this should result to 6

If someone could help correct my misunderstanding that will be very helpful Thank you

public class MyClass { public static void main(String args[]) {

    int valone = 6;
    int valtwo = 2;
   
    int totA = 0;
    int totB = 0;
    
    for(int i=valone; i>valtwo i=i-2) {
        totA = totA + i;
    }
   
    for(int i=valtwo; i<=valone; i++) {
        totB++;
    }
    
  System.out.println(valone);
  System.out.println(valtwo);
  System.out.println(totA);
  System.out.println(totB);
 
}

}


Solution

  • Here is the state at the end of each iteration for both loops.

    Loop 1

    iteration | totA | i
    #1          6    | 4
    #2          10   | 2
    

    The value of i (2) is equal to valueTwo (2) after the second iteration, which fails to satisfy that i > valueTwo, so the loop terminates when totA is 10.

    Loop 2

    iteration | totB | i
    #1          1      3
    #2          2      4
    #3          3      5
    #4          4      6
    #5          5      7
    

    The value of i (7) is greater than valueOne (6), which fails to satisfy that i <= valueOne so the loop terminates when totB is 5.