Filling a circle on a Board object

 

One of the fun aspects of programming is that it allows us to take old mathematical knowledge and use their computational elements to bring them to life.  Take for instance the equation of a circle:

           

           

 

If we are to plot a circle on an x-y coordinate system (in our case, a Board object), we would need to ‘fill’ all the cells or coordinates that satisfy this equation.  This means that for a circle with a radius of 10, we would color all the cells for which  holds true.  With an if statement, this is surprisingly easy: go through the board cell by cell, and fill the cells for which the mathematical relationship or the condition is true. 

 

What if we wanted to fill the whole circle, and not just draw the outline of a circle?  Again, not that difficult.  The points inside the circle are those for which the inequality  is true (you can guess how to fill the outside of a circle).  We’re not quite done, though.  The equation we have assumes that the circle is centered at (0,0).  In order to move it to the center of the coordinate system of our Board object, we need to subtract x and y coordinates of the center cell.  To draw a circle with radius 30 in the center of a 100x100 Board object, we would need to change the inequality to:

 

           

 

 

We’re ready for our program. 

 

 

import java.awt.Color;

 

public class FillCircle

{

  public static void main(String[] args)

  {

    int cols = 100, rows = 100;

    Board b = new Board(cols,rows);

   

    for (int y = 0; y < rows; y++)

    {

      for (int x = 0; x < cols; x++)

      {

        if ((y – rows/2)*(y - rows/2)+(x – cols/2)*(x – cols/2) <= 900)

          b.fillCell(x, y, Color.green);

      }

    }

  }

}