~ Introduction to Programming: C ~

Session 4 - Maths: Operator precedence, statistics and floating point variables

<<  Back to Contents Page

Session 4 - Maths: Precedence, Stats and Floating Point 

In This Session...

In this session we will be covering the following topics:-

Review of Last Session

Last week we covered:-

Floating Point Variables - Working with Decimal Numbers

In the last session, we took a look at a variable as a place to store a specific named piece of information - for example a variable called myAge may contain 23. We looked specifically at integer type variables - i.e. variables that can only store whole numbers. For example:-

#include <stdio.n>
#include <conio.h>
 
void main()
{
  int myAge;
  myAge = 23;
  printf("My age is %d\n",myAge);
}

This is fine unless we wish to store numbers which are not whole. For example, just say we wanted to say that our age is twenty-three-and-a-half. If we tried the following program:-

myAge = 23.5;

This would generate an error when we try to compile the program. When the computer attempts to interpret your instructions into machine code, it tries to put 23.5 in the variable called myAge, and then stops when it realises that you originally stated that the box is to be used for integer (whole number) values.

So how do we put decimal values into the box?  We simply tell the computer that we want the box to hold a different type of information - in this case something called a floating point variable (sometimes also called a real variable). The reasons for this are rather in-depth and mathematical!

To do this, we replace the word int with the word float - the int told the compiler we are declaring a new variable that was to hold integers - i.e. whole numbers, and float tells the compiler we are declaring floating point numbers - i.e. decimal numbers.

So now to declare the variable myAge so it can hold the number 23.5, we have:-

  float myAge;

A Recap on Decimals and Fractions

Here are some commonly used decimal numbers:-

0.0 Zero (nothing)
0.125 An Eighth

0.25

A Quarter (or two-eighths)
0.375 Three-Eighths

0.5

A Half (or two-quarters or four-eighths)
0.625 Five-Eighths

0.75

Three-Quarters (or six-eighths)
0.85 Seven-Eighths
1.0 One (Unity)
17.5 Current percentage for VAT (Sales Tax) in the UK
0.175 Multiply this by a purchase cost to get the amount of VAT to be paid on that item
3.1415926535 Approximation to the value of PI (Times it by diameter of a circle and you get the length of the circle's edge).

A fraction is a portion of a whole. For example, if we have 100 coins, then if we halve the number of coins (i.e. divide it by two) then we get 50 coins. Similarly, if we have 10 coins, then if we halve them we get 5 coins. If we have one coin and half it, we get 0.5 coins.

A fraction is another way of saying "divided by". For example  a half - i.e. ½ - is another way of saying 1 divided by 2 (notice the / is the same as the symbol we use for divide in our C programs).

If you look at the table above, you can see the way some common fractions are written as decimal (float) numbers. Notice that whole numbers are represented by a dot and a zero after the number to show there is no fractional part.

If we divide 2 by 4 to give two-quarters, we get 0.5 - i.e. it is the same as dividing 1 by 2 (also gives 0.5).  You would usually write the smallest possible number - i.e. a half  (0.5) in cases where this happens.

Using printf to display data - %f format modifier

We looked at using printf to display text and integer numbers last week - for example:-

printf("3+3=%d\n",3+3);

This example uses the function printf (found in the stdio.h library) which displays what is between the double-quotes "" on the console (black screen), and anything after this will be inserted into the text where a %character occurs. Remember that everything in the brackets is information to be passed to the printf function

In this example the 3+3 after the comma is calculated (because it is NOT in quotes), and the line becomes:-

printf("3+3=%d\n",6);

The 6 is then substituted in to the %d as an integer (%d means "put the first value after the comma here, and assume it is an integer). The line now becomes:-

printf("3+3=6\n");

Similarly, we can put floating-point numbers onto the console using the %f modifier instead of %d - %f for floating point. For example:-

printf("1.5+3.5=%f\n",1.5+3.5);

becomes

printf("1.5+3.5=%f\n",5.0);

becomes

printf("1.5+3.5=5.00000\n");

You may ask why the large number 0s on the end. This is the default (i.e. standardised) way of printing floating-point numbers. If we wanted to display specifically 5.0, we would have to use the following format:-

printf("1.5+3.5=%3.1f\n",1.5+3.5);

The new format we use is: %width.decimal-placesf

where the width is the number of characters that the number can take up (in this case, there's one digit before the decimal point, the decimal point itsef (the dot), and another digit after the decimal point - three characters).

The decimal-places is the number of digits after the decimal-point - in this case, the single zero - 1.

From this we get %3.1f as the format modifier.

Exercise 9

Type out the following program: -

#include <stdio.h>

#include <conio.h>



void main()

{

  float a,b,c;



  a=0.5; b=1.5; c=2.0;

  printf("a+c=%f\n",a+c);
  getch();

}

Hint: Remember that the \n is interpreted as a "new line" - i.e. it causes the cursor to move to the next line down and to the left of the screen.

Now look at the following table and write down what you think will be displayed on the console (black window) each time when the lines are placed in the program

printf("a+c=%f\n",a+c);  
printf("a+c=%f\n",a+c);  
printf("c-b=%3.1f\n",c-b);  
printf("c-a=%1f\n",c-a);  
printf("b+c=%2f\n",c-a);  

Note that the %3.1f and %1f are the digit 1 and not the letter l (lower-case L).

Now execute (run) the program, and compare the result with the result you expected. Did they match? Do you understand why? If not, ask!

Replace each of the printf statements in turn with the printf statements in the table and re-run the program, noting down the answers that are given.

Taking the second from last example:-

printf("c-a=%1f\n",c-a);

The %1f means that no decimal places are shown - so the dot and anything afterwards are excluded, which means that the entire width of the number is the whole-number part only. As c-a calculates to be 1.5, you might ask what happens to the .5 at the end. In this example, the computer will round to the nearest whole number - 0.5 is exactly between two numbers, so the computer makes a decision to round upwards to 2.0.  So, the number 2 is shown on the console window.

Taking the last example:-

printf("c-a=%2f\n",c-a);

This is the same calculation - so no decimal places, which means the number gets rounded to the nearest whole number (2). The width will be 2 characters, but the number only takes up one character space.

What happens to the other character that isn't needed? The printf function will put a space before the number to make sure it takes up the number of spaces you specify. This is in case (for example) you want to show a big list of numbers in columns on your screen, and want them all to line up underneath each other. 

Exercise 10 - Order of Precedence - Using Parentheses (brackets)

Take the following program. What would you expect to be printed? Try it to see:-

#include <stdio.h>

#include <conio.h>



void main()

{

  float a,b,c,d;



  a=1.0; b=2.0; c=3.0;
 
  d=b*c+a;

  printf("b*c+a=%3.1f\n",d);
 
  d=c+a*b;

  printf("c+a*b=%3.1f\n",d);
 
  d=(a+b+c)/b;

  printf("a+b+c/b=%3.1f\n",d);
 
  getch();

}

Did you get the answers you expected? Take the first example. This probably worked out as you expected - 2 multiplied by 3 gives 6, and add 1 gives 7.

However the second example may have baffled you. Reading from left-to-right, this answer would seem to be given by adding 3 to 1 giving 4 and multiplying this by 2 giving 8. Instead, the answer is actually 5!

Why is this? Well, when performing sums, the computer needs to know what to calculate first. Should it add c and a together and multiply by b, or should it multiply a and b together and add this to c?  It depends how you read the sum.

To eliminate the confusion, a set of rules called rules of precedence are used when performing calculations. This tends to be the same for most computer languages. The rules are that certain operators (i.e. multiply (*), divide (/)) are calculated before others (i.e. add (+) and substract (-)). So when you look at an equation, do the maths around * and / first, find the answer, and then do the sum for + and - afterwards.

In our case,

  d=c+a*b;

* is greater precedence than +, so a*b gets worked out first (i.e. 1*2), giving:-

  d=c+2;

Then c+2 is worked out where the value of c is 3, giving:-

  d=3+2;

i.e.

  d=5;

But what would happen if we really wanted to add c and a together and then times by b? We can use parentheses (i.e. brackets) around the calculation we wish to be looked at first. This makes the calculation inside the brackets of greater precedence than anything else - e.g.

  d=(c+a)*b;

Try this in your program and check that it works as you expect - i.e. if c=3 and a=1 then:-

  d=(3+1)*b;

gives 

  d=4*b;

And then if b=2 then:-

  d=4*2;

giving

  d=8;

Finally, the last example given is calculated as follows:-

  d=(a+b+c)/b;

where a=1 and b=2 and c=3 giving (remember that the brackets come first):-

  d=(1+2+3)/b;

giving:-

  d=6/b;

and then as b=2: -

  d=4/2;

giving

  d=2;

Simple Statistics - Totals, Averages and Percentages

A lot of computer programs involve calculating a list of numbers. For example, lets say we have the following list of numbers (e.g. number of years your employees have worked with you) :-

6 2 4 8 5

The following is a few different statistics we might want of these numbers:-

Exercise 11 - Trying out the statistics

Create a new program that will show the total and average of the five values given above - here's how to do it: -

total      = 25.0

average    = 5.0

percentage = 20.0

In the Next Session...

In the next session we will be covering the following topics:-

(c) Copyright 2002-4 Simon Huggins.   All Rights Reserved.
If you have any issues or questions regarding the content of this web site, please contact the author by clicking here.
Alternatively, you can leave a voice message on 00 44 (0)7050-618-297 or fax on 00 44 (0)7050-618-298

This Page was last updated: 29 January 2004 13:06