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:10Do you want to add another number? (Y/N):YEnter a number:20Do you want to add another number? (Y/N):YEnter a number:30Do you want to add another number? (Y/N):NSum = 60.00Average = 20.00Total numbers = 3
Explanation
Let us understand the program with the numbers 10, 20, and 30.
| Number | Sum Calculation | Updated Sum |
|---|---|---|
| 10 | 0 + 10 | 10 |
| 20 | 10 + 20 | 30 |
| 30 | 30 + 30 | 60 |
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
Post a Comment