C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program to print the average of n numbersThe average is the outcome from the sum of the numbers divided by the count of the numbers being averaged. For example: 1,2,3,4,5 Number of all elements = 5 Sum of all elements = 1+2+3+4+5 =15 Average = Sum of all elements / number of all elements = 15/5 =3 Average =3 Algorithm
Java Programimport static java.lang.Float.sum; import java.util.Scanner; public class Average { public static void main(String[] args) { int n, count = 1; float xF, averageF, sumF = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter the value of n"); n = sc.nextInt(); while (count <= n) { System.out.println("Enter the "+count+" number?"); xF = sc.nextInt(); sumF += xF; ++count; } averageF = sumF/n; System.out.println("The Average is"+averageF); } } Output: Enter the value of n 5 Enter the 1 number? 1 Enter the 2 number? 2 Enter the 3 number? 3 Enter the 4 number? 4 Enter the 5 number? 5 The Average is 3.0 C program#include<stdio.h> void main( ) { int n, count = 1; float x, average, sum = 0; printf("Enter the value of n?"); scanf ("%d",&n); while (count <= n) { printf ("Enter the %d number?",count); scanf("%f", &x); sum += x; ++count; } average = sum/n; printf("\nThe Average is %f\n", average); } Output: Enter the value of n? 5 Enter the 1 number? 1 Enter the 2 number? 2 Enter the 3 number? 3 Enter the 4 number? 4 Enter the 5 number? 5 The Average is 3.0000 Python programn = int(input("Enter the value of n?")) sum=0 count = 1 while (count<=n): x = int(input("Enter the %d number?"%(count))); sum = sum + x; count=count+1; average = sum / n; print("Average using a while loop ", average) Output: Enter the value of n? 5 Enter the 1 number? 1 Enter the 2 number? 2 Enter the 3 number? 3 Enter the 4 number? 4 Enter the 5 number? 5 Average using a while loop 3.0000 Php program<?php $count=1; $sum = 0; $average=0; echo "Enter the value of n?"; $n = readline(); while($count<=$n) { echo "Enter the number"; $x = readline(); $sum = $sum+$x; $count=$count+1; } $average=$sum/$n; echo $average; ?> Output: Enter the value of n? 5 Enter the number 1 Enter the number 2 Enter the number 3 Enter the number 4 Enter the number 5 3.0000 C# programusing System; public class Average { public static void Main() { int userInput; int n, count = 1; float x, average, sum = 0; Console.WriteLine("Enter the value of n?"); n=Convert.ToInt32(Console.ReadLine()); while (count <= n) { Console.WriteLine("Enter the "+count+" number?" ); userInput = Convert.ToInt32(Console.ReadLine()); sum += userInput; ++count; } average = (float)sum/(n); Console.WriteLine("\nThe Average is %f\n"); Console.Write(average); }} Output: Enter the value of n? 5 Enter the 1 number? 1 Enter the 2 number? 2 Enter the 3 number? 3 Enter the 4 number? 4 Enter the 5 number? 5 The Average is 3.0
Next Topic#
|