【问题标题】:Can't find a way to form this pattern找不到形成这种模式的方法
【发布时间】:2022-12-06 03:14:46
【问题描述】:

我需要编写一个 C 程序来显示以下模式“使用循环”:

1 1 1 1
 2 2 2
  3 3
   4

我想过使用循环,但我不能简单地想出一种在字符之间留出空格的方法,因此很难解决。

如何才能做到这一点?

An image of the question and the required pattern

【问题讨论】:

标签: c


【解决方案1】:

您可以使用嵌套的 for 循环来实现这一点。外层循环将遍历从 1 到 4 的数字,内层循环将遍历相同的次数。在内循环中,您可以打印外循环中的数字,然后添加一个空格字符。这是代码示例:

#include <stdio.h>

int n = 4;

int main()
{
    int i, j;
    for (i = 1; i <= n; i++)
    {
        for (j = 0; j < i; j++)
        {
            printf("%d ", i);
        }
    }
    return 0;
}

这将输出以下内容: 1 1 1 1 2 2 2 3 3 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-26
    • 2013-06-07
    • 2014-10-14
    • 2017-04-06
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多