简体   繁体   中英

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
12345
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);
}

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);
    }
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM