Search code examples
cwhile-loopvariable-initialization

Using loop to print out triangle


The task is to print the following shape using while loop only.

*
**
***
****
*****
******
*******
********
*********

The following code is what I have tried already, but it doesn't work unfortunately:

#include "stdafx.h"//Visual Studio 2015
#include <stdio.h>
#include <stdlib.h>// using for command system("pause") ;
#include <math.h>


    int main()
    {
        int i=0, k=0;
        while (i < 10)
        {
            while (k <= i)
            {
                printf("*");
                k++;
            }
            printf("\n");
            i++;
        }
        system("pause");
        return 0;
    }

I can't debug it by myself. Could anyone debug this one for me?


Solution

  • You must put k=0 inside the loop, to make it go back to zero every loop.

        int main() {
            int i=0, k=0;
            while (i < 10)
            {
                k=0; //<-- HERE
                while (k <= i)
                {
                    printf("*");
                    k++;
                }
                printf("\n");
                i++;
            }
            system("pause");
            return 0;
        }