Monday, June 13, 2022

Draw Pyramid in C

 Code: Draw Pyramid in C

100 days of code - day 1

So, I was watching YouTube videos, and this programming exercise came up. All you have to do is to write a program that draws a pyramid, using asterisks for stars. The problem is that although the thumbnail shows a nice pyramid, with proper spacings, the actual code shows a solid pyramid with no spacing whatsoever.


This can't be too difficult to do. I wonder why he didn't just do it right? So, I decided to do the coding real quick.


The first change that I did was to use 'X's and '-'s just because they make better looking pyramids. The second change is that I use command line parameters instead of scanf(). Why would you want to do use scanf just for a simple program? I don't. So, I just do it the convenient way!


This is the result of my first attempt:


X

X-X

X-X-X

X-X-X-X

X-X-X-X-X

X-X-X-X-X-X

X-X-X-X-X-X-X

X-X-X-X-X-X-X-X

X-X-X-X-X-X-X-X-X

X-X-X-X-X-X-X-X-X-X


Looks good, but that's no pyramid. I need to introduce the spacings. This is my second attempt:


 X

  X-X

   X-X-X

    X-X-X-X

     X-X-X-X-X

      X-X-X-X-X-X

       X-X-X-X-X-X-X

        X-X-X-X-X-X-X-X

         X-X-X-X-X-X-X-X-X

          X-X-X-X-X-X-X-X-X-X


Oops. Wrong spacings! And this is my third attempt:


         X

        X-X

       X-X-X

      X-X-X-X

     X-X-X-X-X

    X-X-X-X-X-X

   X-X-X-X-X-X-X

  X-X-X-X-X-X-X-X

 X-X-X-X-X-X-X-X-X

X-X-X-X-X-X-X-X-X-X


And there you have it! A beautiful pyramid! All in all, it takes less than 15 minutes, and that's including looking up how to do command line arguments in C. Yeah, I was rusty, but not too rusty. I condensed the code rather tightly. Hopefully, you can read it just fine!


#!/usr/bin/tcc -run


#include <stdio.h>

#include <stdlib.h>

#include <string.h>


int DrawStars(int Stars,int N) {

  if (N>1) DrawStars(Stars,N-1);

  for (Stars-=N;Stars;Stars--) putchar(' ');

  for (;N;N--) printf("X%c",(N>1)?'-':'\n');

  return 0;

}

 

int main (int argc, char *argv[] ) {

  if   (argc<2) puts("Usage: pyramid N\n");

  else DrawStars(atoi(argv[1]),atoi(argv[1]));

  return 0;

int DrawStars(int Stars,int N) {

  if (N>1) DrawStars(Stars,N-1);

  for (Stars-=N;Stars;Stars--) putchar(' ');

  for (;N;N--) printf("X%c",(N>1)?'-':'\n');

  return 0;

}

}



Note: I use Tiny C Compiler for fast compiling speed.


No comments:

Post a Comment