How it works...

GLUT is initialized and a top-level window is created with the label, Displaying Bar Chart. The initial position of the window is set at 0,0, that is, at the x=0 and y=0 coordinate location. The window size is specified as 500 px in width and 500 px in height. The display callback function is invoked for drawing the bar chart.

In the display callback, a result array is initialized to three values. Basically, the values in the resulting array represent the growth in profit percentage of the company in the last three years. Let's assume the growth in the profit percentage of the company in 2019, 2018, and 2017 was 10%, 15%, and 5%, respectively. We want the three bars corresponding to this data to rest on the x axis, so the y coordinate is set to 0. To make the first bar appear after some space, the x coordinate value is set to 1. The width of each bar is set to 2. The color for the bar chart is set to red.

A two-dimensional orthographic viewing region is set up, that is, coordinates are set up for the horizontal and vertical clipping planes. Before drawing the bar chart, the horizontal and vertical x and y axes have to be drawn, so vertices for two lines are grouped in the glBegin and glEnd pair with the GL_LINES keyword.

After drawing the x and y axes, a for loop is set to execute three times because we need to draw three bars. Within the for loop, the bars are given a fixed width of 2 px, and, after every bar chart, the x axis of the next bar is computed. Also, the height of the bar – that is, the y coordinate – is computed on the basis of the profit percentage mentioned in each result array. The bar chart is displayed using the four vertices that are grouped in the glBegin and glEnd pair with the GL_POLYGON keyword.

To compile the program, start the X server and give the following command to compile the program:

gcc opengldrawbar.c -lGL -lGLU -lglut -lm -o opengldrawbar

If no error appears, that means the opengldrawbar.c program has successfully compiled into an executable file: opengldrawbar.exe. This file is executed using the following command:

$./opengldrawbar

We will get the output as shown in the following screenshot:

Figure 12.4

Voilà! We have successfully created a bar chart using data entered in an array. Now let's move on to the next recipe!