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.
@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:
1 2 3
for (int k = 0; k < 14; ++k) {
cout << "\n\t\t\t k = " << pow(2, k);
}
//NestedLoop.cpp
//##
#include <iostream>
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<k;l++){
temp*=2;
}//end inner for
if(k==0) //power of Zero
cout<<1<<endl;
else
cout<<temp<<endl;
}//end outer for
return 0; //indicates success
}//end of main
@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:
@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 << ", " << ;
}
}
}
I made it like this
//NestedLoop.cpp
//##
#include <iostream>
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<k;l++){
temp*=2;
}//end inner for
if(k==0) //power of Zero
cout<<1<<',';
else
cout<<temp<<((k+1)==14?'.':',');
}//end outer for
cout<<endl;
return 0; //indicates success
}//end of main
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!
int main()
{
cout<<"K=";
for(int k=0;k<14;++k)
{
int temp=2;
for(int l=1;l<k;l++)
{
temp*=2;
}//end inner for
if(k==0) //power of Zero
cout<<1<<',';
else
cout<<temp<<((k+1)==14?'.':',');
}//end outer for
cout<<endl;
return 0; //indicates success
}//end of main