Pattern Using for loop

半世苍凉 提交于 2020-01-07 09:35:09

问题


I have to print the following pattern using for loop only.

I have written the following code which gives me till the the numbers increment. How can I decrement then in the other half.

#include<stdio.h>

int main(void)
{
    int x,r;
    for(r=1;r<5;r++)
    {
        for(x=3;x>=r;x--)
        {
            printf(" ");
        }

        for(x=1;x<=r;x++)
        {
            printf("%d",x);
        }

        printf("\n");
    }
    return 0;
}

回答1:


just add a second loop from r-1 to 1?

for (x = r - 1; x > 0; x--)
{
    printf("%d",x);
}



回答2:


Added one more loop

    for(x=1;x<=(r-1);x++)
    {
        printf("%d",x);
    }

whole code.

#include<stdio.h>

int main(void)
{
int x,r;
for(r=1;r<5;r++)
{
    for(x=3;x>=r;x--)
    {
        printf(" ");
    }

    for(x=1;x<=r;x++)
    {
        printf("%d",x);
    }

    for(x=1;x<=(r-1);x++)
    {
        printf("%d",x);
    }


    printf("\n");
}
return 0;}

code running at http://codepad.org/oAdx20ai



来源:https://stackoverflow.com/questions/26277252/pattern-using-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!