0

I want to print the following sequence.
__*
_***
*****
_***
__*


Here _ denotes space.

I have written half program to print upto 5 stars and not able to get for down.

#include <stdio.h>

void main()
{

for(int i=1;i<=3;i++)
{
for(int j=1;j<=3-i;j++)
printf(" ");
for(int k=1;k<=(2*i-1);k++)
printf("*");
printf("\n");
}

}

I can print below 5 stars by using two more for loops but I don't want to do it as it will include many loops which is not presentable.

3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by L7Sqr
0

Here's a hint, I'll let you figure out the last loop.

#include <stdio.h>

int main()/*main returns an int*/
{
  int i, j, k;
  
  for( i = 1; i <= 3; i++)
  {
    for( j = 1; j <= 3 - i; j++)
      printf(" ");
      for( k = 1; k <= (2 * i - 1); k++)
	printf("*");
    printf("\n");
  }
  for( i = 1; i <= 2; i++)
  {
    for( j = 1; j <= i; j++)
      printf("-");
      /*you can figure out the last loop*/
    printf("\n");
  }
  return 0;/*main returns an int*/
}
0

While there are iterative approaches to this type of problem, the solutions lend themselves to recursion. Consider the following pseudocode

fun show_stars (current, increment, max)
   return if (current > max) 
   print_spaces (max - current)
   print_stars (current)
   show_stars (current + incrememt, increment, max) # Recursive call
   print_spaces (max - current)
   print_stars (current)

And you would invoke that like:

show_stars (1, 2, 5)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.