Given a radius of a circle, draw the circle without using floating point arithmetic. The 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 point (x,y), if (x, y) lies inside the circle (or x^2+ y^2 < r^2), then print it, otherwise print space.
C++
#include <stdio.h>
void drawCircle(int r)
{
int N = 2*r+1;
int x, y;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
x = i-r;
y = j-r;
if (x*x + y*y <= r*r+1 )
printf(".");
else
printf(" ");
printf(" ");
}
printf("\n");
}
}
int main()
{
drawCircle(8);
return 0;
}
Java
import java.io.*;
class GFG {
static void drawCircle(int r)
{
int N = (2*r+1);
int x, y;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
x = i-r;
y = j-r;
if (x*x + y*y <= r*r+1 )
System.out.print(".");
else
System.out.print(" ");
System.out.print(" ");
}
System.out.println();
}
}
public static void main (String[] args) {
drawCircle(8);
}
}
Python3
def drawCircle(r) :
N = 2*r + 1
for i in range(N) :
for j in range(N) :
x = i - r
y = j - r
if (x * x + y * y <= r * r + 1 ) :
print(".", end = "")
else :
print(" ", end = "")
print(" ", end = "")
print()
drawCircle(8)
C#
using System;
public class GFG{
static void drawCircle(int r)
{
int N = (2*r+1);
int x, y;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
x = i-r;
y = j-r;
if (x*x + y*y <= r*r+1 )
Console.Write(".");
else
Console.Write(" ");
Console.Write(" ");
}
Console.WriteLine();
}
}
static public void Main (){
drawCircle(8);
}
}
PHP
<?php
function drawCircle($r)
{
$N = 2 * $r + 1;
$x; $y;
for ($i = 0; $i < $N; $i++)
{
for ($j = 0; $j < $N; $j++)
{
$x = $i - $r;
$y = $j - $r;
if ($x * $x + $y * $y <= $r * $r + 1 )
echo ".";
else
echo " ";
echo " ";
}
echo "\n";
}
}
drawCircle(8);
?>
Javascript
<script>
function drawCircle(r) {
var N = (2 * r + 1);
var x, y;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
x = i - r;
y = j - r;
if (x * x + y * y <= r * r + 1)
document.write(". ");
else
document.write(" ");
document.write(" ");
}
document.write("<br/>");
}
}
drawCircle(8);
</script>
Output . . .
. . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . .
. . .
Time complexity : O(N2 )Auxiliary space : O(1)
Last Updated :
16 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...