Complementary task for topic: 3

M Nemeth · 2023-08-29 15:21:04.615220'

Arrays: sum and average

Arrays: sum and average

Write a C program that prompts the user to enter a real number array of size 5 and calculates the sum and average of the array elements.

Hint: Traverse on the table find the sum. Size is known.
Reak number can be float or double.

Solution
#include 

#define SIZE 5 //this is a way to create a constant. Compiler will replace any SIZE variable to 5 (so it happens before the program compiles to computer code

int main() {
    float numbers[SIZE];
    float sum = 0;
    double average;
    
    printf("Enter %d integers:\n", SIZE); // here you can see how to use the constant
    
    for (int i = 0; i < SIZE; i++) { //here too
        scanf("%f", &numbers[i]); //any white character will be good for separator?		
        sum += numbers[i];
    }
    
    average = sum / SIZE;
    
    printf("Sum of the array elements: %f\n", sum);
    printf("Average of the array elements: %.2f\n", average);
    
    return 0;
}



Explanation
In this example, the program declares an float array numbers of size SIZE, which is set to 5 using the #define directive.

The program prompts the user to enter SIZE number of integers using scanf() within a for loop. Each input is stored in the corresponding index of the numbers array. Additionally, the sum of all the entered numbers is calculated using the sum variable.
< < previous    next > >