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?
If you want it to display a running count then you should place
printfinside the for-loop, so it gets executed with each iteration.No. You could actually remove a variable –
y. It is unneeded and you can specify 10 directly in the loop’s conditional: