|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/midtermSol/p4.c
/*
4.
Consider the following array declaration:
int numbers[64];
Assume that the array has been filled with integers. Give me code that sets up a loop that will calculate the
average of all the values in that array, then output the average once the loop finishes.
You must declare all variables (other than the already-declared array) used in the loop, initialize variables
when necessary. You can treat the average as an integer number.
Hint: If you don't remember, you get the average by dividing the sum of all the numbers by the number of elements.
*/
#include <stdio.h>
#include <stdlib.h>
int main(){
int numbers[64];
//generating random numbers to populate the array
for(int i = 0; i < 64; i++){
numbers[i] = rand() % 100; //generating pseudorandom numbers between 0 and 99
}
int sum = 0, avg;
for(int i = 0; i < 64; i++){
sum = sum + numbers[i];
}
avg = sum / 64;
printf("average value = %d\n", avg);
return 0;
}
|