Saturday 6 June 2015

pyramid in C

This is first time I am writing a post in C language.
This pyramid code is very succinct and I also tried to explain it.

#include<stdio.h>
#include<conio.h>
int main()
{
    int n, i, j, k;
    printf("Please enter the value of n : ");
    scanf("%d",&n);
    for(i=-n ; i<=n ; i++){


        k = i;
        if(k<0){
            k = -k;
        }


        for( j=0 ; j<=n ; j++){
            if(j>k)
                printf(" *");
            else
                printf(" ");
        }


    printf("\n");
    }


return 0;
}

It will prints pyramid shape made up of star(*);
Explanation
Here I am taking input an integer value from user and storing it into variable n.
The number of rows is calculated as 2*n + 1.
If the input is n=3 then total number of rows are 7
         *
        * *
       * * *
      * * * *
       * * *
        * *
         *
Similarly if input value is 6 then number of rows are 13.
Here I started a loop
for(i=-n ; i<=n ; i++)
then you can observe as n=3
then loop start from -3 and rotate upto +3.
then -3 to +3 is 7 times rotation.
Then I am storing value of i variable into another variable namely k and each time checking that if value of k is negative then
I simply made it positive.
if(k<0){
            k = -k;
}


Again a loop always rotate from 0 to n times means in this case it is 4 times each.
for( j=0 ; j<=n ; j++)
And each time checking the value of j is greater than k or not. if true then print " *". Here I added single space before * else pattern will not in proper format and if j is less than k then print only space.
If you observe that first time for n=3, value of k=-3 and we made it k=3(plus 3) and it enters inner loop where value of j start with 0 always and reach upto 3 and loop terminate. for first time if(j>k) condition fails and will executes else part hence one space.
Till false condition else executes will prints space. So first it prints only single star. In second time value of k=-2 hence(k=-k)  it becomes k=2 then this time two times * will print after two times of space.

As value of i increases from -3 to +3 value of k first increase and then decrease because of checking condition less than zero and then make it positive. First more number of spaces and gradually number of space decrease and then increase.
Feel free to ask questions, I will try to post more programs and more interview and basic question as generally ask in interview but we don't know and these all are easy.
Hope this post helpful.
Thanks
md asif aftab
Liferay developer
TranIT mPower Labs Pvt ltd.

No comments:

Post a Comment