Calculate Sum and Average of N Numbers without using Arrays: C Program


Write a C program to calculate Sum and Average of N numbers without using Arrays and using while loop.

Related Read:
Basic Arithmetic Operations In C
while loop in C programming

Logic

Here we ask the user to input the limit. Based on that limit value we ask the user to enter the integer numbers. For example, if the user enters value of limit as 5, then we ask the user to enter 5 integer numbers.

If limit is 5, then inside while loop we ask the user to input 5 integer values, and we add those values and keep storing the resulting number inside variable Sum. And simultaneously we keep decrementing the value of variable limit by 1 for each iteration of while loop. Once the value of variable limit is equal to 0 the control exits the while loop. Immediately outside while loop we calculate the average by using the formula:
average = sum / (float)limit;

Important Note: We need to type cast the data type of variable limit to float orelse it’ll give wrong results for certain inputs. Because any number divided by a integer number will return integer part of the result and discard the numbers after decimal point.

We’ve missed this in the video. So please fix the source code while practicing.

Source Code: Calculate Sum and Average of N Numbers without using Arrays: C Program

 
#include<stdio.h>

int main()
{
    int num, limit, sum = 0, temp;
    float avg;

    printf("Enter the limit\n");
    scanf("%d", &limit);

    temp = limit;

    printf("Enter %d numbers:\n", limit);

    while(limit)
    {
        scanf("%d", &num);
        sum = sum + num;
        limit--;
    }
    avg = sum / (float)temp;

    printf("Sum = %d\n", sum);
    printf("Average = %f\n", avg);

    return 0;
}

Output 1:
Enter the limit
5
Enter 5 numbers:
1
2
3
4
5
Sum = 15
Average = 3.000000

Output 2:
Enter the limit
10
Enter 10 numbers:
1
5
9
7
5
3
10
45
50
60
Sum = 195
Average = 19.500000

Calculate Sum and Average of N Numbers without using Arrays: C Program


[youtube https://www.youtube.com/watch?v=z5D1i9fhV6M]

YouTube Link: https://www.youtube.com/watch?v=z5D1i9fhV6M [Watch the Video In Full Screen.]


For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *