C Program to Calculate Sum and Average of N Numbers N संख्याओं का Sum और Average निकालने का C प्रोग्राम

The sum of numbers is the total obtained by adding all the given numbers. The average is calculated by dividing the sum by the total number of values.

Formula:

[ Average = Sum/ Total Number of Values ]

किसी दी गई संख्या श्रृंखला का Sum सभी संख्याओं को जोड़कर प्राप्त किया जाता है। Average निकालने के लिए Sum को कुल संख्याओं की संख्या से विभाजित किया जाता है।

C Program

#include <stdio.h>
int main(void) {
float n, sum = 0, avg;
int i = 0;
char ch = 'y';
while (ch == 'y' || ch == 'Y') {
printf("Enter a number:\n");
if (scanf("%f", &n) != 1) {
printf("Invalid input! Please enter a valid number.\n");
return 1;
}
sum = sum + n;
i++;
printf("Do you want to add another number? (Y/N):\n");
if (scanf(" %c", &ch) != 1) {
printf("Invalid choice!\n");
return 1;
}
if (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N') {
printf("Invalid choice! Please enter Y or N.\n");
return 1;
}
}
if (i > 0) {
avg = sum / i;
printf("\nSum = %.2f\n", sum);
printf("Average = %.2f\n", avg);
printf("Total numbers = %d\n", i);
}
return 0;
}

Sample Output

Enter a number:
10
Do you want to add another number? (Y/N):
Y
Enter a number:
20
Do you want to add another number? (Y/N):
Y
Enter a number:
30
Do you want to add another number? (Y/N):
N
Sum = 60.00
Average = 20.00
Total numbers = 3

Explanation

Let us understand the program with the numbers 10, 20, and 30.

NumberSum CalculationUpdated Sum
100 + 1010
2010 + 2030
3030 + 3060

The total sum is 60 and the total number of values is 3.

[ Average = 60 / 3 = 20 ]

The program uses a while loop to accept numbers repeatedly. The variable sum stores their total, while i counts how many numbers have been entered. When the user enters N, the loop terminates and the average is calculated.

प्रोग्राम में while लूप का उपयोग करके यूजर से बार-बार संख्याएँ इनपुट की जाती हैं। sum वेरिएबल सभी संख्याओं का योग स्टोर करता है तथा i वेरिएबल कुल संख्याओं की गिनती करता है। जब यूजर N दर्ज करता है, तो लूप समाप्त हो जाता है और Average निकाला जाता है।

Modern C Compatibility Note

This program uses standard C and works with modern compilers such as GCC, Clang, and Visual Studio C. It does not require conio.h, clrscr(), getch(), or fflush(stdin).

This program demonstrates how to calculate the sum and average of any number of values using a while loop and simple arithmetic operations.

यह प्रोग्राम while लूप और सामान्य Arithmetic Operations की सहायता से दी गई संख्याओं का Sum और Average निकालना सिखाता है।

Comments

Popular posts from this blog

C Language Topics in Hindi and English

Complete C Programming Syllabus | Advanced C Roadmap for Students

Top High-Paying Tech Skills to Learn in 2025