If you're a beginning programmer and want to get more deeply into programming with variables, you've come to the right place. This article, the second of three parts, is excerpted from chapter two of the book Beginning C, written by Ivor Horton (Apress, 2004; ISBN: 1590592530).

First Steps in (C) Programming, continued - More Complex Expressions (Page 6 of 8 )

You know that arithmetic can get a lot more complicated than just dividing a couple of numbers. In fact, if that was all you were trying to do, then you may as well use paper and pencil. Now that you have the tools of addition, subtraction, multiplication, and division at your disposal, you can start to do some really heavy calculations.

For these more complicated calculations, you’ll need more control over the sequence of operations when an expression is evaluated. Parentheses provide you with this capability. They can also help to make expressions clearer when they’re getting intricate.

Parentheses in Arithmetic Expressions

You can use parentheses in arithmetic expressions, and they work much as you’d expect. Subexpressions contained within parentheses are evaluated in sequence from the innermost pair of parentheses to the outermost, with the normal rules that you’re used to for operator precedence, where multiplication and division happen before addition or subtraction. Therefore, the expression 2 * (3 + 3 * (5 + 4)) evaluates to 60. You start with the expression 5 + 4, which produces 9. Then you multiply that by 3, which gives 27. Then you add 3 to that total (giving 30) and multiply the whole lot by 2.

You can also insert spaces to separate operands from operators to make your arithmetic statements more readable. If you’re not quite sure of how an expression will be evaluated according to the precedence rules, you can always put in some parentheses to make sure it produces the result you want.

This time you’ll have a go at calculating the circumference and area of a circular table from an input value for its diameter radius. You may remember from elementary math the equations to calculate the area and circumference of a circle using π or pi (circumference = 2πr and area = πr^{2}, where r is the radius). If you don’t, then don’t worry. This isn’t a math book, so just look at how the program works.

This time you’ll have a go at calculating the circumference and area of a circular table from an input value for its diameter radius. You may remember from elementary math the equations to calculate the area and circumference of a circle using πor pi (circumference = 2πr and area = πr, whereis the radius). If you don’t, then don’t worry. This isn’t a math book, so just look at how the program works.

/* Program 2.8 calculations on a table */ #include <stdio.h> void main() { float radius = 0.0f; /* The radius of the table */ float diameter = 0.0f; /* The diameter of the table */ float circumference = 0.0f; /* The circumference of the table */ float area = 0.0f; /* The area of a circle */ float Pi = 3.14159265f; printf("Input the diameter of the table:"); scanf("%f", &diameter); /* Read the diameter from the keyboard */ radius = diameter/2.0f; /* Calculate the radius */ circumference = 2.0f*Pi*radius; /* Calculate the circumference */ area = Pi*radius*radius; /* Calculate the area */ printf("\nThe circumference is %.2f", circumference); printf("nThe area is %.2f\n", area); }

Here’s some typical output from this example:

-------------------------------------------- Input the diameter of the table: 6 The circumference is 18.85 The area is 28.27 --------------------------------------------

HOW IT WORKS

Up to the firstprintf()the program looks much the same as those you’ve seen before:

float radius = 0.0f; /* The radius of the table */ float diameter = 0.0f; /* The diameter of the table */ float circumference = 0.0f; /* The circumference of the table */ float area = 0.0f; /* The area of a circle */ float Pi = 3.14159265f;

You declare and initialize five variables, wherePihas its usual value. Note how all the initial values have anfat the end because you’re initializing values of typefloat. Without thefthe values would be of typedouble. They would still work here, but you would be introducing some unnecessary conversion that the compiler would have to arrange, from typedoubleto typefloat.

The following statement outputs a prompt for input from the keyboard:

printf("Input the diameter of the table:");

The next statement deals with reading the value for the diameter of the table. You use a new standard library function, thescanf()function, to do this:

scanf("%f", &diameter); /* Read the diameter from the keyboard */

Thescanf()function is another function that requires thestdio.hheader file to be included. This function handles input from the keyboard. In effect it takes what you enter through the keyboard and interprets it as specified by the first argument, which is a control string between double quotes. In this case the control string is"%f"because you’re reading a value of typefloat. It stores the result in the variable specified by the second argument,diameterin this instance. The first argument is a control string similar to what you’ve used with theprintf()function, except that here it controls input rather than output.

You’ve undoubtedly noticed something new here: the&preceding the variable namediameter. This is called the address of operator, and it’s needed to allow thescanf()function to store the value that is read in your variable,diameter. The reason for this is bound up with the way argument values are passed to a function. For the moment, I won’t go into a more detailed explanation of this; you’ll see more on this in Chapter 11. The only thing to remember is to use the address of operator (the&sign) before a variable when you’re using thescanf()function, and not to use it when you use theprintf()function.

You’ll see a lot more on howscanf()works later in the book, but for now the basic set of format specifiers you can use for reading data of various types are as follows:

To read a value of type short

%hd

To read a value of type int

%d

To read a value of type long

%ld

To read a value of type float

%f or %e

To read a value of type double

%lf or %le

In the%ldand%lfformat specifiers,lis a lowercaseL. Don’t forget, you must always prefix the name of the variable that’s receiving the input value with&. Also, if you use the wrong format specifier—if you read a value into a variable of typefloatwith%d, for instance—the data value in your variable won’t be correct, but you’ll get no indication that a junk value has been stored.

Next, you have three statements that calculate the results you’re interested in:

radius = diameter/2.0f; /* Calculate the radius */ circumference = 2.0f*Pi*radius; /* Calculate the circumference */ area = Pi*radius*radius; /* Calculate the area */

The first statement calculates the radius as half of the value of the diameter that was entered. The second statement computes the circumference of the table, using the value that was calculated for the radius. The third statement calculates the area. Note that if you forget thefin2.0f, you’ll probably get a warning message from your compiler. This is because without thef, the constant is of typedouble, and you would be mixing different types in the same expression. You’ll see more about this later.

The next two statements output the values you’ve calculated:

printf("\nThe circumference is %.2f", circumference); printf("\nThe area is %.2f\n", area);

These twoprintf()statements output the values of the variablescircumferenceandareausing the format specifier%.2f. As you’ve already seen, in both statements the format control string contains text to be displayed, as well as a format specifier for the variable to be output. The format specification outputs the values with two decimal places after the point. The default field width will be sufficient in each case to accommodate the value that is to be displayed.

Of course, you can run this program and enter whatever values you want for the diameter. You could experiment with different forms of floating-point input here, and you could try entering something like1E1f, for example.