Nested Processing – Solution

This month’s Exercise wasn’t astronomically difficult, but I did spend some time devising a solution. My goal was to try to avoid writing a nested loop. This goal proved unattainable.

To review, given an array of five integers, write code that outputs a text-mode bar graph based on the integers’ values. Here is my solution:

2020_07-Exercise.c

#include <stdio.h>

int main()
{
    int v[5] = { 5, 3, 8, 7, 2 };
    int a,b;

    for(a=0;a<5;a++)
    {
        printf("%d: ",a+1);
        for(b=0;b<v[a];b++)
            putchar('*');
        printf(" (%d)\n",v[a]);
    }

    return(0);
}

Obviously, a nested loop is required. The outer loop, governed by variable a, plows through the array elements. The inner loop, powered by variable b, outputs asterisks to make the bar chart.

Extra fluff in the code helps make the output pretty:

Line 10 outputs the element number, adding one to variable a to make the value sensical to humans: printf("%d: ",a+1);

Line 13 outputs a summary after each bar is generated, listing the number of asterisks: printf(" (%d)\n",v[a]);

Here’s the output:

1: ***** (5)
2: *** (3)
3: ******** (8)
4: ******* (7)
5: ** (2)

This solution could also be done with while loops or a mixture of while and for loops.

For my non-nested loop attempts, the closest I cam to devising a single-loop solution is the following code, which isn’t an official solution, so it doesn’t count:

#include <stdio.h>

int main()
{
    int v[5] = { 5, 3, 8, 7, 2 };
    int a;

    for(a=0;a<5;a++)
    {
        printf("%d: %*c (%d)\n",
                a+1,
                v[a],
                '*',
                v[a]
              );
    }

    return(0);
}

In Line 10, the printf() variable-width placeholder is used as %*c to fake a kinda bar graph. The * specifies a variable width, which can work for a single character. Here’s the output:

1:     * (5)
2:   * (3)
3:        * (8)
4:       * (7)
5:  * (2)

Alas, this solution just doesn’t cut it because a bar graph isn’t output.

I thought about using a function to generate the asterisks, but it too would have contained a loop. And there’s no way I’m going to use goto, which would be cheating in my opinion.

So the solution remains simple and not impossible to attain. I hope you arrived at something similar.

5 thoughts on “Nested Processing – Solution

  1. Very cool video. I’ve wanted to do things like that, but just don’t get the math.

    I can’t imagine any way to do it without a loop. The “length” variable could be an offset, not a counter. Still, without counting the bar graph output, I don’t see how.

  2. He has a nondescript American accent, but his YouTube bio says he’s born in Russia.

Leave a Reply