It is necessary to find the sum of the elements of the array after finding the first negative element and output all elements after the first negative element. For example, there is an array {0,2,-5,7,4,9,3,-2,5,4,5} you need to find the first negative number, here -5 , then print the sum of the remaining elements 7,4,9,3,-2,5,4,5} . I did not quite work out:

  int[]arr = {0,2,-5,7,4,9,3,-2,5,4,5}; int firstNegative = 0; int countIndex = 0; int sum = 0; for (int i = 0; i < arr.length; i++) { countIndex++; if (arr[i] < 0) { firstNegative = arr[i]; for (int j = 0; j < (arr.length - countIndex); j++) { sum+=arr[j]; } break; } System.out.println(arr[i]); } System.out.println("My first: " + firstNegative); System.out.println("Sum is: " + sum); 
  • “I didn’t quite work out” - can you say what happened? - Igor
  • I consider the sum but from the zero index sum+=arr[j] and how to count from the index where is the first negative number? - Nevada

1 answer 1

Your second cycle idea, I would say, is not very good. If you read the task carefully, then you will understand that you just need to skip the elements before you find the first negative number.

  int[] arr = {0, 2, -5, 7, 4, 9, 3, -2, 5, 4, 5}; boolean firstNegativeFound = false; int sum = 0; for (int i = 0; i < arr.length; i++) { if (!firstNegativeFound && arr[i] < 0) { firstNegativeFound = true; continue; } if (firstNegativeFound) { sum += arr[i]; } System.out.println(arr[i]); } System.out.println("Sum is: " + sum); //35 
  • TC seems to want to add negative numbers, except the first. - Igor
  • @igor The task says 'then print the sum of the remaining elements 7,4,9,3, -2,5,4,5}' that is, everything after the first negative. - Mikhail Chibel
  • Thanks, now I see! - Nevada
  • In general, of course, the problem is obviously educational and the author had to think a little before asking. - Mikhail Chibel
  • one
    @MikhailChibel Your code does not add negative numbers to the sum. - Igor