Menu Close

Average of N Numbers (User Input) – FORTRAN

When it comes to calculating the average of a set of numbers, Fortran provides a reliable and straightforward solution.

In this article, we will explore how to write a Fortran program that calculates the average of ‘n’ numbers, using simple and easy-to-understand code.

 

program average_calculation
    implicit none
    
    integer :: n, i
    real :: number, sum, average
    
    ! Prompt the user for the number of inputs
    write(*, *) "Enter the number of values:"
    read(*, *) n
    
    ! Initialize sum to zero
    sum = 0.0
    
    ! Read the numbers from the user and calculate the sum
    do i = 1, n
        write(*, *) "Enter number ", i, ":"
        read(*, *) number
        sum = sum + number
    end do
    
    ! Calculate the average
    average = sum / real(n)
    
    ! Display the result
    write(*, *) "The average is: ", average
    
end program average_calculation

 

Explanation

Step 1: Defining the Problem:

To find the average of ‘n’ numbers, we need to sum all the numbers together and then divide the sum by the total count of numbers.

 

Step 2: Setting Up the Fortran Program:

To begin, we’ll create a new Fortran program and define the necessary variables.

Let’s call the variable for the sum ‘total’ and the variable for the average ‘average’.

Additionally, we’ll need a counter variable to keep track of the number of inputs.

 

Step 3: Gathering Inputs:

To calculate the average, we need to collect ‘n’ numbers from the user. We can achieve this by using a loop that prompts the user to enter a number and adds it to the total sum. The loop will continue until ‘n’ numbers have been entered.

 

Step 4: Calculating the Average:

Once all the numbers are collected, we can calculate the average by dividing the total sum by ‘n’. This can be done by assigning the value of the total sum to the average variable and then dividing it by ‘n’.

 

Step 5: Displaying the Result:

Finally, we will display the average to the user. This can be achieved by using a simple output statement, such as “The average of the numbers is: [average]”.

 

More Related Stuff