Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Assignment 11: Dynamically (re)allocate scores array
- Loading branch information
Showing
1 changed file
with
34 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,61 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
#include <string.h> | ||
|
||
#define INITIAL_CAPACITY 3 | ||
|
||
int main(void) | ||
{ | ||
char answer[] = "Y"; | ||
char answer[] = "y"; | ||
|
||
float scores[10]; | ||
//allocate store for 3 scores | ||
double *scores = malloc(INITIAL_CAPACITY * sizeof(double)); | ||
if(!scores) | ||
{ | ||
fprintf(stderr, "Failed to allocate scores array.\n"); | ||
return 1; | ||
} | ||
|
||
int capacity = INITIAL_CAPACITY; | ||
|
||
//initialize a variable to increase and iterate through our array to store scores | ||
int i = 0; | ||
int numScores; | ||
|
||
while (strcmp(answer, "Y") == 0) | ||
for(numScores = 0; strcmp(answer, "y") == 0; ++numScores) | ||
{ | ||
//dynamically | ||
if(numScores == capacity) | ||
{ | ||
capacity *= 2; | ||
scores = realloc(scores, capacity * sizeof(double)); | ||
if(!scores) | ||
{ | ||
fprintf(stderr, "Failed to reallocate scores array.\n"); | ||
return 1; | ||
} | ||
} | ||
|
||
//store input in our array | ||
printf("Enter a test score: "); | ||
scanf("%f", &scores[i]); | ||
|
||
//increase our counter | ||
i++; | ||
scanf("%lf", &scores[numScores]); | ||
|
||
//ask the user if they would like to continue | ||
printf("Would you like to continue? Y/N "); | ||
printf("Would you like to continue? y/n "); | ||
scanf("%s", &answer); | ||
} | ||
|
||
int loop; | ||
int sum = 0; | ||
double sum = 0; | ||
|
||
//start a loop that will start at 0, and then it'll iterate through our scores array until it reaches the end | ||
//each element in the array will be added to the sum so that we can find the average | ||
for(loop = 0; loop < i; loop++) | ||
for(int loop = 0; loop < numScores; loop++) | ||
{ | ||
sum = sum + scores[loop]; | ||
sum += scores[loop]; | ||
} | ||
|
||
//do the maths | ||
float average; | ||
printf("%.2f is the average.\n", sum / numScores); | ||
|
||
average = (float)sum/loop; | ||
free(scores); | ||
|
||
printf("%.2f is the average.\n", average); | ||
return 0; | ||
} |