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

Lets write a C program to calculate Sum and Average of N numbers using Arrays and using macros and for loop.

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

Formula To Calculate Sum and Average

int a[5] = {2, 4, 6, 5, 9};

sum = 2 + 4 + 6 + 5 + 9;
average = sum / 5.0;

Result
sum = 26;
average = 5.2;

Important Note:
Look at the formula for calculating average. If you divide any number by integer number, it’ll only return integer value and discard the digits after decimal point. So make sure to divide the number by floating point value. To convert integer to float, make use of typecasting syntax.

Typecasting

int N = 5;

sum = 2 + 4 + 6 + 5 + 9;
average = sum / (float)N;

Since N is integer type variable, dividing any number by N would give us integer data. For some input it’ll result in wrong result. To fix it, we make use of typecasting and cast the type of N to float using above syntax.

Example: Expected Output

Enter 5 integer numbers
5
2
6
4
3

Sum of 5 numbers: 20

Average of 5 numbers: 4.000000

array with size 5

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


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

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

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

Method 1

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, sum = 0;
    float avg;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i < N; i++)
    {
        sum = sum + a[i];
    }

    avg = sum / (float)N;

    printf("\nSum of %d numbers: %d\n", N, sum);
    printf("\nAverage of %d numbers: %f\n", N, avg);

    return 0;
}

Output 1:
Enter 5 integer numbers
2
5
6
8
10

Sum of 5 numbers: 31

Average of 5 numbers: 6.200000

Output 2:
Enter 5 integer numbers
1
2
3
4
5

Sum of 5 numbers: 15

Average of 5 numbers: 3.000000

Logic To Calculate Sum and Average of Array Elements

We ask the user to input N integer numbers. N is a macro and we’ve assigned 5 to it. Integer numbers input by the user is stored inside array variable a[N]. N being the size of the array.

SUM
We use for loop and iterate N times to fetch all the array elements. Variable i is assign a initial value of 0 and for loop iterates until i < N. Inside for loop we add the value of individual array element(a[i]) to previous value of variable sum. Once i < N condition is false, control exits for loop.

AVERAGE
Outside for loop we calculate average by using the formula:
average = sum / (float)N;

Once sum and average are calculated we output the result on to the console window.

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

Method 2: Improved Source Code

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, sum = 0;
    float avg;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
    {
        scanf("%d", &a[i]);
        sum = sum + a[i];
    }

    avg = sum / (float)N;

    printf("\nSum of %d numbers: %d\n", N, sum);
    printf("\nAverage of %d numbers: %f\n", N, avg);

    return 0;
}

You could even calculate sum inside the for loop which is used to accept input from the user. Whenever user inputs a number it is immediately added to the previous value of variable sum.

Advantages of using above source code
We don’t iterate through the array to fetch individual elements of the array and then add it to calculate sum. We calculate sum inside first for loop itself which is used to accept input by user. This method is faster and cheaper on resource usage.

Important Notes:

1. Make use of macros to assign size of array.
2. Make sure to declare variable avg(to calculate average) as float or double.
3. Make sure to divide variable sum by floating point or double type value and not by integer. In order to convert a integer variable or macro, make use of typecasting.

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

C Program To Calculate Average and Percentage of Marks Obtained

Write a function that receives marks received by a student in 3 subjects and returns the average and percentage of these marks. Call this function from main() and print the results in main().

Analyze The Above Problem Statement

1. We need to write a user defined function.
2. Our function will be passed with 3 floating point numbers.
3. Since the problem statement is asking us to return more than 1 value, we need to make use of pointer concept.
4. We will not be using arrays in this program since the number of inputs is fixed to 3. We can take 3 variables to store the values entered/input by the user. i.e., marks obtained by the student in 3 subjects.

Related Read:
Basics of Pointers In C Programming Language

Very Important Note:

Any address preceded by a * (Indirection operator) will fetch the value present at that address.

Video Tutorial: C Program To Calculate Average and Percentage of Marks Obtained using Pointer


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

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


Source Code: C Program To Calculate Average and Percentage of Marks Obtained

#include<stdio.h>

void percentage(float, float, float, int*,
                float*, float*, float*);

int main()
{
    float a, b, c, total = 0, avg = 0, percent = 0;
    int max;

    printf("Enter marks obtained in 3 subjects\n");
    scanf("%f%f%f", &a, &b, &c);

    printf("What's the total marks(of 3 subjects combined) 
            to which the exam was conducted\n");
    scanf("%d", &max);

    percentage(a, b, c, &max, &total, &avg, &percent);

    printf("\nTotal Marks Obtained = %0.2f\n", total);
    printf("Average = %0.2f\n", avg);
    printf("Percentage = %0.2f\n", percent);

    return 0;
}

void percentage(float x, float y, float z, int *max,
                float *tot, float *avg, float *per)
{
    *tot = x + y + z;
    *avg = *tot / 3.0;

    *per = *tot * 100.0 / (float)*max;
}

Output 1:
Enter marks obtained in 3 subjects
42
41
32
What’s the total marks(of 3 subjects combined) to which the exam was conducted
150

Total Marks Obtained = 115.00
Average = 38.33
Percentage = 76.67

Output 2:
Enter marks obtained in 3 subjects
123
145
140
What’s the total marks(of 3 subjects combined) to which the exam was conducted
450

Total Marks Obtained = 408.00
Average = 136.00
Percentage = 90.67

Output 3:
Enter marks obtained in 3 subjects
92
85
96
What’s the total marks(of 3 subjects combined) to which the exam was conducted
300

Total Marks Obtained = 273.00
Average = 91.00
Percentage = 91.00

Logic To Calculate Average and Percentage of Marks Obtained

We ask the user to input marks obtained by the student for 3 subjects. And then we also ask the user to input the maximum marks(for 3 subjects combined) for which the exam was conducted, and we store it in variable max.

We pass the values of a, b and c, and the address of max, total, avg and precent to percentage() function.

Inside percentage() Function
Inside percentage() function we calculate the Total marks obtained, average marks and percentage for the 3 subjects of the student and store it back as values at the address passed.

We make use of following formulas:
Total = a + b + c;
Average = Total / 3.0;

we are dividing Total by 3.0 because we have 3 subjects. It represents the number of subjects for which we’re calculating the Average.

percentage = Total x 100.0 / Max;

Here Max is the maximum marks(for all the subjects combined) for which the exam was conducted.

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

Calculate Sum, Average, Variance and Standard Deviation: C Program

Write a function that receives 5 integers and returns the sum, average and standard deviation of these numbers. Call this function from main() and print the results in main().

Analyze The Above Problem Statement

1. We need to write a function to calculate the results.
2. Our function receives 5 integers.
3. We need to calculate sum, average or mean and standard deviation inside the function.
4. Problem statement is asking us to return 3 values from the function, which is not possible. But we can work around and use pointers to make it work. So the problem statement is indirectly asking us to use pointers to return more than 1 value from the function.
5. We will not be using arrays in this program since the number of inputs is fixed to 5. We can take 5 variables to store the values entered/input by the user.

Note: Perfect code for above problem statement is present at the end of this blog post / article. In the video we’ve made some modifications to get accurate results for various user inputs. None-the-less, you can find the exact c source code for above problem statement at the end of this blog post.

Related Read:
Basics of Pointers In C Programming Language
Assignment Operators in C

Very Important Note:

Any address preceded by a * (Indirection operator) will fetch the value present at that address.

Video Tutorial: Calculate Sum, Average, Variance and Standard Deviation: C Program


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

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


Source Code: Calculate Sum, Average, Variance and Standard Deviation: C Program

#include<stdio.h>
#include<math.h>

void stand_devi(float, float, float, float, float,
                float*, float*, float*, float*);

int main()
{
    float a, b, c, d, e;
    float sum = 0, avg = 0, sd = 0, vari = 0;

    printf("Enter 5 numbers\n");
    scanf("%f%f%f%f%f", &a, &b, &c, &d, &e);

    stand_devi(a, b, c, d, e, &sum, &avg, &vari, &sd);

    printf("\nSum = %0.2f\n", sum);
    printf("Mean / Average = %0.2f\n", avg);
    printf("Variance = %0.2f\n", vari);
    printf("Standard Deviation = %0.2f\n", sd);

    return 0;
}

void stand_devi(float a, float b, float c, float d, float e,
                float *sum, float *avg, float *v, float *sd)
{
    *sum = a + b + c + d + e;
    *avg = *sum / 5.0;

    *v   += pow( (a - *avg), 2 );
    *v   += pow( (b - *avg), 2 );
    *v   += pow( (c - *avg), 2 );
    *v   += pow( (d - *avg), 2 );
    *v   += pow( (e - *avg), 2 );

    *v   = *v / 5.0;
    *sd  = sqrt(*v);
}

Output:
Enter 5 numbers
50
-5
14
122
41

Sum = 222.00
Mean / Average = 44.40
Variance = 1885.84
Standard Deviation = 43.43

Logic To Calculate Sum, Average, Variance and Standard Deviation

We pass 5 floating point variables and address of 4 floating point variables to the function stand_devi().

Using below formula we calculate sum, average/mean, variance and standard deviation:

*sum = a + b + c + d + e;
*avg = *sum / 5.0;

*variance = ( (a – *avg) x (a – *avg) + (b – *avg) x (b – *avg) + (c – *avg) x (c – *avg) + (d – *avg) x (d – *avg) + (e – *avg) x (e – *avg) ) / 5.0;

*standard_deviation = sqrt(*variance);

Inside stand_devi() function we are calculating sum, average, variance and standard deviation and storing it inside the address of variables sum, avg, vari, sd. So value changes is reflected in the entire program and not just inside stand_devi() method.

C Program Source Code Which Matches the Problem Statement Exactly

#include<stdio.h>
#include<math.h>

void stand_devi(int, int, int, int, int,
                float*, float*, float*);

int main()
{
    int a, b, c, d, e;
    float sum = 0, avg = 0, sd = 0;

    printf("Enter 5 numbers\n");
    scanf("%d%d%d%d%d", &a, &b, &c, &d, &e);

    stand_devi(a, b, c, d, e, &sum, &avg, &sd);

    printf("\nSum = %0.2f\n", sum);
    printf("Mean / Average = %0.2f\n", avg);
    printf("Standard Deviation = %0.2f\n", sd);

    return 0;
}

void stand_devi(int a, int b, int c, int d, int e,
                float *sum, float *avg, float *sd)
{
    float v = 0; // Variance

    *sum = a + b + c + d + e;
    *avg = *sum / 5.0;

     v   += pow( (a - *avg), 2 );
     v   += pow( (b - *avg), 2 );
     v   += pow( (c - *avg), 2 );
     v   += pow( (d - *avg), 2 );
     v   += pow( (e - *avg), 2 );

     v   /= 5.0;

    *sd  = sqrt(v);
}

Output:
Enter 5 numbers
50
69
92
30
-60

Sum = 181.00
Mean / Average = 36.20
Standard Deviation = 52.29

Here we’re following all the things mentioned in the problem statement. We are taking 5 integer values and passing it to our user defined function. Inside the function we are calculating the sum, average and standard deviation and storing it at address of variables sum, avg, and sd. This modification or change is reflected everywhere in the program as we are modifying the value present at address. Addresses are unique and any changes made to the value present at a address reflects everywhere in the program. That’s how we are able to print the result i.e., values of sum, avg and sd inside main() function, after calling stand_devi() function.

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

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

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