## Overview

This lesson gets into the basic mechanics of working with variables in programs. The lesson shows students how to create and assign values to variables and navigates through a series of common misconceptions about variables and how they work. Along the way, the lesson tries to build up the student's mental model of how computers and programs work, which is essential for being able to reason about programs.

## Vocabulary

• Data Type: All values in a programming language have a "type" - such as integer, number, text, or boolean - that dictates how the computer will interpret it. For example, 7 + 5 is interpreted differently than "7" + "5"
• Expression: Any valid unit of code that resolves to a value.
• Variable: A placeholder for a piece of information that can change.

## Goals

Students will be able to:

• Use variables in a program to store values.
• Store the value returned by an Action (e.g. RandomIntegerBetween(1, 10)) in a variable for use in a program.
• Debug problems related to variable re-assignment.
• Write arithmetic expressions that involve variables.
• Reason about multi-line segments of code in which variables are re-assigned multiple times.

## Purpose

Developing a good mental model for how variables work in computer programs is absolutely essential to long-term success as a programmer. However, because most students have had years worth of math classes before taking this course, there are two major misconceptions that early students often have about variables. We suggest that you try to avoid relating this material to mathematics at all. Some of the words and symbols are the same, but:

• When we are assigning values to a variable name, say "gets" in place of the "=" sign. For example, "integer age = 15" would be read as "the integer variable age gets the value of 15." When assigning a value to a variable the "=" sign is an instruction to store a value in memory, NOT a statement of equality
• "Variables" in computer science are just named pieces of memory, NOT unknowns in an equation or symbols for undetermined values.

Thus, lines of code that assign values to variables and expressions that use variables are really instructions to retrieve and store values in memory. And those values change while the program executes. Consider the following lines of code:

``````a = a + b
b = a + b
``````

Being able to reason about what's happening in consecutive lines of code like these correlates highly with a person's success in programming because you must have a good mental model for program execution and what the computer is doing.

## Getting Started

You are now pretty well acquainted with the basic mechanics of making event-driven apps. There is a pattern to writing these programs that you should be used to:

• Add User Interface (UI) elements/objects to the screen
• Give the UI elements/objects meaningful names or IDs
• Add event handlers to those UI elements/objects

However there's a whole bunch of things that we can't do in our apps yet. The next step is to learn how to control the computer's memory to remember things while the program is running.

Most apps keep track of some information that changes and updates as you use the app. For example, a simple game can keep track of your score and the number of lives you have left as you play.

Note that keeping track of data while a program is running is different from remembering things in the long term across multiple uses of the app, things like storing the all-time high score or remembering your user profile. Most programs need to use memory for even basic processing tasks.

But you will want to write programs that keep track of data. These apps/programs use and control the computer's memory to do this, and learning how to use memory in programs is a powerful skill to have. Today we'll start!

## Activity 1: Controlling Memory with Variables

The programming tasks in this lesson acquaint students with the basics of working with variables and building up a mental model for how programs use and manage memory. To keep things simple, the output will mostly be simple text displayed to the screen.

This lesson gets into the basic mechanics of controlling the computer's memory, by working with variables in programs.

We're going to focus on some bare-bones examples so that students get the basic ideas behind creating and using variables. We will be displaying text in the console rather than enhancing an app for now.

Understanding the typical pitfalls of learning variables for the first time, combined with establishing a good mental model, will make working with memory and variables in the future much easier.

• To create a chunk of memory to use in a program you must indicate the "type" of data that will be stored in that memory location (e.g. integer, number, text, boolean)
• To assign a value to a variable means to store a value in memory; you will use the "=" sign.
• Variable re-assignment typically means to change the value of a variable based on its current value (e.g. adding a point to the variable score: score = score + 1)

In the next two lessons students will learn how to work with variables and then incorporate them into a game to keep score.

In this lesson students will learn to:

• Move memory around - learning some of the basic mechanics and properties of working with variables.
• Basic mechanics - students will complete some bare-bones examples to understand the basic ideas behind creating and using memory through variables.
• Establish a good "mental model" for working with variables - learning the imprtance of having a good mental model before you get in too deep will allow students to go further and faster later on.
• Getting past misconceptions - understanding the typical pitfalls of learning variables for the first time, combined with establishing a good mental model will make working with memory and variables much easier in the future.

### Activity 1: Student Instructions

Let's get started with the most basic example of using and controlling the computer's memory with variables.

``````//Creates a text type variable named "teamName" and assigns the value of "Tigers" to it
text teamName = "Tigers"

//Creates an integer type variable named "score" and assigns the value of "0" to it
integer score = 0

//Displays a message that includes the "teamName" and the current "score" to the output screen
output "The " + teamName + " current score is: " + score
``````

#### Coding Challenge: Declare a Variable

Create/Declare an integer variable "lives," assign it a value, and then display it to the console using a descriptive message that indicates what value is being displayed. Use the example above to help you.

## Declaring a Variable

#### Debugging Challenge: Fix the Error

See if you can find the error in the following code block. If you are having trouble locating the error try running the program, fix the error and run it again.

## Debugging with Variables

When you get the program running correctly the output should look like this:

``````5
12
``````

When you are displaying the "value" of a variable to the output screen you should NOT use quotes. Notice the difference between these two statements - the comments next to each line explains the differences:

``````output "score"  //will display the literal characters s-c-o-r-e
output score  //will retreive the value of score and display it``````

## Activity 2: Controlling Memory - Other ways to store values

When assigning values to variables we know that the "=" sign is not a statement of mathematical equality. It is an instruction to move memory around. One tip to help you remember this is to read a variable declaration statement like `integer score = 0` as: "The variable score gets the value 0" or maybe just "score gets 0" to be brief. Another example: `integer newScore = score + 1` should be read as "newScore gets score plus 1."

When you read the = sign as "gets," and say it out loud that way, you'll prevent confusing yourself, and other programmers will know what you are talking about.

As we're about to see there are other ways to store values in variables besides just hard-coding single numbers. But in all cases, even when it's more complicated, using the word "gets" when you see a variable assignment will help you create a mental model of what's happening.

### Activity 2: Student Instructions

A common thing to want to do is store the result of an arithmetic expression. The 4 basic arithmetic operations + - * / are available.

``````integer result = 7 + 3  //stores 10 in "result"

integer value = 7 - 3  //stores 4 in "value"

integer score = 7 * 3  //stores 21 in "score"

number bonus = 7.0 / 2.0  //stores 3.5 in "bonus"

integer average = (10 + 15 + 10 + 20 + 15) / 5  //stores 14 in "average"

``````

The expression itself is NOT stored in the variable, rather with arithmetic instructions like these you are asking to compute the expression first, and then store the answer (a single number) in the variable.

#### Text and Variables Together

Sometimes it's useful to display text along with the value of a variable in the same line of output. To do this you use the "+" sign to attach a variable to text. We used this concept in the first example with the `output "The " + teamName + " current score is: " + score` statement.

If both operands are numbers "+" means to add those two numbers together.

``````integer num1 = 5 + 7  //stores the sum of 5 + 7 (12) in the variable num1
output num1 + 10  //outputs the sum of variable num1's value (12) and 10 to the screen, in this case 22
``````

If either of the operands is a string "+" treats both operands as if they were strings and combines them to create a single string. This is potentially confusing behavior especially if the text looks like numbers. For example this code block will display 16100 to the screen.

``````integer num = 100
output "16" + num
``````

This is because Quorum Programming Language sees that you are trying to display a mix of text and variable values. "16" (in quotes) is a string of ASCII characters not a number. And so everything is converted to text and the characters in the result of "16" + "100" comes out to "16100".

Tip: It's common to want to sandwich a variable between some text when displaying it. You can "add" together multiple pieces of text and variables using the "+" operator. For example, you can do this:

``````integer numLikes = 7
output "So far " + numLikes + " people like this page."
say "So far " + numLikes + " people like this page."
``````

#### Coding Challenge: Combining Text and Variables

We have given you the starting code shown below. You should modify the code by combining text and variables to output/say this single line of text "You have 3 lives left with score: 0."

## Combining Text and Variables

#### Expessions with Variables

Arithmetic becomes much more interesting when we use other variables in our expressions. For example you can do this:

``````number quiz1 = 99.5
number quiz2 = 89.0
number quiz3 = 93.5
number avg = (quiz1 + quiz2 + quiz3) / 3
``````

The end result of an expression with variables is the same as one without. The major difference is that values are retrieved from memory in order to do the calculation rather than simply hard-coded. To compute the expression the computer will:

1. Retrieve each of the values of the variables used in the expression.
2. Evaluate the arithmetic expression.
3. Store the computed value in memory.

#### Coding Challenge: Calculating the "Total Score"

In the starting code we have provided you with variables that might be the kinds of things you would keep track of in a game totalTime, points, and lives.

Right now the totalScore is set to 0. We want you to compute a totalScore so that the person is rewarded for having a lot of points and lives, but penalized for taking a lot of time.

Write an expression to calculate the player's total score and store that calculation in the totalScore variable. The calculation you should use is: the player's points times their lives divided by the totalTime.

## Calculating the Total Score

For the values provided the program display should look like this:

``````Points: 15
Lives: 3
Total Time: 9
------------------------------------
``````

#### Other Ways to Assign Values to Variables

Programs become much more interesting when the values in variables change while the program is running. We can also assign to a variable the value returned by an action. Remember our random number generator from Lesson 2 where we used the following line of code:

`integer randomInt = random:RandomIntegerBetween(1, 10)`

Because the RandomIntegerBetween() action evaluates to an integer, it means that we can treat it as though it were a number.

#### Coding Challenge: Dice Game

Using the template below, create a program that simulates the rolling of two dice and reports (displays) their individual values as well as the sum. The program should:

• Generate two random integers between 1 and 6 and store each result in its own variable
• Output and Say the individual values of the two dice
• Output and Say the sum of the two dice

Every time you run the program the result will be a little different.

We have given you starting code that shows what to do for the first die. The rest of the code is up to you! When you are done the output in the app display should look similar to this:

``````Rolling Dice!
You rolled a: 5
and a: 2
For a total of: 7``````

## Dice Game

#### Getting User Input

Programs become even more interesting when we can interact with the user. To store user input into a variable we would use the following line of code:

`text name = input("What is your name?")`

This will prompt the user with the message "What is your name?" and store the user's input into the text type variable "name." Since all user input is read in as a text type, we will have to manipulate the input to change the data type for our specific purpose. For instance if we want to store user input in an integer type variable we would have to place a "cast" on the input like this:

`integer age = cast(integer, input("What is your age?"))`

This will prompt the user with the message "What is your age?" and then cast (change) the user input to an integer type and finally store the value in the integer type variable "age."

Note: If you try and "cast" the text value "bob" to an integer type value, you will receive what is called a cast error since "bob" is NOT an integer, but a name.

#### Coding Challenge: Simple Calculator

Let's use the technique of casting user input to make a simple calculator. Write a program that will:

• Ask the user to enter a number and store the "casted" input to an integer type variable
• Then ask the user to enter a second number, again storing the "casted" input to an integer type variable
• Display the result of some calculation (e.g. add the two integers, multiply the two integers, etc.)

We have given you starting code that shows you how to get the first number, the rest of the code is up to you.

Debugging Tip: Every start parenthesis "(" needs and end parethesis ")".

## Simple Calculator

#### Variable Reassignment - Part 1

So far we have only set a variable's value once. But it's called a variable for a reason - its value can change (or vary) throughout a program. This is useful and necessary for keeping track of things like a score in a game.

To re-assign a value to a variable all you have to do is maintain a mental model of what's happening:

• Variables are containers for information
• The = sign is an instruction to set the value
• A series of assignment statements is a list of instructions to execute one at a time - it's not a series of equations that define the state of the world.

Make a Prediction: Study the code in the online IDE below and make a prediction about what will happen when you run the code. What will the values of a and b be at the end of the program?

Add an output statement at the end of the code for both variables to see if you were correct. If not, go back and add output statements for the variables throughout the code so that you can see the change in the variable's value as it occurs.

Notice: In the code below, after the integer type variable "a" has been created using `integer a = 3` to change a variable's value, you only need to refer to the variable by its name. The type "integer" only needs to be used once - when the variable is being created (declared) for the first time. It is a common mistake to use the type everytime you want to use a variable, but just remember that when you include the type you are creating a new variable. The computer will give you an error if you try to create the same variable more than once.

## Make a Prediction: Variable Re-assignment

#### Variable Reassignment - Part 2: Updating Values

All of our examples so far have shown how to set the value of a variable by using combinations of numbers and other variables. But what if you wanted to do something like add 10 to the current value of a variable?

Because updating the value in a variable is just moving memory around, the process has to go something like this:

• Read the current value of a variable
• Store the new value back into the same variable

The technical term for this is called variable re-assignment - when you change the value of a variable based on its current contents. To increase the value of "num1" by 10 you would need to do this:

`num1 = num1 + 10`

Make a Prediction: We start you out with some code again. Trace the code and predict what you think the output will be at each step. Run the program and see if you were right. Add an output statement at the very end to see the last value of someNum and see if your full prediction is correct.

## Make a Prediction: Updating Values

#### Coding Challenge: Moving Memory

The next two challenges present coding tasks related to "moving memory" around in your program

Goal: Set the value of the variables to make the output display the defined "Expected Output"

• You may only add lines of code that re-assign values of the variables provided
• You may only use the assignment ( = ) and arithmetic operators ( + - * / )
• You may not type or introduce any numbers
• You may not add or create any new variables
• You may not change or alter the output statement at all

Example: Provided Code

``````integer x = 2
integer y = 3

output "The value of y is: " + y + "(y should be 5)"
``````

Example: Possible Solution

``````integer x = 2
integer y = 3
y = y + x
output "The value of y is: " + y + "(y should be 5)"
``````

Now you try one. Use the starter code below to display the expected output:

## Moving Memory - Level 1

Okay let's try one that is a little bit harder:

## Moving Memory - Level 2

Hint: This one requires you to be a little clever. Think about setting the value of one variable that you could then use to easily set the value of the other variables. Then the trick is to figure out how to use the variables you've been given to make that useful value.

Hopefully you now understand the gist of working with variables. The example below is something that definitely wouldn't make sense in math class, but you should be able to reason about it as a piece of code. Because it's code, you can also insert statements to display the value of the variables as they change. You don't have to guess!

``````integer num = 0
num = num + 1
num = num + 1
num = num + 1
``````

## Wrap Up

This lesson was subtly one of the most important for you as a programmer. Being able to predict the value of a variable by tracing the code means that you have a good mental model for how programs execute code and how machines work.

Some research has shown that being able to answer questions about simple variable re-assignment correlates highly with doing well in programming overall. So you're on your way!

## Extended Learning

Students can make their own program that prompts the user for some numeric values and then performs an action. The user input values could be used to print a calculation to the screen, or they could be used to control a program (such a the number of times to repeat an action).

## Standards Alignment

• CSTA K-12 Computer Science Standards: CPP.L2:5, CPP.L3A:3, CPP.L3A:4, CPP.L3A:5
• CSTA K-12 Computer Science Standards: CT.L2:12, CT.L3A:1, CT.L3A:3
• Computer Science Principles: 5.2.1(C, F)