简体   繁体   中英

Is there a way to add integers while incrementing and then while decrementing? in a sequence

I am having trouble to add a set of integers in a sequence. I have three variable: start, number, and end. If I "start" at 5, then add all the integers up to "number" ( for example 9), then decrement from 9 to the integer "end" (in this case to -1): (5,9,-1) => 5+6+7+8+9+8+7+6+5+4+3+2+1+0+ - 1, which then i would print the result: total = 70. how can i accomplish this?

public class SequenceNumbers {

  public static void main(String[] args) {

    int start = 5;
    int num = 9;
    int end = -1;
    
    int sum = 0;
    for(int i = start; i <= num; i++)
    {
        // sum = sum + i;
        sum += i;
    }

    int total = 0;
    for ( int n = num; n != end; n--) {
        
        total = (sum + (num - 1));
    }
    
   System.out.println("Result = " + total);
  }
}

In the second loop, you overwrite total in each iteration. I'd keep the same pattern you had in the first loop, and just keep adding to sum . Note that it should start with num - 1 , though, so you don't count that number twice:

int sum = 0;
for(int i = start; i <= num; i++) {
    sum += i;
}

for ( int i = num - 1; i >= end; i--) {
    sum += i;
}

System.out.println("Result = " + sum);

I guess you need this for an exercise? But if you need a one-liner, this is a possible solution:

import java.util.*;
import java.util.stream.*;
public class MyClass {
    public static void main(String args[]) {
;
      int start = 5;
      int num = 9;
      int end = -1;
      
      int total = Stream.concat(Stream.iterate(start, n -> n + 1).limit(num-start+1), Stream.iterate(num-1, n -> n - 1).limit(num-end)).mapToInt(Integer::intValue).sum();

      System.out.println("Result = " + total);
    }
}

You were almost there. All your code is fine until this one line in your second for loop:

total = (sum + (num - 1));

This line says "set total equal to sum plus one less than num ". There's a problem there; sum and num are never changed by the for loop, so actually your for loop is doing nothing. You've set up your for loop nicely, though, and you gave yourself the variable n . All you need to do is keep adding to sum , and add n each time, like so:

sum += n;

Then in your println you can just use sum instead of total , like so:

System.out.println("Result = " + sum);

On second iteration for the total result you should decrement from max number which is 9 to min number which is -1. That means greater or equal to lowest value. ; >=; -- ; >=; -- .

The != comparison operator is to compare two values and the result is always a boolean type .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM