Contents

Add until n is greater than (with.Java)

   Oct 5, 2023     1 min read

In this article, we learned how to add until n is greater than n (with.Java).

We’ll do this by solving a coding test problem, reflecting on the problem we solved, and exploring other ways to solve it.

Let’s start with the problem

Problem

An array of integers numbers and an integer n are given as parameters.

Write a solution function that adds the elements of numbers one by one, starting at the front, and returns the sum of the elements added up to this point when the sum is greater than n.

Example input and output
numbersnresult
[34, 5, 71, 29, 100, 34]123139
[58, 44, 27, 10, 100]139239

My solution to the problem

class Solution {
    public int solution(int[] numbers, int n) {
        int answer = 0;
        for(int i = 0; i < numbers.length; i++){
            answer += numbers[i];
            if(answer > n) break;
        }
        } return answer;
    }
}
solution description

int answer = 0; : Initialize the variable answer to store the result.

for(int i = 0; i < numbers.length; i++) : Iterate over the input array numbers, examining each element.

answer += numbers[i];: add the current element to answer. This will sequentially sum the elements of the array.

if(answer > n) break;: Terminates the loop if the sum exceeds n. In other words, stops summing the moment the sum exceeds n.

return answer;: Returns the final summed result, answer.