在for循环中多次打印字符

时间:2022-02-01 08:03:24

I want to use printf and for loop to print a character multiple times per line depending on the input; i.e. if the input is 3 i want to print:

我想使用printf和for循环每行多次打印一个字符,具体取决于输入;即如果输入为3我想要打印:

a
aa
aaa

this is the loop, which doesn't work at all.

这是循环,根本不起作用。

for (int i = 0; i < n; i++)
{
    printf("a", i);
    printf("\n");
}

I just don't understand how to print it multiple times on a single line.

我只是不明白如何在一行上多次打印。

2 个解决方案

#1


2  

Use two nested for loops:

使用两个嵌套for循环:

for (int i = 0; i < n; i++)
{
    for(int j=0;j<=i;j++) {
       printf("a");
    }
    printf("\n");
}

As suggested in one of the comments in this answer and as per the discussion in this link, putchar is faster than printf if you are printing only one character. So if you are ok with using putchar instead of printf, try the following code instead:

正如本答案中的一条评论中所建议的那样,根据此链接中的讨论,如果您只打印一个字符,则putchar比printf更快。因此,如果您可以使用putchar而不是printf,请尝试使用以下代码:

char ch = 'a', newLine = '\n';
for (int i = 0; i < n; i++)
{
    for(int j=0;j<=i;j++) {
       putchar(ch);
    }
    putchar(newLine);
}

#2


2  

Unless you need to use a for-loop, I think this would be better for many cases:

除非你需要使用for循环,否则我认为这对许多情况会更好:

printf("%.*s\n", 5, "aaaaaaaaaaaaaaaaaaaaaaaaa"); 

Which will print the first 5 letters of the string (which happens to be more than enough a's)

这将打印字符串的前5个字母(恰好足够了)

Put into a complete program:

投入完整的计划:

int main() {
    int i;
    for(i=0; i < 10; ++i)
        printf("%.*s\n", i+1, "aaaaaaaaaaaaaaaaaaa");
    return 0;
}

Output:

输出:

a
aa
aaa
aaaa
aaaaa
aaaaaa
aaaaaaa
aaaaaaaa
aaaaaaaaa
aaaaaaaaaa

#1


2  

Use two nested for loops:

使用两个嵌套for循环:

for (int i = 0; i < n; i++)
{
    for(int j=0;j<=i;j++) {
       printf("a");
    }
    printf("\n");
}

As suggested in one of the comments in this answer and as per the discussion in this link, putchar is faster than printf if you are printing only one character. So if you are ok with using putchar instead of printf, try the following code instead:

正如本答案中的一条评论中所建议的那样,根据此链接中的讨论,如果您只打印一个字符,则putchar比printf更快。因此,如果您可以使用putchar而不是printf,请尝试使用以下代码:

char ch = 'a', newLine = '\n';
for (int i = 0; i < n; i++)
{
    for(int j=0;j<=i;j++) {
       putchar(ch);
    }
    putchar(newLine);
}

#2


2  

Unless you need to use a for-loop, I think this would be better for many cases:

除非你需要使用for循环,否则我认为这对许多情况会更好:

printf("%.*s\n", 5, "aaaaaaaaaaaaaaaaaaaaaaaaa"); 

Which will print the first 5 letters of the string (which happens to be more than enough a's)

这将打印字符串的前5个字母(恰好足够了)

Put into a complete program:

投入完整的计划:

int main() {
    int i;
    for(i=0; i < 10; ++i)
        printf("%.*s\n", i+1, "aaaaaaaaaaaaaaaaaaa");
    return 0;
}

Output:

输出:

a
aa
aaa
aaaa
aaaaa
aaaaaa
aaaaaaa
aaaaaaaa
aaaaaaaaa
aaaaaaaaaa