Scripting and Programming C173: Unit 2 – Variables/Assignments

(24 pages)

2.1 Variables and assignments (general)

Remembering a value

Here’s a variation on a common schoolchild riddle.

By the way, the real riddle ends with the question “What is the bus driver’s name?” and the subject usually says “How should I know?”. The riddler then says “I started with YOU are driving a bus.”

The numPeople box above served the same purpose as a variable in a program, introduced below.

Variables and assignments

In a program, a variable is a named item, such as x or numPeople, used to hold a value.

An assignment statement assigns a variable with a value, such as x = 5. That statement means x is assigned with 5, and x keeps that value during subsequent statements, until x is assigned again.

An assignment statement’s left side must be a variable. The right side is an expression. Example statements are x = 5, y = a, or z = w + 2. The 5, a, and w + 2 are each an expression that evaluates to a value.

  1. In programming, a variable is a place to hold a value. Here, variables x, y, and z are depicted graphically as boxes.
  2. An assignment statement assigns the left-side variable with the right-side expression’s value. x = 5 assigns x with 5.
  3. y = x assigns y with x’s value, which presently is 5. z = x + 2 assigns z with x’s present value plus 2, so 5 + 2 or 7.
  4. A subsequent x = 3 statement assigns x with 3. x’s former value of 5 is overwritten and thus lost. Note that the values held in y and z are unaffected, remaining as 5 and 7.
  5. In algebra, an equation means “the item on the left always equals the item on the right”. So for x + y = 5 and x * y = 6, one can determine x = 2 and y = 3 or vice versa.
  6. Assignment statements look similar to algebra equations but have VERY different meaning. The left side MUST be one variable.
  7. The = isn’t “equals”, but is an action that PUTS a value into the variable. Assignment statements only make sense when executed in sequence.

= is not equals

In programming, = is an assignment of a left-side variable with a right-side value. = is NOT equality as in mathematics. Thus, x = 5 is read as “x is assigned with 5”, and not as “x equals 5”. When one sees x = 5, one might think of a box labeled x having the value 5 put in.

Assignments with variable on left and right

Because = means assignment in programming, a variable may appear on both the left and right side of a statement, as in x = x + 1. If x was originally 6, x is assigned with 6 + 1, or 7. The statement overwrites the original 6 in x.

  1. A variable may appear on both sides of an assignment statement. After x = 1, then x = x * 20 assigns x with 1 * 20 or 20, overwriting x’s previous value 1.
  2. Another x = x * 20 assigns x with 20 * 20 or 400, which overwrites x’s previous value 20.
  3. Only the latest value is held in x. The previous values are shown greyed out above but in actuality are completely gone.

2.2 Variables (integer)

Variable declarations

variable declaration declares a new variable, specifying the variable’s name and type. A variable of type integer can hold whole number values, like 1, 999, 0, or -25 (but not 3.5 or 0.001). In Coral, an integer variable’s initial value is 0. The example program below declares a variable named userAge that can hold an integer value.

When a statement that assigns a variable with a value executes, the program puts the value into the variable. The variable will hold that value until the variable is assigned with another value.

Because computer memory is limited, an integer cannot hold arbitrarily-large values. In Coral, as in many programming languages, the range is about -2 billion to +2 billion.

Assignment statements

An assignment statement assigns the variable on the left-side of the = with the current value of the right-side expression. Ex: numApples = 8 assigns numApples with the value of the right-side expression (in this case 8).

An expression may be a number like 80, a variable name like numApples, or a simple calculation like numApples + 1. Simple calculations can involve standard math operators like +, -, and *, and parentheses as in 2 * (numApples – 1).

In the code below, litterSize is assigned with 3, and yearlyLitters is assigned with 5. Later, annualMice is assigned with the value of litterSize * yearlyLitters (3 * 5, or 15), which is then printed. Next, litterSize is assigned with 14, yearlyLitters is assigned with 10, and annualMice is assigned with their product (14 * 10, or 140), which is printed.

  1. The program declares two integer variables yourFriends and totalFriends.
  2. The program gets input and assigns yourFriends with 200.
  3. The assignment statement reads yourFriends (200), multiplies yourFriends by yourFriends, and assigns totalFriends with the product of 40000.
  4. The program outputs totalFriends, which holds the total people your friends’ know.
  5. Assignment reads totalFriends (40000) and yourFriends (200), multiplies those values, and assigns totalFriends with the result of 8000000.
  6. The program outputs totalFriends, which now holds the total people your friends’ friends know.

Six degrees of separation

The above example relates to the popular idea that any two people on earth are connected by just “six degrees of separation”, accounting for overlapping of known-people.

Rules for identifiers

A name created by a programmer for an item like a variable or function is called an identifier. An identifier must:

  • be a sequence of letters (a-z, A-Z), underscores (_), and digits (0-9)
  • start with a letter

Note that _ is called an underscore.

Identifiers are case sensitive, meaning upper and lower case letters differ. So numCats and NumCats are different.

reserved word (or keyword) is a word that is part of the language, like integer, Get, or Put. A programmer cannot use a reserved word as an identifier. A list of reserved words appears at the end of this section.

Rules for identifiers

A name created by a programmer for an item like a variable or function is called an identifier. An identifier must:

  • be a sequence of letters (a-z, A-Z), underscores (_), and digits (0-9)
  • start with a letter

Note that _ is called an underscore.

Identifiers are case sensitive, meaning upper and lower case letters differ. So numCats and NumCats are different.

reserved word (or keyword) is a word that is part of the language, like integer, Get, or Put. A programmer cannot use a reserved word as an identifier. A list of reserved words appears at the end of this section.

Table 2.3.1: Coral reserved words / function names (for the flowchart version; the code version has more).

Get
Put
to
from
input
output
integer
float
array
and
or
not
RaiseToPower
SquareRoot
AbsoluteValue
RandomNumber
SeedRandomNumbers

Basics

An expression is a combination of items, like variables, literals, operators, and parentheses, that evaluates to a value. Ex: 2 * (x + 1) is an expression. If x is 3, the expression evaluates to the value 8. Expressions are commonly used on the right side of an assignment statement, as in y = 2 * (x + 1).

literal is a specific value in code, like 2. An operator is a symbol that performs a built-in calculation, like the operator + which performs addition. Common programming operators are shown below.Table 2.4.1: Arithmetic operators.

Arithmetic operatorDescription
+The addition operator is +, as in x + y.
The subtraction operator is , as in x – y. Also, the – operator is for negation, as in -x + y, or x + -y.
*The multiplication operator is *, as in x * y.
/The division operator is /, as in x / y.

Evaluation of expressions

An expression evaluates to a value, which replaces the expression. Ex: If x is 5, then x + 1 evaluates to 6, and y = x + 1 assigns y with 6.

An expression is evaluated using the order of standard mathematics, such order known in programming as precedence rules, listed below.Table 2.4.2: Precedence rules for arithmetic operators.

ConventionDescriptionExplanation
( )Items within parentheses are evaluated firstIn 2 * (x + 1), the x + 1 is evaluated first, with the result then multiplied by 2.
unary –– used for negation (unary minus) is nextIn 2 * -x, the -x is computed first, with the result then multiplied by 2.
* /Next to be evaluated are * and /, having equal precedence.
+ –Finally come + and – with equal precedence.In y = 3 + 2 * x, the 2 * x is evaluated first, with the result then added to 3, because * has higher precedence than +. Spacing doesn’t matter: y = 3+2 * x would still evaluate 2 * x first.
left-to-rightIf more than one operator of equal precedence could be evaluated, evaluation occurs left to right.In y = x * 2 / 3, the x * 2 is first evaluated, with the result then divided by 3.
  1. An expression like 3 * (x + 10 / w) evaluates to a value, using precedence rules. Items within parentheses come first, and / comes before +, yielding 3 * (x + 5).
  2. Evaluation finishes inside the parentheses: 3 * (x + 5) becomes 3 * 9.
  3. Thus, the original expression evaluates to 3 * 9 or 27. That value replaces the expression. So y = 3 * (x + 10 / w) becomes y = 27, so y is assigned with 27.
  4. Many programmers prefer to use parentheses to make order of evaluation more clear when such order is not obvious.

Using parentheses to make the order of evaluation explicit

A common error is to omit parentheses and assume an incorrect order of evaluation, leading to a bug. Ex: If x is 3, then 5 * x+1 might appear to evaluate as 5 * (3+1) or 20, but actually evaluates as (5 * 3) + 1 or 16 (spacing doesn’t matter). Good practice is to use parentheses to make order of evaluation explicit, rather than relying on precedence rules, as in: y = (m * x) + b, unless order doesn’t matter as in x + y + z.

Example: Calorie expenditure

A website lists the calories expended by men and women during exercise as follows (source):Men: Calories = [(Age × 0.2017) — (Weight × 0.09036) + (Heart Rate × 0.6309) — 55.0969] × Time / 4.184

Women: Calories = [(Age × 0.074) — (Weight × 0.05741) + (Heart Rate × 0.4472) — 20.4022] × Time / 4.184

Below are those expressions written using programming notation:caloriesMan = ( (ageYears * 0.2017) – (weightPounds * 0.09036) + (heartBPM * 0.6309) – 55.0969 ) * timeSeconds / 4.184

caloriesWoman = ( (ageYears * 0.074) – (weightPounds * 0.05741) + (heartBPM * 0.4472) – 20.4022 )* timeSeconds / 4.184

2.5 Arithmetic expressions (integer)

Below is a simple program that includes an expression involving integers.

Style: Single space around operators

A good practice is to include a single space around operators for readability, as in numItems + 2, rather than numItems+2. An exception is minus used as negative, as in: xCoord = -yCoord. Minus (-) used as negative is known as unary minus.

2.6 Example: Health data

Calculating user’s age in days

This section presents an example program that computes various health related data based on a user’s age using incremental development. Incremental development is the process of writing, compiling, and testing a small amount of code, then writing, compiling, and testing a small amount more (an incremental amount), and so on.

The initial program below calculates a user’s age in days based on the user’s age in years. The assignment statement userAgeDays = userAgeYears * 365 assigns userAgeDays with the product of the user’s age and 365, which does not take into account leap years.

Considering leap years and calculating age in minutes

The program below extends the previous program by accounting for leap years when calculating the user’s age in days. Since each leap year has one extra day, the statement userAgeDays = userAgeDays + (userAgeYears / 4) adds the number of leap years to userAgeDays. Note that the parentheses are not needed but are used to make the statement easier to read.

The program also computes and outputs the user’s age in minutes.

2.7 Floating-point numbers (float)

Floating-point (float) variables

floating-point number is a real number, like 98.6, 0.0001, or -666.667. The term “floating-point” refers to the decimal point being able to appear anywhere (“float”) in the number. A variable declared as type float stores a floating-point number.

floating-point literal is a number with a fractional part, even if that fraction is 0, as in 1.0, 0.0, or 99.573. Good practice is to always have a digit before the decimal point, as in 0.5, since .5 might mistakenly be viewed as 5.

  1. The program declares three float variables milesTraveled, hoursToFly, and hoursToDrive. Each is automatically assigned with 0.0.
  2. The program gets input and assigns milesTraveled with 400.5.
  3. The assignment statement reads milesTraveled (400.5), divides by 500.0, and assigns hoursToFly with the result of 0.801.
  4. The assignment statement divides milesTraveled by 60.0 and assigns hoursToDrive with the result of 6.675.
  5. The program outputs the time to fly or drive 400.5 miles.

Scientific notation

A system may print large or small floating-point values using scientific notation. Ex: If a float variable holds the value 299792458.0 (the speed of light in m/s), the value may be printed as 2.99792e+08. The printed value may have some rounding for conciseness, and the power of 10 makes the number’s magnitude more apparent. The value held in the variable is unchanged.

Choosing a variable type (float vs. integer)

A programmer should choose a variable’s type based on the type of value held.

  • Integer variables are typically used for values that are counted, like 42 cars, 10 pizzas, or -95 days.
  • Floating-point variables are typically used for values that are measured, like 98.6 degrees, 0.00001 meters, or -666.667 grams.
  • Floating-point variables are also used when dealing with fractions of countable items, such as the average number of cars per household.

Note: Some programmers warn against using floating-point for money, as in 14.53 representing 14 dollars and 53 cents, because money is a countable item (reasons are discussed further in another section). Integers may be used to represent cents or to represent dollars when cents are not included, such as for an annual salary (e.g., 40000 dollars, which are countable).

Floating-point divide by zero

Dividing a nonzero floating-point number by zero results in infinity or -infinity, depending on the signs of the operands. Printing a floating-point variable that holds infinity or -infinity outputs Infinity or -Infinity.

If the dividend and divisor in floating-point division are both 0, the division results in a “not a number”. Not a number indicates an unrepresentable or undefined value. Printing a floating-point variable that is not a number outputs NotANumber.

Manipulating floating-point output

Some floating-point numbers have many digits after the decimal point. Ex: Irrational numbers (Ex: 3.14159265359…) and repeating decimals (Ex: 4.33333333…) have an infinite number of digits after the decimal. By default, most programming languages output at least 5 digits after the decimal point. But for many simple programs, this level of detail is not necessary. A common approach is to output floating-point numbers with a specific number of digits after the decimal to reduce complexity or produce a certain numerical type (Ex: Representing currency with two digits after the decimal). The syntax for outputting the float myfloat with three digits after the decimal point is
Put myfloat to output with 3 decimal places

When outputting a certain number of digits after the decimal using printf(), Coral rounds the last output digit, but the floating-point value remains the same.

2.8 Using math functions

Basics

Some programs require math operations beyond +, -, *, /, like computing a square root. Coral has a few built-in math operations, known as functions.

function is a list of statements executed by invoking the function’s name, with such invoking known as a function call. Any function input values, or arguments, appear within ( ), and are separated by commas if more than one. Below, the function SquareRoot is called with one argument, areaSquare. The function call evaluates to a value, as in SquareRoot(areaSquare) below evaluating to 7.0, which is assigned to sideSquare.

Table 2.8.1: Coral’s built-in math functions.

FunctionBehaviorExample
SquareRoot(x)Square root of xSquareRoot(9.0) evaluates to 3.0.
RaiseToPower(x, y)Raise x to power y: xyRaiseToPower(6.0, 2.0) evaluates to 36.0.
AbsoluteValue(x)Absolute value of xAbsoluteValue(-99.5) evaluates to 99.5.

Example: Mass growth

The example below computes the growth of a biological mass, such as a tree. If the growth rate is 5% per year, the program computes 1.05 raised to the number of years. A similar program could calculate growth of money given an interest rate.

Calls in arguments

Commonly a function call’s argument itself includes a function call. Below, xy is computed via RaiseToPower(x, y). The result is used in an expression that is an argument to another call, in this case to RaiseToPower() again: RaiseToPower(2.0, RaiseToPower(x, y) + 1).

  1.  x(^y) can be computed using RaiseToPower(x, y).
  2. A function’s argument can be an expression, including a call to another function. 2(xy+1) can be computed as RaiseToPower(2.0, RaiseToPower(x, y) + 1).
  3. Upon execution, if x = 3.0 and y = 2.0, then RaiseToPower(x, y) is called and evaluates to 9.0. Next, RaiseToPower(2.0, 9.0 + 1) is called, yielding 1024.0.

2.9 Random numbers

Generating a random number

Some programs need to use a random number. Ex: A game program may need to roll dice, or a website program may generate a random initial password.

The RandomNumber() function is a built-in Coral function that takes two arguments, lowValue and highValue, and returns a random integer in the range lowValue to highValue. Ex: RandomNumber(1, 10) returns a random integer in the range 1 to 10.

Pseudo-random

The integers generated by RandomNumber() are known as pseudo-random. “Pseudo” means “not actually, but having the appearance of”. Internally, the RandomNumber() function has an equation to compute the next “random” integer from the previous one, (invisibly) keeping track of the previous one. For the first call to RandomNumber(), no previous random integer exists, so the function uses a built-in integer known as the seed. Coral automatically seeds the pseudo-random number generator with a number based on the current time. Since, the time is different for each program run, the program will get a unique sequence.

Reproducibility is important for testing some programs. A programmer can specify the seed using the function SeedRandomNumbers(), as in SeedRandomNumbers(10) or SeedRandomNumbers(99). Note that the seeding should only be done once in a program, before the first call to RandomNumber().

2.10 Integer division

Division: Integer rounding

When the operands of / are both integers, the operator performs integer division, which does not generate any fraction. The / operator performs floating-point division if at least one operand is a floating-point type.

  1. If both operands of / are integers, the operator performs integer division: No fractional part is generated. Thus 10 / 4 is 2, not 2.5. And 3 / 4 is 0, not 0.75.
  2. Programmers may forget, causing strange logic errors. (1 / 2) * b * h is always (0) * b * h or 0. And c * (9 / 5) + 32 is always c * (1) + 32.
  3. The same applies for integer variables. No fraction is generated for y = w / x if w and x are integers, even if y is a floating-point type.
  4. If at least one operand of / is a floating-point type, then floating-point division occurs. So if integer w = 10 and float x = 4.0, then w / x is 2.5.

2.11 Type conversions

Type conversions

A calculation sometimes must mix integer and floating-point numbers. For example, given that about 50.4% of human births are males, then 0.504 * numBirths calculates the number of expected males in numBirths births. If numBirths is an integer variable (integer because the number of births is countable), then the expression combines a floating-point and integer.

type conversion is a conversion of one data type to another, such as an integer to a float. Coral automatically performs several common conversions between integer and float types, and such automatic conversion is known as implicit conversion.

  • For an arithmetic operator like + or *, if either operand is a float, the other is automatically converted to float, and then a floating-point operation is performed.
  • For assignments, the right side type is converted to the left side type.

integer-to-float conversion is straightforward: 25 becomes 25.0.

float-to-integer conversion just drops the fraction: 4.9 becomes 4.

  1. 0.504 is a floating-point literal. numBirths is an integer variable. Coral sees “float * integer” and performs an implicit integer-to-float type conversion.
  2. If numBirths is 316, 316 is first converted 316.0.
  3. Then, the program computes 0.504 * 316.0 yielding 159.264. expectedMales is a float variable and is assigned with that result.
  1. 0.504 is a floating-point literal. numBirths is an integer variable. Coral sees “float * integer” and performs an implicit integer-to-float type conversion.
  2. If numBirths is 316, 316 is first converted 316.0.
  3. Then, the program computes 0.504 * 316.0 yielding 159.264. expectedMales is a float variable and is assigned with that result.

Type casting

A programmer sometimes needs to explicitly convert an item’s type. Ex: If a program needs a floating-point result from dividing two integers, then at least one of the integers needs to be converted to a float so floating-point division is performed. Otherwise, integer division is performed, evaluating to only the quotient and ignoring the remainder.

type cast converts a value of one type to another type. A programmer can type cast an integer to float by multiplying the integer by the float literal 1.0. Ex: If myIntVar is 7, then myIntVar * 1.0 converts integer 7 to float 7.0.

The program below casts the numerator to float so floating-point division is performed.

Common errors

A common error is to accidentally perform integer division when floating-point division was intended. The program below undesirably performs integer division rather than floating-point division.

Another common error is to cast the entire result of integer division, rather than the operands, thus not obtaining the desired floating-point division.

  1. The programmer wants to use floating-point division to compute the average of midtermScore (an integer) and finalScore (an integer).
  2. (midtermScore + finalScore) is evaluated first. If midtermScore is 90 and finalScore is 85, the expression evaluation to (90 + 85) or 175.
  3. Next, 175 / 2 is evaluated. Both operands are integers, so integer divisions is performed, yielding 87.
  4. Multiplying by 1.0 converts 87 to 87.0. Casting the result of integer division does not perform the desired floating-point division.

2.12 Modulo operator

The basic arithmetic operators include not just +, -, *, /, but also %. The modulo operator (%) evaluates to the remainder of the division of two integer operands. Ex: 23 % 10 is 3.

Examples:

  • 24 % 10 is 4. Reason: 24 / 10 is 2 with remainder 4.
  • 50 % 50 is 0. Reason: 50 / 50 is 1 with remainder 0.
  • 1 % 2 is 1. Reason: 1 / 2 is 0 with remainder 1.
  • 10 % 4.0 is not valid. “Remainder” only makes sense for integer operands.

2.13 Data types

A programmer should choose a data type that best matches the value being held or represented. The following describes common data types used in most programming languages.Table 2.13.1: Common data types.

Data typeDescription
IntegerAn integer is a whole number value, like 1, 999, 0, or -25.
FloatA float is a floating-point number, which is a real number, like 98.6, 0.0001, or -666.667.
CharacterA character is a single letter, like ‘A’, ‘p’, or ‘%’.
StringA string is a sequence of characters, like “Hello” or “The forecast for today is sunny with highs of 75F.”.
BooleanA Boolean refers to a quantity that has only two possible values, true or false.
ArrayAn array is an ordered list of items of a given data type, like an array of integers or an array of floats.

Coral supports variables of integer, float, and array data type, string literals that can be put to output, and Boolean values resulting for equality, relational, or logical operators.

2.14 Constants

constant is a named value item that holds a value that cannot change. Constants are commonly used in programs to hold the value of mathematical or physical constants, such as Pi, the speed of light, or kilograms per pound. Constants can also be used for any value that should not change during the program’s execution.

A good practice is to minimize the use of literal numbers in code by using constants to improve code readability. Ex: newPrice = origPrice – 5 is less clear than newPrice = origPrice – PRICE_DISCOUNT, where PRICE_DISCOUNT is a constant.

A common convention, or good practice, is to name constants using upper case letters with words separated by underscores, to make constants clearly visible.

  1. A constant is a named value item that holds a value that cannot change. SOUND_SPEED is a float constant holding the speed of sound at sea level in miles/hour.
  2. SEC_PER_HOUR is an integer constant holding the number of seconds in one hour.
  3. The program gets the time between seeing lightning and hearing thunder, and then estimates how far away the lightning strike was.
  4. Constants can be used in expressions. SEC_PER_HOUR is used to calculate the time in hours, and SOUND_SPEED is used to calculate the distance in miles.

2.15 Code: Variables and assignments

A programmer can use code to describe a flowchart’s variables and statements by:

  1. Declaring each variable’s type and name, one variable declaration per line. Ex: integer userAge declares the variable named userAge of type integer.
  2. Listing each program statement in order, one statement per line.

To provide separation between different parts of a program, variable declarations and program statements are often separated by a blank line, which is considered whitespace and not part of the program structure.

  1. A program’s variables are declared by specifying the type and name, one per line.
  2. A program’s statements are listed in order of execution, one statement per line. A blank line separates the variable declarations and statements for readability, but is not required in code.

2.16 Variables/Assignments Summary

This chapter’s key points included:

  • A variable declaration declares a new variable, specifying the variable’s name and type.
  • An assignment statement assigns the variable on the left-side of the = with the current value of the right-side expression.
  • An expression is a combination of items, like variables, literals, operators, and parentheses, that evaluates to a value.
  • A name created by a programmer for an item like a variable or function is called an identifier, which must follow certain rules to be valid. Programmers typically follow identifier naming conventions that are defined by their company, team, teacher, etc.
  • An expression is evaluated using precedence rules that follow the evaluation order of standard mathematics.
  • Incremental development is the process of writing and testing a small amount of code, then writing and testing a small amount more (an incremental amount), and so on.
  • A variable declared as type float stores a floating-point number, which is a real number, like 98.6, 0.0001, or -666.667.
  • A programmer should choose a variable’s type based on the type of value held. Integer variables are typically used for values that are counted. Floating-point variables are typically used for values that are measured or when dealing with fractions of countable items, such as the average number of cars per household.
  • Programming languages typically have built-in functions to perform common operations needed by programmers, such as performing mathematical operations like square root or raising a number to a power.
  • A function is a list of statements executed by invoking the function’s name, with such invoking known as a function call.
  • Programming languages typically have built-in functions for generating random numbers. The integers generated by a random number generator are known as pseudo-random. “Pseudo” means “not actually, but having the appearance of”. Internally, the RandomNumber() function has an equation to compute the next “random” integer from the previous one.
  • When the operands of / are both integers, the operator performs integer division, which does not generate any fraction.
  • For integer division, the second operand of / or % must never be 0, because division by 0 is mathematically undefined. A divide-by-zero error occurs at runtime if a divisor is 0, causing a program to terminate.
  • A type conversion is a conversion of one data type to another, such as an integer to a float.
  • zyFlowchart, and other programming languages, automatically performs several common conversions between integer and float types, and such automatic conversion is known as implicit conversion.
  • If a programmer needs to explicitly convert an item’s type, the programmer can use a type cast to converts value of one type to another type.
  • The modulo operator (%) evaluates to the remainder of the division of two integer operands.
  • A constant is a named value item that holds a value that cannot change. Constants are commonly used in programs to hold the value of mathematical constants or a value that should not change during the program’s execution.


Leave a Reply

Your email address will not be published. Required fields are marked *