In: Computer Science
Write a C program that does the following.
(a) Start with comment statements at the top (before your includes) with the following info: Name, Date
(b) Write the following functions:
void setupRandArray(int n, int x[], int min, int max)
void printArray(int n, int x[], char label[])
float getAverage(int n, int x[]) int getMaximum(int n, int x[])
int getCountInRange(int n, int x[], int min, int max)
Note: This function returns the number elements of x that are between min and max (including min and max).
(c) Write a main to test your functions. Create an array of random test scores between 70 and 100. Compute the average score, the high score, and the number of B grades.
A typical output is shown below. Do all printing of results at the end of main. Run your program twice: once with 10 scores and then with 20 scores. Put your output in comments underneath main.
Hint: Set up a variable for the array size in main so that you can easily change it.
scores: 78 93 72 98 94 92 86 90 83 75
ave: 81.2
high: 98
numB: 2
scores: 88 71 95 83 88 90 72 89 79 73 94 91 86 88 78 92 82 81 76 70
ave: 83.2
high: 95
numB: 8
C Code:
//Name : ---- Roll :----
#include <stdio.h>
#include <stdlib.h>
//function defintion to create or setup random array of size n between min and max
void setupRandArray(int n, int x[], int min, int max){
for(int i=0; i<n; i++)
{
x[i] = (rand() % (max-min+1)) + min; //rand() is function to generate random numBer.
}
}
void printArray(int n, int x[], char label[]){
printf("scores %s",label);
for(int i=0; i<n; i++)
{
printf("%d ", x[i]); //printing array elements
}
}
double getAverage(int n, int x[]) //function defintion for calculating average
{
double ans = 0;
for(int i=0; i<n; i++)
{
ans += x[i]; //calculating sum of all elements
}
return ans/n; //returning the sum of elements
}
int getMaximum(int n, int x[]) //function defintion for calculating maximum in array
{
int max = -1;
for(int i=0; i<n; i++)
{
if(max < x[i])
{
max = x[i];
}
}
return max; //returning max value
}
int getCountInRange(int n, int x[], int min, int max) //function defintion to calculate no in range
{
int cnt=0;
for(int i=0; i<n; i++)
{
if(x[i] >= min && x[i] < max) //checking for range
cnt++;
}
return cnt; //return the no. which are in range
}
int main()
{
int n = 20,high,numB;
double avg;
int arr[n];
int min = 70, max = 100;
char label []=": ";
setupRandArray(n, arr, min, max);
printArray(n, arr, label);
avg = getAverage(n, arr);
high = getMaximum(n, arr);
numB = getCountInRange(n, arr, 90, 100);
printf("\nave: %.1f\n", avg);
printf("high: %d\n", high);
printf("numB: %d\n", numB);
}
//Output for 10 elemnts
/*scores : 80 92 80 96 81 77 78 71 93 75
ave: 82.3
high: 96
numB: 3*/
//Output for 20 elements
/*scores : 80 92 80 96 81 77 78 71 93 75 71 98 70 95 80 96 89 77 92 81
ave: 83.6
high: 98
numB: 7*/
Output for 10 elements:
Output for 20 elements:
If you have any doubt feel free to ask and if you like the answer please upvote it .
Thanks