Program to find sum and average of n elements entered by the user. Allocate memory dynamically using malloc() / calloc() functions.
// Program to find sum and average of n elements entered by the user.
// Allocate memory dynamically using malloc()/calloc() functions.
#include<stdio.h>
#include<stdlib.h>
int main() {
int n, i, sum=0;
float avg;
printf("Enter the number of elements : ");
scanf("%d",&n);
int *p = (int *)calloc(n, sizeof(int));
for (i=0; i<n; i++){
printf("\nEnter the %dth element : ", i+1);
scanf("%d", &p[i]);
}
for (i=0; i<n; i++){
sum += p[i];
}
avg = (float)sum / n;
printf("\nThe sum of %d elements is : %d\nAverage is : %0.2f ", n, sum, avg);
return 0;
}
Output :
Enter the number of elements : 5
Enter the 1th element : 4
Enter the 2th element : 3
Enter the 3th element : 5
Enter the 4th element : 7
Enter the 5th element : 3
The sum of 5 elements is : 22
Average is : 4.40
No comments:
Post a Comment