how would you print 2 powers series from 0 to 100 (like pow(2,0),pow(2, 1).........pow( 2,100)) with out using mathematical operators
program without using mathamatical operators
Collapse
X
-
One problem you may run into is overflow. In this example, it prints 2^29, but not 2^30. Integers are 32-bit numbers, the most significant is reserved for the sign. If we include 2^30 in the loop, we shift it, 2^31 becomes a negative number, and the loop is still valid. One could always test while(number != (1<<31)). However, if the loop keeps going, since integers are typically 32-bit, (1 << 32) = 0 because the 1 overflows and is lost.
Code:int main() { int number = 1; // assume 32-bit. while(number != (1 << 31)) // logical shift left, bitwise operator { cout << number << endl; number = (number << 1); } system("PAUSE"); return 0; }
Comment
-
You should be careful using signed values in shift operations, particularly the right shift operation on a signed value is either undefined behaviour or implementation defined behaviour.
I normally try to stick to unsigned variables when using shift operators as the results are more consistent cross platform.
If you are using unsigned values you can then use 0 as the end condition of the loop
Code:int main() { unsigned int number; // assume 32-bit. for(number=1; number != 0; number <<= 1) { cout << number << endl; } system("PAUSE"); return 0; }
Comment
Comment