dmubu
dmubu

Reputation: 1133

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?

Upvotes: 1

Views: 5995

Answers (8)

Akhilesh Sinha
Akhilesh Sinha

Reputation: 881

if you know that you have to increment it for only 10 times. Then why to use extra variable ? use this....

for(x = 1; x<=1024; x*=2)
    {
    printf("%d ",x);
    }

Upvotes: 0

Zishan
Zishan

Reputation: 623

your answer contradict with your source code,if you want to print 1,2,4,8,16,... you will get first element 2, because you are multiplying every iteration 2 times than its value, you do not need to use extra variable,moreover you can remove y,put directly 10 and use printf statement inside {}.hope it will help

Upvotes: 0

Michel
Michel

Reputation: 544

int x = 1;
int y = 10;
int i = 0;

int main() {
  for(i = 0; i < y; i++) {
    x *= 2;
    printf("%d\n", x);
  }
  return 0;
}

Output:

2
4
8
16
32
64
128
256
512
1024

Upvotes: 0

Marlon
Marlon

Reputation: 20312

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

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124642

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.

Your example contradicts your requirement. Incrementing an integer and doubling it would look produce 1, 4, 6, 8, 10, 12, 14...n. They are simply multiples of two. Your example produces powers of two, i.e.,

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

Upvotes: 1

MrDatabase
MrDatabase

Reputation: 44455

Think you want the printf statement inside the for loop... between the { and the }.

Upvotes: 0

Dyno Fu
Dyno Fu

Reputation: 9044

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

Upvotes: 0

Mysticial
Mysticial

Reputation: 471229

It looks fine to me. If you want it to print at each iteration, you need to move the printf into the loop.

Also, your code will only work in C99 or with GCC's default extensions since you have int i inside the for loop.

Upvotes: 4

Related Questions