Tuesday, November 25, 2008

Lesson 3 : Basic Mathematics

Objective
Now that you understand the basics of using variables, we’re going to use some
variables with numbers. We will create two variables that contain different
numbers, then we will create a third variable by adding the first two variables
together.

Step 1
Open a new window in your Text Editing Program.

Step 2
Type in the lines just as they appear in the text below:

$x = 1;
$y = 2;
$z = $x + $y;
echo “Answer: ”, $z;
?>


Step 3
Name this file addition.php and save it in your Project Folder.

Step 4
Upload addtion.php to your server.

Step 5
View the page (www.YourWebDomain.com/addition.php) in your Web Browser.
You should see the words “Answer: 3” in your Web Browser.


We just created a file that adds two variables together and then outputs the
answer to the screen. Now we’ll go line by line to help.

Line 2 and Line 3

$x = 1;
$y = 2;


These lines of code create two variables.
The first variable is named $x. We give this variable a value equal to “1”. When
you are using a numeric value, you do not need to put quotes around the value.
Our second variable is named $y. We give this variable a value equal to “2”.

Line 4

$z = $x + $y;

This line of code creates a variable named $z. Instead of typing the actual value
of $z, we create a value for $z by adding $x and $y. Since the variable $x holds
the value “1” and the variable $y holds the value “2”, the variable $z takes on a
value of “3”.

Line 5

echo “Answer: ”, $z;

This line of code uses the echo command, some text and our variable $z.
Whenever you want to display text on the screen, you use the echo command.
In Lesson 2, we learned that we can mix plain text and variables to create an
output. In this example, we use the text “Answer: “ and then display the variable
$z. When this displays on the screen, it shows “Answer: 3”.


You can use different values and different mathematical functions to create
different values and outputs. You can also output more than one variable at a
time. Try this example in the text below:

$x = 20;
$y = 5;
$z = $x - $y;
echo $x, “ - “, $y, “ = “, $z;
?>

Try giving your variables different values and try using different mathematical
functions to see what you can display on your screen.


Exercise 3-2
After a variable has been defined, you can redefine that variable by giving it a
new value. When you display a variable on the screen, it will display whatever
value it contains at that point in the code. Try this example in the text below:


$x = 60;
$y = 40;
$z = $x + $y;
echo “Answer 1: “, $z;
$x = 30;
$y = 20;
$z = $x - $y;
echo “Answer 2: “, $z;
?>


Conclusion
In Lesson 3 we learned how to use numeric variables and mathematical
functions to create new variables and how to display those variables in our Web
Browser.

In Lesson 4 we will explore how to make this more useful by getting input from
the user and using that input to generate an answer.

No comments: