Computer Science, asked by donaldtrump12327, 5 months ago

Write a program in java to find the sum of all the numbers entered by the user using while loop. The Program should execute till a negative number is entered.​

Answers

Answered by udayagrawal49
3

Answer: The required Java program is :-

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    System.out.print("Enter a number = ");

    int sum = 0;

    while(true) {

        int i = scan.nextInt();

        if (i>0) {

            sum += i;

            System.out.println("Sum = "+sum);

            System.out.print("Enter another number = ");

        }

        else {

            System.out.println("You have entered a negative number. Final sum is "+sum);

        }

    }

   }

}

Note :-

The above program is saved in a file named Main.java

Also, try-catch block can be used to avoid errors.

Similar questions