Simple Calculations

Chapter: Simple Calculations

Performing simple calculations in C is done via arithmetic expressions very similar to what is done in other programming languages. C has a well-defined hierarchy of operations, but even if you memorize that whole hierarchy and are entirely comfortable with the priorities of the operators, it is a good idea to make good use of parentheses to make it clear to us mere mortals just what you mean.

This is a program to print numbers and their squares, from 0 up to whatever is input on the commandline.


Exercise 2

Find out about argc and argv and see if you can figure out how I override the default value of n in this program. You may also want to look up the atoi function that converts strings (ASCII -- hence the "a") to ints. Write your own program to print numbers and their squares over a given range. You may, of course, begin with my program and edit it to produce your own. If the name of your compiled program is squares then squares -3 4 should print out the numbers from -3 to 4 along with their squares (9 4 1 0 1 4 9 16).

That was an easy adaptation of the code I gave you. Nevertheless, you did have to work with and modify both an if and a for structure. So you now understand both conditional and looping structures in C. They are a lot like the corresponding structures in Java.

Just as in Java, you can nest structures within each other. Study this program, compile it, and run it. If you were to name it two.c and compile it to an executable called two then two 4 will produce 1/1 1/2 1/3 2/1 2/2 2/3 3/1 3/2 3/3.

Be sure you can answer all these questions before you proceed. If you have trouble with any then you must consult your lab instructor:

When you're comfortable with the above, you can tackle the next exercise.


Exercise 3

Write a program to print out all Pythagorean triples (x,y,z) such that max(x,y,z) < n. n is an integer on the commandline. (x,y,z) is a Pythagorean triple if all are positive ints and x2 + y2 = z2. To avoid duplicates, let's insist the ints in the triple appear in increasing order.

Sample run:

> pythag 14
(3, 4, 5) is Pythagorean
(5, 12, 13) is Pythagorean
(6, 8, 10) is Pythagorean

Notice that (6, 8, 10) is basically the same triple as (3, 4, 5). For extra credit, see if you can suppress the printing of triples that can be obtained from previous triples by multiplying each member by a constant.




rhyspj@gwu.edu