C Program to Calculate Average Using Arrays

@codevarsity
 · 
2.1k views
 · 

A simple C program that takes n number of element from user (where, n is specified by user), stores data in an array and calculates the average of those numbers.

Code

/*C Program to Calculate Average Using Arrays*/
#include <stdio.h>

int main()
{
    int n, i;
    float num[100], sum = 0.0, average;

    printf("Enter the numbers of elements: ");
    scanf("%d", &n);

    while (n > 100 || n <= 0)
    {
        printf("Error! number should in range of (1 to 100).\n");
        printf("Enter the number again: ");
        scanf("%d", &n);
    }

    for(i = 0; i < n; ++i)
    {
        printf("%d. Enter number: ", i+1);
        scanf("%f", &num[i]);
        sum += num[i];
    }

    average = sum / n;
    printf("Average = %.2f", average);

    return 0;
}

Output

Enter the numbers of elements: 6
1. Enter number: 45.3
2. Enter number: 67.5
3. Enter number: -45.6
4. Enter number: 20.34
5. Enter number: 33
6. Enter number: 45.6
Average = 27.69

Explanation

C Program to Calculate Average Using Arrays

In the structure complex, we are using float datatype for variables, real and imag since our concern is to add any two complex numbers with a possible fractional value.

In the main() function, the real part and the imaginary part of the complex numbers are taken separtely using scanf().

The structures n1 and n2 are passed as an argument of function add(). The function computes the sum and returns the structure variable temp to the main() function.

The final result is printed using printf() throught the main() function.

Tags

#while  #return 

Comments