Programming Examples

Java program to print the sum of negative numbers, sum of positive odd numbers and sum of positive even numbers


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

Solution

import java.util.*;
class FindSum
{
	public static void main(String arr[])
	{
		int num,sum_negative=0,sum_pos_odd=0,sum_pos_even=0;
		Scanner sc=new Scanner(System.in);
		do
		{
			System.out.print("Enter Any Number");
			num=sc.nextInt();
			if(num<0)
			{
				sum_negative=sum_negative+num;
			}
			else
			{
				if(num%2==0)
				{
					sum_pos_even=sum_pos_even+num;
				}
				else
				{
					sum_pos_odd=sum_pos_odd+num;
				}
			}
		}while(num!=0);
		System.out.println("Sum of Negative Number: "+sum_negative);
		System.out.println("Sum of Positive Even Number: "+sum_pos_even);
		System.out.println("Sum of Positive Odd Number: "+sum_pos_odd);
	}
}
Output

Enter Any Number3

Enter Any Number2

Enter Any Number5

Enter Any Number6

Enter Any Number7

Enter Any Number-6

Enter Any Number-4

Enter Any Number-2

Enter Any Number3

Enter Any Number0

Sum of Negative Number: -12

Sum of Positive Even Number: 8

Sum of Positive Odd Number: 18

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz