Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Iterative Constructs in Java

Chapter 9

Iterative Constructs in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Sum of Negative, Positive Even, and Positive Odd Numbers


32. Write a program to print the sum of negative numbers, sum of positive even numbers and sum of positive odd numbers from a list of n numbers entered by the user. The program terminates when the user enters a zero.

Program Title: Sum of Negative, Positive Even, and Positive Odd Numbers

import java.util.Scanner;

 

public class SumNumbers {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        int sumNegative = 0;

        int sumPositiveEven = 0;

        int sumPositiveOdd = 0;

 

        System.out.println("Enter numbers (0 to terminate):");

 

        while (true) {

            int num = sc.nextInt();

 

            if (num == 0) {

                break; // terminate when 0 is entered

            }

 

            if (num < 0) {

                sumNegative += num;

            } else if (num > 0 && num % 2 == 0) {

                sumPositiveEven += num;

            } else if (num > 0 && num % 2 != 0) {

                sumPositiveOdd += num;

            }

        }

 

        System.out.println("Sum of negative numbers: " + sumNegative);

        System.out.println("Sum of positive even numbers: " + sumPositiveEven);

        System.out.println("Sum of positive odd numbers: " + sumPositiveOdd);

 

        sc.close();

    }

}

Output

Sample Input / Output
Enter numbers (0 to terminate):
5
-2
8
-7
3
0
Sum of negative numbers: -9
Sum of positive even numbers: 8
Sum of positive odd numbers: 8 

How It Works

  1. Use a while loop that runs indefinitely.
  2. Read a number from the user. If it’s 0, break the loop.
  3. Check the number:
    • If negative → add to sumNegative
    • If positive and even → add to sumPositiveEven
    • If positive and odd → add to sumPositiveOdd
  4. Display all sums at the end.