How to create a pyramid pattern using only ONE loop?

To get such a type of pattern, we usually follow either space loop logic (3 loops) or if-else logic (2 loops). But, if someone asked you to get this pyramid pattern using a single loop ???

It is possible, we can code and get the desired pyramid pattern using only a single loop.

#include <stdio.h>
int main()
	int i,n=5;
	int x=n;
	   printf(" ");
	   printf("* ");  // whitespace after *
 return 0;

Get the code for this pattern and other patterns in C, C++, Java, Python, etc. here:

To get this pattern printed with a single loop, we will run it (n*n) times, as we cannot use two separate loops for rows and columns.

We may use if-else controlled by the variable ‘x’, to check whether to print whitespace ‘ ‘ or an asterisk ‘*’. The value of variable ‘x’ is updated on every run when the condition (i%n==0) is true.

Tutorial (YouTube)

YouTube tutorial

Related Post

Leave a Reply

Your email address will not be published.