C Primer Plus第6版第6章编程练习4

时间:2017-12-24 22:21:45

标签: c loops for-loop

使用以下代码,我能够更改每一行的第一个字母并打印所有字母但不是必需的。任何帮助将不胜感激。提前感谢您的帮助。

//This is a program to print a pattern of the letters
//A to U.  Printing a number of letters
//with the row number. First row/one letter, second row/
//two letters, etc.
//A
//BC
//DEF
//GHIJ
//KLMNO
//PQRSTU

#include <stdio.h>

#define ROWS 6
#define CHARS 21

int main(void)
{
    int row;
    char ch;

    for(row = 0; row < ROWS; row++)
    {
        for(ch = ('A' + row); ch < ('A' + CHARS); ch++)
            printf("%c", ch);
        printf("\n");
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

我们初学者应该互相帮助。你来了。

#include <stdio.h>
#include <string.h>

int main( void )
{
    const char *s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const size_t N = strlen(s);

    while (1)
    {
        printf("Enter a non-negative number (0 - exit): ");

        size_t n;
        if (scanf("%zu", &n) != 1 || n == 0) break;

        size_t k = 0;

        for (size_t i = 0; i < n; i++)
        {
            for (size_t j = 0; j <= i; j++)
            {
                printf("%c", s[ k++ % N ]);
            }
            putchar('\n');
        }
    }

    return 0;
}

程序输出可能看起来像

Enter a non-negative number (0 - exit): 12
A
BC
DEF
GHIJ
KLMNO
PQRSTU
VWXYZAB
CDEFGHIJ
KLMNOPQRS
TUVWXYZABC
DEFGHIJKLMN
OPQRSTUVWXYZ
Enter a non-negative number (0 - exit): 0