Exercise
2D Array: Display Circle
Objective
Develop a Python program that creates a 70x20 two-dimensional array of characters, "draws" a circle with a radius of 8 inside it, and displays it on screen.
Hint: The points in the circle can be obtained using:
x = xCenter + r * cos(angle)
y = yCenter + r * sin(angle)
"sin" and "cos" expect the angle to be measured in radians, instead of degrees. To convert from one unit to the other, remember that 360 degrees = 2π radians (or 180 degrees = π radians): float radians = (angle * Math.PI / 180.0);
You might draw 72 points (as there are 360 degrees in a circle, they would be spaced 5 degrees from each other).
Hint: In Python, cosine is math.cos, sine is math.sin, and π is math.pi.
Example Python Exercise
Show Python Code
import math
# Define the dimensions of the array
rows = 20
cols = 70
# Create a 70x20 two-dimensional array initialized with spaces
array = [[' ' for _ in range(cols)] for _ in range(rows)]
# Circle parameters
radius = 8
x_center = 35 # Horizontal center of the circle
y_center = 10 # Vertical center of the circle
# Draw the circle by calculating points
for angle in range(0, 360): # We use steps of 1 degree for more precision
radians = math.radians(angle) # Convert angle to radians
x = int(x_center + radius * math.cos(radians)) # Calculate x position
y = int(y_center + radius * math.sin(radians)) # Calculate y position
# Make sure the point is within the bounds of the array
if 0 <= x < cols and 0 <= y < rows:
array[y][x] = 'O' # Mark the point with 'O'
# Display the array (circle)
for row in array:
print(''.join(row))
Output
OOOOOOOOOOOOOOOOOOOOOOOO
O O
O O
O O
O O
O O
O O
O O
O O
O O
O O
O O
O O
O O
OOOOOOOOOOOOOOOOOOOOOOOO
Share this Python Exercise