14th tutorial for right angle triangle patterns



Till now we have seen almost one kind of patterns in which we have printed numbers and alphabets in same manner, now we are going to print numbers only but using some kind of computations.




This is what something new for you all, as we have just printed the stuffs till now. To perform this pattern look like:




As shown in figure, we have to print 10 one after another in right angle triangle. So in program we can do it as follows:




The logic used to print 1 and 0 is that by dividing the number i.e. j with 2 and printing its remainder we get 1 0 1 0 as output. You may wonder how, let me explain you that also.

Here we have initialize j with 1 and every time the loop executes j is incremented. So for j=1 the answer of (j%2) will be 1 as its remainder is 1. Now j will be incremented to 2, so (j%2) will give you 0, thus it will give 1 0 1 0 till user have entered the number of lines. This logic is for finding 1 0 1 0 series.

Now this series is to be printed in right angle triangle pattern. For that the for loop will remains same as we have earlier used. The i loop is for incrementing new line and j loop is decremented as we want 1 in first line and 10101 in the last line. For loop is written as follows:
for(i=1;i<=k;i++)

for(j=i;j>=1;j--)

Thus we learn interesting logic behind this program which very simple to implement.


{ 0 comments ... read them below or add one }

Post a Comment