Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Arrays: Case study of large powers of two


1. Arrays: Case study of large powers of two
Let us develop a program to print out the powers of 2 from 0 to 80.

For more information, see the following.

2. Approach
Powers of two:
2 ^ 0 is 1 2 ^ 1 is 2 2 ^ 2 is 4 2 ^ 3 is 8 2 ^ 4 is 16 ...


3. Carry
No carry:
 4 *2 --  8

Carry:
 8 *2 -- 16


4. C program
We can start with a simple C program.

Here is the C code.

What might be wrong with this program? Here is the output of the C code.


5. Problem
Unfortunately, the programming language C overflows after 30 bits, goes to the maximum negative integer, then to zero and then remains at zero. Nothing happens. No run-time error. No compile-time error. Nothing. C just keeps on going.

How can we address this problem?

6. Solution
In such cases, we need a new data representation and an new solution (algorithm and pseudo-code).

7. Arrays
We will represent each decimal digit, 0 to 9 with an array element as follows. Call the array a.

8. Printing
To print the representation, print the digits in the array a from high to low.

To double, mulitple the digit at position 0 by 2, and then, if greater than 10, carry to the next digit/array position.

9. Program
Here is the C code.

Here is the output of the C code.


10. End of page

11. Multiple choice questions for this page