In: Computer Science
All Code should be written in C:
1. Write a C program which prompts the user to enter two integer values. Your program should then print out all numbers between 1 and 1000 that are divisible by both of those numbers.
2. Modify your program from question 1 such that the first 1000 numbers that are divisible by both numbers are printed out, instead of numbers up to 1000.
3. Using dynamic memory, allocate memory for an array of 100 floating point numbers. Fill this array with random numbers between 0 and 1, and print them to the screen. HINT: Use RAND_MAX, which represents the largest possible value returned by the rand() function.
4. Modify question 3 such that the program writes the values to a file called "floats.txt" in text format, one per line, instead of to the screen
Here is the completed code for each part. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
//CODE FOR PART 1
#include<stdio.h>
int main(){
//declaring two integers
int a, b;
//asking for two integers
printf("Enter two integer values: ");
//reading two integers
scanf("%d %d",&a,&b);
//looping from i=1 to i=1000
for(int i=1;i<=1000;i++){
//if i is divisible by a and b, printing it
if(i%a==0 && i%b==0){
printf("%d\t",i);
}
}
printf("\n");
return 0;
}
//CODE FOR PART 2
#include<stdio.h>
int main(){
//declaring two integers
int a, b;
//asking for two integers
printf("Enter two integer values: ");
//reading two integers
scanf("%d %d",&a,&b);
int i=1; //starting value
int counter=0; //count of numbers divisible by a and b
//loops until counter hits 1000
while(counter<1000){
//if i is divisible by a and b, printing it
if(i%a==0 && i%b==0){
printf("%d\t",i);
//incrementing counter
counter++;
}
//next value
i++;
}
printf("\n");
return 0;
}
//CODE FOR PART 3
#include<stdio.h>
#include<stdlib.h>
int main(){
//creating a dynamic float array of 100 elements
float *arr = (float*) malloc(100 * sizeof(float));
//looping from i=0 to i=99
for(int i=0;i<100;i++){
//generating a random number between 0 and 1, assigning to arr[i]
arr[i]=(rand()/(float)RAND_MAX);
//printing the number
printf("%f\n",arr[i]);
}
//de allocating memory
free(arr);
return 0;
}
//CODE FOR PART 4
#include<stdio.h>
#include<stdlib.h>
int main(){
//creating a dynamic float array of 100 elements
float *arr = (float*) malloc(100 * sizeof(float));
//opening a file 'floats.txt' in write mode
FILE* op=fopen("floats.txt","w");
//looping from i=0 to i=99
for(int i=0;i<100;i++){
//generating a random number between 0 and 1, assigning to arr[i]
arr[i]=(rand()/(float)RAND_MAX);
//printing the number to the file
fprintf(op,"%f\n",arr[i]);
}
//de allocating memory
free(arr);
//closing file, saving changes
fclose(op);
return 0;
}