Saturday 24 August 2013

Draw An Asterisk (*) Half Pyramid

I have seen this problem around the internet, and maybe in hard copy somewhere. I decided to write my version of it. The idea is to draw a half pyramid of asterisks (I had to google that to find how it's spelled, always thought it was ASTERIX, like the comic book character) depending on the number user enters.

User must enter a number, greater than 0, up to 21, and it will draw the half pyramid. I have tried to explain the logic in the comments as best as I can.

The program isn't as long as it looks, the comments make it longer.

Sample:




Code:

#include <stdio.h>

void main()
{
    int input,counter,loop;

    printf("Enter a number (Greater than 0 up to 21): ");
    scanf("%i",&input);
    counter=input; /*Whatever user enters is also saved in "counter"*/

    if(input<=21 && input >0) /*make sure its a valid input*/
    {
        /*let the lines be drawn until "input", which is used to count the
        number of spaces to be drawn is not 0*/
        while(input>0)
        {
            /*Draw spaces, the first line of spaces is equal to the
            number the user input*/
            for(loop=0;loop<input;loop++)
            {
                printf(" ");
            }
            /*then draw the asterisks. Since at the first line, when we want only one
             "*", counter-input will be zero since counter=input, we specify the
             condition number to be "counter+1 minus input" which is 1, so at least one "*"
             is drawn*/
            for(loop=0;loop<counter+1-input;loop++)
            {
               printf("*");
            }
            /*go to new line after every line of spaces and asterisk/s are done*/
            printf("\n");
            /*reduce the "input" (number of spaces) by 1.*/
            input--;
        }

    }
    else
    {
        printf("Invalid Input");
    }
}

Incidentally, when I was writing this code, one of my compiles in the middle produced this. Reminded me of the background in old space war kind of games. The output varies somewhat depending on the number you input:

#include <stdio.h>

void main()
{
    int input,loop;

    printf("Enter a number (21 or less, greater than 0): ");
    scanf("%i",&input);

    if(input<=21 && input >0)
    {
        while(input>0)
        {
            for(loop=0;loop<input-1;loop++)
            {
                printf(" ");
            }
            printf("*");
        }
    }
}

No comments:

Post a Comment