In: Computer Science
Write a program in C which randomly generates two integers X and Y between 10 and 50, and then creates a dynamic array which can hold as many numbers as there are between those two random numbers. Fill the array with numbers between X and Y and print it on screen. Do not forget to free the allocated memory locations whenever they are no longer needed.
Example:
Randomly generated numbers are: 43 23
Expected Output :
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
ANSWER:
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
int main(void) {
int x, y, min, max;
srand(time(0)); // using current time for seeding the random number generator.
x = 10+rand()%41 ; // Generate random number between 10 and 50
y= 10+rand()%41;
printf("Randomly generated numbers are: %d %d \n",x,y);
int value = abs(y-x)+1;
int *array= (int *)malloc(sizeof(int)*value);
if(x<y){
min = x;
max = y;
}
else{
min =y;
max=x;
}
int c=0;
for(int i=min;i<=max;i++){
array[c] = i;
c+=1;
}
int temp=0;
for(int j=min;j<=max;j++){
printf("%d ",array[temp]);
temp+=1;
}
// Freed up dynamically allocated memory.
free(array);
return 0;
}
NOTE: The above code is in C language. Please refer to the attached screenshots for code indentation and sample I/O.
SAMPLE OUTPUT:
[**The output may vary. Since, on each execution of the
program, random numbers are generated]
1.
2.
3.
4.