Dremendo Tag Line

Input 10 numbers and find average of positive numbers using while loop in Java

while Loop - Question 4

In this question, we will see how to input 10 numbers and find the average of only positive numbers in Java programming using while loop. To know more about while loop click on the while loop lesson.

Q4) Write a program in Java to input 10 numbers and find the average of only positive numbers using while loop.

Program

import java.util.Scanner;

public class Q4
{
    public static void main(String args[])
    {
        int i=1,n,sum=0,c=0;
        float avg=0;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 10 numbers");
        while(i<=10)
        {
            n=sc.nextInt();
            if(n>0)
            {
                sum=sum+n;
                c=c+1;
                avg=sum/(float)c;
            }

            i=i+1;
        }
        System.out.println("Average of positive numbers = " + avg);
    }
}

Output

Enter 10 numbers
-12
-6
12
-4
20
3
-89
-51
-7
5
Average of positive numbers = 10.0
video-poster