You are on page 1of 7

Programming in Java for Engineers Rev 03

BASIC PROGRAM CALCULATIONS

AIM
To introduce the concept of performing calculations using variables and operators in a program.

BACKGROUND
Programs are entered normally using a text editor such as Notepad or a similar program. This means that all
the instruction needs to be written on the same line. We need to learn how to write calculations on the one
line. The examples below build up our ability to do this.

EXAMPLE 1
To calculate the area of a circle on paper, we would write:

Area of Circle = 𝜋𝑟 2

We can’t do this on a computer as it all has to be on one line. We need to write this in a program as:

areaOfCircle = 3.14 * (r * r);

where the calculation is all on one line.

The line above is called an assignment. A variable is assigned a


value based on the result of the calculation.
The right hand side of the calculation (to the right of the equals
sign) is called the expression.

In the above example,


 areaOfCircle is called a program variable which will contain
the answer. There needs to be no spaces in a variable name.
 The ‘*’ means multiply.
 The semi colon at the end of the line is needed in some
computer programs to indicate the end of the line.

EXAMPLE 2
Calculating the volume of a cylinder

We can write this on a computer as:

volCylinder = Math.PI * (r * r) * h;

~1~
Programming in Java for Engineers Rev 03

 Math.PI is used in Java to indicate 3.14.


 Math.pow(answer, 2) can be used to square the value stored in
answer.

~2~
Programming in Java for Engineers Rev 03

EXAMPLE 3
Adding 1 to a variable. This is written as:

answer = answer + 1;

Thus, if answer had the value of 6 before the calculation, then it has the value of 7 after the instruction is
executed.

So, implicitly, the above instruction should be read as:

LET answer equal to (answer + 1)

EXAMPLE 4
Java and other programming languages have inbuilt functions, similar to a calculator. Calculating the Square
root of 25. We use the sqrt function in the Math class to perform the calculation for us.

number = 25;
answer = Math.sqrt(number);

In a easier to read format…

LET number equal to 25


LET answer = √𝑛𝑢𝑚𝑏𝑒𝑟
= √25
= 5

DISCUSSION OF CONCEPTS
The above examples have shown various assignments. They are all computer instructions which calculate a
value for a variable using some expressions. We can perform a number of instructions to arrive at an answer.
We can also use various operators.

EXAMPLE 5
Calculate the roots of the following quadratic equation:

𝑥 2 + 6𝑥 − 5 = 0

Using the quadratic formula:

−𝑏 ± √𝑏 2 − 4𝑎𝑐
𝑥=
2𝑎

Where a=1, b=6 and c=5

We can calculate this using our calculators to get two solutions for 𝑥. However, how can we do this for a
program?

If we break it into parts, we can, in our program write:

a = 1;
b = 6;
c = 5;

~3~
Programming in Java for Engineers Rev 03

result1 = (b * b) – (4 * a * c);
result1 = Math.sqrt(result1);
root1 = ((-b) + result1) / (2 * a);
root2 = ((-b) – result1) / (2 * a);

As we see, the instructions for the computer program must be all programmed on one line for each
instruction. And in this case, the complex formula needed to be broken down into simple steps. However,
now we have the main part of our program which will calculate quadratic roots.

In this case, a, b, c, result1, root1, root2 are all variables which we define in our program.

The mathematical symbols (+, -, *, /. %) are called operators. This means that they operate on the numbers in
the calculation.

Operators are the symbols such as add, multiply, divide, etc


which are used in calculations. Some operators such as %,
which is the remainder operator (modulus) are not as obvious.

Operators are very common in programs.


There can be more than one operator in an expression.

Some examples of operators are:


ARITHMETIC O PERATORS + Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

UNARY OPERATORS ++ increments a variable by 1


(operate on a single variable) -- Decrement a variable by 1

COMPARISION OPERATORS == Equal to


!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

LOGICAL OPERATORS && Logical AND


|| Logical OR
! NOT operator. Inverts the value of a
Boolean from False to True or vice versa.

In the next chapter we will look at logical operators when making decisions. E.g. IF ((a >= 50) AND (b >= 100)).

We will finish with some more examples of calculations using variables and operators.

~4~
Programming in Java for Engineers Rev 03

EXAMPLE 6
Calculate the total of these products and add VAT of 21% to the total to find the overall price to charge the
customer.

DVD Movie, €3.75


MP3 soundtrack, €0.99
Guitar stand, €17.00

To do this is easy without a program. We simply add these together, get 21% of the total and add it on. To
write this out in a program, we need to follow the guidelines in the previous examples.

dvdMovie = 3.75;
mp3Track = 0.99;
guitarStand = 17.00;
VATRate = 0.21;

subtotal = dvdMovie + mp3Track + guitarStand;


vatAmount = subtotal * VATRate;
total = subtotal + vatAmount;

This may be a little long winded for this example but it allows us to get proficient at using program for more
useful calculations later.

The above example uses a number of variables. Note that the


numerical values are first assigned to variables (first four lines) and
then the calculations are performed on the variables only. This is
good programming practice to separate the numerical values or data
from the calculation instructions.

Variables cannot have a space or start with a number. Hence the


above example uses variables which do not contain spaces. Normally
variables are spelt in lower case and capital letters indicate new
words. E.g. thisIsAnExampleAndItIsEasyToRead

The variables A and a are not the same in Java and most
programming languages. Variable names are case sensitive.

We could have written the calculation section more concisely:

total = (dvdMovie + mp3Track + guitarStand) +


((dvdMovie + mp3Track + guitarStand) * VATRate);

However, it may be at the expense of clarity. Clarity is more preferable as another programmer may take over
the program and need to understand it. Always make the next person’s job as easy as possible!

~5~
Programming in Java for Engineers Rev 03

EXAMPLE 7

Increment a variable called calc by 1


Decrement a variable called count by 1
Increment a variable called amount by 3
Decrement a variable called amount by 2
Get the remainder of 50 divided by 3

calc++; or calc = calc + 1;

count--; or count = count – 1;

amount+=3; or amount = amount + 3;

amount-=2; or amount = amount – 2;

remainder = 50 % 3;

SUMMARY OF CHAPTER
We examined basic calculations which are commonly used in our programs. We saw that these instructions
are called assignments. An assignment essentially sets a variable value to the result of an expression. An
expression can contain other variables, operations and numbers.

We introduced ourselves to the common operators used and we saw that assignments need to be expressed
on one line at a time. Often complex calculations are broken down to simpler assignments. Brackets are used
(like in mathematics) to ensure that the expression in the brackets are evaluated first.

Java and other programming languages supply functions to perform calculations, such as we would find on a
scientific calculator.

We got an introduction to the concept of variables. Variables are very common in a program. They are simply
holders for values of data to be stored. Each run of a program may see different data values be inserted into
the same variables.

~6~
Programming in Java for Engineers Rev 03

QUESTIONS
1. What are the operators for
i. Greater than and equal to
ii. Less than
iii. Not equal to
iv. Equal to
2. What is a variable?
3. Explain in your own words what an operator is.
4. Give an example of setting a variable to a value.
5. Given a variable called counter = 6, write the instructions to:
i. Increment the variable by 1
ii. Decrement the value by 1
iii. Add 20 to the variable.
iv. Decrement the value by 10.
1
6. Given the formula for the volume of a cone as 𝜋𝑟 2 ℎ, write the programming instructions to
3
calculate the volume of the cone, given r = 6 and h = 4.
7. Write the programming instructions to perform the following:
i. Create two variables called a, b, and c
ii. Assign them the values 30, 45 and 60 respectively.
iii. Add a and b together and multiply the result by c.
iv. Divide the result or (iii) by twice the value of a
8. Check your answer using a calculator to verify your instructions are correct.
9. What is the difference between the = and == operators in Java?
10. Research on the internet the functions in Java for:
i. Calculating the cube of a number. E.g. 𝑥 3
3
ii. Calculating the cubed root of a number E.g. √𝑥

~7~

You might also like