Exercise
Two Dimensional Array 2: Circunference On Screen
Objective
Write a C# program that declares creates a 70x20 two-dimensional array of characters, "draws" a circumference or radius 8 inside it, and displays it on screen.
Hint: the points in the circumference 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, you must remember that 360 degrees = 2 PI radians (or 180 degrees = PI radians): float radians = (angle * Math.PI / 180.0);
You might draw 72 points (as there are 360 degrees in a circumference, they would be spaced 5 degreees from each other)
Hint: in C#, cosine is Math.Cos, sine is Math.Sin and PI is Math.PI
Write Your C# Exercise
C# Exercise Example
using System; // Importing the System namespace for accessing Console, Math, and other functionalities
class Program
{
static void Main()
{
// Declare a 70x20 two-dimensional array to represent the screen buffer
char[,] screenBuffer = new char[20, 70]; // 20 rows and 70 columns
// Fill the screen buffer with empty spaces initially
for (int row = 0; row < screenBuffer.GetLength(0); row++)
{
for (int col = 0; col < screenBuffer.GetLength(1); col++)
{
screenBuffer[row, col] = ' '; // Filling the array with empty spaces
}
}
// Define the center of the circle and the radius
int xCenter = 35; // Center column (x-coordinate) of the screen buffer
int yCenter = 10; // Center row (y-coordinate) of the screen buffer
int radius = 8; // Radius of the circle
// Draw the points of the circle using the parametric equations for a circle
for (int angle = 0; angle < 360; angle += 5) // Loop through 360 degrees with 5 degree increments
{
// Convert angle to radians
double radians = (angle * Math.PI / 180.0);
// Calculate the x and y coordinates of the point on the circumference
int x = (int)(xCenter + radius * Math.Cos(radians)); // Calculate x-coordinate
int y = (int)(yCenter + radius * Math.Sin(radians)); // Calculate y-coordinate
// Place the point 'O' in the calculated position on the screen buffer
if (x >= 0 && x < screenBuffer.GetLength(1) && y >= 0 && y < screenBuffer.GetLength(0))
{
screenBuffer[y, x] = 'O'; // Mark the point on the screen buffer
}
}
// Display the content of the screen buffer (the array)
for (int row = 0; row < screenBuffer.GetLength(0); row++)
{
for (int col = 0; col < screenBuffer.GetLength(1); col++)
{
Console.Write(screenBuffer[row, col]); // Print each character in the array
}
Console.WriteLine(); // Move to the next line after each row is printed
}
}
}