dmubu dmubu - 4 days ago 5
C Question

For loop output in C

I am trying to understand the for loop better. I have the following variables:

x = 1

y = 10

I want to increment x and double it ten times with a for loop to have the following output: 1, 2, 4, 8, 16, etc.

This is what I have, but it is not quite doing the trick:

int x = 1;

int y = 10;

for (int i = 0; i < y; i++)
{
x *= 2;

}

printf("%d\n", x);


Do I need another variable to do this?

Answer

If you want it to display a running count then you should place printf inside the for-loop, so it gets executed with each iteration.

Do I need another variable to do this?

No. You could actually remove a variable - y. It is unneeded and you can specify 10 directly in the loop's conditional:

int i = 0;
int x = 1;

for (i = 0; i < 10; i++)
{
    x *= 2;
    printf("%d\n", x);
}
Comments