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.
Please try this Exercise on your own before you check out what I’ve done.
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.
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.
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.)