Computer Applications
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 entered by the user. The list terminates when the user enters a zero.
Answer
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
Related Questions
How many times will the following loop execute? Write the output of the code:
int x=10; while (true){ System.out.println(x++ * 2); if(x%3==0) break; }Define a class to accept a number from user and check if it is an EvenPal number or not.
(The number is said to be EvenPal number when number is palindrome number (a number is palindrome if it is equal to its reverse) and sum of its digits is an even number.)
Example: 121 – is a palindrome number
Sum of the digits – 1+2+1 = 4 which is an even number