Menu
Topics Index
...
`

Find the average of numbers till given number


If you need explanation Read this topic

If you need Answer Take test on this topic

Write a program to find the average of all numbers till a given number.

Input (Integer) Output (Integer)
7 (1 + 2 + 3 + 4 + 5 + 6 + 7) / 7 = 4
15 (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15) / 15 = 8



class Average
{
    public static void main(String s[])
    {
        System.out.println("Average of numbers till 5 is " + averageOfNumbers(5));

    }


    public static int averageOfNumbers(int input)
    {
        int output = 0;
        return output;
    }

}
Topic: for Loop In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

for(int i = 1; i <= input; i++)
{
  output += i;
}
output /= input;

Posted by Gopinath Manchikanti    2014-11-24 06:02:19


for(int i=1;i<= input ;i++){
output +=i;
}
output /=input ;

Posted by Dereje Goshu    2014-11-24 06:07:26


Step 1: calculate sum of all the numbers starting from 1 to the given number.This can be achieved by using the for loop by iterating from 1 to the given number and adding the values cumulatively for every iteration
Step 2: Divide the sum obtained from Step1 with given number to get the average

Posted by Shashanka Mogaliraju    2014-11-24 06:45:28


Here we can write For loop, Initializing loop control variable i to 1 and the condition Which is less than equal to input.. By satisfying this condition The output may be printed by incrementing the initial varible upto the given input and stores in output,  To get the average of given input, The stores output can be divided by the given input.

Posted by Sai Ram    2014-11-24 06:48:36


single step without the concept of loops is  
output=(input+1)/2;// basics of average is 1+2+3+.......+n=n(n+1)/2 average=n(n+1)/2/n=(n+1)/2;
return output;

Posted by Sai Veerendra    2014-11-24 08:49:32


here we need to iterate the the from 1 to till the given num...to iterate we need to use the loops...to find avg first we need to find the sum of the given range..so here we need to take an varaible and must be iniatilized with the 0...while iterating every time we need to add the loop control to the sum...once we complete thr iteration..than we need to divide this sum by the given input than we will get the avg

Posted by Uday Kumar    2014-11-24 15:50:38


This dose is now closed and the winners are Shashanka Mogaliraju,  for 'First Correct Comment', Sai Ram, Sai Veerendra,  for 'Second Correct Comment'. The 'lucky liker' is Uday Kumar. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2014-11-25 04:35:18


© meritcampus 2019

All Rights Reserved.

Open In App