ICSE Class 10 Computer Applications Question 45 of 69

Iterative Constructs in Java — Question 45

Back to all questions
45
Question

Question 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.

import java.util.Scanner;

public class KboatNumberSum
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int nSum = 0, eSum = 0, oSum = 0;
        System.out.println("Enter Numbers:");
        while (true) {
            int n = in.nextInt();
            
            if (n == 0) {
                break;
            }
            
            if (n < 0) {
                nSum += n; 
            }
            else if (n % 2 == 0) {
                eSum += n;
            }
            else {
                oSum += n;
            }
        }
        
        System.out.println("Negative No. Sum = " + nSum);
        System.out.println("Positive Even No. Sum = " + eSum);
        System.out.println("Positive Odd No. Sum = " + oSum);
    }
}
Output
BlueJ output of KboatNumberSum.java
Answer