Java Program to Print Circle Pattern
In this tutorial, we are going to print circle pattern. Make a circle out of stars using a positive number n, which is the circle's radius.
Example:
Input: n = 5
Output:
***** ** ** ** ** ** ** ** ** *****
Explanation: A circle with a diameter of five units is created by this pattern.
The circular shape is formed by the arrangement of the asterisks and surrounding spaces.
Asterisks around the circle's centre are positioned and spaced differently to preserve symmetry.
Approach: Using the distance formula
ALGORITHM:
Step 1: Determine the size of the circle by taking an integer as input.
Step 2: Cycle through each point on a grid with dimensions using two nested loops.
Step 3: The distance formula can be used to determine the distance between the present point and the circle's centre.
Step 4: Determine the distance in relation to the radius.
Step 5: Points outside the circle are represented by a space that is printed.
Step 6: Print the circle pattern after setting the radius.
Filename: PrintCirclePattern.java
public class PrintCirclePattern { // print the pattern of circle static void patternPrinting(int r) { double distance; for (int q = 0; q <= 2 * r; q++) { for (int s = 0; s <= 2 * r; s++) { distance = Math.sqrt((q - r) * (q - r) + (s - r) * (s - r)); // distance has to be in the range of (radius - 0.5) // and (radius + 0.5) to print asterisks (*) if (distance > r - 0.5 && distance < r + 0.5) System.out.print("*"); else System.out.print(" "); } System.out.print(" "); } } public static void main(String[] args) { // radius of the circle int r = 5; patternPrinting(r); } }
Output:
***** * * * * * * * * * * * * * * * * * * *****
Complexity analysis:
Time complexity: The program has the time complexity of O(radius* radius)
Space complexity: The program has the space complexity of O(1).