In: Computer Science
In Java:
Write a program that prompts the user to enter a positive number until the user input a negative number. In the end, the program outputs the sum of all the positive numbers.
You should use do-while loop (not while, not for). You cannot use break or if statement in the lab.
Hint: if the program adds the last negative number to your sum, you can subtract the last number from the sum after the loop.
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//initialize variables
int num,sum = 0,ans;
//loop runs continuously untill user entered negative number
do{
//prompts user to enter number and store it in num variable
System.out.print("Enter number: ");
num= sc.nextInt();
//add each number to find sum of all number
sum = sum + num;
}
//when user entered negative number loop terminates
while( num > 0);
//in sum negative number is also added.
//To find sum of all positive number subtract the
//negative number from sum and store result in ans
ans = sum - num;
//prints the result
System.out.println("Sum:" + ans);
}
}
Output: