# How does drawing circle work?

``````
void drawCircle(float cx, float cy, float r, float num_segments){
glBegin(GL_LINE_LOOP);

for(int i = 0; i < num_segments; i++){
float theta = 2.0f * PI * i / num_segments;

float x = r * cosf(theta);
float y = r * sinf(theta);

glVertex2f(x + cx, y + cy);
}

glEnd();
}

``````

This is newbie question but how does above code work? why is this function able to draw a circle?

Where can I learn computer graphical maths such as above? any recommended website/videos?

The above converts polar coordinates (radius and angle) to rectangular (Cartesian) coordinates (X and Y). Thus, the loop generates a sequence of points with a fixed radius r and increasing angles (theta is proportional to the loop counter, i).

This follows from the definition of sine and cosine, which should be explained in any introductory text on trigonometry.

Most texts on the mathematics related to computer graphics would probably assume the above as prior knowledge.

The main areas of mathematics involved in computer graphics are algebra and linear algebra, with differential calculus being useful for some more advanced topics (e.g. determining tangents and normals to curves and curved surfaces).

About the only trigonometry that’s required for computer graphics is conversion between polar and rectangular coordinates. Conversion in one direction is given above, the inverse (conversion from rectangular to polar coordinates) is:

``````
double r = sqrt(x*x + y*y);    // Pythagoras' theorem
double theta = atan2(y, x);

``````