csscrub - 1 month ago 20

C++ Question

So I need some help with this. I want to print out all integers between 2 and 2^20 that are integer powers of 2. I figured out that I need to increase the power by 1 each time but I can't seem to figure out what goes inside the inner for loop. I cannot use the pow() function

`c = 2;`

cout << "\nPROBLEM C" << endl;

for (int powerC = 1; powerC <= 20; powerC++) // powerC is exponent

{

cout << setw(5) << powerC << " ";

counterC++;

for (int x = 1; x <= 20; x++) // where I am having trouble with

{

c = (c*powerC);

cout << setw(5) << c;

} // end inner for loop

if (counterC % 8 == 0)

{

cout << endl;

}

}

cout << "\nNumber of numbers = " << counterC;

Answer

This is much simpler by using the `<<`

operator.

Since 2 is 2^1, you want to print all integers from 2^1 to 2^20 inclusively, or 20 numbers:

```
int c = 2;
for (int i=0; i<20; i++)
{
std::cout << c << std::endl;
c <<= 1;
}
```

Source (Stackoverflow)

Comments