Nested Processing

After a few intermediate to advanced Exercises, I decided to try something that’s a little easier this month. Still, even if you’re a pro, it helps to pull back and try something basic just to see what you can do with it.

For this month’s Exercise, the challenge is to output a primitive, text mode bar graph. The data is held in an array:

int v[5] = { 5, 3, 8, 7, 2 };

Your job is to write the code that outputs a five line bar graph that looks something like this:

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

That’s it, though multiple methods exist to solve this problem.

I tried to write a version without using nested loops, but that just didn’t work. And, yes, calling a function with a second loop is still a nested loop. Therefore, somehow you’ll probably devise a solution with a nested loop. To not do so would be remarkable, so be sure to share such a solution.

I’ll post my solution in a week’s time. Please try this Exercise on your own before you check out what I’ve done.

4 thoughts on “Nested Processing

  1. In Python you can multiply a string by an integer:

    “*” * 5 = “*****”

    and the JavaScript string has a repeat method:

    “*”.repeat(5) = “*****”

    I don’t think there is anything comparable in the C library. Maybe someone ele can think of some obscure function or clever workaround?

    I think it is logically impossible to do your exercise without nested loops, and the Python and JavaScript methods just bury it under a layer of abstraction.

  2. Thanks for sharing the other methods, which I’m unfamiliar with. You’ll see my non-nested loop workaround on the 8th. It’s not as nifty as what you posted.

  3. #include <stdio.h>
    #define MAX_VALUE 11    /* Suppose the highest value in bar graph is 10 */
    void create_str_of_stars(char *str)
            int i;
            for(i = 0; i < MAX_VALUE-1; i++)
                *(str+i) = '*';
           *(str+i) = '\0';
     int main(void)
          int v[5] = { 5, 3, 8, 7, 2};
          char str_of_stars[MAX_VALUE];
          int i;
          for(i = 0; i < 5; i++)
              printf("%d: %.*s (%d)\n", i+1, v[i], str_of_stars, v[i]);
          return 0;
  4. Ivan, your solution similar to what I attempted in my solution (posting Wednesday), but yours is far more clever! If you declared the str_of_stars string as a constant, I believe it would work without two loops.

    (And I cleaned up your code. Remember to use the <pre> tag to allow for preformatted text in the comments.)

Leave a Reply