Pin It

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

Program to print the sum of negative numbers, sum of positive even numbers and the sum of positive odd numbers from a list of numbers (N) entered by the user. The list terminates when the user enters a zero in Java.

package com.hubberspot.java.example;

import java.util.Scanner;

public class SumArray {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int [] numbers = new int[0];

        int number;
        String nextLine;
        do {
            System.out.print("Enter the number : ");
            number = scanner.nextInt();
            nextLine = scanner.nextLine();

            if(number != 0) {
                numbers = add(numbers, number);
            }

        } while(number != 0);

        int negativeSum = 0; 
        int oddSum = 0; 
        int evenSum = 0;

        for(int i = 0; i < numbers.length; i++ )
        {
            if( numbers[i] < 0 )
            {
                negativeSum = negativeSum + numbers[i];
            }
            else if( numbers[i] % 2 == 0 )
            {
                evenSum = evenSum + numbers[i];
            }
            else
            {
                oddSum = oddSum + numbers[i];
            }
        }
        System.out.println( "Sum of negative numbers : " + negativeSum );
        System.out.println( "Sum of positive even numbers: " + evenSum );
        System.out.println( "Sum of positive odd numbers: " + oddSum );

    }

    private static int[] add(int[] numbers, int number) {

        int[] tempArray = new int[numbers.length + 1];

        for(int i = 0; i < numbers.length; i++) {
            tempArray[i] = numbers[i];
        }

        tempArray[tempArray.length - 1] = number;
        return tempArray;

    }

}


Output of the program : 

 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot