Draw a circle without floating point arithmetic
Last Updated :
21 Jun, 2022
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 point (x,y), if (x, y) lies inside the circle (or x2+ y2 < r2), then print it, otherwise print space.
Approach:
1. draw the rectangle
2. check if the point lie inside or on the circle using formula x2+ y2 < r2.
3. If it fulfill the condition print the star else print blank space
Algorithm:
Step 1: Take the input of radius
Step 2: Calculate the size of rectangle
Step 3: Draw the rectangle using the nested for loop
Step 4: Start coordinates from left most corner
Step 5: Check if the coordinates lie inside the circle, if yes Print the star else print blank 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
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 arg[])
{
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 ()
if __name__ = = "__main__" :
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;
$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)
{
let N = 2*r+1;
let x, y;
for (let i = 0; i < N; i++)
{
for (let 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)
Space Complexity: O(N2)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...