Search code examples
javaarrayssum

How to get sum of array elements between two zeros


first input: size of array: 5

second input: 0 -2 4 0 6

output: 2

Here is what I have tried. It is also adding the numbers before zero:

My code's output:

array size: 10

elements: 6 19 0 -3 4 8 0 -6 9 59

my output: 25 9

import java.util.Scanner;
import java.util.Vector;
public class Main{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int arr[] = new int[n]; 
        Vector<Integer> A = new Vector<Integer>();

    int sum = 0;
        for(int i=0; i<arr.length; i++){
            arr[i] = in.nextInt();
        }
 
   
    for(int i = 0; i < arr.length; i++)
    {
       if (arr[i] == 0)
       {
           i++;
           break;
       }
    }
 
   
    for(int i=0; i < arr.length; i++)
    {
        
    
       if (arr[i] == 0)
       {
           A.add(sum);
           sum = 0;
       }
        
       else
       {
           sum += arr[i];
       }
    }

    for(int j = 0; j < A.size(); j++)
    {
       System.out.print(A.get(j) + " ");
    }
    }
}

Solution

  • You don't need 2 loops, one to look for the first zero and then sum up.

    
    public class Main {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int n = in.nextInt();
            int arr[] = new int[n];
            List<Integer> sums = new ArrayList<>();
            int sum = 0;
    
            // read input
            for (int i = 0; i < arr.length; i++) {
                arr[i] = in.nextInt();
            }
    
            boolean isCounting = false;
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] != 0 && isCounting) {
                    sum += arr[i];
                } else if(arr[i] == 0){
                    // if already counting then finish the sum
                    if (isCounting) {
                        sums.add(sum);
                        sum = 0;
                    } else { // else start counting
                        isCounting = true;
                    }
                }
            }
            System.out.println(sums);
        }
    }