Skip to content

Commit

Permalink
Assignment 11: Dynamically (re)allocate scores array
Browse files Browse the repository at this point in the history
  • Loading branch information
Phidelux committed Feb 6, 2020
1 parent e8e7f90 commit da0b32d
Showing 1 changed file with 34 additions and 17 deletions.
51 changes: 34 additions & 17 deletions Assignment-11/assignment11.c
@@ -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;
}

0 comments on commit da0b32d

Please sign in to comment.