# How to draw a circle using circle equation $x^2+y^2=r^2$?

How to draw a circle using circle equation $x^2+y^2=r^2$?

If I merely have an area of some sort, where I want to draw the circle, say $200 \times 200$, then can I merely loop through this like

for ( i,j in 200 x 200):
j=sqrt(r^2-i^2)


or so.

• Your pseudocode has a variable $j$ in the for loop and a variable $j$ being assigned to? Also taking the square root will give you the positive square root only so either you need to consider also collecting the negative root, or use a different approach such as through trig functions Mar 17, 2017 at 18:35
• That’s a very simple and straightforward approach, but is inefficient and, if what you’re doing is using the computed coordinates to turn pixels on, produces undesirable artifacts. The circle can end up with gaps in some places and blobs of pixels in others. You’ll get much better results with something like Bresenham’s algorithm.
– amd
Mar 18, 2017 at 0:50

So you are on the right track! Try something like the following:

for (x in [0,200]):
fillPixel([x,posY], color)
fillPixel([x,negY], color)


Obviously this is pseudocode, but hopefully it's enough to give you the idea. If you need any other help just comment! :)

N.B: I'm assuming that the circle does actually fit into a 200x200 grid of pixels. You should probably check this before entering the loop!

• What if the thing inside sqrt() becomes negative? When radius < x^2. Mar 18, 2017 at 7:12

This and some others are answered in e.g.:

CS G140 Graduate Computer Graphics Prof. Harriet Fell Spring 2009 Lecture 4 – January 28, 2009 https://www.ccs.neu.edu/home/fell/CSG140/Lectures/CSG140SP2009-4.pdf

Credit to Thomas Russel.

Here's a variation on Thomas Russell's answer that avoids taking the square root of a negative number. By limiting the range of x-values you also limit the y-values to the bounds of the circle as defined by the radius, $$x^2+y^2=radius^2$$:

for x in [-radius, radius]: