Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

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

0 votes
asked Mar 17, 2019 by anonymous

3 Answers

0 votes
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

{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int N=0;

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

N=Integer.parseInt(br.readLine());

Average obj=new Average();

obj.find(N);

}

}
0 votes
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);

}

}
0 votes
answered Mar 20, 2019 by Dion Houston (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;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...