Abszol
Abszol

Reputation: 57

Trying To Understand The For Loop Completely

I understand how mostly everything works in a loop in Java but I came to a realization that I am failing to understand one thing which is The Order a Loop Operates.

Basically I am failing to understand this because of this simple but boggling piece of code that was displayed in my class, the code is displayed below.

public class Test {
    public static void main (String[] args) {
        int sum = 0;
        for (int k = 1; k < 10; k += 2)
        {
            sum += k;
            System.out.print(sum + " ");
        }
    }
}

The output the program puts out is 1 4 9 16 25

Now I understand how it repeats and spits out the numbers but how does it go about even creating 1. Now you can say it created 1 by taking k and adding it to sum but shouldn't k be equaling 3?

It goes k = 1; This sets k equal to 1. k < 10; Checks if k is less than 10. Then the question is when k += 2; Shouldn't k now equal to 3 but instead sum is now somehow equal to 1 after this operation occurred of adding 2 to 1, 2 + 1 = 3 but 3 + 0 = 1? How does this even go about.

My rationalizing for this is that any program I thought was to interpret code line by line or uniformly and not jumping around.

Overall my question is, how is sum equal to 1 when k is actually equal to 3.

Upvotes: 1

Views: 127

Answers (8)

ChriskOlson
ChriskOlson

Reputation: 513

Let's break up your code. The keyword for just means loop. It will start @ 1 and continue as long as k is less than 10. It will also increase by k+=2. To translate, it means k = k +2

Inside the loop sum = sum + k. It will then print the value that sum has plus a space.

k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25

and keep repeating. Let me know if you still have trouble grasping this concept

Upvotes: 0

Woody008
Woody008

Reputation: 96

Oh believe I had same problem. And you have to understand this quickly because when you are going to start doing bubble sort it will confuse you even more.

The thing you need to understand is that, its that it doesnt actually add +2 to 'k' until its done reading whats inside your 'for loop'

So this is how it starts, its starts with what you set 'k' for which is 1.

k = 1 is it less than 10? Yes, then do whats in the 'for loop' . Sum at first was initiated to 0. then in the first loop we add the value of k to whatever sum already has. So sum = 0, k = 1. Therefore 0 +1 = 1. then next line ouput the value of sum with space. AND here is the IMPORTANT PART, it has now reach the end of the loop. So now it will add +2 to the value that k already has.

So k = 1 + 2 = 3. And now we start the second loop. k=3, is less than 10? yes, ok do whats in for loop. add k to whatever value that sum already has. Sum is = 1 right ? and k is now equal to 3 right? So 3 + 1 = 4. And it display sum with a space and it has reach the end of the for loop so it add +2 to k that already has 3 in it which will equal to 5. and the loop continues.

oouff hope that helps! So remember it adds +2 at the end of the loop. Sorry if theres some typos typing from my samsung kinda annoying a bit cuz i have japanese keyboard... Good luck! has to

Upvotes: 1

Tim B
Tim B

Reputation: 41210

The sections of the for loop are run at different times.

  1. The first section is run once at the start to initialize the variables.

  2. The second is run each time around the loop at the START of the loop to say whether to exit or not.

  3. The final section is run each time around the loop at the END of the loop.

All sections are optional and can just be left blank if you want.

You can also depict a for loop as a while loop:

for (A;B;C) {
    D;
}

is the same as:

A;
while (B) {
    D;
    C;
}

Upvotes: 5

Gerard
Gerard

Reputation: 2860

k is only incremented after the loop iteration. In general for any loop the values are updated after a loop iteration so k goes 1,3,5,7,9 and so the sum is correct.

Upvotes: 2

Michael Yaworski
Michael Yaworski

Reputation: 13483

The last condition, k += 2 occurs after the first iteration of the loop.

So it's

k = 1, sum = 1
k = 3, sum = 4
k = 5, sum = 9
k = 7, sum = 16
k = 9, sum = 25

Upvotes: 2

Bernhard Barker
Bernhard Barker

Reputation: 55649

It goes like this:

  1. Initialize (k = 1)

  2. Check condition (k < 10) (stop if false)

  3. Run the code in the loop (sum += k and print)

  4. Increment (k += 2)

  5. Repeat from step 2

Following this logic, you get that 1 is printed first.

Upvotes: 2

MrMike
MrMike

Reputation: 1540

Let's step through your code:

  1. We setup an int with initial value of 0 and assign it to sum.
  2. We setup a for loop, setting int k = 1, and we will loop while k is less than 10, and after each iteration, 2 will be added to k.

So, the first iteration, k = 1. sum currently equals 0, so sum += k is actually 0 = 0 + 1 = 1. There's the 1 you are getting.

For the second iteration, k = 3. sum currently equals 1, so sum += k is actually 1 = 1 + 3 which is 4. There's the 4 that is showing up.

Repeat this for the rest of the loop!

Upvotes: 3

Martin Dinov
Martin Dinov

Reputation: 8825

In the first iteration of the loop, k=1. The k+=2 is only run at the beginning of the next iteration of the loop. The loop variable update condition (the last part of the for loop - i.e. the k+=2 part) never runs on the first iteration but does run on every other one, at the start. Therefore what you have is:

Iteration 1:

k=1
sum = 0 + 1; //so sum = 1

Iteration 2:

k=1+2 // so k=3
sum = 1 + 3 // so sum = 4

Iteration 3:

k=3+2 //k=5
sum = 4 + 5 //sum=9

etc...

Upvotes: 2

Related Questions