### Help with for loop (generating multiples)

Right now i am doing an assignment for class using loops (for, while, and do - while). i have to write a for loop to display: 1,2,4,8,16,32,64......8192.
That is what i cant figure out how to do; when i run it it gives me 2,4,6,8,10,12 ect. p.s. i have to use an int that equals zero. for example int k; k = 0; This is what i have. Someone show me the light, thanks.

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <studio.h>

using namespace std;

int _tmain()
{
int k;

k = 0;

for ( k = 0; k < 14; k++ )

{
cout << "\n\t\t\t k = " << ( k*2);
}
return 0;
}

Last edited on
you can use the bit shifting operator <<:

`cout << "\n\t\t\t k = " << ( 1<<k);`
@coder's suggestion is the right way, but probably not the way your teacher would be expecting. Considering you are using cmath, a better loop would be something like this:
 ``123`` ``````for (int k = 0; k < 14; ++k) { cout << "\n\t\t\t k = " << pow(2, k); }``````
@coder777 how does 1<<K work to give the sequence? I have the same assignment, and am not allowed to use pow.
Hi @Rudy Ortiz,
are you allowed
to use nested
loops?

i.e.

 ``` Eyenrique-MacBook-Pro:Desktop Eyenrique\$ ./NestedLoop k=1 k=2 k=4 k=8 k=16 k=32 k=64 k=128 k=256 k=512 k=1024 k=2048 k=4096 k=8192 ```

 ``12345678910111213141516171819202122232425`` ``````//NestedLoop.cpp //## #include using std::cout; using std::endl; int main(){ for(int k=0;k<14;++k){ int temp=2; cout<<" k="; for(int l=1;l
@iamthecure
It works by bit shifting. The left shift operator moves all the bits one along, filling in with zeros. Since the bits values are powers of two, this is how it works. Here is an example:
 ``` 0 0 0 0 0 0 0 1 ; 1 << 0 = 1 0 0 0 0 0 0 1 0 ; 1 << 1 = 2 0 0 0 0 0 1 0 0 ; 1 << 2 = 4 0 0 0 0 1 0 0 0 ; 1 << 3 = 8 ; so on ```
Last edited on
@eyenrique
it works but when I try to organize the code the values change, even though I didn't delete anything . I must have it in this format

for ( n = 0; n < 1; n++ )
{
for ( k = 0; k < 20; k++ )
{
if ( k == 0)
{
cout << " " << ;
}
else if ( k > 0 )
{
cout << ", " << ;
}
}
}

temp=2;
for(int k=0;k<14;++k)
{
cout<<", ";
for(int l=1;l<k;l++)
{
temp*=2;
}
if(k==0)
cout<<1;
else
cout<<temp;
}
@Rudy Ortiz please keep track of
what other users have been
told to you and
use code tags;

 format? sorry but what do you mean? something like this?

 ``` K=1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192. ```

 ``12345678910111213141516171819202122232425262728`` ``````//NestedLoop.cpp //## #include using std::cout; using std::endl; int main(){ cout<<"K="; for(int k=0;k<14;++k){ int temp=2; for(int l=1;l
That helped a bit but I don't get why you put the if and else outside of the inner for... the format I wanted it in is a little like this, either way, thanks for your help!

 ``123456789101112131415161718192021`` ``````int main() { cout<<"K="; for(int k=0;k<14;++k) { int temp=2; for(int l=1;l
Topic archived. No new replies allowed.