In: Computer Science
Write a C program that uses a loop which prompts a user for an integer 10 times and stores those integers in an array. The program will print out the numbers entered by the user with a comma and a space separating each number so the numbers can be read easily. The program will then calculate and print out the sum, integer average and floating point average (to 4 decimal points) of the numbers in the array. The information being printed out should be labeled correctly with newline characters placed so the output is readable. You will also create a BubbleSort function to sort the integers from small to large. The array will be passed by reference to the function where the function will reorder the integers in the array. You should not duplicate the array in anyway.
Remember your assignment must be submitted by 11:59:59pm on the due date, or else it will be considered late and will not be accepted. Please make sure your C code is thoroughly commented to explain what your program is doing. You should only submit the C source code, not the compiled program.
NOTE: Pseudo-code for a basic Bubble Sort routine:
procedure BubbleSort( A : array of integers to sort) repeat swapped = false for item in A inclusive do: if A[i-1] > A[i] then swap A[i-1] and A[i] swapped = true end if end for until not swapped end procedure |
Sample Output:
$>./assignment3 Enter element 1 into the array 5 Enter element 2 into the array 7 Enter element 3 into the array 6 Enter element 4 into the array 1 Enter element 5 into the array 2 Enter element 6 into the array 3 Enter element 7 into the array 4 Enter element 8 into the array 8 Enter element 9 into the array 9 Enter element 10 into the array 0 5, 7, 6, 1, 2, 3, 4, 8, 9, 0 The sum of the integers in the array is 45 The integer average of the integers in the array is 4 The float average of the integers in the array is 4.5000 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 $> |
C Program:
#include <stdio.h>
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(int * const arr, const int size){
int i, j=0;
for(i=0;i<size-1;i++){
for(j=0;j<size-1;j++){
if(arr[j] >arr[j+1]){
swap(&arr[j],&arr[j+1]);
}
}
}
}
int main() {
int arr[10];
int sum,avg;
float avg1;
for(int i=0;i<10;i++){
printf("Enter element %d into the array: ",i+1);
scanf("%d",&arr[i]);
sum+=arr[i];
}
for(int i=0;i<10;i++){
if(i!=9)
printf("%d, ",arr[i]);
else
printf("%d\n",arr[i]);
}
bubbleSort(arr,10);
avg=sum/10;
avg1=(double)sum/10;
printf("The sum of integers in the array is %d\n",sum);
printf("The integer average of the integers in the array is %d\n",avg);
printf("The integer average of the integers in the array is %f\n",avg1);
for(int i=0;i<10;i++){
if(i!=9)
printf("%d, ",arr[i]);
else
printf("%d",arr[i]);
}
}
if you like the answer please provide a thumbs up.