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;
	
	for(i=1;i<=n*n;i++)
	{
	  if(i<x)
      {
	   printf(" ");
      }
	  else
	  {
	   printf("* ");  // whitespace after *
	  }
      
	  if(i%n==0)
      {
	   x=x+n-1;
	   printf("\n");
      }
	}
	
 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.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.