Write a program to calculate the sum of a group of positive

Write a program to calculate the sum of a group of positive integer variables.The program asks the user input variables. Any inputted negative value indicates the end of input process. Finally the program output the sum of them

Solution

SumOfPositiveNos.java

import java.util.Scanner;

public class SumOfPositiveNos {

   public static void main(String[] args) {
       //Declaring variables
       int num,sum=0;
      
       //Scanner class object is used to read the inputs entered by the user
       Scanner sc=new Scanner(System.in);
      
       //This loop continue to execute until the user enters a positive number
       while(true)
       {
          
           //Getting the number entered by the user
       System.out.print(\"Enter Positive Number(Negative to exit):\");
       num=sc.nextInt();
      
       /* checking the number is less than zero or not
       * If yes then control will come out of the loop
       * if not adding to the sum variable
       */
       if(num<0)
           break;
       else
       {
          
       //Calculating the sum of positive numbers  
       sum+=num;
           continue;
       }
      
       }
       //Displaying the sum of positive numbers
System.out.println(\"Sum of positive numbe is :\"+sum);
   }

}

___________________________

Output:

Enter Positive Number(Negative to exit):45
Enter Positive Number(Negative to exit):11
Enter Positive Number(Negative to exit):23
Enter Positive Number(Negative to exit):78
Enter Positive Number(Negative to exit):23
Enter Positive Number(Negative to exit):33
Enter Positive Number(Negative to exit):44
Enter Positive Number(Negative to exit):-3
Sum of positive numbe is :257

________Thank YOu

Write a program to calculate the sum of a group of positive integer variables.The program asks the user input variables. Any inputted negative value indicates t
Write a program to calculate the sum of a group of positive integer variables.The program asks the user input variables. Any inputted negative value indicates t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site