954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ Math Challenge(Circle in Asterisks)

Well we all have seen the common questions on creating squares and hollow squares out of asterisks in C++, but how about creating a program that prints out a circle in asterisks? Obviously this would look like an oval due to line adjustment, but it would be quite interesting to see if someone could do it.

I have tried myself and I must admit it is a fairly decent challenge.

If you figure it out, post your code here!

Hint: r^2 = x^2 + y^2

restrictment
Posting Whiz in Training
228 posts since Oct 2009
Reputation Points: 102
Solved Threads: 17
 

Piece of cake, kinda crude approximation tho.

#include <iostream>
#include <cmath>
#include <string>
#include <vector>

using namespace std;

const unsigned CANVAS_WIDTH = 20;
const unsigned CANVAS_HEIGHT = 20;
const unsigned char BACKGROUND_FILL = '#';
const char POINT = '*';
const float PI = 3.14159265f;
const float DEGREE_TO_RADIAN_FACTOR = 0.0174532925f;

typedef std::vector<std::string> Canvas;

float toRadians(const float deg){ return deg * DEGREE_TO_RADIAN_FACTOR;}
int roundPositive(const float n){ return int(n + 0.5f); }

Canvas createDefaultCanvas(){
 return Canvas(CANVAS_HEIGHT, std::string(CANVAS_WIDTH,BACKGROUND_FILL) );
}
void fillCircle(Canvas& canvas,const unsigned radius){

 const int canvasMidX = canvas[0].size() / 2; //assume same width for each height
 const int canvasMidY = canvas.size() / 2;
 const int STEP_SIZE = 1;
 for(int deg = 0; deg < 360; deg += STEP_SIZE){
     float radian = toRadians(deg);
     float x = cos(radian) * radius + canvasMidX;
     float y = sin(radian) * radius + canvasMidY;
     x = roundPositive(x);
     y = roundPositive(y);
     canvas[y][x] = POINT;
 }
}

void showCanvas(const Canvas& canvas){
 for(unsigned height = 0; height < canvas.size(); ++height){
  for(unsigned width = 0; width < canvas[height].size(); ++width){
   cout << canvas[height][width];
  }
  cout << endl;
 }
}
int main(){
 using namespace std;

 const unsigned RADIUS = 5;
 Canvas canvas = createDefaultCanvas();

 fillCircle(canvas,RADIUS);

 showCanvas(canvas);

 return 0;
}

example output :

####################
####################
####################
####################
####################
########*****#######
######***###***#####
######*#######*#####
#####**#######**####
#####*#########*####
#####*#########*####
#####*#########*####
#####**#######**####
######*#######*#####
######***###***#####
########*****#######
####################
####################
####################
####################
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

Would look more like a circle if the characters were square and line spacing was the same as character spacing.

#include <iostream>
using namespace std;

int main()
{
	double r = 1.2;

	for( double y = -r-0.1; y <= r+0.2; y += 0.1 )
	{
		for( double x = -r-0.1; x <= r+0.2; x += 0.1 )
		{
			if( (x*x + y*y <= (r*r)*1.1) && (x*x + y*y >= (r*r)*0.9) )
				cout << "*";
			else
				cout << "#";
		}
		cout << endl;
	}
	return 0;
}


Output:

###########################
##########*******##########
#######****#####****#######
######**###########**######
#####**#############**#####
####*#################*####
###**#################**###
##**###################**##
##*#####################*##
##*#####################*##
#**#####################**#
#*#######################*#
#*#######################*#
#*#######################*#
#*#######################*#
#*#######################*#
#**#####################**#
##*#####################*##
##*#####################*##
##**###################**##
###**#################**###
####*#################*####
#####**#############**#####
######**###########**######
#######****#####****#######
##########*******##########
###########################
sfuo
Practically a Master Poster
656 posts since Jul 2009
Reputation Points: 164
Solved Threads: 99
 

Very Cool. Now how about a solid circle? =o

restrictment
Posting Whiz in Training
228 posts since Oct 2009
Reputation Points: 102
Solved Threads: 17
 

C'mon, lets address the aspect ratio.

#include <iostream>

int foo(double a, double b, double x, double y) {
    return ((x*x)/(a*a) + (y*y)/(b*b));
}

int main () {
    int b = 4, a = 10;
    const int min = -15, max = 15;
    int x = min, y = min;
    for (; y < max; ++y) {
        for (x = min; x < max; ++x)
            std::cout << (foo(a,b,x,y) == 1 ? '*' : '#');
        std::cout << std::endl;
    }
    return 0;
}
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
#########*************########
######*******************#####
####*****#############*****###
##*****#################*****#
##****###################****#
#*****###################*****
##****###################****#
##*****#################*****#
####*****#############*****###
######*******************#####
#########*************########
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
L7Sqr
Practically a Master Poster
657 posts since Feb 2011
Reputation Points: 201
Solved Threads: 124
 
#include <iostream>
#include <cmath>
#include <sstream>

int pth (int x,int y)  {
	return std::sqrt (std::pow(x,2)+std::pow(y,2));
 }

int main (int argc,char* argv[])  {
	int c=0;
	int r;
	std::istringstream i(argv[1]);
        i >> r;
	
	const int width=r;
	const int length=r*1.5;

	for (int y=width;y >= -width;y-=2)  {
		for (int x=-length;x <= length;x++)  {
			if ((int) pth(x,y)==r) std::cout << "*";
			else std::cout << " ";
		 }
		std::cout << "\n";
	 }
	std::cin.get();
 }
                                      ***************                                      
                                ***                     ***                                
                             **                             **                             
                          **                                   **                          
                        *                                         *                        
                      *                                             *                      
                    **                                               **                    
                   *                                                   *                   
                  *                                                     *                  
                 *                                                       *                 
                *                                                         *                
                *                                                         *                
               *                                                           *               
               *                                                           *               
               *                                                           *               
               *                                                           *               
               *                                                           *               
               *                                                           *               
               *                                                           *               
                *                                                         *                
                *                                                         *                
                 *                                                       *                 
                  *                                                     *                  
                   *                                                   *                   
                    **                                               **                    
                      *                                             *                      
                        *                                         *                        
                          **                                   **                          
                             **                             **                             
                                ***                     ***                                
                                      ***************
caut_baia
Posting Whiz
387 posts since Apr 2010
Reputation Points: 25
Solved Threads: 49
 
#include <iostream>
#include <cmath>
#include <sstream>

int pth (int x,int y)  {
	return std::sqrt (std::pow(x,2)+std::pow(y,2));
 }

int main (int argc,char* argv[1])  {
	if (argv[1]==NULL) argv[1]="30";
	int c=0;
	int r;
	std::istringstream i(argv[1]);
        i >> r;
	
	const int width=r;
	const int length=r*1.5;
	bool in=1;

	for (int y=width;y >= -width;y-=2)  {
		for (int x=-length;x <= length;x++)  {
			if (pth(x,y)==r && pth(x-1,y)!=r)  {
				std::cout << "*";
				in^=1; 
			 }
			else if (in) std::cout << "*";
			else std::cout << " ";
		 }
		std::cout << "\n";
	 }
	std::cin.get();
 }
***************************************                                                    
                                *************************                                  
                             ********************************                              
                          **************************************                           
                        *******************************************                        
                      ***********************************************                      
                    **************************************************                     
                   *****************************************************                   
                  *******************************************************                  
                 *********************************************************                 
                ***********************************************************                
                ***********************************************************                
               *************************************************************               
               *************************************************************               
               *************************************************************               
               *************************************************************               
               *************************************************************               
               *************************************************************               
               *************************************************************               
                ***********************************************************                
                ***********************************************************                
                 *********************************************************                 
                  *******************************************************                  
                   *****************************************************                   
                    **************************************************                     
                      ***********************************************                      
                        *******************************************                        
                          **************************************                           
                             ********************************                              
                                *************************                                  
                                      *****************************************************
caut_baia
Posting Whiz
387 posts since Apr 2010
Reputation Points: 25
Solved Threads: 49
 

Using midpoint circle algorithm:

#include <stack>
#include <string>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

typedef std::vector<std::string> Canvas;

void setPixel(int x, int y, Canvas& canvas){
	canvas[y][x] = '*';
}
//midpoint circle algorithm -- src via wiki
void renderCircle(const int x0, const int y0, const int radius,Canvas& c){
  int f = 1 - radius;
  int ddF_x = 1;
  int ddF_y = -2 * radius;
  int x = 0;
  int y = radius;
 
  setPixel(x0, y0 + radius, c);
  setPixel(x0, y0 - radius, c);
  setPixel(x0 + radius, y0, c);
  setPixel(x0 - radius, y0, c);
 
  while(x < y)
  {
    // ddF_x == 2 * x + 1;
    // ddF_y == -2 * y;
    // f == x*x + y*y - radius*radius + 2*x - y + 1;
    if(f >= 0) 
    {
      y--;
      ddF_y += 2;
      f += ddF_y;
    }
    x++;
    ddF_x += 2;
    f += ddF_x;    
    setPixel(x0 + x, y0 + y, c);
    setPixel(x0 - x, y0 + y, c);
    setPixel(x0 + x, y0 - y, c);
    setPixel(x0 - x, y0 - y, c);
    setPixel(x0 + y, y0 + x, c);
    setPixel(x0 - y, y0 + x, c);
    setPixel(x0 + y, y0 - x, c);
    setPixel(x0 - y, y0 - x, c);
  }
}

void show(const Canvas& c){
	struct _show{
		void operator()(const std::string& str){ cout << str << endl; }
	};
	std::for_each(c.begin(),c.end(),_show());
}
int main(){
	const unsigned RADIUS = 10;
	Canvas c = Canvas(50,string(50,' ') );
	renderCircle(25,25,RADIUS,c);
	show(c);
 return 0;
}
*******
                    **       **
                   *           *
                  *             *
                 *               *
                *                 *
                *                 *
               *                   *
               *                   *
               *                   *
               *                   *
               *                   *
               *                   *
               *                   *
                *                 *
                *                 *
                 *               *
                  *             *
                   *           *
                    **       **
                      *******
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

C'mon, lets address the aspect ratio.

#include <iostream>

int foo(double a, double b, double x, double y) {
    return ((x*x)/(a*a) + (y*y)/(b*b));
}

int main () {
    int b = 4, a = 10;
    const int min = -15, max = 15;
    int x = min, y = min;
    for (; y < max; ++y) {
        for (x = min; x < max; ++x)
            std::cout << (foo(a,b,x,y) == 1 ? '*' : '#');
        std::cout << std::endl;
    }
    return 0;
}
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
#########*************########
######*******************#####
####*****#############*****###
##*****#################*****#
##****###################****#
#*****###################*****
##****###################****#
##*****#################*****#
####*****#############*****###
######*******************#####
#########*************########
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################


@L7Sqr: Cool program man, could be please also comment the code so that beginners like me would know what is happening in every line of code, thanks in advance!

hasnain2009
Newbie Poster
1 post since Sep 2011
Reputation Points: 10
Solved Threads: 0
 

You can read about the equation here - that is what the foo function does. The rest of the program just loops over the bounds of our drawing area evaluating that formula and drawing a * when it evaluates to 1.

L7Sqr
Practically a Master Poster
657 posts since Feb 2011
Reputation Points: 201
Solved Threads: 124
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: