Program to find the average of numbers in a given range

Description

To calculate the average between the given range, first find the sum of the number
 in given range and divide the sum by total number present in that range.

C/C++

/* C Program to find the average of numbers in a given range */
//Save it as AverageNumber.c

#include<stdio.h>
int main(){

    int i, beg, last, sum=0, countNum=0;
    float average;

    printf("Enter the first number of range : ");
    scanf("%d",&beg);

    printf("Enter the last number of range : ");
    scanf("%d",&last);

    
    //Traverse from start to end in a range
    
    for(i=beg;i<=last;i++){
        
        //Calculate the sum between the range
        
        sum+=i;
        
        //Count the number between range
        
        countNum++;
    }
    
    //Find the average
    
    average = (float)sum/countNum;

    printf("The average is : %.3f",average);

    return 0;
}
Input:
Enter the first number of range : 
2
Enter the last number of range : 
5

Output:
The average is : 3.500

Java

/* Java Program to find the average of numbers in a given range */
//Save it as AverageNumber.java


import java.io.*;
import java.util.Scanner;

public class AverageNumber {

    public static void main(String[] args) {
        
            Scanner scanner = new Scanner(System.in);
        
            int i, beg, last, sum=0, countNum=0;
        float average;

        System.out.println("Enter the first number of range : ");
        beg = scanner.nextInt();

        System.out.println("Enter the last number of range : ");
        last = scanner.nextInt();
        
        
        //Traverse from start to end in a range
        
        for(i=beg;i<=last;i++){
            
        	//Calculate the sum between the range
            
            sum+=i;
            
            //Count the number between range
            
            countNum++;
        }
        
        //Find the average
        
        average = (float)sum/countNum;

        System.out.println("The average is : "+average);
    }
}
Input:
Enter the first number of range : 
2
Enter the last number of range : 
5

Output:
The average is : 3.5

Related Programs

1) Program to print all Squares of numbers from 1 to given Range
2) Program to find sum of first and last digit of a number
3) Program To Check Armstrong Number
4) Check whether a given number is a perfect number or not
5) Program to find all prime numbers in given range
6) Program to Check Leap Year
7) Program to generate Random number in a given Range
8) Program to Display Fibonacci Series
9) Program to Find ASCII value of a character
10) Program to Check Whether a Character is a Vowel or Not
11) Program to Check Whether a Number is Prime or Not
Share Me

Leave a Reply