Search code examples
cfor-loopprogress

Work out the overall progress (%) of three nested for loops


I have three nested for loops, each of which obviously have a limit. To calculate the progress of any one of the three for loops, all that I need to do is to divide the current iteration by the total number of iterations that the loop will make. However, given that there are three different for loops, how can I work out the overall percentage complete?

int iLimit = 10, jLimit = 24, kLimit = 37;

for (int i = 0; i < iLimit; i++) {
    for (int j = 0; j < jLimit; j++) {
        for (int k = 0; k < kLimit; k++) {
            printf("Percentage Complete = %d", percentage);
        }
    }
}

I tried the following code, but it reset after the completion of each loop, reaching a percentage greater than 100.

float percentage = ((i + 1) / (float)iLimit) * ((j + 1) / (float)jLimit) * ((k + 1) / (float)kLimit) * 100;

Solution

  • You can easily calculate the "change in percentage per inner cycle"

    const double percentChange = 1.0 / iLimit / jLimit / kLimit;
    

    Note, this mathematically equivalent to 1/(iLimit*jLimit*kLimit), however if iLimitjLimitkLimit is sufficiently large, you'll have an overflow and unexpected behavior. It's still possible to have an underflow with the 1.0/... approach, but its far less likely.

    int iLimit = 10, jLimit = 24, kLimit = 37;
    
    const double percentChange = 1.0 / iLimit / jLimit / kLimit;
    double percentage = 0;
    
    for (int i = 0; i < iLimit; i++) {
        for (int j = 0; j < jLimit; j++) {
            for (int k = 0; k < kLimit; k++) {
                percentage += percentChange;
                printf("Percentage Complete = %d\n", (int)(percentage * 100));
            }
        }
    }