Problem: Given an integer Array of size n, the task is to write C programming code to calculate the average of all the elements present in the given array.
Example:
Input: arr[] = {3, 5, 9, 2, 8} Output: 5.40 Explanation: Sum of elements = 3+5+9+2+8 = 27 Total number of elements = 5 Average = 27/5 = 5.40
Algorithm to Calculate Array Average.
Here is a step-by-step algorithm to calculate the average of an array in C language using pseudocode:
- Declare an integer variable n to store the size of the array.
- Declare an integer array arr of size n.
- Declare an integer variable sum and initialize it to 0.
- Declare a float variable avg and initialize it to 0.
- Read the value of n from the user.
- Read the values of the array arr[] from the user.
- Traverse the array arr from index 0 to index n-1.
- Add each element of the array arr to the variable sum.
- Calculate the average of the array by dividing the sum of the elements by the number of elements in the array.
- Store the result in the variable avg.
- Display the value of avg.
Pseudocode to Calculate the Average of all elements of an array.
1. Declare n as integer 2. Declare arr[n] as integer 3. Declare sum as float and initialize it to 0 4. Declare avg as float and initialize it to 0 5. Read n from user 6. Read arr from user 7. for i = 0 to n-1 do 8. sum = sum + arr[i] 9. end for 10. avg = sum / n 11. Display avg
C Program to Calculate the Average of all elements of an array.
C Code:
//C program to find average of array elements #include <stdio.h> int main() { int size; printf("Enter the size of the array: "); scanf("%d", &size); int arr[size]; printf("Enter %d elements:\n", size); // Input array elements and calculate sum int sum = 0; for (int i = 0; i < size; i++) { scanf("%d", &arr[i]); sum += arr[i]; } // Calculate average float average = (float) sum / size; printf("Average of array elements: %.2f\n", average); return 0; }
Enter the size of the array: 6
Enter 6 elements:
12 9 3 2 10 5
Average of array elements: 6.83
Time Complexity: O(n) where is the size of the given array
Space Complexity: O(1) as constant extra space is required.
Related Articles:
No comments:
Post a Comment