### The Plan

- Obtain an angle from the user.
- Convert to radians.
- Create a canvas of a blank 2D char array.
- Run a loop over each element to check whether the point lies on (y = 0, x > 0) or (y - x tanθ). The tolerance is ±0.75 so that we can have as many points, for better looks.
- Finally print the array.
- The math function from the C- library is tan (double), which requires a double value. So we have used double throughout, but it may not be optimal.

### Pre-requisites

We are going to use a canvas of 2D array to implement this program. For a better understanding please refer the article(s):

### The Source Code

You can copy paste this directly into your cpp file and compile

#include <iostream> #include <cstdio> #include <cmath> using namespace std; int main() { const double PI = 3.14; double angle; cout << "Angle in degree?:"; cin >> angle; // convert to radians double radians = (PI * angle)/180.0; // prepare the canvas const int DIMEN = 24; // fill the canvas with NULLs char canvas [DIMEN][DIMEN] = {{0}}; for(int row = 0; row < DIMEN; row++) { for(int col = 0; col < DIMEN; col++) { // origin is at the center, // so obtain the x and y coord- //-inates of each element with // respect to the middle double x = col - DIMEN/2; double y = DIMEN/2 - row; if(y < 0) { continue; } // equation to be plotted: y = mx // y = x tanθ double eqn = y - x * tan(radians); // select all those points that // satisfy the above line, // tolerance of ±0.75 so that // more points can be shown // and also select all // those as lie on the "horizontal // arm" of the angle towards // the +x side if( (abs(eqn) <= 0.75) || ((0 == y) && (x >= 0) ) ) { canvas[row][col] = '*'; } } } // print for(int row = 0; row < DIMEN; row++) { for(int col = 0; col < DIMEN; col++) { // THERE IS A SPACE AFTER %c // ... done for nicer looks printf("%c ", canvas[row][col]); } cout << endl; } printf("Angle: %0.2f degree\n",angle); return 0; }

### The Output

The output may be a bit distorted.

Angle in degree?:45 * * * * * * * * * * * * * * * * * * * * * * * Angle drawn: 45.00 degree

### More Posts

### Similar Posts

This Blog Post/Article "C/C++ Program to draw an angle with stars" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.