Programming with Passion

Make the best out of everything.

Thursday 5 September 2019

Diamond Patter using only one while loop | Yamaha Interview Question

Diamond Patter using only one while loop

This problem was asked in Yamaha Interview. Please consider doing it yourself before looking at the answer.

#include<stdio.h>
int main(){
    int line = 1, p = 25, sp=2, st=1;
int spptr = 0, stptr = 0;
    while(p--){
        if(spptr < sp){
            printf("  ");
            spptr++;
        }
        else if (stptr < st){
            printf("* ");
            stptr++;
        }
        else{
            printf("\n");
            line++;
            sp = 3 - line;
            if (sp<0)
                sp = -sp;
            st = (line*2)-1;
            if(line>3){
                st = st%4;
            } 
            spptr = 0;
            stptr = 0;
        }
    }
}

Here is I have taken a variable p = 25 which
is indicating the grid size in which the
diamond is printed, a line number initially 1,
sp(spaces to print) initially 2,
st(stars to print), spptr(space pointer
currently at 0),stptr(star pointer
currently at 0).So, now inside the while loop
it checks if the spptr is less than sp or not
if it is then it prints spaces,else it checks
if stptr is less than st or not if yes than it
prints the star, else it increments the line
number,then changes the spaces to print
according to the line number, changes the
stars to print according to line number,
and re-initialises the spptr & stptrto 0.

No comments:

Post a Comment