# .write a program using function that accepts a number N as a input and returns the average of numbers from 1 to N?

answered Mar 17, 2019 by Shresth Bindal
import java.io.*;

class Average

{

void find(int N)

{

double a=0.0;

int sum=0;

for(int i=1;i<=N;i++)

{

sum+=i;

}

a=sum/N;

System.out.println(" Average is" +a);

}

public static void main(String args[]) throws IOException

{

int N=0;

System.out.println("Enter number");

Average obj=new Average();

obj.find(N);

}

}
answered Mar 18, 2019 by anonymous
import java.util.*;

class Nikhil{

public static void main(String[] args){

Scanner sc=new scanner(System.in);

int n=sc.nextInt();

double a;

for(int i=1;i<=n;i++)

{a=a+i;
}

a/=n;

System.out.println(a);

}

}
answered Mar 20, 2019 by (240 points)
OK, so let me do this as two parts -- great question!  First, I'm assuming you mean (e.g.) for an input of 5, you want the average of 1, 2, 3, 4, 5.  1+2+3+4+5=15 / 5 = 3.

This is pretty straight forward to write:

int main() {
unsigned n, c;
double sum;

printf("What is the max number? ");
scanf("%d", &n);

for (c=1; c <= n; sum+=c++) ;
printf("average=%lf", sum / n);

return 0;
}

However, the real trick here is to realize you don't need to do a loop :)  For the sequence 1,2,3,4,5

1+5 = 6 / 2 = 3
2+4 = 6 / 2 = 3
3 = 3 / 1 = 3

In other words, the average of a range of numbers from 1...N is (N+1) / 2. You can therefore re-write this as:

int main() {
unsigned n, c;
double sum;

printf("What is the max number? ");
scanf("%d", &n);

printf("average=%lf", ((double)(n+1)/2));

return 0;
}