Programming Logic/Variables
Variables and Conditionals, lesson 1
Focus
editIn this lesson, you will expand your knowledge on the use of variables and conditional statements.
Introduction
editIn Introduction to Programming you learned that computer programs are sets of instructions that computers follow. In nearly every program written, the program must store information supplied after the program was created. Such information may include user input, custom settings, or calculated values. Because this information can vary the term variable is used to describe the element of a program which stores this information. For example, a name
variable could contain "Jack" or "Jill" or any other value. Consider the following VBScript example:
Dim name name = "James" MsgBox name
If you are running windows, create a new text document called "variable_demo.vb" then copy-and-paste the above code into the file and save it. You can then double-click the file to execute the code (if you get a security warning, click Yes or OK as needed). Notice that the message that pops up says "James".
Now modify the file to change the value of name
to "Jimmy":
Dim name name = "Jimmy" MsgBox name
Execute the file again and notice that even though the MsgBox name
line did not change, the message that pops up says "Jimmy". This is because the value stored in the name
variable has changed.
An extremely common example of a computer program is a calculator. The user can give the calculator program input such as numbers and mathematical operators, but how does the calculator program handle the information given to it? In this section, you will learn how and why programmers use variables.
The Calculator Program: A Closer Look
editIn the above examples, a user wishes to use a computer program to add two numbers together. For simplicity, let us assume that the computer program is designed explicitly to add any two numbers that the user enters at the command prompt.
Enter the first number to be added : 4 Enter the last number to be added : 2 The total is 6.
The pseudocode for this program would look something like this
1. Ask the user to "Enter the first number to be added" and remember it as $FIRST. 2. Ask the user to "Enter the last number to be added" and remember it as $LAST. 3. Remember the result of $FIRST + $LAST as $RESULT. 4. Tell the user that "The total is " $RESULT.
More to come!