Personal DB
How I define - for loop
Ayin Kim
2022. 4. 5. 12:00
반응형
How to improve this code more efficiently? In other words, how to be accepted in interview?
int main(void)
{
int scores[3];
scores[0] = get_int("Score: ");
scores[1] = get_int("Score: ");
scores[2] = get_int("Score: ");
printf("Average: %f\n", (scores[0] + scores[1] + scores[2] / 3.0);
Obviously, get_int can be replaced to something else. To reduce that repetitive one.
In this case, the expert said they will use loop.
int main(void)
{
int scores[3];
for (int i = 0; i < 3; i++)
{
scores[i] = get_int("Score: ");
}
printf("Average: %f\n", (scores[0] + scores[1] + scores[2] / 3.0);
And still improvable! How?
int main(void)
{
int n = get_int("How many scores? ");
int scores[n];
for (int i = 0; i < n; i++)
{
scores[i] = get_int("Score: ");
}
printf("Average: %f\n", (scores[0] + scores[1] + scores[2] / 3.0);
Now, whole program works dynamically. This process is dynamic.
Although this is probably basic, this is important to reduce the size of its data.