0% found this document useful (0 votes)
15 views9 pages

Variables and Constants in Programming

Chapter 2 of 'Programming Logic and Design' focuses on declaring and using variables and constants in programming. It explains the importance of variables as named memory locations that can hold varying values, the need for declarations before use, and the distinction between named and unnamed constants. Additionally, it covers naming conventions for variables, data types, and the process of assigning values to variables through assignment statements.

Uploaded by

josephjshowers23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views9 pages

Variables and Constants in Programming

Chapter 2 of 'Programming Logic and Design' focuses on declaring and using variables and constants in programming. It explains the importance of variables as named memory locations that can hold varying values, the need for declarations before use, and the distinction between named and unnamed constants. Additionally, it covers naming conventions for variables, data types, and the process of assigning values to variables through assignment statements.

Uploaded by

josephjshowers23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PROGRAMMING LOGIC AND DESIGN

CHAPTER 2: WORKING WITH DATA

In this chapter, you will learn about:


 Declaring and using variables and constants
 Assigning values to variables

DECLARING AND USING VARIABLES AND CONSTANTS


As you learned in Chapter 1, data items include all the text, numbers, and other
information that are processed by a computer. When you input data items into a
computer, they are stored in variables in memory where they can be processed and
converted to information that is output.
When you write programs, you work with data in three different forms: variables;
literals, or unnamed constants; and named constants.

Working with Variables


Variables are named memory locations whose contents can vary or differ over time.
For example, in the number-doubling program in Figure below, myNumber and
myAnswer are variables. At any moment in time, a variable holds just one value.
Sometimes, myNumber holds 2 and myAnswer holds 4; at other times, myNumber
holds 6 and myAnswer holds 12. The ability of variables to change in value is what
makes computers and programming worthwhile. Because one memory location can
be used repeatedly with different values, you can write program instructions once
and then use them for thousands of separate calculations. One set of payroll
instructions at your company produces each individual’s paycheck, and one set of
instructions at your electric company produces each household’s bill.

IBSA College Notes 1


PROGRAMMING LOGIC AND DESIGN

Flowchart and pseudocode for the number-doubling program

In most programming languages, before you can use any variable, you must include
a declaration for it. A declaration is a statement that provides a data type and an
identifier for a variable. An identifier is a variable’s name. A data item’s data type
is a classification that describes the following:

What values can be held by the item


 How the item is stored in computer memory
 What operations can be performed on the data item

In this book, two data types will be used: num and string. When you declare a
variable, you provide both a data type and an identifier.
Optionally, you can declare a starting value for any variable. Declaring a starting
value is known as initializing the variable. For example, each of the following
statements is a valid declaration. Two of the statements include initializations, and
two do not:

num mySalary
num yourSalary = 14.55

IBSA College Notes 2


PROGRAMMING LOGIC AND DESIGN

string myName
string yourName = "Juanita"

The figure below shows the number-doubling program from Figure above with the
added declarations shaded. Variables must be declared before they are used in a
program for the first time.

Flowchart and pseudocode of number-doubling program with variable declarations

In many programming languages, if you declare a variable and do not initialize it,
the variable contains an unknown value until it is assigned a value. A variable’s
unknown value is commonly called garbage. In many languages it is illegal to use a
garbage-holding variable in an arithmetic statement or to display it as output. Even
if you work with a language that allows you to display garbage, it serves no purpose
to do so and constitutes a logical error. When you create a variable without
assigning it an initial value (as with myNumber and myAnswer in Figure above),
your intention is to assign a value later—for example, by receiving one as input or
placing the result of a calculation there.

IBSA College Notes 3


PROGRAMMING LOGIC AND DESIGN

Naming Variables
The number-doubling example in Figure above requires two variables: myNumber
and myAnswer. Alternatively, these variables could be named userEntry and
programSolution, or inputValue and twiceTheValue. As a programmer, you choose
reasonable and descriptive names for your variables. The language interpreter then
associates the names you choose with specific memory addresses.

Every computer programming language has its own set of rules for creating
identifiers. Most languages allow letters and digits within variable names. Some
languages allow hyphens in variable names, such as hourly-wage, and some allow
underscores, as in hourly-wage. Other languages allow neither. Some languages
allow dollar signs or other special characters in variable names (for example,
hourly$); others allow foreign-alphabet characters, such as Ω or ∆ .

Different languages put different limits on the length of variable names, although in
general, the length of identifiers in newer languages is virtually unlimited. In many
languages, identifiers are case sensitive, so HoUrLyWaGe, hourlywage, and
hourlyWage are three separate variable names. The format used in the last
example, in which the variable starts with a lowercase letter and any subsequent
word begins with an uppercase letter, is called camel casing— variable names
such as hourlyWage have a “hump” in the middle. The variable names in this book
are shown using camel casing.

Even though every language has its own rules for naming variables, you should not
concern yourself with the specific syntax of any particular computer language when
designing the logic of a program.
The logic, after all, works with any language. The variable names used throughout
this book follow only two rules:

1. Variable names must be one word. The name can contain letters, digits,
hyphens, underscores, or any other characters you choose, with the exception of
spaces. Therefore, r is a legal variable name, as are rate and interestRate. The
variable name interest rate is not allowed because of the space.

IBSA College Notes 4


PROGRAMMING LOGIC AND DESIGN

2. Variable names should have some appropriate meaning. This is not a


formal rule of any programming language. When computing an interest rate in a
program, the computer does not care if you call the variable g, u84, or fred. As long
as the correct numeric result is placed in the variable, its actual name doesn’t really
matter. However, it’s much easier to follow the logic of a statement like set
finalBalance = initialInvestment * interestRate, than a statement like set f = i * r, or
set someBanana = j89 * myFriendLinda.
When a program requires changes, which could be months or years after you write
the original version, you and your fellow programmers will appreciate clear,
descriptive variable names in place of cryptic identifiers.

Notice that the flowchart in Figure above follows the preceding two rules for
variables: both variable names, myNumber and myAnswer, are one word without
embedded spaces, and they have appropriate meanings. Some programmers name
variables after friends or create puns with them, but computer professionals
consider such behavior unprofessional and amateurish.

Understanding Unnamed, Literal Constants and their Data Types


Computers deal with two basic types of data—text and numeric. When you use a
specific numeric value, such as 43, within a program, you write it using the digits
and no quotation marks.
A specific numeric value is often called a numeric constant (or literal numeric
constant) because it does not change—a 43 always has the value 43. When you
use a specific text value, or string of characters, such as “Amanda”, you enclose the
string constant (or literal string constant) within quotation marks. The
constants 43 and “Amanda” are examples of unnamed constants—they do not
have identifiers like variables do.

Understanding the Data Types of Variables


Like literals, variables can also be different data types.
A numeric variable is one that can hold digits and have mathematical operations
performed on it. Also, you usually have the option of having a numeric variable hold
a decimal point and a sign indicating positive or negative. In the statement set
myAnswer = myNumber * 2, both

IBSA College Notes 5


PROGRAMMING LOGIC AND DESIGN

myAnswer and myNumber are numeric variables; that is, their intended contents
are numeric values, such as 6 and 3, 14.8 and 7.4, or −18 and −9.

A string variable can hold text, such as letters of the alphabet, and other special
characters, such as punctuation marks. If a working program contains the
statement set lastName = "Lincoln", then lastName is a string variable. A string
variable can also hold digits either with or without other characters. For example,
“235 Main Street” and “86” are both strings. A string like “86” is stored differently
than the numeric value 86, and you cannot perform arithmetic with the string.

You can assign data to a variable only if it is the correct type. If you declare taxRate
as a numeric variable and inventoryItem as a string, then the following statements
are valid:
set taxRate = 2.5
set inventoryItem = "monitor"

Declaring Named Constants


Besides variables, most programming languages allow you to create named
constants. A named constant is similar to a variable, except it can be assigned a
value only once. You use a named constant when you want to assign a useful name
to a value that will never be changed during a program’s execution. Using named

IBSA College Notes 6


PROGRAMMING LOGIC AND DESIGN

constants makes your programs easier to understand by eliminating magic


numbers.
A magic number is an unnamed constant, like 0.06, whose purpose is not
immediately apparent.

For example, if a program uses a sales tax rate of 6%, you might want to declare a
named constant as follows:
num SALES_TAX = 0.06
You then might use SALES_TAX in a program statement similar to the following:
set taxAmount = price * SALES_TAX

The way in which named constants are declared differs among programming
languages. This book follows the convention of using all uppercase letters in
constant identifiers, and using underscores to separate words for readability. Using
these conventions makes named constants easier to recognize.

When you declare a named constant, program maintenance becomes easier. For
example, if the value of the sales tax changes from 0.06 to 0.07 in the future, and
you have declared a named constant SALES_TAX, then you only need to change the
value assigned to the named constant at the beginning of the program, and all
references to SALES_TAX are automatically updated. If you have used the unnamed
literal 0.06 instead, you would have to search for every instance of the value and
replace it with the new one.

Assigning Values to Variables


When you create a flowchart or pseudocode for a program that doubles numbers,
you can include a statement such as the following:
set myAnswer = myNumber * 2
Such a statement is an assignment statement. This statement incorporates two
actions. First, the computer calculates the arithmetic value of myNumber * 2.
Second, the computed value is stored in the myAnswer memory location.
The equal sign is the assignment operator. The assignment operator always
operates from right to left; the value of the expression to the right of the operator is
evaluated before the assignment to the operand on the left occurs. The operand to

IBSA College Notes 7


PROGRAMMING LOGIC AND DESIGN

the right of an assignment statement can be a value, a formula, a named constant,


or a variable. The operand to the left of an assignment operator must be a name
that represents a memory address—the name of the location where the result will
be stored.
For example, if you have declared a numeric variable named someNumber, then
each of the following is a valid assignment statement:
set someNumber = 2
set someNumber = 3 + 7
Additionally, if you have declared another numeric variable named
someOtherNumber and assigned a value to it, then each of the following is a valid
assignment statement:
set someNumber = someOtherNumber
set someNumber = someOtherNumber * 5

IBSA College Notes 8


PROGRAMMING LOGIC AND DESIGN

IBSA College Notes 9

You might also like