Calculate the sum and average of array elements using C programming language

Calculate the sum and average of array elements using C programming language
Posted on 28-08-2023

Calculate the sum and average of array elements.

Code:

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i]; // Add each element to the sum
}

float average = (float)sum / size; // Calculate the average as a float

printf("Sum: %d\n", sum);
printf("Average: %.2f\n", average);

return 0;
}

 

Explanation:

#include <stdio.h>

This line includes a pre-existing library called stdio.h. This library helps us to interact with the standard input and output functions, like printf and scanf.

int main() {

This is the starting point of our program. main() is a special function where the execution of the program begins. The int before main() indicates that this function will return an integer value when it's done executing.

int arr[] = {10, 20, 30, 40, 50};

Here, we're declaring an integer array named arr and initializing it with five values: 10, 20, 30, 40, and 50.

int size = sizeof(arr) / sizeof(arr[0]);

We're calculating the number of elements in the array using this line. The sizeof() function returns the number of bytes occupied by its argument. So, sizeof(arr) gives the total size of the array, and sizeof(arr[0]) gives the size of a single element (which is an integer). Dividing the total size by the size of one element gives us the number of elements in the array.

int sum = 0;

We're initializing a variable named sum with the value 0. This variable will be used to store the sum of all the elements in the array.

for (int i = 0; i < size; i++) {

This is a loop that will run from 0 up to the value of size - 1. It's using a variable i to keep track of the current position in the array.

sum += arr[i];

Inside the loop, we're adding the value of the element at index i in the array to the sum variable. This accumulates the total sum of all elements in the array.

}

This curly brace marks the end of the loop.

float average = (float)sum / size;

After the loop, we're calculating the average by dividing the sum by the size of the array. We're casting sum to a float to ensure accurate division.

printf("Sum: %d\n", sum);
printf("Average: %.2f\n", average);

Finally, we're using the printf function to print the calculated sum and average. %d is a placeholder for an integer value, and %.2f is a placeholder for a floating-point value with two decimal places.

return 0;

We're signaling the end of the main() function and returning an integer value of 0, which is typically used to indicate a successful execution of the program.

}

This closing curly brace marks the end of the main() function and the end of the program.

 

Algorithm:

  1. Include the standard input-output library (stdio.h).

  2. Start the main function:

    • Declare an integer array arr and initialize it with values 10, 20, 30, 40, and 50.

    • Calculate the number of elements in the array using sizeof(arr) divided by sizeof(arr[0]), and store it in the variable size.

    • Initialize an integer variable sum with the value 0.

    • Start a loop from i = 0 to i < size:

      • Add the value of arr[i] to the variable sum.

    • End the loop.

    • Calculate the average by dividing sum (cast to a float) by size, and store it in the variable average.

    • Print the sum using printf, using the format specifier %d.

    • Print the average using printf, using the format specifier %.2f to display it with two decimal places.

    • End the main function by returning 0.

  3. End of the program.

This algorithm outlines the steps taken in the program to calculate the sum and average of the elements in the array and then print the results.

Time Complexity:

The time complexity of the above program can be analyzed by breaking it down into different parts:

  1. Initializing the array: The initialization of the array arr takes constant time, so its time complexity is O(1).

  2. Calculating the size: The calculation of the size of the array using sizeof(arr) divided by sizeof(arr[0]) is also a constant-time operation, so its time complexity is O(1).

  3. Loop for calculating the sum: The loop that iterates through the array elements to calculate the sum runs for size iterations, where size is the number of elements in the array. Since it iterates through each element once, the time complexity of this loop is O(n), where n is the number of elements in the array.

  4. Calculating the average: The calculation of the average involves a few basic arithmetic operations and type casting, which are constant-time operations, so its time complexity is O(1).

  5. Printing: The two printf statements for printing the sum and average are also constant-time operations, so their time complexity is O(1).

Adding up all these components, the overall time complexity of the program can be approximated as O(n), where n is the number of elements in the array. This is because the dominant factor in terms of time consumption is the loop that iterates through the array elements to calculate the sum. Other parts of the program involve constant-time operations or operations that do not depend on the size of the input (array).

It's worth noting that for small arrays, the effect of the loop might not be significant, and the program would execute quickly regardless of the linear time complexity. However, as the array size increases, the time taken by the loop becomes more significant.

Space Complexity:

The space complexity of a program refers to the amount of memory space it requires for its execution, primarily driven by the memory used by variables, data structures, and function calls. Let's break down the space complexity of the given program:

  1. Array (arr): The array itself takes up space in memory to store the individual elements. The space required is proportional to the number of elements in the array, so the space complexity for the array is O(n), where n is the number of elements.

  2. Variables (size, sum, average, i): These variables are used to store various values during the program's execution. Regardless of the array's size, these variables require a constant amount of space, so the space complexity for variables is O(1).

  3. Function Call Stack: As the program executes the loop, function calls are made to printf to print the results. Each function call requires a small amount of memory on the call stack. Since there are only a few function calls (independent of the array size), the space complexity due to function calls is also O(1).

  4. Overall Space Complexity: Adding up the space complexities from each aspect:

    • Array: O(n)

    • Variables: O(1)

    • Function Call Stack: O(1)

The overall space complexity of the program is O(n), where n is the number of elements in the array. This is because the dominant factor in terms of space consumption is the array itself, which grows proportionally with the input size. Other components, such as variables and function calls, require constant space regardless of the array size.

Thank You