COS 126: Spring 1997Table of
Powers |
Due: Wed. 2/19, 11:59pm |

In this assignment, you'll write three versions of a program to print the
powers of a given integer. The display below shows the input and output of the
program for three different integers: 3, 15, and 126.

type identifies input.*Slanted*

% |
% |
% |

The purpose of this assignment is to familiarize yourself with the **while**
and **for** loop statements in C and with the **if-else**
selection statement, and to learn a bit about how the computer represents
integers.

As illustrated above, your program should prompt for a number ("```
Enter
a number:
```

"), read an integer *x* (e.g., 3), and print a
table of the powers of *x*. For this assignment, you can assume that
*x* > 1.

Write and submit three versions of your program:

`usewhile.c`

: A version that uses only**while**loops (and**if-else**statements, if you need them).`usefor.c`

: A version that uses only**for**loops.`usebreak.c`

: A version that uses either**while**or**for**loops and the**break**statement.

The break statement terminates the loop in which it appears prematurely. For example,

sum = 0; for (i = 1; i <= n; i++) { sum = sum + i; if (sum > 100) break; }

computes the sum of the first `n`

integers, but quits early if
that sum exceeds 100. Break statements should be used sparingly, because they
can lead to unstructured code. But there a few loop idioms that are more clear
with break statements, as you'll see in this assignment. For more information
about break statements, see Dietel and Dietel, Sec. 4.9.

One question remains: How many powers should your program print? As the
display above suggests, the answer is "As many as you can compute".
You'll compute *x ^{i}* by multiplying

`*`

How can you test if an *x ^{i}* is too big? Given

`a`

and `b`

, you can't just write "`if (a*b <= 2147483647)`

..." because you can't compute `a*b`

. You can avoid computing
`a*b`

by rearranging this conditional and testing if ```
a <=
2147483647/b
```

for any positive value of `b`

. There are other
approaches to this probem that also avoid computing `a*b`

when it's
too big.Finally, it's best to use symbolic constants in your code instead of numbers
like 2147483647, because the symbolic constants are self-documenting and help
avoid platform dependencies. For example, 2147483647 is not the largest integer
on Alpha computers. The standard symbolic constant `INT_MAX`

is the
largest integer. You can use `INT_MAX`

by including `limits.h`

in your program; that is, put the line

#include <limits.h>

at the beginning of your code.

Turn in all three versions of your program and your documentation with the command

/u/cs126/bin/submit 2 readme usewhile.c usefor.c usebreak.c

Copyright © 1996 David R. Hanson / drh@cs.princeton.edu

$Revision: 1.4 $ $Date: 1996/09/19 10:22:06 $