Search code examples
c++loopsfor-loopnested-loopsshapes

More complex shapes using nested for loops in C++


I have seen some where they do simple examples of X or triangles or diamonds etc. I'd like to know how to make a complex shape like this:

#                 #
 ##             ##
  ###         ###
   ####     ####
    ###########
    ###########
   ####     ####
  ###         ###
 ##             ##
#                 #

I'm extremely new to programming, don't know the basic functions of the code itself.

#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
  int spaces = 4;
  int hashes = 1;
  for(int row=0;row<10;row++)
  {
      for(int spaces=0;spaces<4;spaces++)
      {
          cout<<" ";
      }
      for(int hashes=0;hashes<1;hashes++)
      {
          cout<<"#";
      }
      cout<<endl;

      if(row<5&&row>6)
      {
          spaces--;
          hashes+=2;
      }
      else
      {
          spaces++;
          hashes-=2;
      }

  } 
  return 0;
}

Solution

  • An easy way would be to use a "raytracing" approach; i.e.

    for (int y=0; y<rows; y++) {
        for (int x=0; x<cols; x++) {
            if (func(x, y)) {
                std::cout << "#";
            } else {
                std::cout << " ";
            }
        }
        std::cout << "\n";
    }
    

    for example with rows = cols = 20 and func defined as

    bool func(int x, int y) {
        return (x-10)*(x-10) + (y-10)*(y-10) < 8*8;
    }
    

    you would get a circle