(Single-dimension Array) Write a C program that will create an integer array wit
ID: 3762063 • Letter: #
Question
(Single-dimension Array) Write a C program that will create an integer array with 1000 entries. After creating the array, initialize all values in the array to 0. Next, loop through the array and save a random number between 1-5 in each entry of the array. Once you have completed this, display the following and then end the program: A: The sum of all of the numbers in the array B: The average of all the numbers in the array C: The number of times each number (1-5) occurred (there are several ways to do this and you are allowed to create a secondary array)
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int Array[1000], Count[6], i, sum = 0;
float avg;
for(i = 0; i < 1000; i++) /*Initialize all elements with 0.*/
Array[i] = 0;
srand(time(NULL)); /*Generate a random seed.*/
for(i = 0; i < 1000; i++) /*Assign random values between 1 and 5 to array elements.*/
Array[i] = rand() % 5 + 1;
for(i = 0; i < 1000; i++) /*Calculate the sum of the elements in the array.*/
sum += Array[i];
avg = (float)sum / 1000; /*Calculate the average of the elements in the array.*/
for(i = 0; i < 1000; i++) /*Count the frequency of each element in the array.*/
Count[Array[i]]++;
printf("The sum of the elements is: %i ", sum);
printf("The average of the elements is: %f ", avg);
printf("The frequency of each element in the array is: ");
for(i = 1; i <= 5; i++)
printf("%i appeared %i times. ", i, Count[i]);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.