I still pretty new to programming and my only prior experience before C was Javascript. I'm doing the CS50 Introduction to Computer Science and in one of the lectures there's an example code that computes the average of some user input. It looks like this:
#include <cs50.h>
#include <stdio.h>
const int TOTAL = 3;
float average(int length, int array[])
int main(void)
{
int scores[TOTAL];
for (int i = 0; i < TOTAL; i++)
{
scores[i] = get_int("Score: ");
}
printf("Average: %f\n", average(TOTAL, scores);
}
float average(int length, int array[])
{
int sum = 0;
for (int i = 0; i < length; i++)
{
sum += array[i];
}
return sum / (float) length;
}
The feature that I'm trying to add is to dynamically store the size of the array depending of the user input, instead of having one variable (TOTAL in this case). For example: I need to have a loop that is always asking the user for a score (instead of just 3 times like the code above), and when the user types zero(0), the loops breaks and the size of the array is defined by how many times the user has typed some score.
This is what I've done:
int main(void)
{
int score;
// start count for size of array
int count = - 1;
do
{
score = get_int("Score: ");
// add one to the count for each score
count++;
}
while (score != 0);
// now the size of the array is defined by how many times the user has typed.
int scores[count];
for (int i = 0; i < count; i++)
{
// how do I add each score to the array???
}
}
My problem is how to add each score that the user types to the array. In advance thanks!!!