- Let's look at the solution to the challenge
of printing a bar chart.
It is pretty straightforward.
Let's see.
We have one function that we'll call
a showOneBar function, multiple times.
The function showBarChart is simply there
to be a placeholder for all these bars
that will be printed.
It's not a very efficient one,
as we will learn later on,
that it is possible.
For now, we're just calling
the function that prints one bar
five times with multiple lengths,
as you can see in line 24 through 28.
10, 12, 5, 6, and 8.
The most interesting function is the showOneBar.
Here, we're doing a few things.
At the core of this function
is the loop in line 33 through 35.
It is a for loop that prints a number of dots,
but the way to print this dot,
you can use the option 8 key.
Bar length is the parameter of the function
that decides how many of those dots
should be printed.
So, if I pass at eight, then from zero to i
equals less than eight, which is seven.
So, from zero to seven, it's actually eight dots.
So, in a for loop, I'm printing
the precise number of dots
since I know what this is.
The only one other touch
is before I print the bar
I'm actually displaying the number of dots,
the bar length, and if you notice,
in the printf, there is
a percent, and then 3d.
Because I want to ensure
that all the bars will start at the same location,
I am forcing the bar length number
to be displayed over three spaces.
For example, the number 20 takes two spaces.
The number one takes one space.
The number 100 takes three spaces.
So I assume I will not need more than that
because we are not going to write a program
that prints very, very, very long bars.
So, three spaces should be enough.
Therefore, I am ensuring that every bar
starts at the same place on the left side.
All I need to do now is
from main to call showBarChart,
which in turn calls showOneBar
five times with different values,
and the bar will be printed.
Let's test this.
Here it is, a bar chart with five.
I can always add more bars as needed.
For example, save and run this again.
And as you can see,
I have another bar chart.
So, lo and behold,
we saw that C can be a calculator,
C can give you statistics, financial calculation.
Now, it can also print graphs.