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.
Java
Java Iterative Stmts
69 Likes
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

Answered By
25 Likes
Related Questions
To execute a loop 5 times, which of the following is correct?
Convert the following for loop segment to an exit-controlled loop.
for (int x = 1, y = 2; x < 11; x += 2, y += 2) { System.out.println(x + "\t" + y); }
Define a class to accept a number and check whether it is an FDS Number or not. A number is called an FDS Number if the sum of the factorials of its digits equals the number itself.
Example 1:
Input: 145
Output: FDS Number [1! + 4! + 5! = 1 + 24 + 120 = 145]Example 2:
Input: 123
Output: Not an FDS Number [1! + 2! + 3! = 1 + 2 + 6 ≠ 123]import java.util.Scanner; class KboatFDSNum { static int fact(int d) { int f = 1; _______(1)_________ { _______(2)_________ } _______(3)_________ } public static void main(String args[]) { Scanner in = new Scanner(System.in); System.out.print("Enter a number: "); int num = in.nextInt(); int t = num, sum = 0; _______(4)_________ { _______(5)_________ _______(6)_________ _______(7)_________ } _______(8)_________ { _______(9)_________ } else { _______(10)_________ } } }
Give the output of the following program segment. How many times is the loop executed?
for(x=10; x>20;x++) System.out.println(x); System.out.println(x*2);