Next: More About Emacs
Up: Arithmetic Expressions
Previous: Arithmetic Expressions

Operator Precedence

We've written a program that will read in two numbers and then print out their average. Look at ``examples/average1.f'' (or view it directly).

Make sure that you understand how the program works. It's very straightforward and isn't much different from programs you've already seen in the text. Be sure to ask for help if you don't understand something.

Now compile and run the program. Try running the program several times with different input values. If it doesn't do what you expect, ask for help.

Now let's experiment by making a few small changes to the program. You will be making the changes. After you make each change, compile and run the program. Try to explain the behavior that you observe before looking at our explanations.

  1. Change (X + Y) / 2 to X + Y / 2

    Click here for explanation

  2. Change X + Y / 2 to X/2 + Y/2

    Click here for explanation

  3. Change X/2 + Y/2 to X + Y * .5

    Click here for explanation

  4. Change X + Y * .5 to (X + Y) * .5

    Click here for explanation

There are five arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (**). Furthermore, both addition and subtraction can be used both as dyadic (two argument) and monadic (one argument) operators. For example, X - Y is subtraction while -X is negation.

When you write an arithmetic expression in a program, Fortran must decide in what order to evaluate it. Fortran has a set of rules (called ``precedence rules'') that it uses to determine this order. You can either learn them (by studying section 3.2) or you can use parentheses to group expressions.

Even if you memorize the precedence rules you'll often have to use parentheses (for example, consider our original example program). If you know the precedence rules you can save typing a few parentheses and your programs will look a bit prettier, but that's all.

As a beginning programmer, it's best to use parentheses whenever there's any doubt in your mind as to the order in which an expression will be evaluated. You'll pick up the precedence rules as you get more experience.

Right now, the most important thing is being aware that the order in which expressions are evaluated is not always left-to-right.


Next: More About Emacs
Up: Arithmetic Expressions
Previous: Arithmetic Expressions

Hamlet Project
hamlet@cs.utah.edu