Write a C program
Design a program that uses an array to store 10 randomly generated integer numbers in the range from 1 to 50. The program should first generate random numbers and save these numbers into the array. It will then provide the following menu options to the user:
The options 2 and 3 should call an appropriate user-defined function and pass the array to the function to compute the largest and the average value respectively. Design and call these two user-defined functions. The average value should be calculated and displayed with a precision of two decimal places.
The program should loop back to the main menu until the user selects the option to exit the program.
Use the register storage class for two the most frequently used variables in your program.
Submit your program's source code (i.e., .c file) and a file with screen captures of your program's
Implement the program as follows:
Program:
#include <stdio.h>
#include <stdlib.h>
int largest(int numbers[]){ /* define the function largest() that accepts numbers array */
int largest=numbers[0], j; /* initialize largest as first element */
for(j = 0; j<10;j++){ /* for each element in array */
if(numbers[j]>largest){ /* update largest if the element > largest */
largest = numbers[j];
}
}
return largest; /* return largest */
}
double average(int numbers[]){ /* define the function average() that accepts numbers array */
int sum = 0, j; /* initialize sum to 0 */
for(j = 0; j<10;j++){ /* for each element in array */
sum = sum + numbers[j]; /* add it to sum */
}
return sum/10.0; /* calculate average as sum/10 and return average */
}
int main() /* define main() function */
{
int numbers[10], input; /* declare integer variables */
register int i, choice; /* declare register storage variables using the keyword, register */
srand(0); /* initialize random module */
for(i=0; i<10;i++){ /* generate 10 random numbers and store it in numbers array */
numbers[i] = rand()%50 + 1; /* limit generated random numbers in range 1-50 */
}
do{ /* Display menu options */
printf("\n1. Display 10 random numbers stored in the array.");
printf("\n2. Compute and display the largest number in the array.");
printf("\n3. Compute and display the average value of all numbers.");
printf("\n4. Exit");
printf("\nPlease enter an option : "); /* ask the user to enter an input */
scanf("%d", &input); /* read input */
choice = input; /* store input value in choice */
switch(choice){
case 1: printf("\nNumbers are: "); /* display all the numbers if choice = 1 */
for(i=0; i<10;i++){
printf("%d ",numbers[i]);
}
break;
case 2: printf("\nLargest is : %d", largest(numbers)); /* display largest using largest() if choice = 2 */
break;
case 3: printf("\nAverage is : %.2f", average(numbers)); /* display average using average() if choice = 3 */
break;
}
}while(choice!=4); /* repeat until choice!= 4 */
return 0;
}
Screenshot:
Output:
Please don't forget to give a Thumbs Up.
Get Answers For Free
Most questions answered within 1 hours.