Find the Average of N Numbers in C

Find the Average of N Numbers in C

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(nnttStudytonight – Best place to learnnnn);

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(nnnEnter %d elementsnn, 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(nnnAverage of the entered numbers is = %f”, (sum/n));
printf(nnnntttCoding is Fun !nnn);

return 0;
}

Here’s the complete code for the program:

#include<stdio.h>
int main()
{
printf(nnttStudytonight – Best place to learnnnn);

int n, i;
float sum = 0, x;

printf(“Enter number of elements: “);
scanf(“%d”, &n);
printf(nnnEnter %d elementsnn, n);

for(i = 0; i < n; i++)
{
scanf(“%f”, &x);
sum += x;
}

printf(nnnAverage of the entered numbers is = %f”, (sum/n));
printf(nnnntttCoding is Fun !nnn);

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

Please follow and like us:
Pin Share