In C Language (not C++) Write a program that: Sizes an array to hold 5000 values
ID: 3680602 • Letter: I
Question
In C Language (not C++) Write a program that:
Sizes an array to hold 5000 values of type int.
Using the rand( ) function, create random numbers from 1-1000 and place into the array.
Computes the following values for the array (use of functions is optional):
i.Sum of the array values
ii.Computes the minimum value in the array
iii.Computes the maximum value in the array
iv.Computes the mean (average) of the values in the array
v.Changes the array based on following logic: 0-500 converted to 1, 500 to 1000 converted to 2
Prints out the array values to the screen
Prints out the array values to a file “results.txt”
Explanation / Answer
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int a[5000],r,min,max,i,total;//Declaring array of 5000 and min,max,total
float mean;//To hold mean value
FILE *fp;//File pointer
srand(time(NULL));
//Storing 5000 random values into array
for(i=0;i<5000;i++)
{
r=rand()%1001;//Random number to be in between 1-1000
while(r==0)
{
r=rand()%1001;
}
a[i]=r;
}
//Calculation of minimum value is done below
min=10000;
for( i=0;i<5000;i++)
{
if(a[i]<min)
{
min=a[i];
}
}
printf("Minimum Value= %d ",min);
max=-10000;
//Calculation of maximum value is done below
for(i=0;i<5000;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
printf("Maximum Value = %d ",max);
total=0;
//Calculating Mean in the array
for(i=0;i<5000;i++)
{
total=total+a[i];
}
mean=(float)total/5000.0;
printf("Total Mean = %f ",mean);
fp=fopen("result.txt","w");
for(i=0;i<5000;i++)
{
//Prints into results.txt
//printf("%d ",a[i]);
fprintf(fp,"%d ",a[i]);
}
//Setting value of a[i]=0 if a[i]<=500 else a[i]=1
for(i=0;i<5000;i++)
{
if(a[i]<=500)
{
a[i]=0;
}
else
{
a[i]=1;
}
}
}
If you have any doubts please comment below