Programming Examples

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


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 numbers (N) entered by the user. The list terminates when the user enters a zero.

Solution

import java.util.*;
class SUM
{
	public static void main(String arr[])
	{
		Scanner sc=new Scanner(System.in);
		int i,n,se=0,so=0;
		for(;true;)
		{
		System.out.println("Enter a number:");
		n=sc.nextInt();
		if(n==0)
		break;
		if(n%2==0 && n>0)
		se+=n;
		else if(n%2==1 && n>0)
		so+=n;
		}
		System.out.println("Sum of positive even no.s="+se);
		System.out.println("Sum of positive odd no.s="+so);
	}	
}
Output

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 NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad