Hello I was wondering if anyone could help me with this prog
Hello I was wondering if anyone could help me with this programming assignment in C. Thanks in advance! :
Write a program that will prompt the user to input student scores to an array. The program should prompt the user for the size of the array. The array must be dynamic memory allocation using malloc() function and don’t forget to de-allocation. The score value is between 0 – 100. The program will display the smallest and greatest of those values. It also displays the average score. Write two functions that sort the student scores from small - large and another one sort for largest - smallest.
Solution
#include <stdio.h>
#include<stdlib.h>
void sortAsc(int *scores,int size)
{
int i,j,pos,temp;
for (i = 0 ; i < size-1 ; i++ )
{
pos = i;
for ( j = i + 1 ; j < size ; j++ )
{
if ( scores[pos] > scores[j] )
pos = j;
}
if ( pos != i )
{
temp = scores[i];
scores[i] = scores[pos];
scores[pos] = temp;
}
}
}
void sortDesc(int *scores,int size)
{
int i,j,pos,temp;
for (i = 0 ; i < size-1 ; i++ )
{
pos = i;
for ( j = i + 1 ; j < size ; j++ )
{
if ( scores[pos] < scores[j] )
pos = j;
}
if ( pos != i )
{
temp = scores[i];
scores[i] = scores[pos];
scores[pos] = temp;
}
}
}
void printArray(int *scores,int size)
{
int i;
for(i=0;i<size;i++)
printf(\"%d \",scores[i]);
printf(\"\ \");
}
int main(void) {
// your code goes here
int number;
printf(\"Enter the size of the array : \");
scanf(\"%d\",&number);
int *scores = (int*)malloc(number*sizeof(int));
int smallest = -1,largest = -1;
int sum = 0;
int i = 0;
for(i=0;i<number;i++)
{
printf(\"Enter a score in 0 - 100 range : \");
scanf(\"%d\",&scores[i]);
if(smallest==-1)
{
smallest = scores[i];
largest = scores[i];
}
else
{
if(scores[i]<smallest)
smallest = scores[i];
if(scores[i]>largest)
largest = scores[i];
}
sum = sum+scores[i];
}
float avg = sum/number*1.0;
printf(\"The largest score is %d \ \",largest);
printf(\"The smallest score is %d \ \",smallest);
printf(\"Average score is %f \ \",avg);
printf(\"Scores in ascending order : \");
sortAsc(scores,number);
printArray(scores,number);
printf(\"Scores in descending order : \");
sortDesc(scores,number);
printArray(scores,number);
free(scores);
return 0;
}
OUTPUT:
Enter the size of the array : 5
Enter a score in 0 - 100 range : 100
Enter a score in 0 - 100 range : 20
Enter a score in 0 - 100 range : 30
Enter a score in 0 - 100 range : 60
Enter a score in 0 - 100 range : 50
The largest score is 100
The smallest score is 20
Average score is 52.000000
Scores in ascending order : 20 30 50 60 100
Scores in descending order : 100 60 50 30 20


