Introduction
In this lab, we will learn how to write a C Program to find the average of n numbers. We will use a loop to input n numbers from the user and then find the average of the entered numbers.
Note: You need to create the file
~/project/main.c
yourself to practice coding and learn how to compile and run it using gcc.
cd ~/project
# create main.c
touch main.c
# compile main.c
gcc main.c -o main
# run main
./main
Declare variables and initialize sum to 0
First, we will declare and initialize variables that will hold the values of n, counter, sum, and x.
#include<stdio.h>
int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int n, i;
float sum = 0, x;
/* code continues... */
}
Get the input from the user
In this step, we will display the prompt to the user to enter the number of elements, and scan the input from the user.
printf("Enter number of elements: ");
scanf("%d", &n);
printf("\n\n\nEnter %d elements\n\n", n);
Get the input numbers and calculate the sum
In this step, we will scan the inputs from the user and calculate the sum of all the entered numbers using a for loop.
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
Calculate the average and display the result
In this step, we will calculate the average of the numbers, and display the result to the user.
printf("\n\n\nAverage of the entered numbers is = %f", (sum/n));
printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}
Here's the complete code for the program:
#include<stdio.h>
int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int n, i;
float sum = 0, x;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("\n\n\nEnter %d elements\n\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
printf("\n\n\nAverage of the entered numbers is = %f", (sum/n));
printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}
Summary
In this lab, we learned how to use a for loop to read n numbers from the user, calculate their sum, and find their average. The average of n numbers is an essential concept in programming, and this lab provides an excellent opportunity to practice these concepts.
π Practice Now: Average of N Numbers
Want to Learn More?
- π³ Learn the latest C Skill Trees
- π Read More C Tutorials
- π¬ Join our Discord or tweet us @WeAreLabEx
Top comments (0)