Given a radius of a circle, draw the circle without using floating point arithmetic.

Following program uses a simple concept. Let the radius of the circle be r. Consider a square of size (2r+1)*(2r+1) around the circle to be drawn. Now walk through every point inside the square. For every every point (x,y), if (x, y) lies inside the circle (or x^2+ y^2 < r^2), then print it, otherwise print space.

[pastacode lang=”c” manual=”%23include%20%3Cstdio.h%3E%0A%0Avoid%20drawCircle(int%20r)%0A%7B%0A%2F%2F%20Consider%20a%20rectangle%20of%20size%20N*N%0Aint%20N%20%3D%202*r%2B1%3B%0A%0Aint%20x%2C%20y%3B%20%2F%2F%20Coordinates%20inside%20the%20rectangle%0A%0A%2F%2F%20Draw%20a%20square%20of%20size%20N*N.%0Afor%20(int%20i%20%3D%200%3B%20i%20%3C%20N%3B%20i%2B%2B)%0A%7B%0Afor%20(int%20j%20%3D%200%3B%20j%20%3C%20N%3B%20j%2B%2B)%0A%7B%0A%2F%2F%20Start%20from%20the%20left%20most%20corner%20point%0Ax%20%3D%20i-r%3B%0Ay%20%3D%20j-r%3B%0A%0A%2F%2F%20If%20this%20point%20is%20inside%20the%20circle%2C%20print%20it%0Aif%20(x*x%20%2B%20y*y%20%3C%3D%20r*r%2B1%20)%0Aprintf(%22.%22)%3B%0Aelse%20%2F%2F%20If%20outside%20the%20circle%2C%20print%20space%0Aprintf(%22%20%22)%3B%0Aprintf(%22%20%22)%3B%0A%7D%0Aprintf(%22%5Cn%22)%3B%0A%7D%0A%7D%0A%0A%2F%2F%20Driver%20Program%20to%20test%20above%20function%0Aint%20main()%0A%7B%0AdrawCircle(8)%3B%0Areturn%200%3B%0A%7D” message=”C Program” highlight=”” provider=”manual”/]

Output:

Circle
[ad type=”banner”]

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,