0% found this document useful (0 votes)
102 views39 pages

DCIT104 Lecture 3

This lecture covers whitespace, variables, assignments, and identifiers in programming fundamentals. It discusses why precise formatting is important in programming and considers variables, their declaration and initialization, and assignment statements. The lecture outline includes whitespace and formatting, variables and assignments, variable types like integers, and style guidelines for identifiers.

Uploaded by

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

DCIT104 Lecture 3

This lecture covers whitespace, variables, assignments, and identifiers in programming fundamentals. It discusses why precise formatting is important in programming and considers variables, their declaration and initialization, and assignment statements. The lecture outline includes whitespace and formatting, variables and assignments, variable types like integers, and style guidelines for identifiers.

Uploaded by

Muel Opoku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

DCIT 104

PROGRAMMING
FUNDAMENTALS

Lecture 3 – Whitespaces, Variables, Assignments, and


Identifiers
Lecturer: Dr. Moses Akazue
Contact Information: [email protected]
Session Overview

This lecture starts by considering why whitespaces


and precise formatting matters in programming is
important. We then go further to study variables
(types, declaration and initialization), assignment
statements, identifiers, rules for identifiers and style
guidelines for identifiers
Session Outline

• White spaces and precise formatting


• Variables and assignments
• Variable declaration and initialization
• Int variable type
• Assignment statements
• Identifiers and style guidelines for identifiers
Whitespace and Precise Formatting

For program output, whitespace is any blank space or newline. Most


coding activities strictly require a student program's output to exactly
match the expected output, including whitespace. Students learning
programming often complain:

"My program is correct, but the system is complaining about output


whitespace. ”

However, correctness often includes output being formatted correctly.

Google Confidential and Proprietary


zyBooks
Precisely Formatting a Meeting Invite

Google Confidential and Proprietary


zyBooks
Programming is All About Precision

Programming is all about precision. Programs must be created precisely


to run correctly. Ex:

• = and == have different meanings.


• Using i where j was meant can yield a hard-to-find bug.
• Declaring a variable as int when char was needed can cause confusing
errors.
• Not considering that n could be 0 in sum/n can cause a program to fail
entirely in rare but not insignificant cases.
• The difference between typing x/2 vs. x/2.0 can have huge impacts.
• Counting from i being 0 to i < 10 vs. i <= 10 can mean the difference
between correct output and a program outputting garbage.
Google Confidential and Proprietary
zyBooks
Participation Activity 1

Consider the example above.


1. The programmer on the left intentionally inserted a newline in the first sentence, namely "Kia
Smith ... video meeting". Why?
a) Probably a mistake
b) So the text appears less jagged
c) To provide some randomness to the output
2. The programmer on the right did not end the first sentence with a newline. What effect did that
omission have?
a) "Join meeting" appears on the same line
b) No effect
3. The programmer on the left neatly formatted the link, the "Phone:" text, and phone numbers.
What did the programmer on the right do?
a) Also neatly formatted those items
b) Output those items without neatly formatting
4. On the right, why did the "Reminder..." text appear on the same line as the separator text "------"?
a) Because programs behave erratically
b) Because the programmer didn't end the output with a newline
5. Whitespace _____ important in program output.
a) is
b) is not Google Confidential and Proprietary
Programming is All About Precision

• In programming, every little detail counts. Programmers must get in a


mindset of paying extreme attention to detail.
• Another reason for caring about whitespace in program output is to
help new programmers get into a "precision" mindset when
programming.
• Paying careful attention to details like whitespace instructions,
carefully examining feedback regarding whitespace differences, and
then modifying a program to exactly match expected whitespace is an
exercise in strengthening attention to detail.
• Such attention can lead programmers to make fewer mistakes when
creating programs, thus spending less time debugging, and instead
creating programs that work correctly
Google Confidential and Proprietary
zyBooks
Participation Activity 2

Programmers benefit from having a mindset of thinking precisely and paying attention to
details. The following questions emphasize attention to detail. See if you can get all of
the questions correct on the first try.

1. How many times is the letter F (any case) in the following?


If Fred is from a part of France, then of course Fred's French is good.
2. How many differences are in these two lines?
Printing A linE is done using printIn
Printing A linE is done using print1n
3. How many typos are in the following?
Keep calmn and cary one.
4. If I and E are adjacent, I should come before E, except after C (where E should come
before I). How many violations are in the following?
BEIL CEIL ZIEL YIEIK TREIL
5. A password must start with a letter, be at least 6 characters long, include a number,
and include a special symbol. How many of the following passwords are valid?
Google Confidential and Proprietary
hello goodbye Maker1 dog!three Oops_again 1augh#3
Programmer Attention to Details

The focus needed to answer the above correctly on the first try is the
kind of focus needed to write correct programs. Due to this fact, some
employers give "attention to detail" tests to people applying for
programming positions.

See for example this test, or this article discussing the issue. Or, just web
search for "programmer attention to details" for more such tests and
articles.

Google Confidential and Proprietary


C++ Example: Salary Calculation

The following program calculates yearly and monthly salary given an hourly wage. The
program assumes a work-hours-per-week of 40 and work-weeks-per-year of 50.

• Type the code below into your IDE and change the incorrect code to print a monthly
salary. Then run the program.

Google Confidential and Proprietary


C++ Example: Married Couples Names

• Gustav Kissiedu and Akua Mperey are engaged. What are


possible last name combinations for the married couple
(listing Gustav first)?

• Copy the program code on the next slide into your IDE and
run the program to see three possible married-couple names.

• Extend the program to print the two hyphenated last name


options (Kissiedu-Mperey, and Mperey-Kissiedu). Run the
program again.

Google Confidential and Proprietary


zyBooks
C++ Example: Married Couples Names Code

#include <iostream>
#include <string>
using namespace std;

int main() {
string firstName1;
string lastName1;
string firstName2;
string lastName2;

cout << "What is the first person's first name?" << endl;
cin >> firstName1;
cout << "What is the first person's last name?" << endl;
cin >> lastName1;

cout << "What is the second person's first name?" << endl;
cin >> firstName2;
cout << "What is the second person's last name?" << endl;
cin >> lastName2;

cout << "Here are some common married-couple names:" << endl;
cout << firstName1 << " " << lastName1 << " and " << firstName2 << " " << lastName2 << endl;
cout << firstName1 << " and " << firstName2 << " " << lastName1 << endl;
cout << firstName1 << " and " << firstName2 << " " << lastName2 << endl;
// FIXME: Print two hyphenated last name options, with either last name
// appearing first. (A hyphen can be written as "-")

return 0; Google Confidential and Proprietary


}
Variables and Assignments

In a program, a variable is a named item, such as x or numPeople,


used to hold a value.
• An assignment assigns a variable with a value, such as x = 5. That
assignment means x is assigned with 5, and x keeps that value
during subsequent assignments, until x is assigned again.
• An assignment's left side must be a variable. The right side can be
an expression, so an assignment may be x = 5, y = x, or z = x + 2.
The 5, x, and x + 2 are each an expression that evaluates to a value.

= 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 value being put into a
box. Google Confidential and Proprietary
zyBooks
Variables and Assignments

Google Confidential and Proprietary


zyBooks
Assignments with Variable on Left and Right

Because in programming = means assignment, a variable


may appear on both the left and right as in x = x + 1.

• If x was originally 6, x is assigned with 6 + 1, or 7. The


assignment overwrites the original 6 in x.
• Increasing a variable's value by 1, as in x = x + 1, is
common, and known as incrementing the variable.

Google Confidential and Proprietary


zyBooks
A Variable May Appear on the Left or Right

Google Confidential and Proprietary


zyBooks
Variables (int): Variable Declarations

• A variable declaration is a statement that declares a new variable,


specifying the variable's name and type.
• Ex: int userAge; declares a new variable named userAge that
can hold an integer value.
• The compiler allocates a memory location for userAge capable of
storing an integer.
• Ex: In the animation below, the compiler allocated userAge to
memory location 97, which is known as the variable's address.
• The choice of 97 is arbitrary and irrelevant to the programmer, but
the idea that a variable corresponds to a memory location is
important to understand.
Google Confidential and Proprietary
zyBooks
Variables (int)

• When a statement that assigns a variable with a value


executes, the processor writes the value into the variable's
memory location.
• Likewise, reading a variable's value reads the value from
the variable's memory location.
• The programmer must declare a variable before any
statement that assigns or reads the variable, so that the
variable's memory location is known.

Google Confidential and Proprietary


zyBooks
A Variable Refers to a Memory Location

Google Confidential and Proprietary


zyBooks
Computer Optimization

Modern compilers may optimize variables away, allocate


variables on the stack, or use registers for variables. However,
the conceptual view of a variable in memory helps understand
many language aspects.

Google Confidential and Proprietary


zyBooks
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). assign
• 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).
• An integer like 80 appearing in an expression is known as
an integer literal.
Google Confidential and Proprietary
zyBooks
Assigning a Variable

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.

Google Confidential and Proprietary


zyBooks
Challenge Activity 1: Assigning a Sum

Using the code stub below, write a statement that assigns numCoins with
numNickels + numDimes. E.g.,: 5 nickels and 6 dimes results in 11 coins.
•Note: These activities may test code with different test values. This activity will perform
two tests: the first with nickels = 5 and dimes = 6, the second with nickels = 9 and dimes =
0.
#include <iostream>
using namespace std;

int main() {
int numCoins;
int numNickels;
int numDimes;

numNickels = 5;
numDimes = 6;

/* Your solution goes here */

cout << "There are " << numCoins << " coins" << endl;

return 0;
Google Confidential and Proprietary
}
Initializing Variables

• Although not required, an integer variable is often assigned an initial value


when declared.
– Ex: int maxScore = 100; declares an int variable named maxScore with
an initial value of 100.
– See example program below

Google Confidential and Proprietary


zyBooks
Participation Activity 3: Declaring/Initializing Variables

1. Declare an integer variable named numDogs, initializing the


variable to 0 in the declaration.

2. Declare an integer variable named daysCount, initializing the


variable to 365 in the declaration.

Google Confidential and Proprietary


zyBooks
Challenge Activity 2: Declaring/Initializing Variables

• Using the code stub below, write one statement that declares an
integer variable numHouses initialized to 25

#include <iostream>
using namespace std;

int main() {

/* Your solution goes here */

cout << numHouses << endl;

return 0;
}
Google Confidential and Proprietary
Assignment Statement with Same Variable on Both Side

• Commonly, a variable appears on both the right and left side of


the = operator.
– Ex: If numItems is 5, after numItems = numItems +
1 executes, numItems will be 6.
• The statement reads the value of numItems (5), adds 1, and
assigns numItems with the result of 6, which replaces the value
previously held in numItems.

Google Confidential and Proprietary


zyBooks
Variable Assignments Overwrite a Variable’s Previous Values

Google Confidential and Proprietary


zyBooks
Challenge Activity 3: Adding a Number to a Variable

• Using the code stub below, write a statement that increases numPeople by 5.
– Ex: If numPeople is initially 10, the output is: There are 15 people.

#include <iostream>
using namespace std;

int main() {
int numPeople;

cin >> numPeople;

/* Your solution goes here */

cout << "There are " << numPeople << " people." << endl;

return 0;
}
Google Confidential and Proprietary
zyBooks
Common Errors

• A common error is to read a variable that has not yet been assigned
a value.
• If a variable is declared but not initialized, the variable's memory
location contains some unknown value, commonly but not always
0.
• A program with an uninitialized variable may thus run correctly on
system that has 0 in the memory location, but then fail on a
different system—a very difficult bug to fix.
• A programmer must ensure that a program assigns a variable with a
value before reading.

Google Confidential and Proprietary


zyBooks
Common Errors

• A common error by new programmers is to write an


assignment statement in reverse.
– Ex: numKids + numAdults = numPeople, or 9 =
beansCount.
– Those statements won't compile, but writing numCats =
numDogs in reverse will compile, leading to a hard-to-find
bug.

Google Confidential and Proprietary


zyBooks
Identifiers

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 or underscore
• Note that "_", called an underscore, is considered to be a letter.
• Identifiers are case sensitive, meaning upper and lower case
letters differ. So numCats and NumCats are different.

Google Confidential and Proprietary


zyBooks
Identifiers: Reserved Word

• A reserved word is a word that is part of the language, like


int, short, or double.
• A reserved word is also known as a keyword. A programmer
cannot use a reserved word as an identifier.
• Many language editors will automatically colour a
program's reserved words.
• A list of reserved words appears at the end of this section.

Google Confidential and Proprietary


zyBooks
Style Guide for Identifiers

• While various (crazy-looking) identifiers may be valid,


programmers may follow identifier naming conventions (style)
defined by their company, team, teacher, etc. Two common
conventions for naming variables are:
– Camel case: Lower camel case abuts multiple words,
capitalizing each word except the first, as in numApples or
peopleOnBus.
– Underscore separated: Words are lowercase and separated by
an underscore, as in num_apples or people_on_bus.
• Neither convention is better. The key is to be consistent so code is
easier to read and maintain.
Google Confidential and Proprietary
zyBooks
Style Guide for Identifiers

• Good practice is to create meaningful identifier names that


self-describe an item's purpose.
• Good practice minimizes use of abbreviations in identifiers
except for well-known ones like num in numPassengers.
• Programmers must strive to find a balance. Abbreviations
make programs harder to read and can lead to confusion.
• Long variable names, such as
averageAgeOfUclaGraduateStudent may be meaningful, but
can make subsequent statements too long and thus hard to
read.
Google Confidential and Proprietary
zyBooks
Naming Conventions

In this course, lower camel case is used for variable naming.


This material strives to follow another good practice of using
two or more words per variable such as numStudents rather
than just students, in order to:
• Provide meaningfulness,
• Make variables more recognizable when variable names
appear in writing like in this text or in a comment
• Reduce conflicts with reserved words or other
already-defined identifiers.

Google Confidential and Proprietary


zyBooks
C++ Reserved Words/Keywords

Google Confidential and Proprietary


zyBooks
References

• Felleisen, M., Findler, R. B., Flatt, M., & Krishnamurthi, S.


(2011). How to Design Programs: An Introduction to
Programming and Computing, Cambridge, MA: MIT Press
• Frank Vahid, and Roman Lysecky (2019). Programming in
C++, August 2019. zyBook ISBN: 978-1-5418-9966-7

Google Confidential and Proprietary

You might also like