The nested loop does not work properly

advertisements

I'm trying to make a program that asks how many days have you practiced, and then for each day ask how many flights you made and then determine the average of those flights for each day, this is my code right now:

#include <stdio.h>

int main() {
    int days, flights, i;
    double length, total, average;

printf("How many days have you been practicing?\n");
scanf("%d", &days);

for(i=1; i<=days; i++) {
    printf("How many flights were completed in day #%d?\n", i);
    scanf("%d", &flights);
        for(i=1; i<=flights; i++){
            printf("How long was flight #%d?\n", i++);
            scanf("%lf", &length);
            length += total;
            average = total / flights;
            printf("Day #%d: The average distance is %.3lf\n", i, average);
            }
    }
    return 0;
}

Right now an example output looks like this:

How many days have you been practicing?

2

How many flights were completed in day #1?

2

How long was flight #1?

5.00

Day #3: The average distance is 0.000.

How many flights were completed in day #2?

3

How long was flight #1?

7.50

How long was flight #3?

13.00

Day #5: The average distance is 0.000.

As you can see there are multiple problems with the output right now, the average distance is not calculating, I am not able to input numbers for each flight, and the flight and day #'s are incorrect. Any help would be greatly appreciated as I am new to this! As an example the final output should look something like this:

How many days have you been practicing?

2

How many flights were completed in day #1?

2

How long was flight #1?

5.00

How long was flight #2?

10.00

Day #1: The average distance is 7.500.

How many flights were completed in day #2?

3

How long was flight #1?

7.50

How long was flight #2?

13.00

How long was flight #3?

15.75

Day #2: The average distance is 12.083.


There were several problems, I left a comment for each fix I made. Let me know if you have questions

#include <stdio.h>

int main() {
    int days, flights, i, j;
    double length, total, average;

    printf("How many days have you been practicing?\n");
    scanf("%d", &days);

    for (i = 1; i <= days; i++) {
        printf("How many flights were completed in day #%d?\n", i);
        scanf("%d", &flights);

        // Reset total
        total = 0.0;

        // Use a different index variable than i, I used j
        for (j = 1; j <= flights; j++) {
            // Do not increment i here (I removed i++)
            printf("How long was flight #%d?\n", j);
            scanf("%lf", &length);

            // This was probably backwards, you never assigned total
            //length += total;
            total += length;
        }

        // Compute the average per day outside the flights loop
        average = total / flights;
        printf("Day #%d: The average distance is %.3lf\n", i, average);
    }

    return 0;
}