Computer Science, asked by sosororous, 22 hours ago

Enter n: 10
Average of the summation from 1 to 10 is 5.50

.???

Answers

Answered by anindyaadhikari13
7

\textsf{\large{\underline{Correct Question}:}}

  • Write a program to find the average of first n natural numbers.

\textsf{\large{\underline{Solution}:}}

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);

   }

}

\textsf{\large{\underline{Logic}:}}

  • 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'.

\textsf{\large{\underline{Alternative Method}:}}

Sum of first n terms is given as:

\sf\implies S_{n}=\dfrac{n(n+1)}{2}

Therefore, the average of the sum will be:

\sf\implies Average=\dfrac{S_{n}}{n}

\sf\implies Average=\dfrac{n(n+1)}{2n}

\sf\implies Average=\dfrac{n+1}{2}

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.

Attachments:
Similar questions