Home > database >  Write a method called AddUp100 which takes in one value (an integer) and returns the sum of the next
Write a method called AddUp100 which takes in one value (an integer) and returns the sum of the next

Time:11-15

Write a method called AddUp100 which takes in one value (an integer) and returns the sum of the next 100 numbers (int) on completion of the method. It does not consider the starting number, just the next 100 numbers. The method will return an int.

The method accepts any integer (positive or negative) which in the int range and prints out the addition of the next 100 numbers. It then returns the answer as an integer

Note: it only prints out the sum of the numbers.

So if 12 was entered, the program would print out

i.e. the program would add up 13 14 15 ... 112. = 6250

This is my try:

private static int AddUp100(int input) {
    input = input   1;
    int sum  = input;
    
    for (int i = 0; i < 10; i   ) {
        sum  = sum   i; 
        System.out.println("Sum in loop is: "   sum);
    }
    
    System.out.println("Sum is: "   sum);
    return input;
}

}

Second edit - It shows the correct adding up of numbers, however how do i tell the program to add only the next 100 numbers not more ?

private static int AddUp100(int input) {
    int sum  = 0;
    input = input   1;
    System.out.println("input before loop "   input);
    
    for (int i = input ; i < 100; i  ) {
        sum = sum   i;
        System.out.println("Sum:  "   sum);
    }
    return sum;
}

CodePudding user response:

This can simplified to

    long sum = 0;
    long input = 12;
    for (int loop = input   1; loop <= input   100; loop   ) 
        sum  = loop;
    
    System.out.println(sum);

output

    6250

As you can start with any int value, then it would be better to store the sum and input in a long value to prevent Integer overflow i.e. Integer.MAX_VALUE 1

CodePudding user response:

Just write a for loop that runs 100 times. Within the loop, add the current input to the sum and increment the input by 1.

private static int AddUp100(int input) {
    int sum  = 0;
    input = input   1;
    System.out.println("input before loop "   input);
    
    for (int i = 0 ; i < 100; i  ) {
        sum  = input;
        input  = 1
        System.out.println("Sum:  "   sum);
    }
    return sum;
}
  • Related