Enter n: 10
Average of the summation from 1 to 10 is 5.50
.???
Answers
- Write a program to find the average of first n natural numbers.
As no language is mentioned, I am using Java.
import java.util.Scanner;
public class Brainly{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n,i;
double sum=0;
System.out.print("Enter n - ");
n=sc.nextInt();
sc.close();
for(i=1;i<=n;i++)
sum+=i;
sum/=n;
System.out.println("The average of first n natural numbers: "+sum);
}
}
- Accept the limit from the user, say N.
- Initialise sum = 0.
- Repeat I = 1 to N.
- Add 'I' to sum.
- Increment the value of 'I' by 1.
- Change sum to sum/n.
- Display 'sum'.
Sum of first n terms is given as:
Therefore, the average of the sum will be:
We can input the value of 'n' from the user and calculate the average using this formula.
Here comes the approach.
import java.util.Scanner;
public class Brainly{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n,i;
double sum=0;
System.out.print("Enter n - ");
n=sc.nextInt();
sum=(n+1)/2.0;
System.out.println("Average of first "+n+" natural numbers is: "+sum);
}
}
See the attachment for output.