Program to print 2D shapes in C++


In this tutorial, we will be discussing a program to print out 2D shapes.

For this we will be provided with the various parameters required to make a shape such as radius, side length and side breadth, etc. And our task is to print a shape accordingly with no thickness.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_circle(int radius){
   for (int i = 0; i <= 2 * radius; i++){
      for (int j = 0; j <= 2 * radius; j++){
         double distance = sqrt((double)(i - radius) * (i -
         radius) + (j - radius) * (j - radius));
         if (distance > radius - 0.5 &&
            distance < radius + 0.5)
            printf("*");
         else
         printf(" ");
      }
      printf("\n");
   }
}
void print_rectangle(int l, int b){
   int i, j;
   for (i = 1; i <= l; i++){
      for (j = 1; j <= b; j++)
         if (i == 1 || i == l || j == 1 || j == b)
            printf("*");
         else
            printf(" ");
         printf("\n");
   }
}
void print_triangle(int side){
   int i, j;
   for (i = 1; i <= side; i++){
      for (j = i; j < side; j++)
         printf(" ");
      for (j = 1; j <= (2 * i - 1); j++){
         if (i == side || j == 1 || j == (2 * i - 1))
            printf("*");
         else
            printf(" ");
      }
      printf("\n");
   }
}
void print_hexagon(int length){
   int l, j, i, k;
   for (i = 1, k = length, l = 2 * length - 1; i < length;
   i++, k--, l++){
      for (j = 0; j < 3 * length; j++)
         if (j >= k && j <= l)
            printf("*");
         else
            printf(" ");
            printf("\n");
      }
      for (i = 0, k = 1, l = 3 * length - 2; i < length; i++,
      k++, l--){
         for (j = 0; j < 3 * length; j++)
         if (j >= k && j <= l)
            printf("*");
         else
         printf(" ");
         printf("\n");
      }
   }
   void calc_pattern(int choice){
      int radius, length, breadth, side;
      switch (choice){
         case 1:
            radius = 4;
            print_circle(radius);
            break;
         case 2:
            length = 3, breadth = 8;
            print_rectangle(length, breadth);
            break;
         case 3:
            side = 6;
            print_triangle(side);
            break;
         case 4:
            side = 4;
            print_hexagon(side);
            break;
         default:
            printf("Invalid choice\n");
   }
}
int main(){
   int choice = 1;
   calc_pattern(choice);
   return 0;
}

Output

      *****
     **  **
    **   **
  *        *
 *          *
 *          *
  **      **
   **    **
    *****

Updated on: 19-Dec-2019

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements