In: Computer Science
1. Create a program that generates n values in range [low, high].
• Create a function generate_vals which takes as input an array of double values and three integers representing the size of the array, low value of range, and high value of range, respectively. The function should use rand() to generate the requested number of values.
• Prompt the user to enter the size of their array as shown below. It cannot exceed a maximum size of 128. If it does, set the size equal to 128 and continue with the program.
• Prompt the user to enter a low and high value as shown below. These values will be used to limit the range that each generated number can be.
• Print the generated values such that it matches the format below.
Example Run:
Enter size: 8
Enter low value: 9
Enter high value: 18
16.05, 16.19, 17.20, 10.78, 12.02, 15.91, 11.50, 13.99
SOURCE CODE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_vals(double arr[], int size, int low, int high);
int main()
{
// seed the random number generator
srand(time(0));
int size, low, high;
double arr[128];
// taking input
printf("Enter size: ");
scanf("%d", &size);
printf("Enter low value: ");
scanf("%d", &low);
printf("Enter high value: ");
scanf("%d", &high);
// calling function
generate_vals(arr, size, low, high);
// printing values
for (int i = 0; i < size; i++)
{
printf("%.2f ", arr[i]);
}
return 0;
}
// function to generate random float values in a given range
void generate_vals(double arr[], int size, int low, int high)
{
// in order to generate a random float of 2 decimal places
// we shall first generate random int numbers between range
// low*100 and high*100. Dividing the result by 100 shall
// give us a decimal random number of 2 decimal places
int l_range = low*100, h_range = high*100;
for (int i = 0; i < size; i++)
{
// genrating random int numbers between range
// low*100 and high*100
arr[i] = rand() % (h_range - l_range + 1) + l_range;
// dividing by 100 to get result
arr[i] /= 100.0;
}
}
SOURCE CODE SCREENSHOT
OUTPUT