How to do it...

The following are the steps for drawing a bar chart with the values defined in an array:

  1. Initialize GLUT, define the size of the top-level window, set its initial position for display, and display the window on the screen.
  2. Define the callback function that is auto-invoked after creating a window for drawing the bar chart.
  3. An array is defined in the callback that defines the height of the bar chart. The width of the bar chart is fixed at 2 px.
  4. A two-dimensional orthographic viewing region is set up, that is, coordinates are set up for horizontal and vertical clipping planes.
  5. To display the horizontal and vertical x and y axes, the vertices for the two lines are grouped in a glBegin and glEnd pair with the GL_LINES keyword.
  6. In order to display three bars, a for loop is set to execute three times. To display bars one beside the other, the x axis of the next bar is computed. The height of each bar is computed on the basis of the array defined in step 3.
  7. The bar chart is displayed using the four vertices that are grouped in the glBegin and glEnd pair with the GL_POLYGON keyword.

The program for drawing a bar chart on the basis of values in an array is as follows:

//opengldrawbar.c

#include <GL/glut.h>

void display(){
float x,y,width, result[] = {10.0, 15.0, 5.0};
int i, barCount = 3;
x=1.0;
y = 0.0;
width = 2.0;
glColor3f(1.0, 0.0, 0.0);
glClearColor(1.0, 1.0, 1.0, 1.0);
gluOrtho2D(-5, 20, -5, 20);
glBegin(GL_LINES);
glVertex2f(-30, 0.0);
glVertex2f(30, 0.0);
glVertex2f(0.0, -30);
glVertex2f(0.0, 30);
glEnd();
for(i=0; i<barCount; i++){
x = (i * width) + i + 1;
glBegin(GL_POLYGON);
glVertex2f(x, y);
glVertex2f(x, y+result[i]);
glVertex2f(x+width, y+result[i]);
glVertex2f(x+width, y);
glEnd();
}
glFlush();
}

int main(int argc, char *argv[]){
glutInit(&argc, argv);
glutInitWindowPosition(0, 0);
glutInitWindowSize(500, 500);
glutCreateWindow("Drawing Bar Chart");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Now, let's go behind the scenes to understand the code better.