开发者

For C Language: How to do you Display a growing Series of Numbers using the For Loop per line?

How do you make C use the For Loop Statement and generate this:

1

12

123

1234

1234开发者_如何学C5

123456

1234567

12345678

I know this requires that the value "1" to be continuously be multiplied with "10" and added with "1".


since the sequence ended with 12345678, this loop only goes to 8, if wanted otherwise, the constraints should be changed approriately

int result = 0;
int i;
for(i = 1; i < 9; i++)
{
    result = result * 10 + i;
    printf("%d\n", result);
}


As an alternative to using integers to contain the result, you might want to use a character buffer, appending the loop index. If you need 10+, you could mod the index and continue with a repeating sequence for the desired length.

No code given, as it is homework!


Is this homework?

Use a variable to keep track of the current number. On the next iteration, multiply by ten and add the next number in the series.

#include "stdio.h"
int main() {
    int current = 0;
    int i;
    for (i = 1; i < 10; i++) {
        current = current * 10 + i;
        printf("%d\n", current);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜