Printing a character multiple times in a for loop

时间:2017-01-03 00:03:01

标签: c printf

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:

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 个答案:

答案 0 :(得分:2)

使用两个嵌套的for循环:

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

正如本答案中的一条评论中所建议的那样,根据此link中的讨论,如果您只打印一个字符,则putcharprintf更快。因此,如果您可以使用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);
}

答案 1 :(得分:2)

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

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

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

加入完整的程序:

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

输出:

a
aa
aaa
aaaa
aaaaa
aaaaaa
aaaaaaa
aaaaaaaa
aaaaaaaaa
aaaaaaaaaa