C Program To Calculate Sum and Average of N Numbers without using Arrays, using For Loop


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

Related Read:
Basic Arithmetic Operations In C
For Loop In C Programming Language
Calculate Sum and Average of N Numbers without using Arrays: C Program

Video Tutorial: C Program To Calculate Sum and Average of N Numbers without using Arrays, using For Loop


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

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


Logic To Calculate Sum and Average of N Numbers without using Arrays

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 for loop we ask the user to input 5 integer values, and we add those values to the previous value present in variable sum. Simultaneously we keep incrementing the value of variable count by 1 for each iteration of for loop. Once the value of variable count is greater than the value of limit, then the control exits for loop. Immediately outside for loop we calculate the average by using the formula:

average = sum / limit;

Source Code: C Program To Calculate Sum and Average of N Numbers without using Arrays, using For Loop

#include<stdio.h>

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

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

    printf("Enter %f numbers\n", limit);
    for(count = 1; count <= limit; count++)
    {
        scanf("%d", &num);
        sum = sum + num;
    }
    avg = sum / limit;

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

    return 0;
}

Output 1:
Enter the limit
6
Enter 6 numbers
1
5
9
3
5
7
Sum = 30
Average = 5.00

Output 2:
Enter the limit
14
Enter 14 numbers
5
6
3
2
1
4
9
7
8
0
-5
-6
0
-10
Sum = 24
Average = 1.71

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 *