NO

Author Topic: While loop  (Read 2040 times)

dankie

  • Guest
While loop
« on: February 20, 2014, 07:29:54 AM »
I want to use while loop to print *  but i have done everything it just print this *  with this code:
                                                    **                                                                    *
                                                    ***                                                                  *
                                                    ****                                                                *
                                                    *****                                                              *
                                                    ******                                                            *

#include<stdio.h>
void main ()
{
 int i;
 i=1;
 while (i<=6)
     {
        printf("\n* ");
        i++;
      }
getchar();
}

Offline lingo

  • Member
  • *
  • Posts: 27
Re: While loop
« Reply #1 on: February 20, 2014, 10:25:19 AM »
You have to loop twice, one loop for lines and one loop for columns (stars).
Try this:

 int i = 1;
 while (i<=6)
     {
        int j = ++i;   // must be one more star than lineno
        while (j--)
          putchar('*'); // is faster than: printf("*");
        putchar('\n');
      }

Note: Your output is only possible with stop condition i<6 not i<=6.
There are more nifty solutions, but that is on your own.

HTH
Lingo

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: While loop
« Reply #2 on: February 20, 2014, 10:34:09 AM »
If this homework is printf exercise it is possible without second loop just with format string ;)
May the source be with you