Java count while index on each other Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Java count while index on each other without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I want to count int index = 1;. I want it to be added up on each other. For example: 1 + 2 + 3 etc. How can i do this? I’ve already tried this:

public void countOneToTen() {
        int index = 1;
        while(index <= 10) {
            index = index + index;
        }
        System.out.println(index);
    }

Answer

You need to decouple your “sum” variable and your index variable.

Introduce another variable to hold the sum:

public void countOneToTen() {
    int sum = 0;
    int index = 1;
    while (index <= 10) {
        sum += index;
        index++;
    }
    System.out.println(sum);
}

Also, use for loops to limit variable scope:

public void countOneToTen() {
    int sum = 0;
    for (int index = 1; index <= 10; index++) {
        sum += index;
    }
    System.out.println(sum);
}

Your approach didn’t work because your index should go from 1 to 10, but the moment you modify it you throw this iteration off course.

Here’s what I mean:

index =                 1
// index: 1
index = index + index = 2
// index: 2
index = index + index = 4
// We've skipped 3.
// etc.
index = index + index = 8
index = index + index = 16 > 10

1 + 2 + 4 + 8 = 15

Just for fun, here’s the Java 8 stream approach:

IntStream.rangeClosed(1, 10).sum();

(thanks to Oleg for pointing out the existence of rangeClosed)

🙂

and here’s the single-statement approach using the general summation of an arithmetic sequence:

image

int sum = terms * (min + max) / 2;
We are here to answer your question about Java count while index on each other - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji