You can approximate a filled circle in the console by visiting points on a grid and printing a star when a point lies inside the circle. This example combines nested loops with an if statement.
Source code
Save this example as CirclePatternExample.java.
public class CirclePatternExample {
public static void main(String[] args) {
int radius = 5;
for (int y = -radius; y <= radius; y++) {
for (int x = -radius; x <= radius; x++) {
if (x * x + y * y <= radius * radius) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Explanation
Imagine a circle centered at (0, 0). A grid point (x, y) is inside or on its boundary when x * x + y * y <= radius * radius. Comparing squared values avoids calculating a square root.
The outer loop visits the vertical coordinates from -radius to radius. The inner loop visits the horizontal coordinates over the same range. Both endpoints are included, so a radius of five produces an 11-by-11 grid of logical cells.
For each point, the if statement prints a star and a space when the point belongs to the circle. Otherwise, it prints two spaces. Both branches occupy two character positions, preserving column alignment. This spacing often makes the circle look more balanced because terminal characters are usually taller than they are wide.
The result is a coarse approximation of a filled circle, not a smooth outline. Its appearance depends on the radius and terminal font. Keep the radius small for this beginner example: very large values can overflow the int multiplications and produce an impractically large output.
Run the example
With a JDK installed, open a terminal in the directory containing the source file and run:
javac CirclePatternExample.java
java CirclePatternExample
Output
*
* * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * *
*
Display the output in a monospaced font to keep the pattern aligned. Trailing spaces are omitted from the output shown here.
Try it yourself
Try radii of 3 and 8. Compare the edges and observe how a larger grid gives the circle more detail.
