tags:

views:

129

answers:

3

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".

+1  A: 

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);
    }
}
advait
If you think it's homework, you might want to not post complete code.
walkytalky
Hey thanks.. :0)
Abraham
@Abraham, Now when someone answers your question, click the check mark next to it to accept it as the answer.
James
+3  A: 

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);
}
Grizzly
You seem to be missing a main method...
Stephen
I assumed that part should be obvious, so no reason to write it
Grizzly
@Stephen: If this is homework, then that's ok. This way he didn't post the whole solution.
klez
+2  A: 

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!

Edward Leno