Quick Index

Overview


The term variable goes by many names: var, placeholder, slot, parameter, argument, ...

In this section we will discuss vars and get an idea of their purpose.

Examples Setup


Rectangle
A basic rectangle.

Governing equation:

area = width * height


Examples


Variables (Placeholders)
variable = placeholder

Here we show our equation with our three variables (placeholders)
XX=YY*ZZ
area width height
Populated Variables (#1)
Variables populated with values.
20=10*2
area width height
Populated Variables (#2)
Variables populated with a different set of values.
300=20*15
area width height
Quiz - Populated Variables
What would be another example of populated values?



Any numbers you like for B and C.

And A is calculated from B and C.

A=B*C
area width height


Variables vs Constants


Definitions:


Quiz - Variables vs Constants
Given the equation shown.
How many variables?
How many constants?



Three vars -- x, j and z.
Two constants -- 10 and 3.

z = 10 + (3*x) + j

Variables In Code


Quiz #1 - Variables
How many variables can you identify in this pseudocode?



7 variables

- instance vars (1)
- method param (1)
- local vars (4)
- loop var (1)

Variables are a big part of program code.



class Accumulator {

	constructor() {
		//Initialize instance var
		this.result = 0;
	}

	increaseBy(amount) {
		let newResult = this.result + amount;
		this.result = newResult;
	}

	getResult() {
		return this.result;
	}

}

//---------------------------------

class AccumulatorTest {
	test1() {
		let accumulator = new Accumulator();
		let array = [10, 20, 30, 40];
		for (let nextNumber of array)
			accumulator.increaseBy(nextNumber);
		console.log("Result: " + accumulator.getResult());
	}
}

//---------------------------------

let test = new AccumulatorTest();
test.test1();
Quiz #2 - Variables
How many variables can you identify in this Java code?



7 variables

- instance vars (1)
- method params (2)
- local vars (3)
- loop var (1)

public class Accumulator {

	private int result = 0;

	public Accumulator() {
		this.result = 0;
	}

	public void increaseBy(int amount) {
		int newResult = this.result + amount;
		this.result = newResult;
	}

	public int getResult() {
		return this.result;
	}

	public static void main(String[] args) {
		Accumulator accumulator = new Accumulator();
		int[] array = new int[] {10, 20, 30, 40};
		for (int nextNumber: array)
			accumulator.increaseBy(nextNumber);
		System.out.println("Result: " + accumulator.getResult());
	}

}

References














Navigation