Create an array of size 10, input values and display sum and average of all elements in the array.
#include <stdio.h>
int main() {
int arr[10], i, sum = 0; // Step 1: Declare array and variables
float avg;
// Step 2: Input elements from user
printf("Enter 10 integers:\n");
for(i = 0; i < 10; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Step 3: Calculate sum
for(i = 0; i < 10; i++) {
sum += arr[i];
}
// Step 4: Calculate average
avg = sum / 10.0;
// Step 5: Display results
printf("\nSum of all elements = %d", sum);
printf("\nAverage of all elements = %.2f", avg);
return 0;
}
🧠Step-by-Step Explanation
🔹 Step 1: Variable Declaration
int arr[10], i, sum = 0;
float avg;
arr[10]
creates an integer array with 10 elements
sum
initialized to 0 to accumulate total
avg
declared as float for precise division
i
will be used as loop counter
🔹 Step 2: Input Array Elements
for(i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
- Loop runs 10 times (i = 0 to 9)
- Prompts user for each element
- Stores input in array using index
i
&arr[i]
gets memory address for storage
🔹 Step 3: Calculate Sum
for(i = 0; i < 10; i++) {
sum += arr[i];
}
- Iterates through each array element
- Adds each element's value to
sum
- After loop completes,
sum
contains total
🔹 Step 4: Calculate Average
avg = sum / 10.0;
- Divides
sum
by 10.0 (float division)
- Using
10.0
instead of 10
ensures decimal result
- Result stored in
avg
variable
🔹 Step 5: Display Results
printf("\nSum of all elements = %d", sum);
printf("\nAverage of all elements = %.2f", avg);
- First printf displays integer sum
- Second printf shows average with 2 decimal places
%.2f
format specifier controls decimal precision
🖨️ Sample Output:
Enter 10 integers:
Element 1: 5
Element 2: 10
Element 3: 15
Element 4: 20
Element 5: 25
Element 6: 30
Element 7: 35
Element 8: 40
Element 9: 45
Element 10: 50
Sum of all elements = 275
Average of all elements = 27.50
💡 Key Concepts:
- Array Basics: Fixed-size collection of same-type elements
- Loop Structures: for loops for controlled iteration
- Type Conversion: Importance of 10.0 for float division
- I/O Formatting: Using %.2f for decimal precision
- Memory Management: Array elements stored contiguously
No comments:
Post a Comment