Saturday, 25 July 2015

Star Pattern Program - 1

/*
 C Program to print following pattern.

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

 */

// Include Section
#include<stdio.h>

// Declarations
/* printPattern
 * Description : This function prints the pattern
 * Param         : int- number of lines to be printed.
 * Return        : void
 */
void printPattern(int);

// Definitions
int main()
{
    int i_numberOfLines = 0;
    printf("Enter how many line you want to print : ");
    scanf("%d",&i_numberOfLines);
    
    printPattern(i_numberOfLines);
}

void printPattern(int i_numberOfLines)
{
    // hItr is horizontal iterator which moves one row at a time.
    for(int hIter=0; hIter < i_numberOfLines; hIter++)
    {
        // for loop to print first number of start.
        // On every line number of stars is equal to current line number.
        for(int starIter = 0; starIter <= hIter; starIter ++)
            printf("*");
        
        // Now we have to print spaces.
        //The max number of stars that can be there is 2*number of lines.
        // On every line we print before and after spaces * equal to current line number.
        // So number of spaces to print = (2*number of lines) - (2*current Line)
        for(int spaceIter = 0; spaceIter < ((2*i_numberOfLines - 2*hIter)-1); spaceIter++)
            printf(" ");
        
        // Now print again * equal to current line number
        for(int starIter = 0; starIter <= hIter; starIter ++)
            printf("*");
        
        // Go to next line
        printf("\n");
    }

}

No comments:

Post a Comment