Programming Fundamentals 1674091002
Programming Fundamentals 1674091002
Programming
Fundamentals
Contents xv
Author Acknowledgements 5
Chapter I. Introduction to
Programming
Strings 459
String Functions 462
Dave Braunschweig
String Formatting 465
File Input and Output 468
Kenneth Leroy Busbee
Loading an Array from a Text File 474
Program Plan 478
C++ Examples 480
Dave Braunschweig
C# Examples 484
Dave Braunschweig
Java Examples 488
Dave Braunschweig
JavaScript Examples 491
Dave Braunschweig
Python Examples 495
Dave Braunschweig
Swift Examples 498
Dave Braunschweig
Practice: Strings and Files 502
Kenneth Leroy Busbee
Exception Handling 507
• Preface
• Introduction to Programming
• Data and Operators
• Functions
• Conditions
• Loops
• Arrays
• Strings and Files
• Object-Oriented Programming
Contents | xv
About this Book
A Note to Readers
Dave Braunschweig
Learning Modules
Conceptual Approach
The learning modules of this textbook were, for the most part,
written without consideration of a specific programming
language. Concepts are presented generically, with program
logic demonstrated first in pseudocode and flowchart format.
Language-specific examples follow the general overview.
References
Author Acknowledgements | 5
happened.
6 | Author Acknowledgements
Dave Braunschweig
References
Author Acknowledgements | 7
CHAPTER I
INTRODUCTION TO
PROGRAMMING
Overview
Chapter Outline
◦ C++
◦ C#
◦ Java
Introduction to Programming | 9
◦ JavaScript
◦ Python
◦ Swift
• Practice
Learning Objectives
10 | Introduction to Programming
Systems Development
Life Cycle
KENNETH LEROY BUSBEE
Overview
Discussion
Key Terms
applications
An information system or collection of programs that
handles a major task.
implementation
The phase of a Systems Development Life Cycle where the
programmers would be assigned to write specific
programs.
life cycle
Systems Development Life Cycle: Planning – Analysis –
Design – Implementation – Maintenance
system analyst
Computer professional in charge of creating applications.
References
Overview
• Inputs
• Processing
• Outputs
14 | Program Design
This IPO approach works very well for beginning programmers.
Sometimes, it might help to visualize the program running
on the computer. You can imagine what the monitor will look
like, what the user must enter on the keyboard and what
processing or manipulations will be done.
At first, you will not need a hierarchy chart because your first
programs will not be complex. But as they grow and become
more complex, you will divide your program into several
modules (or functions).
Program Design | 15
application software that helps create an information system
and/or programs. This type of software is called Computer-
Aided Software Engineering (CASE).
Key Terms
IPO
Inputs – Processing – Outputs
pseudocode
English-like statements used to convey the steps of an
algorithm or function.
test data
Providing input values and predicting the outputs.
References
16 | Program Design
Program Quality
DAVE BRAUNSCHWEIG
Overview
Discussion
Program Quality | 17
purpose or in some cases even unanticipated purposes.
Such issues can make or break its success even regardless
of other issues. This involves a wide range of textual,
graphical and sometimes hardware elements that
improve the clarity, intuitiveness, cohesiveness, and
completeness of a program’s user interface.
• Portability: the range of computer
hardware and operating system platforms on which the
source code of a program can be compiled/
interpreted and run. This depends on differences in the
programming facilities provided by the different
platforms, including hardware and operating system
resources, expected behavior of the hardware and
operating system, and availability of platform specific
compilers (and sometimes libraries) for the language of
the source code.
• Maintainability: the ease with which a program can be
modified by its present or future developers in order to
make improvements or customizations,
fix bugs and security holes, or adapt it to new
environments. Good practices during initial development
make the difference in this regard. This quality may not be
directly apparent to the end user but it can significantly
affect the fate of a program over the long term.
• Efficiency/performance: the measure of system resources
a program consumes (processor time, memory space,
slow devices such as disks, network bandwidth and to
some extent even user interaction): the less, the better.
This also includes careful management of resources, for
example cleaning up temporary files and
eliminating memory leaks.
• Readability: the ease with which a human reader can
comprehend the purpose, control flow, and operation of
source code. It affects the aspects of quality above,
including portability, usability and most importantly
18 | Program Quality
maintainability. Readability is important because
programmers spend the majority of their time reading,
trying to understand and modifying existing source code,
rather than writing new source code. Unreadable code
often leads to bugs, inefficiencies, and duplicated code.
Key Terms
efficiency
The measure of system resources a program consumes.
maintainability
The ease with which a program can be modified by its
present or future developers.
portability
The range of computer hardware and operating
system platforms on which the source code of a program
can be compiled/interpreted and run.
readability
The ease with which a human reader can comprehend the
purpose, control flow, and operation of source code.
reliability
How often the results of a program are correct.
robustness
How well a program anticipates problems due to errors.
usability
The ease with which a person can use the program.
References
Program Quality | 19
Pseudocode
KENNETH LEROY BUSBEE
Overview
Discussion
Input
1. Wikipedia: Pseudocode
20 | Pseudocode
display a message asking the user to enter the first age
get the first age from the keyboard
display a message asking the user to enter the second age
get the second age from the keyboard
Processing
calculate the answer by adding the two ages together and di
Output
display the answer on the screen
pause so the user can see the answer
Pseudocode | 21
Key Terms
pseudo
Means false and includes the concepts of fake or imitation.
References
22 | Pseudocode
Flowcharts
KENNETH LEROY BUSBEE
Overview
Discussion
1. Wikipedia: Flowchart
Flowcharts | 23
Simple Flowcharting Symbols
Terminal
Flow Lines
Note: The default flow is left to right and top to bottom (the
same way you read English). To save time arrowheads are often
only drawn when the flow lines go contrary the normal.
Input/Output
24 | Flowcharts
Process
Decision
Module Call
Flowcharts | 25
Connectors
On-Page Connector
Off-Page Connector
26 | Flowcharts
Simple Examples
Functions
Function main
Pass In: nothing
Doing some lines of code
Call: clear monitor
Flowcharts | 27
Doing some lines of code
Pass Out: value zero to the operating system
End function
Function main
Filename: Solution_Lab_04_Pseudocode.txt
Purpose: Convert Temperature from Fahrenheit to Celsius
Author: Ken Busbee; © 2008 Kenneth Leroy Busbee
Date: Dec 24, 2008
28 | Flowcharts
input
display a message asking user for the temperature in Fahren
get the temperature from the keyboard
processing
calculate the Celsius by subtracting 32 from the Fahrenheit
temperature then multiply the result by 5 then
divide the result by 9. Round up or down to the whole numbe
HINT: Use 32.0 when subtracting to ensure floating-point ac
output
display the celsius with an appropriate message
pause so the user can see the answer
Flowcharts | 29
Sequence control structured continued
Advanced Examples
If age > 17
Display a message indicating you can vote.
Else
Display a message indicating you can't vote.
Endif
30 | Flowcharts
If then Else control structure
pseudocode: Case
Case of age
0 to 17 Display "You can't vote."
18 to 64 Display "You are in your working years."
65 + Display "You should be retired."
End case
Flowcharts | 31
Iteration (Repetition) Control Structures
pseudocode: While
pseudocode: For
32 | Flowcharts
For control structure
pseudocode: Do While
Flowcharts | 33
pseudocode: Repeat Until
Key Terms
decision symbol
A diamond used in flowcharting for asking a question and
making a decision.
flow lines
Lines (sometimes with arrows) that connect the various
flowcharting symbols.
flowcharting
A programming design tool that uses graphical elements
to visually depict the flow of logic within a function.
34 | Flowcharts
input/output symbol
A parallelogram used in flowcharting for input/output
interactions.
process symbol
A rectangle used in flowcharting for normal processes
such as assignment.
References
Flowcharts | 35
Software Testing
KENNETH LEROY BUSBEE
Overview
Discussion
Test data consists of the user providing some input values and
predicting the outputs. This can be quite easy for a simple
program and the test data can be used twice.
36 | Software Testing
correct results (code checking)
Input
display a message asking user for their hours worked
get the hours from the keyboard
display a message asking user for their pay rate
get the rate from the keyboard
Processing
calculate the gross pay by:
multiplying the hours worked by the hourly rate
Output
display the gross pay on the monitor
pause so the user can see the answer
Software Testing | 37
$15.50 per hour. We should verify that the pseudocode is
prompting the user for this data.
The test data can be developed and used to test the algorithm
that is documented (in our case our pseudocode) during the
program design phase. Once the program is code with
compiler and linker errors resolved, the programmer gets to
play user and should test the program using the test data
developed. When you run your program, how will you know
that it is working properly? Did you properly plan your logic to
accomplish your purpose? Even if your plan was correct, did it
get converted correctly (coded) into the chosen programming
language? The answer (or solution) to all of these questions is
our test data.
38 | Software Testing
2. The conversion of the plan to code might be wrong
3. The test data results were calculated wrong
Key Terms
code checking
Using test data to check the coded program in a specific
language (like C++).
model checking
Using test data to check the design model (usually done in
pseudocode).
References
Software Testing | 39
Integrated
Development
Environment
KENNETH LEROY BUSBEE
Overview
Discussion
40 | Integrated Development
Environment
ASCII text into a source code file. A unique file extension
(Examples: .asm .c .cpp .java .js .py) is used to identify it as
a source code file. As you might guess for our examples –
Assembly, “C”, “C++”, Java, JavaScript, and Python, however,
they are just ASCII text files (other text files usually use the
extension of .txt). The source code produced by the
programmer must be converted to an executable machine
code file specifically for the computer’s CPU (usually an Intel
or Intel-compatible CPU within today’s world of computers).
There are several steps in getting a program from its source
code stage to running the program on your computer.
Historically, we had to use several software programs (a text
editor, a compiler, a linker, and operating system commands)
to make the conversion and run our program. However, today
all those software programs with their associated tasks have
been integrated into one program. However, this one program
is really many software items that create an environment used
by programmers to develop software. Thus the
name: Integrated Development Environment or IDE.
Resolving Errors
1. Compiler
2. Linker
Logic Error (from the output within the “Black Box” area)
compiler
Converts source code to object code.
debugging
The process of removing errors from a program. 1)
compiler 2) linker 3) logic
linker
Connects or links object files into an executable file.
loader
Part of the operating system that loads executable files
into memory and directs the CPU to start running the
program.
pre-processor
The first step the compiler does in converting source code
to object code.
text editor
A software program for creating and editing ASCII text
files.
warning
A compiler alert that there might be a problem.
References
Overview
Discussion
Version Control | 47
‘rewind’ your file to an older version. From this basic aim of
2
version control, a range of other possibilities is made available.
3
Version control allows you to:
48 | Version Control
would also retain a ‘history’ of the previous version should you
4
wish to revert back to one of these later on.
5
Popular version control systems include:
• Git
• Helix VCS
• Microsoft Team Foundation Server
• Subversion
Git
• Bitbucket
• GitHub
Version Control | 49
• git clone <url>
• git pull
• git add .
• git commit -m "reason for commit"
• git push
Key Terms
branch
A separate working copy of files under version control
which may be developed independently from the origin.
clone
Create a new repository containing the revisions from
another repository.
commit
To write or merge the changes made in the working copy
back to the repository.
50 | Version Control
merge
An operation in which two sets of changes are applied to a
file or set of files.
push
Copy revisions from the current repository to a remote
repository.
pull
Copy revisions from a remote repository to the current
repository.
version control
The management of changes to documents, computer
programs, large websites, and other collections of
information.
References
Version Control | 51
Input and Output
KENNETH LEROY BUSBEE
Overview
Discussion
1. Wikipedia: Input/output
Our program now loaded into memory has basically two areas:
Key Terms
device
A piece of equipment that is electronically connected to
the memory so that data can be transferred between the
memory and the device.
escape code
A code directing an output device to do something.
extraction
Aka reading or getting data from an input device.
insertion
Aka writing or sending data to an output device.
standard input
The keyboard.
standard output
The monitor.
References
Overview
Discussion
Hello World | 55
letters or exclamation mark), and was inherited from a 1974 Bell
3
Laboratories internal memorandum by Brian Kernighan.
Program Plan
Input:
None
Process:
None
Output:
Hello world!
Pseudocode
Function Main
... This program displays "Hello world!"
Output "Hello world!"
56 | Hello World
End
Output
Hello world!
5
Each code element represents:
Flowchart
Hello World | 57
Examples
Key Terms
comment
A programmer-readable explanation or annotation in the
source code of a computer program.
References
58 | Hello World
C++ Examples
DAVE BRAUNSCHWEIG
Overview
Example
Hello World
1. Wikipedia: C++
2. TIOBE: Index
C++ Examples | 59
// http://www.cplusplus.com/doc/tutorial/program_structure/
#include <iostream>
int main()
{
std::cout << "Hello world!";
}
Output
Hello world!
Discussion
3
Each code element represents:
• // begins a comment
• #include <iostream> includes standard input and
output streams
• int main() begins the main function, which returns an
integer value
• { begins a block of code
• std::cout is standard output
• << directs the next element to standard output
• "Hello world!" is the literal string to be displayed
• ; ends each line of C++ code
• } ends a block of code
60 | C++ Examples
C++ IDEs
Cloud-Based IDEs
• CodeChef
• GDB Online
• Ideone
• paiza.IO
• PythonTutor
• repl.it
• TutorialsPoint
Local IDEs
• Code::Blocks
• Dev-C++
• Microsoft Visual Studio
References
C++ Examples | 61
C# Examples
DAVE BRAUNSCHWEIG
Overview
62 | C# Examples
Example
Hello World
Output
Hello world!
Discussion
3
Each code element represents:
• // begins a comment
• public class Hello begins the Hello World program
C# Examples | 63
• { begins a block of code
• public static void Main() begins the main function
• System.Console.WriteLine() calls the standard output
write line function
• "Hello world!" is the literal string to be displayed
• ; ends each line of C# code
• } ends a block of code
C# IDEs
Cloud-Based IDEs
• CodeChef
• C# Pad
• .NET Fiddle
• Ideone
• paiza.IO
• Rextester
• repl.it
• TutorialsPoint
Local IDEs
64 | C# Examples
References
C# Examples | 65
Java Examples
DAVE BRAUNSCHWEIG
Overview
66 | Java Examples
Example
Hello World
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Output
Hello world!
Discussion
3
Each code element represents:
• // begins a comment
• class hello begins the Hello World program
• { begins a block of code
• public static void main(String[] args) begins the
Java Examples | 67
main function
• System.out.println() calls the standard output print
line function
• "Hello world!" is the literal string to be displayed
• ; ends each line of Java code
• } ends a block of code
Java IDEs
Cloud-Based IDEs
• CodeChef
• GDB Online
• Ideone
• paiza.IO
• PythonTutor
• repl.it
• TutorialsPoint
Local IDEs
• BlueJ
• jEdit
• jGRASP
68 | Java Examples
References
Java Examples | 69
JavaScript Examples
DAVE BRAUNSCHWEIG
Overview
1. Wikipedia: JavaScript
2. TIOBE: Index
70 | JavaScript Examples
Example
console.log("Hello world!")
Output
Hello world!
Discussion
• // begins a comment
• console.log() writes to the JavaScript console output log
• "Hello world!" is the literal string to be displayed
JavaScript Examples | 71
alert("Hello world!")
Output
Hello world!
Discussion
• // begins a comment
• alert() calls the window alert function to display a
message
• "Hello world!" is the literal string to be displayed
Output
Hello world!
72 | JavaScript Examples
Discussion
• // begins a comment
• document.write() writes output to the current document
• "Hello world!" is the literal string to be displayed
JavaScript IDEs
Cloud-Based IDEs
Local IDEs
• Brackets
• Visual Studio Code
JavaScript Examples | 73
References
74 | JavaScript Examples
Python Examples
DAVE BRAUNSCHWEIG
Overview
Example
Hello World
Python Examples | 75
# https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for
print("Hello world!")
Output
Hello world!
Discussion
3
Each code element represents:
• # begins a comment
• print() calls the print function
• "Hello world!" is the literal string to be displayed
Python IDEs
Cloud-Based IDEs
• CodeChef
• GDB Online
76 | Python Examples
• Ideone
• paiza.IO
• Python Fiddle
• PythonTutor
• repl.it
• TutorialsPoint
Local IDEs
• IDLE
• Thonny
References
Python Examples | 77
Swift Examples
DAVE BRAUNSCHWEIG
File:Swift logo
with text.svg Overview
Example
Hello World
78 | Swift Examples
print("Hello world!")
Output
Hello world!
Discussion
3
Each code element represents:
• // begins a comment
• print() calls the print function
• "Hello world!" is the literal string to be displayed
Swift IDEs
Cloud-Based IDEs
• GDB Online
• IBM Swift Sandbox
• Ideone
Swift Examples | 79
• iSwift
• paiza.IO
• repl.it
Local IDEs
• AppCode
• Atom
• Xcode
References
80 | Swift Examples
Practice: Introduction
to Programming
Review Questions
True / False:
Answers:
1. false
2. false
3. false
Practice: Introduction to
Programming | 81
4. false
5. false
6. true
7. true
8. false
9. true
10. false
Short Answer:
Activities
References
Overview
Chapter Outline
◦ C++
◦ C#
◦ Java
Learning Objectives
Discussion
Understanding Constants
21
12.34
'A'
"Hello world!"
false
null
Language Example
#define PI 3.14159
C++ or
const double PI = 3.14159;
Python PI = 3.14159
Language Example
C# double value = 3;
var value = 3;
JavaScript
let value = 3;
Python value = 3
Key Terms
constant
A data item whose value cannot change during the
program’s execution.
variable
A data item whose value can change during the program’s
execution.
Discussion
Technical to Language
Identifier Names | 91
language. However, all programming languages have some
form of the technical rules listed here.
• Meaningful
• Be case consistent
Industry Rules
92 | Identifier Names
expected to follow. Among these are three common identifier
casing standards:
These rules are decided by the industry (those who are using
the programming language).
Key Terms
camel case
The practice of writing compound words or phrases such
that each word or abbreviation in the middle of the phrase
begins with a capital letter, with no intervening spaces or
punctuation.
Pascal case
The practice of writing compound words or phrases such
that each word or abbreviation in the phrase begins with a
Identifier Names | 93
capital letter, including the first letter, with no intervening
spaces or punctuation.
reserved word
Words that cannot be used by the programmer as
identifier names because they already have a specific
meaning within the programming language.
snake case
The practice of writing compound words or phrases in
which the elements are separated with one underscore
character (_) and no spaces, with each element’s initial
letter usually lowercased within the compound and the
first letter either upper or lower case.
References
94 | Identifier Names
Data Types
Overview
Discussion
Data Types | 95
Common data types include:
Pseudocode
Function Main
... This program demonstrates variables, literal constants,
Declare Integer i
Declare Real r
Declare String s
Declare Boolean b
Assign i = 1234567890
Assign r = 1.23456789012345
Assign s = "string"
Assign b = true
96 | Data Types
Output "Real r = " & r
Output "String s = " & s
Output "Boolean b = " & b
End
Output
Integer i = 1234567890
Real r = 1.23456789012345
String s = string
Boolean b = true
Data Types | 97
Flowchart
98 | Data Types
Data Types | 99
Key Terms
Boolean
A data type representing logical true or false.
data type
Defines a set of values and a set of operations that can be
applied on those values.
floating point
A data type representing numbers with fractional parts.
integer
A data type representing whole numbers.
string
A data type representing a sequence of characters.
References
Discussion
The integer data type has similar attributes and acts or behaves
similarly in all programming languages that support it.
short 16 bits / 2
C++ -32,768 to32,767
bytes
long 32 bits /
C++ -2,147,483,648 to 2, 147,483,647
4 bytes
short 16 bits / 2
C# -32,768 to32,767
bytes
int 32 bits /
C# -2,147,483,648 to 2, 147,483,647
4 bytes
short 16 bits / 2
Java -32,768 to32,767
bytes
int 32 bits /
Java -2,147,483,648 to 2, 147,483,647
4 bytes
Int32 32 bits /
Swift -2,147,483,648 to 2, 147,483,647
4 bytes
For C++ and Swift the size of a default integer varies with the
compiler being used and the computer. This effect is known
as being machine dependent. These variations of the integer
data type are an annoyance for a beginning programmer. For
a beginning programmer, it is more important to understand
Key Terms
machine dependent
An attribute of a programming language that changes
depending on the computer’s CPU.
References
2. Mozilla: Math.round()
3. Python.org: Integers
Discussion
64
15
double bits /
C# decimal ±1.79769313486231570E+308
8
digits
bytes
32
7
float bits /
Java decimal ±3.40282347E+38
4
digits
bytes
64
15
double bits /
Java decimal ±1.79769313486231570E+308
8
digits
bytes
64
15
bits /
JavaScript Number decimal ±1.79769313486231570E+308
8
digits
bytes
64
15
Python float() bits / decimal ±1.79769313486231570E+308
8
digits
bytes
32
7
Float bits /
Swift decimal ±3.40282347E+38
4
digits
bytes
64
15
Double bits /
Swift decimal ±1.79769313486231570E+308
8
digits
bytes
double
The most often used floating-point family data type used.
mantissa exponent
The two integer parts of a floating-point value.
precision
The effect on the domain of floating-point values given a
larger or smaller storage area in bytes.
References
Discussion
Reserved
Language Example
Word
C# char 'A'
For now, we will address only the use of strings and characters
as constants. Most modern compilers that are part of an
Integrated Development Environment (IDE) will color the
source code to help the programmer see different features
more readily. Beginning programmers will use string constants
to send messages to standard output.
Key Terms
ASCII
American Standard Code for Information Interchange
character
A data type representing single text characters like the
alphabet, numeral digits, punctuation, etc.
double quote marks
Used to create string type data within most programming
languages.
single quote marks
Used to create character type data within languages that
differentiate between string and character data types.
string
A series or array of characters as a single piece of data.
References
Discussion
The Boolean data type is also known as the logical data type
and represents the concepts of true and false. The name
“Boolean” comes from the mathematician George Boole; who
in 1854 published: An Investigation of the Laws of Thought.
Boolean algebra is the area of mathematics that deals with
the logical representation of true and false using the numbers
0 and 1. The importance of the Boolean data type within
programming is that it is used to control programming
structures (if then else, while loops, etc.) that allow us to
implement “choice” into our algorithms.
The Boolean data type has the same attributes and acts or
behaves similarly in all programming languages. However,
Key Terms
Boolean
A data type representing the concepts of true or false.
one’s complement
The value obtained by inverting all the bits in the binary
representation of a number (swapping 0s for 1s and vice
versa).
References
Overview
Discussion
C# null no value
NaN
Reserved word used to indicate a non-numeric value in a
numeric variable.
null
Reserved word used to represent a missing value or invalid
value.
Discussion
• Parentheses
• Exponents
Key Terms
associativity
Determines the order in which the operators of the same
precedence are allowed to manipulate the operands.
evaluation
The process of applying the operators to the operands and
resulting in a single value.
References
Overview
Discussion
Simple Assignment
age = 21
Assignment | 119
Assignment with an Expression
total_cousins = 4 + 3 + 5 + 2
students_period_1 = 25
students_period_2 = 19
total_students = students_period_1 + students_period_2
Key Terms
assignment
An operator that changes the value of a modifiable data
object.
References
120 | Assignment
Arithmetic Operators
Overview
Discussion
Addition +
Subtraction -
Multiplication *
Division /
age + 1
Function Main
... This program demonstrates arithmetic operations.
Declare Integer a
Declare Integer b
Assign a = 3
Assign b = 2
Output "a = " & a
Output "b = " & b
Output "a + b = " & a + b
Output "a - b = " & a - b
Output "a * b = " & a * b
Output "a / b = " & a / b
Output "a % b = " & a % b
End
Output
a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1.5
a % b = 1
Overview
Discussion
11 / 4
What is modulus? It’s the other part of the answer for integer
division. It’s the remainder. Remember in grade school you
would say, “Eleven divided by four is two remainder three.” In
11 % 4
1. 14 / 4
2. 5 / 13
3. 7 / 2.0
1. 14 % 4
2. 5 % 13
3. 7 % 2.0
integer division
Division with no fractional parts.
modulus
The remainder part of integer division.
References
Overview
Discussion
+5 + -2
-2 - +5
7 - -2
-money
money * -1
money
+money
money * +1
For all three lines, if the value stored in money is 6 the value of
the expression is 6. Even if the value in money was negative 77
the value of the expression would be negative 77. The operator
does nothing because multiplying anything by 1 does not
change its value.
Possible Confusion
Exercises
Key Terms
minus
Aka unary negative.
plus
Aka unary positive.
unary negative
An operator that causes negation.
unary positive
A worthless operator almost never used.
References
Overview
Discussion
Lvalue and Rvalue refer to the left and right side of the
assignment operator. The Lvalue (pronounced: L value)
concept refers to the requirement that the operand on the
left side of the assignment operator is modifiable, usually a
variable. Rvalue concept pulls or fetches the value of the
expression or operand on the right side of the assignment
operator. Some examples:
age = 39
age < 17
JACK_BENNYS_AGE = 39
JACK_BENNYS_AGE = 65;
oldest = 55
age = oldest++
Lvalue
The requirement that the operand on the left side of the
assignment operator is modifiable, usually a variable.
Rvalue
Pulls or fetches the value stored in a variable or constant.
References
Discussion
55 + 1.75
Implicit Demotion
int money;
money = 23.16;
Promotion
Demotion
C# Convert.ToInt32(3.14)
Java Math.floor(3.14)
JavaScript Math.floor(3.14)
Python int(3.14)
Swift Int(3.14)
#include <string.h>
C++
std::stod("3.14")
C# Convert.ToDouble("3.14")
Java Double.parseDouble("3.14")
JavaScript parseFloat("3.14")
Python float("3.14")
Swift Double("3.14")
demotion
Going from a larger domain to a smaller domain.
explicit
Changing a value’s data type with the cast operator.
implicit
A value that has its data type changed automatically.
promotion
Going from a smaller domain to a larger domain.
truncation
The fractional part of a floating-point data type that is
dropped when converted to an integer.
References
Overview
Discussion
Program Plan
Input:
Display prompt
Get Fahrenheit temperature
Process:
Convert Fahrenheit temperature to Celsius
Output:
Display Fahrenheit and Celsius temperatures
Pseudocode
Function Main
... This program converts an input Fahrenheit temperature t
Output fahrenheit & "° Fahrenheit is " & celsius & "° Celsi
End
Output
Overview
Data Types
#include <iostream>
#include <sstream>
int main() {
int i;
double d;
string s;
bool b;
i = 1234567890;
d = 1.23456789012345;
s = "string";
b = true;
cout << "Integer i = " << i << endl;
cout << "Double d = " << d << endl;
cout << "String s = " << s << endl;
Output
Integer i = 1234567890
Real r = 1.23457
String s = string
Boolean b = 1
Discussion
• // begins a comment
• #include <iostream> includes standard input and
output streams
• #include <sstream> includes standard string streams
• using namespace std allows reference to string, cout,
and endl without writing std::string, std::cout, and
std::endl.
• int main() begins the main function, which returns an
integer value
• { begins a block of code
• int i defines an integer variable named i
• ; ends each line of C++ code
• double d defines a double floating-point variable named
d
• string s defines a string variable named s
• bool b defines a Boolean variable named b
• i = , d = , s =, b = assign literal values to the
Arithmetic
#include <iostream>
#include <sstream>
int main() {
int a;
int b;
a = 3;
b = 2;
a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1
a % b = 5
Discussion
Temperature
int main() {
double fahrenheit;
double celsius;
cout << fahrenheit << "° Fahrenheit is " << celsius << "° C
return 0;
}
Output
Discussion
References
Overview
Data Types
using System;
i = 1234567890;
d = 1.23456789012345;
s = "string";
b = true;
C# Examples | 153
Console.WriteLine("String s = " + s);
Console.WriteLine("Boolean b = " + b);
}
}
Output
Integer i = 1234567890
Double d = 1.23456789012345
String s = string
Boolean b = True
Discussion
• // begins a comment
• using System allows references to Boolean and Console
without writing System.Boolean and System.Console
• public class DataTypes begins the Data Types program
• { begins a block of code
• public static void Main() begins the main function
• int i defines an integer variable named i
• ; ends each line of C# code
• double d defines a double floating-point variable named
d
• string s defines a string variable named s
• Boolean b defines a Boolean variable named b
• i = , d = , s =, b = assign literal values to the
corresponding variables
• Console.WriteLine() calls the standard output write line
function
154 | C# Examples
• } ends a block of code
Arithmetic
using System;
a = 3;
b = 2;
Output
a = 3
b = 2
a + b = 5
C# Examples | 155
a - b = 1
a * b = 6
a / b = 1
a % b = 5
Discussion
Temperature
using System;
Console.WriteLine(
fahrenheit.ToString() + "° Fahrenheit is " +
celsius.ToString() + "° Celsius" + "\n");
156 | C# Examples
}
}
Output
Discussion
References
C# Examples | 157
Java Examples
DAVE BRAUNSCHWEIG
Overview
Data Types
i = 1234567890;
d = 1.23456789012345;
s = "string";
b = true;
Integer i = 1234567890
Double d = 1.23456789012345
String s = string
Boolean b = true
Discussion
• // begins a comment
• public class DataTypes begins the Data Types program
• { begins a block of code
• public static void main(String[] args) begins the
main function
• int i defines an integer variable named i
• ; ends each line of Java code
• double d defines a double floating-point variable named
d
• string s defines a string variable named s
• boolean b defines a Boolean variable named b
• i = , d = , s =, b = assign literal values to the
corresponding variables
• System.out.println calls the standard output print line
function
• } ends a block of code
Arithmetic
a = 3;
b = 2;
Output
a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1
a % b = 1
Discussion
Temperature
import java.util.*;
Output
References
Overview
Data Types
var n;
var s;
var b;
n = 1.23456789012345;
s = "string";
b = true;
Output
Number n = 1.23456789012345
String s = string
Boolean b = true
Discussion
◦ // begins a comment
◦ var n, s, and b define variables
◦ ; ends each line of JavaScript code
◦ i = , d = , s =, b = assign literal values to the
corresponding variables
◦ output() calls the output function
◦ function output(text) defines a output function
that checks the JavaScript environment and writes to
the current document, the console, or standard
output as appropriate.
Arithmetic
a = 3;
b = 2;
output("a = " + a);
output("b = " + b);
output("a + b = " + (a + b));
output("a - b = " + (a - b));
output("a * b = " + a * b);
output("a / b = " + a / b);
output("a % b = " + (a % b));
Output
a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
Discussion
Temperature
var fahrenheit;
var celsius;
Output
Discussion
References
Overview
Data Types
i = 1234567890
f = 1.23456789012345
s = "string"
b = True
print("Integer i =", i)
print("Float f =", f)
print("String s =", s)
print("Boolean b =", b)
Output
Integer i = 1234567890
Float f = 1.23456789012345
String s = string
Boolean b = true
• # begins a comment
• i = , d = , s =, b = assign literal values to the
corresponding variables
• print() calls the print function
Arithmetic
a = 3
b = 2
print("a =", a)
print("b =", b)
print("a + b =", (a + b))
print("a - b =", (a - b))
print("a * b =", a * b)
print("a / b =", a / b)
print("a % b =", (a % b))
Output
a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1.5
Discussion
Temperature
Output
Discussion
References
Overview
Data Types
var i: Int
var d: Double
var s: String
var b: Bool
i = 1234567890
d = 1.23456789012345
s = "string"
b = true
print("Integer i =", i)
print("Double d =", d)
print("String s =", s)
print("Boolean b =", b)
Integer i = 1234567890
Double d = 1.23456789012345
String s = string
Boolean b = true
Discussion
• // begins a comment
• var i: Int defines an integer variable named i
• var d: Double defines a double floating-point variable
named d
• var s: String defines a string variable named s
• var b: Bool defines a Boolean variable named b
• i = , d = , s =, b = assign literal values to the
corresponding variables
• print() calls the print function
Arithmetic
var a: Int
var b: Int
a = 3
b = 2
print("a =", a)
Output
a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1
a % b = 1
Discussion
Temperature
Output
Discussion
References
True or false:
Answers:
1. true
2. false
3. true
4. true
Short Answer:
Activities
References
Overview
Chapter Outline
• Modular Programming
• Hierarchy or Structure Chart
• Function Examples
• Parameters and Arguments
• Call by Value vs. Call by Reference
• Return Statement
• Void Data Type
• Scope
• Programming Style
• Standard Libraries
• Code Examples
◦ Program Plan
◦ C++
◦ C#
◦ Java
◦ JavaScript
◦ Python
◦ Swift
• Practice
Functions | 181
Learning Objectives
182 | Functions
Modular Programming
Overview
Concept of Modularization
When you call a function you use its identifier name and a set
of parentheses. You place any data items you are passing inside
the parentheses. After our program is compiled and running,
the lines of code in the main function are executed, and when
it gets to the calling of a specific task function, the control of
the program moves to the function and starts executing the
lines of code in the function. When it’s done with the lines of
Program Layout
Key Terms
braces
Used to identify a block of code in languages such as C++,
C#, Java, and JavaScript.
function
What modules are called in many predominant
programming languages of today.
function call
A function’s using or invoking of another function.
function definition
The code that defines what a function does.
References
Overview
Key Terms
hierarchy chart
Convey the relationship or big picture of the various
functions in a program.
structure chart
Another name for a hierarchy chart.
References
Overview
Discussion
Function Main
... This program asks the user for a Fahrenheit temperature
... converts the given temperature to Celsius,
... and displays the results.
Function GetFahrenheit
Declare Real fahrenheit
Overview
Discussion
CalculateCelsius(98.6, 37.0)
CalculateCelsius(fahrenheit=98.6, celsius=37.0)
CalculateCelsius(celsius=37.0, fahrenheit=98.6)
argument
A value provided as input to a function.
parameter
A variable identifier provided as input to a function.
References
Overview
Call by Value
Function Main
Declare Real fahrenheit
Output
Call by Reference
Key Terms
call by reference
Parameters passed by calling functions may be modified
by called functions.
call by value
Parameters passed by calling functions cannot be
modified by called functions.
References
Overview
Discussion
Function Main
...
Assign fahrenheit = GetFahrenheit()
...
End
Function GetFahrenheit
Declare Real fahrenheit
Function Main
...
Assign fahrenheit = GetTemperature()
...
End
Function GetTemperature
Declare Real temperature
Key Terms
return
A branching control structure that causes a function to
jump back to the function that called it.
References
The void data type, similar to the Nothing data type described
earlier, is the data type for the result of a function that returns
1
normally, but does not provide a result value to its caller.
Discussion
The void data type has no values and no operations. It’s a data
type that represents the lack of a data type.
C++ void
C# void
Java void
JavaScript void
Python N/A
Swift Void
Key Terms
References
Overview
Discussion
208 | Scope
source code. It can even be made available to functions in other
object modules that will be linked to your code; however, we
will forgo that explanation now. A key wording change should
be learned at this point. Although the variable has global scope,
technically it is available only from the point of definition to
the end of the program source code. That is why most
variables with global scope are placed near the top of the
source code before any functions. This way they are available to
all of the functions.
Scope | 209
This closed communications model that passes all data into
and out of a function creates an important predecessor
concept for encapsulation which is used in object-oriented
programming.
Key Terms
data area
A part of an object code file used for storage of data.
global scope
Data storage defined outside of a function.
local scope
Data storage defined inside of a function.
scope
The area of a source code file where an identifier name is
recognized.
stack
A part of the computer’s memory used for storage of data.
References
210 | Scope
Programming Style
Overview
Discussion
1. Documentation
2. Vertical Alignment
3. Comments
4. Indentation
5. Meaningful Identifier Names Consistently Typed
6. Appropriate use of Typedef
The above items are not needed in order for the source code
to compile. Technically the compiler does not read the source
For each of these items, check style guides for your selected
programming language to determine standards and best
practices. The following are general guidelines to consider.
Documentation
Vertical Alignment
You see this within the documentation area. All of the items
are aligned up within the same column. This vertical alignment
occurs again when variables are defined. When declaring
variables or constants many textbooks put several items on one
line; like this:
float length;
float width;
Comments
For languages that use curly braces, there are two common
indentation styles:
function(parameters) {
// code
}
function(parameters)
{
// code
}
Key Terms
braces
Used to identify a block of code in languages such as C++,
C#, Java, and JavaScript.
consistent
A rule that says to type identifier names in upper and
lower case consistently throughout your source code.
comments
Information inserted into a source code file for
documentation of the program.
documentation
A method of preserving information useful to others in
understanding an information system or part thereof.
indention
A method used to make sections of source code more
visible.
meaningful
A rule that says identifier names must be easily
understood by another reading the source code.
vertical alignment
A method of listing items vertically so that they are easier
to read quickly.
Discussion
1. define a function
2. declare a function (a prototype is a declaration to a
compiler)
3. call a function
#include <cmath>
C++
std::abs(number);
C# Math.Abs(number);
Java Java.lang.Math.abs(number)
JavaScript Math.abs(number);
Python abs(number)
Swift abs(number)
apple = abs(banana);
abs
A function within a standard library which stands for
absolute value.
confidence
The reliance that Standard Library functions work properly.
standard library
A set of specific task functions that have been added to
the programming language for universal use.
References
Main Program
Get Fahrenheit
Calculate Celsius
Display Result
Get Fahrenheit
Parameters:
None
Process:
Display Prompt
Get Fahrenheit temperature
Return Value:
Fahrenheit temperature
Calculate Celsius
Parameters:
Fahrenheit temperature
Process:
Convert Fahrenheit temperature to Celsius
Return Value:
Celsius temperature
Display Result
Parameters:
Fahrenheit temperature
Celsius temperature
Process:
Display Fahrenheit and Celsius temperatures
Return Value:
None
Temperature
#include <iostream>
double getFahrenheit();
double calculateCelsius(double);
void displayResult(double, double);
int main() {
double fahrenheit;
double celsius;
fahrenheit = getFahrenheit();
celsius = calculateCelsius(fahrenheit);
displayResult(fahrenheit, celsius);
return 0;
}
return fahrenheit;
}
return celsius;
}
Output
References
Temperature
using System;
class Temperature
{
public static void Main (string[] args)
{
double fahrenheit;
double celsius;
fahrenheit = GetFahrenheit();
celsius = CalculateCelsius(fahrenheit);
DisplayResult(fahrenheit, celsius);
}
224 | C# Examples
Console.WriteLine("Enter Fahrenheit temperature:");
input = Console.ReadLine();
fahrenheit = Convert.ToDouble(input);
return fahrenheit;
}
return celsius;
}
Output
References
C# Examples | 225
Java Examples
DAVE BRAUNSCHWEIG
Temperature
import java.util.*;
class Main {
private static Scanner input = new Scanner(System.in);
fahrenheit = getFahrenheit();
celsius = calculateCelsius(fahrenheit);
displayResult(fahrenheit, celsius);
}
return celsius;
}
Output
References
Temperature
main();
function main() {
var fahrenheit = getFahrenheit();
var celisus = calculateCelsius(fahrenheit);
displayResult(fahrenheit, celisus);
}
function getFahrenheit() {
var fahrenheit = input("Enter Fahrenheit temperature:");
return fahrenheit;
}
function calculateCelsius(fahrenheit) {
var celisus = (fahrenheit - 32) * 5 / 9;
return celisus;
}
function input(text) {
if (typeof window === 'object') {
return prompt(text)
}
else if (typeof console === 'object') {
const rls = require('readline-sync');
var value = rls.question(text);
return value;
}
else {
output(text);
var isr = new java.io.InputStreamReader(java.lang.System.in
var br = new java.io.BufferedReader(isr);
var line = br.readLine();
return line.trim();
}
}
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}
References
Temperature
def get_fahrenheit():
print("Enter Fahrenheit temperature:")
fahrenheit = float(input())
return fahrenheit
def calculate_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5 / 9
return celsius
def main():
fahrenheit = get_fahrenheit()
main()
Output
References
Temperature
return fahrenheit
}
return celsius
}
func main() {
var fahrenheit: Double
var celsius: Double
fahrenheit = getFahrenheit()
celsius = calculateCelsius(fahrenheit:fahrenheit)
displayResult(fahrenheit:fahrenheit, celsius:celsius)
}
main()
Output
References
True / False
Answers:
1. true
2. true
3. true
4. true
5. false
6. false
7. false – Although Scope is a brand of mouthwash; we are
looking for the computer-related definition.
8. true
9. true
10. false – It may seem difficult at first, but with a little
practice it is really quite easy.
11. true
12. true
13. false
14. false
Short Answer
References
Overview
Chapter Outline
• Structured Programming
• Selection Control Structures
• If Then Else
• Code Blocks
• Relational Operators
• Assignment vs. Equality
• Logical Operators
• Nested If Then Else
• Case Control Structure
• Code Examples
◦ Program Plan
◦ Condition Examples
◦ C++
◦ C#
◦ Java
◦ JavaScript
◦ Python
◦ Swift
• Practice
Conditions | 239
Learning Objectives
240 | Conditions
Structured
Programming
Overview
Discussion
Key Terms
branching
An uncontrolled structure that allows the flow of
execution to jump to a different part of the program.
control structures
Mechanisms that allow us to control the flow of execution
within a program.
iteration
A control structure that allows some lines of code to be
executed many times.
selection
A control structure where the program chooses between
two or more options.
sequence
A control structure where the program executes the items
in the order listed.
spaghetti code
A pejorative phrase for unstructured and difficult to
3
maintain source code.
structured programming
A method of planning programs that avoids the
branching category of control structures.
Discussion
If age > 17
C# if, else
Case of age
0 to 17 Display "You can't vote."
18 to 64 Display "You're in your working years."
65 + Display "You should be retired."
End
Python N/A
Key Terms
if then else
A two-way selection control structure.
case
A multi-way selection control structure.
References
Overview
Discussion
if expression is true
then do this
else because it is false
do this
Some languages use reserved words of: “if”, “then” and “else”.
Many eliminate the “then”. Additionally the “do this” can be tied
to true and false. You might see it as:
if expression is true
action true
else
action false
And most languages infer the “is true” you might see it as:
if expression
action true
else
action false
The above four forms of the control structure are saying the
same thing. The else word is often not used in our English
speaking today. However, consider the following conversation
between a mother and her child.
Mother answers, “If your room is clean then you may go outside
and play or else you may go sit on a chair for five minutes as
punishment for asking me the question when you knew your
room was dirty.”
if expression
action true
else
do nothing
if expression
action true
Key Terms
if then else
A two-way selection control structure.
mutually exclusive
Items that do not overlap. Example: true or false.
Discussion
if (expression)
statement
else
statement
if(expression)
{
statement;
statement;
}
else
{
statement;
statement;
}
if(expression)
{
statement;
}
else
{
statement;
}
if expression:
statement
statement
else:
statement
statement
if expression then
statement
statement
else
statement
statement
end
block
Another name for a compound statement.
compound statement
A unit of code consisting of zero or more statements.
References
Overview
Discussion
Examples:
• 9 < 25
• 9<3
• 9 > 14
• 9 <= 17
• 9 >= 25
• 9 == 13
• 9 != 13
• 9 !< 25
• 9 <> 25
relational operator
An operator that gives a Boolean value by evaluating the
relationship between two operands.
References
Overview
Discussion
If (pig = 'y')
Output "Pigs are good"
Else
Output "Pigs are bad."
If (pig == 'y')
Output "Pigs are good"
Else
Output "Pigs are bad."
References
Discussion
C++ && || !
C# && || !
Java && || !
JavaScript && || !
Swift && || !
We can say this in English as: It is true that six is greater than
four and that two is less than or equal to fourteen.
6 > 4 && 8
6 > 4 and 8
Truth Tables
x y x and y
false false false
false true false
true false false
true true true
Logical or (||)
x y x or y
false false false
false true true
Logical not
(!)
x not x
false true
true false
Examples
Examples:
• 25 < 7 || 15 > 36
• 15 > 36 || 3 < 7
• 14 > 7 && 5 <= 5
• 4 > 3 && 17 <= 7
• ! false
• ! (13 != 7)
• 9 != 7 && ! 0
• 5 > 1 && 7
More examples:
• 25 < 7 or 15 > 36
• 15 > 36 or 3 < 7
• 14 > 7 and 5 <= 5
• 4 > 3 and 17 <= 7
• not False
• not (13 != 7)
• 9 != 7 and not 0
Key Terms
logical operator
An operator used to create complex Boolean expressions.
truth tables
A common way to show logical relationships.
References
Overview
Discussion
if expression
true action
else
false action
This is the basic form of the if then else control structure. Now
consider:
Multiway Selection
if age equal to 18
you can now vote
else
if age equal to 39
you are middle-aged
else
if age equal to 65
you can consider retirement
else
your age is unimportant
Key Terms
multiway selection
Using control structures to be able to select from more
than two choices.
nested control structures
Placing one control structure inside of another.
References
Overview
Discussion
if age equal to 18
you can vote
else if age equal to 39
you're middle-aged
else if age equal to 65
consider retirement
else
age is unimportant
switch (age)
{
case 18:
message = "You can vote.";
break;
case 39:
message = "You're middle-aged.";
break;
case 65:
message = "Consider retirement.";
break;
default:
message = "Age is unimportant.";
break;
}
switch (choice)
{
case 'A':
Case of age
0 to 17 Display "You can't vote."
18 to 64 Display "You’re in your working years."
65 + Display "You should be retired."
End
case
A control structure that does multiway selection.
switch
A control structure that can be made to act like a case
control structure.
References
Main Program
Get Choice
Either:
Get Fahrenheit temperature
Calculate Celsius
Display Result
Or:
Get Celsius temperature
Calculate Fahrenheit
Display Result
Get Choice
Parameters:
None
Process:
Display prompt
Get choice of Fahrenheit or Celsius conversion
Return Value:
Choice
Get Temperature
Parameters:
Label (Fahrenheit or Celsius)
Process:
Display prompt with label
Get temperature
Return Value:
Temperature
Calculate Fahrenheit
Parameters:
Celsius temperature
Process:
Convert Celsius temperature to Fahrenheit
Return Value:
Fahrenheit temperature
Display Result
Parameters:
Input temperature
From label (Fahrenheit or Celsius)
Output temperature
To label (Fahrenheit or Celsius)
Process:
Display temperatures and labels
Return Value:
None
Temperature
Pseudocode
Function Main
Declare String choice
Declare Real temperature
Declare Real result
Function GetChoice
Declare String choice
Output
Flowchart
Main
String choice
choice = GetChoice()
False True
Choice = "C" Or Choice =
"c"
ProcessCelsius()
False True
Choice = "F" Or Choice = "f"
End
temperature = temperature =
GetTemperature("Celsius") GetTemperature
("Fahrenheit")
result = CalculateCelsius
(temperature) result = CalculateFahrenheit
(temperature)
DisplayResult(temperature,
"Fahrenheit", result, DisplayResult(temperature,
"Celsius") "Celsius", result,
"Fahrenheit")
End
End
GetChoice GetTemperature
(String scale)
String choice
Real temperature
Input Choice
Input temperature
CalculateCelsius CalculateFahrenheit
(Real fahrenheit) (Real celsius)
DisplayResult
(Real temperature, String fromScale, Real result, String
toScale)
End
Temperature
#include <iostream>
int main() {
// main could either be an if-else structure or a switch-ca
char choice;
double temperature;
double result;
// if-else approach
// switch-case approach
switch(choice) {
case 'C':
case 'c':
temperature = getTemperature("Fahrenheit");
result = calculateCelsius(temperature);
displayResult(temperature, "Fahrenheit", result, "C
break;
case 'F':
case 'f':
temperature = getTemperature("Celsius");
result = calculateFahrenheit(temperature);
displayResult(temperature, "Celsius", result, "Fahr
break;
default:
cout << "You must enter C to convert to Celsius or
}
}
return temperature;
}
return celsius;
}
return fahrenheit;
}
Output
References
Temperature
using System;
string choice;
double temperature;
double result;
// if-else approach
if (choice == "C" || choice == "c")
{
temperature = GetTemperature("Fahrenheit");
288 | C# Examples
result = CalculateCelsius(temperature);
DisplayResult(temperature, "Fahrenheit", result, "C
}
else if (choice == "F" || choice == "f")
{
temperature = GetTemperature("Celsius");
result = CalculateFahrenheit(temperature);
DisplayResult(temperature, "Celsius", result, "Fahr
}
else
{
Console.WriteLine("You must enter C to convert to C
}
// switch-case approach
switch(choice)
{
case "C":
case "c":
temperature = GetTemperature("Fahrenheit");
result = CalculateCelsius(temperature);
DisplayResult(temperature, "Fahrenheit", result
break;
case "F":
case "f":
temperature = GetTemperature("Celsius");
result = CalculateFahrenheit(temperature);
DisplayResult(temperature, "Celsius", result, "
break;
default:
Console.WriteLine("You must enter C to convert
break;
}
}
C# Examples | 289
private static double GetTemperature(string label)
{
string input;
double temperature;
return temperature;
}
return celsius;
}
return fahrenheit;
}
290 | C# Examples
Output
References
C# Examples | 291
Java Examples
DAVE BRAUNSCHWEIG
Temperature
import java.util.*;
class Main {
private static Scanner input = new Scanner(System.in);
String choice;
double temperature;
double result;
choice = getChoice();
// if-else approach
if (choice.equals("C") || choice.equals("c")) {
temperature = getTemperature("Fahrenheit");
result = calculateCelsius(temperature);
displayResult(temperature, "Fahrenheit", result, "C
// switch-case approach
switch (choice) {
case "C":
case "c":
temperature = getTemperature("Fahrenheit");
result = calculateCelsius(temperature);
displayResult(temperature, "Fahrenheit", result
break;
case "F":
case "f":
temperature = getTemperature("Celsius");
result = calculateFahrenheit(temperature);
displayResult(temperature, "Celsius", result, "
break;
default:
System.out.println("You must enter C to convert
}
}
return choice;
}
return temperature;
}
return celsius;
}
return fahrenheit;
}
Output
References
Temperature
main();
function main()
{
// main could either be an if-else structure or a switch-ca
var choice;
var temperature;
var result;
choice = getChoice();
// if-else approach
if (choice == "C" || choice == "c") {
temperature = getTemperature("Fahrenheit");
result = calculateCelsius(temperature);
displayResult(temperature, "Fahrenheit", result, "Celsi
}
else if (choice == "F" || choice == "f") {
// switch-case approach
switch(choice) {
case 'C':
case 'c':
temperature = getTemperature("Fahrenheit");
result = calculateCelsius(temperature);
displayResult(temperature, "Fahrenheit", result, "C
break;
case 'F':
case 'f':
temperature = getTemperature("Celsius");
result = calculateFahrenheit(temperature);
displayResult(temperature, "Celsius", result, "Fahr
break;
default:
output("You must enter C to convert to Celsius or F
}
}
function getChoice() {
var choice;
return choice;
}
return temperature;
}
function calculateCelsius(fahrenheit) {
var celsius;
return celsius;
}
function calculateFahrenheit(celsius) {
var fahrenheit;
return fahrenheit;
}
function input(text) {
if (typeof window === 'object') {
return prompt(text)
}
else if (typeof console === 'object') {
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}
Output
References
Temperature
def get_choice():
print("Enter C to convert to Celsius or F to convert to Fah
choice = input()
return choice
def get_temperature(label):
print(f"Enter {label} temperature:")
temperature = float(input())
return temperature
def calculate_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5 / 9
return celsius
def calculate_fahrenheit(celsius):
def main():
choice = get_choice()
if choice == "C" or choice == "c":
temperature = get_temperature("Fahrenheit")
result = calculate_celsius(temperature)
display_result (temperature, "Fahrenheit", result, "Cel
elif choice == "F" or choice == "f":
temperature = get_temperature("Celsius")
result = calculate_fahrenheit(temperature)
display_result (temperature, "Celsius", result, "Fahren
else:
print("You must enter C to convert to Celsius or F to c
main()
Output
References
Temperature
return choice
}
return temperature
}
return celsius
}
fahrenheit = celsius * 9 / 5 + 32
return fahrenheit
}
func main() {
// main could either be an if-else structure or a switch-ca
choice = getChoice()
// if-else approach
if choice == "C" || choice == "c" {
temperature = getTemperature(label:"Fahrenheit")
result = calculateCelsius(fahrenheit:temperature)
displayResult(temperature:temperature, fromLabel:"Fahre
else if choice == "F" || choice == "f" {
temperature = getTemperature(label:"Celsius")
// switch-case approach
switch choice {
case "C", "c":
temperature = getTemperature(label:"Fahrenheit")
result = calculateCelsius(fahrenheit:temperature)
displayResult(temperature:temperature, fromLabel:"F
case "F", "f":
temperature = getTemperature(label:"Celsius")
result = calculateFahrenheit(celsius:temperature)
displayResult(temperature:temperature, fromLabel:"C
default:
print("You must enter C to convert to Celsius or F
}
}
main()
Output
References
Review Questions
True / False
Answers:
1. false
2. true
3. false
4. false
5. false
Expressions
1. 25 < 7
2. 3 < 7
Answers:
1. 0
2. 1
3. 1
4. 0
5. 1
6. 0
7. 1
8. Error, the “not greater than” is not a valid operator.
9. 0
10. 1
11. 0
12. 1
13. 0
14. 1
15. 0
16. Error, there needs to be an operand between the
operators < and &&.
Activities
References
Overview
Chapter Outline
◦ Program Plan
◦ Loop Examples
◦ C++
◦ C#
◦ Java
◦ JavaScript
◦ Python
◦ Swift
• Practice
Loops | 313
Learning Objectives
314 | Loops
Iteration Control
Structures
Overview
Discussion
pseudocode: While
pseudocode: Do While
pseudocode: For
References
Overview
Discussion
There are two commonly used test before loops in the iteration
(or repetition) category of control structures. They are: while
and for. This module covers the: while.
Child: The child says nothing, but mother knows the child had
Cheerios for breakfast and history tells us that the child most
likely spilled some Cheerios on the floor.
Mother says: “While it is true that you see (As long as you can
see) a Cheerio on the floor, pick it up and put it in the garbage.”
Infinite Loops
loop_response = 'y';
While loop_response = 'y'
Output "What is your age? "
Input user_age
Output "What is your friend's age? "
Input friend_age
Output "Together your ages add up to: "
Output user_age + friend_age
Output "Do you want to try again? y or n "
Input loop_response
No matter what the user replies during the flag update, the
test expression does not do a relational comparison but does
an assignment. It assigns ‘y’ to the variable and asks if ‘y’ is true?
Since all non-zero values are treated as representing true, the
answer to the test expression is true. Viola, you have an infinite
loop.
The examples above are for an event controlled loop. The flag
updating is an event where someone decides if they want the
loop to execute again. Often the initialization sets the flag so
that the loop will execute at least once.
counter = 0
While counter < 5
Output "I love ice cream!"
counter += 1
Consider:
counter = 0;
while counter < 5
Output "I love ice cream!"
Variations on Counting
counter = 0;
While counter < age
Output "I love corn chips!"
counter += 1
Key Terms
counting controlled
Using a variable to count up or down to control a loop.
event controlled
Using user input to control a loop.
infinite loop
A sequence of instructions which loops endlessly, either
due to the loop having no terminating condition, having
one that can never be met, or one that causes the loop to
2
start over.
initialize item
An attribute of iteration control structures.
loop attributes
Items associated with iteration or looping control
structures.
might not happen
Indicating that test before loops might not execute the
action.
while
A test before iteration control structure.
Discussion
There are two commonly used test after loops in the iteration
(or repetition) category of control structures. They are: do while
and repeat until. This module covers both.
do
some statements or action
some statements or action
some statements or action
update the flag
while the answer to the question is true
do
some statements or action
some statements or action
some statements or action
update the flag
while expression is true
• Action or actions
• Update of the flag
• Test expression
The English phrasing is, “You do the action while the expression
is true”. This is looping on the true. When the test expression
repeat
some statements or action
some statements or action
some statements or action
update the flag
until the answer to the question becomes true
repeat
some statements or action
some statements or action
some statements or action
update the flag
until expression becomes true
• Action or actions
• Update of the flag
• Test expression
The English phrasing is, “You repeat the action until the
expression becomes true”. This is looping on the false. When
the test expression becomes true, you stop the loop and go
on with the next item in the program. Notice, because this is
a test after loop the action will always happen at least once.
It is called a “test after loop” because the test comes after the
action. It is also sometimes called a post-test loop, meaning the
test is post (or Latin for after) the action and update.
An Example
Do
Output "What is your age? "
Input user_age
Output "What is your friend's age? "
Input friend_age
Output "Together your ages add up to: "
Output age_user + friend_age
Output "Do you want to try it again? y or n "
Input loop_response
While loop_response == 'y'
The three attributes of a test after loop are present. The action
part consists of the 6 lines that prompt for data and then
displays the total of the two ages. The update of the flag is the
displaying the question and getting the answer for the variable
loop_response. The test is the equality relational comparison of
the value in the flag variable to the lower case character of y.
Infinite Loops
loop_response = 'y'
Do
Output "What is your age? "
Input user_age
Output "What is your friend's age? "
Input friend_age
Output "Together your ages add up to: "
Output user_age + friend_age
While loop_response == 'y'
do
Output "What is your age? "
No matter what the user replies during the flag update, the
test expression does not do a relational comparison but does
an assignment. It assigns ‘y’ to the variable and asks if ‘y’ is true?
Since all non-zero values are treated as representing true, the
answer to the text question is true. Viola, you have an infinite
loop.
Key Terms
action item
An attribute of iteration control structures.
at least once
Indicating that test after loops execute the action at least
once.
do while
A test after iteration control structure.
infinite loop
A sequence of instructions which loops endlessly, either
due to the loop having no terminating condition, having
one that can never be met, or one that causes the loop to
3
start over.
References
Overview
Discussion
Computer Implementation
This is fine but what if the user accidentally has on the caps
lock. Then the response of ‘Y’ would not have the control
structure loop and perform the action again. The solution lies
in looking at the flag twice. Consider:
Key Terms
flag
A variable used to store information that will normally be
used to control the program.
References
Overview
Discussion
There are two commonly used test before loops in the iteration
(or repetition) category of control structures. They are: while
and for. This module covers the: for.
for
initialization of the starting value
starting value is less than the stopping value
some statements or action
some statements or action
some statements or action
increment the starting value
An Example
The four attributes of a test before loop (remember the for loop
is one example of a test before loop) are present.
Key Terms
for
A test before iteration control structure typically used for
counting.
References
Overview
Discussion
break
counter = 0;
While counter < 8
Output counter
If counter == 4
break
counter += 1
continue
The following gives the appearance that the loop will print to
the monitor 8 times, but the continue statement causes it not
to print number 4.
return
goto
exit
branching statements
Allow the flow of execution to jump to a different part of
the program.
break
A branching statement that terminates the existing
structure.
continue
A branching statement that causes a loop to stop its
current iteration and begin the next one.
exit
A predefined function used to prematurely stop a
program and return to the operating system.
goto
An unstructured branching statement that causes the
logic to jump to a different place in the program.
return
A branching statement that causes a function to jump
back to the function that called it.
References
Overview
Discussion
That is you fetch the existing value of the counter and add
one then store the answer back into the variable counter. Many
programming languages allow their increment and
decrement operators to only be used with the integer data
Operator Meaning
Code Examples
Basic Concept
counter = counter + 1;
counter += 1;
counter++;
++counter;
Postfix Increment
Prefix Increment
Exercises
Key Terms
decrement
Subtracting one from the value of a variable.
increment
Adding one to the value of a variable.
References
Overview
Discussion
There are times when character and integer data types are
lumped together because they both act the same (often called
the integer family). Maybe we should say they act differently
than the floating-point data types. The integer family values
jump from one value to another. There is nothing between
6 and 7 nor between ‘A’ and ‘B’. It could be asked why not
This circular nature of the integer family works for both integer
and character data types. In theory, it should work for the
Boolean data type as well; but in most programming
languages it does not for various technical reasons.
Key Terms
circular nature
Connecting the negative and positive ends of the domain
of an integer family data type.
loop control
Making sure the attributes of a loop are properly handled.
modular arithmetic
A system of arithmetic for integers where numbers “wrap
around”.
References
Overview
Nested for loops places one for loop inside another for loop.
The inner loop is repeated for each iteration of the outer loop.
Discussion
if expression
true action
else
false action
This is the basic form of the if then else control structure. Now
consider:
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 1
----------------------------------------------------------
1 ! 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 1
2 ! 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 2
3 ! 3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 3
4 ! 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 4
5 ! 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 5
6 ! 6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 6
7 ! 7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | 7
8 ! 8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | 8
9 ! 9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | 81 | 9
10 ! 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 10
Key Terms
complex logic
Often solved with nested control structures.
References
Main Program
Get Starting value
Get Ending value
Get Increment value
Demonstrate While Loop
Demonstrate Do Loop
Demonstrate For Loop
Get Value
Parameters:
Label
Process:
Display prompt with label
Get value
Return Value:
Value
Counting
Pseudocode
... This program demonstrates While, Do, and For loop counting
Function Main
Declare Integer start
Declare Integer stop
Declare Integer increment
Output
Flowchart
Main GetValue
(String name)
Input value
Integer stop
start = GetValue("starting")
stop = GetValue("ending")
increment = GetValue
("increment")
WhileLoop(start, stop,
increment)
DoLoop(start, stop,
increment)
ForLoop(start, stop,
increment)
End
Integer count
Integer count
count = start
count = start
True
count <= stop
False
Output count Output count
End
ForLoop
(Integer start, Integer stop, Integer increment)
Integer count
Next
count = start to stop step
increment
Done
Output count
End
References
Counting
#include
int main() {
int start = getValue("starting");
int stop = getValue("ending");
int increment = getValue("increment");
return 0;
}
cout << "Enter " << name << " value:" <> value;
return value;
}
Output
References
Counting
using System;
C# Examples | 365
return value;
}
366 | C# Examples
for (int count = start; count <= stop; count += increme
{
Console.WriteLine(count);
}
}
}
Output
References
C# Examples | 367
Java Examples
DAVE BRAUNSCHWEIG
Counting
import java.util.*;
return value;
}
References
Counting
main()
function main() {
var start = getValue("starting");
var stop = getValue("ending");
var increment = getValue("increment");
function getValue(name) {
output("Enter " + name + " value:");
var value = Number(input());
return value;
}
function input(text) {
if (typeof window === 'object') {
return prompt(text)
}
else if (typeof console === 'object') {
const rls = require('readline-sync');
var value = rls.question(text);
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}
Output
References
Counting
def get_value(name):
print("Enter " + name + " value:")
value = int(input())
return value
def main():
start = get_value("starting")
stop = get_value("ending")
increment = get_value("increment")
demonstrate_while_loop(start, stop, increment)
demonstrate_do_loop(start, stop, increment)
demonstrate_for_loop(start, stop, increment)
main()
Output
References
Counting
import Foundation
count = start
while count <= stop {
print(count)
count = count + increment
}
count = start
repeat {
print(count)
count = count + increment
} while count <= stop
}
func main() {
var start : Int
var stop : Int
var increment : Int
main()
Output
References
Review Questions
True / False
Answers:
1. false
2. true
3. false
4. false
5. false
6. false
7. true
Activities
While Loops
For Loops
Nested Loops
Overview
Chapter Outline
◦ Program Plan
◦ C++
◦ C#
◦ Java
◦ JavaScript
◦ Python
◦ Swift
• Practice
Arrays | 387
Learning Objectives
388 | Arrays
Arrays and Lists
Overview
Discussion
Arrays can have multiple axes (more than one axis). Each axis
is a dimension. Thus a single-dimension array is also known as
a list. A two-dimension array is commonly known as a table (a
spreadsheet like Excel is a two dimension array). In real life,
there are occasions to have data organized into multiple-
Defining an Array
Language Example
ages[0] = 49;
ages[1] = 48;
ages[2] = 26;
ages[3] = 19;
ages[4] = 16;
dimension
An axis of an array.
list
A single dimension array.
table
A two-dimension array.
References
1
Index notation is used to specify the elements of an array.
Most current programming languages use square brackets []
as the array index operator. Older programming languages,
such as FORTRAN, COBOL, and BASIC, often use parentheses
() as the array index operator.
Discussion
Example:
ages[3] = 20;
Key Terms
array member
An element or value in an array.
index
An operator that allows us to reference a member of an
array.
offset
The method of referencing array members by starting at
zero.
Discussion
Assume an integer array named ages with five values of 49, 48,
26, 19, and 16, respectively. In pseudocode, this might be written
as:
Output ages[0]
Output ages[1]
Output ages[2]
Output ages[3]
Output ages[4]
While this works for short arrays, it is not very efficient, and
quickly becomes overwhelming for longer arrays. One of the
For index = 0 to 4
Output ages[index]
End
This method allows for flexible coding. By writing the for loop
in this fashion, we can change the declaration of the array by
adding or subtracting members and we don’t need to change
our for loop code.
Key Terms
References
Discussion
Pseudocode
Function Main
Output
49
48
26
19
16
Key Terms
array function
A user-defined specific task function designed to process
an array.
References
Discussion
1. Wikipedia: Statistics
Pseudocode
Function Main
Declare Integer Array ages[5]
Declare Integer total
Assign total = 0
For index = 0 to Size(array) - 1
Assign total = total + array[index]
End
Return Integer total
Output
sum
Latin for summa or a total.
References
Discussion
Pseudocode
Function Main
Declare Integer Array ages[5]
Declare Integer maximum
Declare Integer minimum
Output
Key Terms
linear search
Using a loop to sequentially step through an array.
maximum
Aka max or the largest member of an array.
minimum
Aka min or the smallest member of an array.
References
Discussion
#include <algorithm>
C++ sort(array, array + sizeof(array) /
sizeof(int));
C# System.Array.Sort(array)
import java.util.Arrays;
Java
Arrays.sort(array);
JavaScript array.sort();
Python array.sort()
Swift array.sort()
Key Terms
sorting
Arranging data according to their values.
References
Overview
Discussion
Function Main
Declare String Array names[5]
Declare Integer Array ages[5]
DisplayArrays(names, ages)
End
Output
Key Terms
parallel array
An implicit data structure that uses multiple arrays to
References
Overview
Discussion
Pseudocode
Function Main
Declare String Array game[3][3]
Assign game = [ ["X", "O", "X"], ["O", "O", "O"], ["X", "O"
DisplayGame(game)
End
Output "Tic-Tac-Toe"
For row = 0 to 2
For column = 0 to 2
Output game[row][column]
If column < 2 Then
Output " | "
End
End
End
End
Tic-Tac-Toe
X | O | X
O | O | O
X | O | X
Key Terms
array member
An element or value in an array.
dimension
An axis of an array.
index
An operator that allows us to reference a member of an
array.
list
A single dimension array.
offset
The method of referencing array members by starting at
zero.
table
A two-dimension array.
References
Overview
Discussion
int values[] =
C++ int values[3];
{0, 1, 2};
values = [0,
Python values = [None] * 3
1, 2]
#include <list>
C++ insert erase
std::list
push, pop,
JavaScript Array
splice splice
Key Terms
dynamic array
A data structure consisting of a collection of elements that
allows individual elements to be added or removed.
fixed array
A data structure consisting of a collection of elements for
which the size or length is determined when the data
structure is defined or allocated.
References
Main Program
Create name and age arrays
Display arrays
Calculate sum of ages
Calculate maximum age
Calculate minimum age
Display sum, maximum, and minimum
Sort and display ages
Display parallel arrays
Demonstrate fixed array
Demonstrate dynamic array
Demonstrate multidimensional array
Calculate Sum
Parameters:
Array
Process:
Initialize total
Loop for index from 0 to array length by 1
Add array index value to total
Return Value:
Sum
Calculate Maximum
Parameters:
Array
Process:
Initialize maximum to first array value
Calculate Minimum
Parameters:
Array
Process:
Initialize minimum to first array value
Loop for index from 1 to array length by 1
If minimum > array index value
minimum = array index value
Return Value:
Minimum
Arrays
#include <iostream>
#include <list>
#include <algorithm>
int main() {
string names[] = {"Lisa", "Michael", "Ashley", "Jacob", "Em
int ages[] = {49, 48, 26, 19, 16};
demonstrateFixedArray();
demonstrateDynamicArray();
demonstrateMultidimensionalArray();
return 0;
}
void demonstrateFixedArray() {
int arry[5];
srand (time(NULL));
for (int index = 0; index < 5; index++) {
int number = rand() % 100;
arry[index] = number;
}
displayArray(arry, 5);
}
void demonstrateDynamicArray() {
list arry;
void demonstrateMultidimensionalArray() {
string game[3][3] = {
{"X", "O", "X"},
{"O", "O", "O"},
{"X", "O", "X"} };
Output
array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
References
Arrays
using System;
using System.Collections.Generic;
class Arrays {
public static void Main (string[] args)
{
String[] names = {"Lisa", "Michael", "Ashley", "Jacob",
int[] ages = {49, 48, 26, 19, 16};
DisplayArray(ages);
DemonstrateParallelArrays(names, ages);
System.Array.Sort(ages);
DisplayArray(ages);
428 | C# Examples
DemonstrateFixedArray();
DemonstrateDynamicArray();
DemonstrateMultidimensionalArray();
}
C# Examples | 429
}
430 | C# Examples
}
C# Examples | 431
}
}
Console.WriteLine();
}
}
}
Output
array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
array[0] = 65
array[1] = 45
array[2] = 78
array[3] = 32
array[4] = 4
array[0] = 24
array[1] = 62
432 | C# Examples
array[2] = 97
array[3] = 40
array[4] = 82
X | O | X
O | O | O
X | O | X
References
C# Examples | 433
Java Examples
DAVE BRAUNSCHWEIG
Arrays
import java.util.*;
class Main {
public static void main(String[] args) {
String[] names = {"Lisa", "Michael", "Ashley", "Jacob",
int[] ages = {49, 48, 26, 19, 16};
displayArray(ages);
demonstrateParallelArrays(names, ages);
Arrays.sort(ages);
displayArray(ages);
demonstrateFixedArray();
Output
array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
array[0] = 28
array[1] = 30
References
Arrays
main()
function main() {
var names = ['Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily']
var ages = [49, 48, 26, 19, 16];
displayArray(names);
displayArray(ages);
demonstrateParallelArrays(names, ages);
ages.sort();
displayArray(ages);
demonstrateFixedArray();
function displayArray(array) {
for (var index = 0; index < array.length; index++) {
output('array[' + index + '] = ' + array[index]);
}
}
function calculateSum(array) {
var total = 0;
for (var index = 0; index < array.length; index++) {
total += array[index];
}
return total;
}
function calculateMaximum(array) {
var maximum = array[0];
for (var index = 1; index < array.length; index++) {
if (maximum < array[index]) {
maximum = array[index];
}
}
return maximum;
}
function calculateMinimum(array) {
var minimum = array[0];
for (var index = 1; index < array.length; index++) {
if (minimum > array[index]) {
minimum = array[index];
}
}
function demonstrateFixedArray() {
var array = new Array(5);
function demonstrateDynamicArray() {
var array = [];
function demonstrateMultidimensionalArray() {
var game = [
['X', 'O', 'X'],
['O', 'O', 'O'],
['X', 'O', 'X'] ];
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}
Output
array[0] = Lisa
array[1] = Michael
array[2] = Ashley
array[3] = Jacob
array[4] = Emily
array[0] = 49
array[1] = 48
array[2] = 26
References
Arrays
import random
def display_array(array):
for index in range(len(array)):
print('array[' + str(index) + '] = ' +
str(array[index]))
def calculate_sum(array):
total = 0
for index in range(len(array)):
total += array[index]
return total
def calculate_maximum(array):
maximum = array[0]
for index in range(1, len(array)):
if maximum < array[index]:
maximum = array[index]
return maximum
def demonstrate_fixed_array():
array = [None] * 5
for index in range(len(array)):
array[index] = random.randint(0, 100)
display_array(array)
def demonstrate_dynamic_array():
array = []
for index in range(5):
array.append(random.randint(0, 100))
display_array(array)
def demonstrate_multidimensional_array():
game = [
['X', 'O', 'X'],
['O', 'O', 'O'],
['X', 'O', 'X'] ]
def main():
names = ['Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily']
ages = [49, 48, 26, 19, 16]
display_array(names)
display_array(ages)
total = calculate_sum(ages)
maximum = calculate_maximum(ages)
minimum = calculate_minimum(ages)
demonstrate_parallel_arrays(names, ages)
ages.sort()
display_array(ages)
demonstrate_fixed_array()
demonstrate_dynamic_array()
demonstrate_multidimensional_array()
main()
array[0] = Lisa
array[1] = Michael
array[2] = Ashley
array[3] = Jacob
array[4] = Emily
array[0] = 49
array[0] = Lisa
array[1] = Michael
array[2] = Ashley
array[3] = Jacob
array[4] = Emily
array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
array[0] = 18
array[1] = 14
array[2] = 59
array[3] = 99
References
Arrays
import Foundation
func demonstrateFixedArray() {
var array: [Int] = [Int](repeating: 0, count: 5)
srand(UInt32(time(nil)))
for index in 0...4 {
func demonstrateDynamicArray() {
var array: [Int] = []
srand(UInt32(time(nil)))
for _ in 0...4 {
array.append(random() % 100)
}
print(array)
}
func demonstrateMultidimensionalArray() {
var game: [[String]]
game = [
["X", "O", "X"],
["O", "X", "O"],
["X", "O", "X"]
]
displayArray(array:ages)
total = ages.reduce(0, +)
maximum = ages.max()!
minimum = ages.min()!
print("total:", total)
print("maximum:", maximum)
print("minimum:", minimum)
demonstrateParallelArrays(names:names, ages:ages)
ages.sort()
displayArray(array:ages)
demonstrateFixedArray()
demonstrateDynamicArray()
demonstrateMultidimensionalArray()
}
main()
Output
array[0] = 49
References
Review Questions
True / False
Answers:
1. false
2. true
3. true
4. false
5. false
6. false
7. true
Short Answer
Activities
Defined-Value Arrays
Fixed-Length Arrays
References
Overview
Chapter Outline
• Strings
• String Functions
• String Formatting
• File Input and Output
• Exception Handling
• Loading an Array from a File
• Code Examples
◦ Program Plan
◦ C++
◦ C#
◦ Java
◦ JavaScript
◦ Python
◦ Swift
• Practice
Learning Objectives
Discussion
Strings | 459
is a sequenced collection of elements of the same data type
with a single identifier name. This definition perfectly describes
our string data type concept. The simplest array is called a
one-dimensional array; also know as a list because we usually
list the members or elements vertically. However, strings are
viewed as a one-dimensional array that visualize as listed
horizontally. Strings are an array of character data.
C++ string
C# String
Java String
JavaScript String
Python str()
Swift String
460 | Strings
Key Terms
array
A sequenced collection of elements of the same data type
with a single identifier name.
buffer overflow
An anomaly where a program overruns a memory storage
location and overwrites adjacent memory locations.
concatenation
Combining two strings into one string.
string class
A complex data item that uses object oriented
programming.
References
Strings | 461
String Functions
DAVE BRAUNSCHWEIG
Overview
Discussion
comparison <, >, ==, etc. <, >, ==, etc. <, >, ==, etc.
concatenation +, += +, += +, +=
toLowerCase(), lowercased(),
lower(), upper(),
case toUpperCase(),
etc. uppercased()
etc.
comparison <, >, ==, etc. <, >, ==, etc. <, >, ==, etc.
concatenation +, += +, += +, +=
Key Terms
concatenate
2
Join character strings end-to-end.
trim
3
Remove leading and trailing spaces from a string.
References
2. Wikipedia: Concatenation
3. Wikipedia: Trimming (computer programming)
Discussion
snprintf(str, sizeof(str),
"Hello %s!", name);
C++ snprintf()
snprintf(str, sizeof(str),
"$%.2f", value);
String.Format("Hello {0}!",
name);
C# Format()
String.Format("{0:$0.00}",
value);
String.format("Hello %s!",
Java format() name);
String.format("$%.2f", value);
Key Terms
code injection
The exploitation of a computer bug that is caused by
References
Overview
Discussion
Read – Moving data from a device that has been opened into a
memory location defined in your program. For example:
text = read(datafile)
or
text = datafile.read()
close(datafile)
or
datafile.close()
or
# Python3
with open(filespec, mode) as datafile:
# ...
Key Terms
close
Your program requesting the operating system to release
a file that was previously opened.
device token
A key value provided by the operating system to associate
a device to your program.
filename
The name and its extension.
filespec
The location of a file along with its filename.
open
Your program requesting the operating system to let it
have access to an existing file or to open a new file.
read
Moving data from a device that has been opened into a
memory location defined in your program.
stream
3
A sequence of data elements made available over time.
stdin
4
Standard input stream, typically the keyboard.
References
Discussion
Either:
Or:
1. Read the file and dynamically add the records to the array.
1. Read the entire file into memory, split the records and
then process each record.
2. Read the file line by line and process one record at a time.
Processing Fields
Celsius,Fahrenheit
0.0,32.0
1.0,33.8
2.0,35.6
Open file
Read header
While Not End-Of-File
Read line
Increment record count
Close file
dynamic memory
Aka stack created memory associated with local scope.
static memory
Aka data area memory associated with global scope.
References
Main Program
Demonstrate string concatenation
Demonstrate lower case
Demonstrate upper case
Demonstrate find
Demonstrate length
Demonstrate replace
Demonstrate reverse
Demonstrate slice
Demonstrate strip
Demonstrate number formatting
Main Program
Read File
Read File
Parameters:
Filename
Process:
Create exception handler
Open file
While not End-of-File
Read line
Display line
Close file
Strings
#include <algorithm>
#include <iostream>
#include <string>
string toLower(string);
string toUpper(string);
int main() {
string str = "Hello";
return str;
}
return str;
}
Output
string: Hello
tolower: hello
toupper: HELLO
string.find('e'): 1
string.length(): 5
string.replace(0, 1, "j"): jello
string.substr(2, 2): ll
Bob earned $123.46
Files
// References:
// https://en.wikibooks.org/wiki/C%2B%2B_Programming
#include <fstream>
#include <iostream>
#include <string>
void readFile(string);
int main() {
string FILENAME = "temperature.txt";
readFile(FILENAME);
}
file.open(filename, fstream::in);
if (file.is_open()) {
while (getline(file, line))
{
cout << line << endl;
}
file.close();
} else {
cout << "Error reading " << filename << endl;
}
}
Output
Celsius,Fahrenheit
0,32
10,50
20,68
References
Strings
using System;
class Strings
{
public static void Main (string[] args)
{
String str = "Hello";
484 | C# Examples
Output
string: Hello
string.ToLower(): hello
string.ToUpper(): HELLO
string.IndexOf('e'): 1
string.Length: 5
string.Replace('H', 'j'): jello
string(Substring(2, 2)): ll
string.Trim(): Hello
Bob earned $123.46
Files
// References:
// https://en.wikibooks.org/wiki/C_Sharp_Programming
using System;
ReadFile(FILENAME);
}
C# Examples | 485
string line;
try
{
using (file = System.IO.File.OpenText(filename))
{
while (true)
{
line = file.ReadLine();
if (line == null)
{
break;
}
Console.WriteLine(line);
}
}
}
catch(Exception exception)
{
Console.WriteLine("Error reading " + filename);
Console.WriteLine(exception.Message);
}
}
}
Output
Celsius,Fahrenheit
0,32
10,50
20,68
...
80,176
90,194
486 | C# Examples
100,212
References
C# Examples | 487
Java Examples
DAVE BRAUNSCHWEIG
Strings
class Main {
public static void main(String[] args) {
String str = "Hello";
Output
string: Hello
string..toLowerCase(): hello
Files
// References:
// https://en.wikibooks.org/wiki/Java_Programming
import java.util.*;
class Main {
public static void main(String[] args) {
String FILENAME = "temperature.txt";
readFile(FILENAME);
}
while(true) {
line = reader.readLine();
if (line == null) {
Output
Celsius,Fahrenheit
0,32
10,50
20,68
...
80,176
90,194
100,212
References
Strings
main();
function main()
{
var str = "Hello";
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
Output
string: Hello
string..toLowerCase(): hello
string.toUpperCase(): HELLO
string.indexOf('e'): 1
string.length: 5
string.replace('H', 'j'): jello
string(substring(2,4): ll
string.trim(): Hello
string.format(): Bob earned $123.46
Files
const fs = require('fs');
main();
function main() {
const filename = "temperature.txt";
function readFile(filename) {
try {
const text = fs.readFileSync(
filename,
{encoding:"utf8"});
Output
Celsius,Fahrenheit
0,32
10,50
20,68
...
80,176
90,194
100,212
Strings
def main():
string = "Hello"
name = "Bob"
value = 123.456
print("string.format(): {0} earned ${1:.2f}".format(name, v
main()
string: Hello
string.lower(): hello
string.upper(): HELLO
string.find('e'): 1
len(string): 5
string.replace('H', 'j'): jello
string[::-1]: olleH
string[2:4]: ll
string.strip('H'): ello
string.format(): Bob earned $123.46
Files
def read_file(filename):
try:
with open(filename, "r") as file:
for line in file:
line = line.strip()
print(line)
except Exception as exception:
print(exception)
def main():
filename = "temperature.txt"
main()
Output
Celsius,Fahrenheit
0,32
10,50
20,68
...
80,176
90,194
100,212
References
Strings
import Foundation
func main() {
let string:String = "Hello"
main()
Output
string: Hello
string.lowercased(): hello
string.uppercased(): HELLO
find(string, "e"): 1
string.count: 5
string.replacingOccurrences(of:"H", with:"j"): jello
string.reversed(): olleH
substring(2, 2): ll
string.trimmingCharacters("H"): ello
Bob earned $123.46
Files
// References:
import Foundation
func readFile(filename:String) {
var text = ""
do {
text = try String(contentsOfFile: filename, encoding: .
func main() {
let filename:String = "temperature.txt"
readFile(filename:filename)
}
main()
Output
Celsius,Fahrenheit
0,32
10,50
20,68
References
Review Questions
True / False
Answers:
1. false
Short Answer
Activities
String Activities
1. Create a program that asks the user for a single line of text
containing a first name and last name, such as Firstname
Note: Each of the following activities uses code only to read the
file. It is not necessary to use code to create the file.
References
Discussion
throw // an exception
try {
C++ throw // code statements
C# try } catch {
Java
JavaScript catch // handle exception
Swift finally } finally {
// clean up
}
raise # an exception
try:
raise
# code statements
try
Python except:
except
# handle exception
finally
finally:
# clean up
defer {
// clean up
}
defer
throw // an exception
throw
Swift do {
do try
try // code statements
catch
} catch {
// handle exception
}
exception
Anomalous or exceptional conditions requiring special
2
processing.
interrupt
A request for the processor to interrupt currently
executing code (when permitted), so that the event can be
3
processed in a timely manner.
References
Overview
Chapter Outline
◦ C++
◦ C#
◦ Java
◦ JavaScript
◦ Python
◦ Swift
• Practice
Learning Objectives
Object-Oriented
Programming | 511
2. Gain exposure to object-oriented programming.
3. Given example source code, create a program that uses
object-oriented programming concepts to solve a given
problem.
Overview
Discussion
Key Terms
attribute
4
A specification that defines a property of an object.
class
An extensible program-code-template for creating
objects, providing initial values for state (member
References
Overview
Discussion
Encapsulation | 517
inside the object and write separate code to perform the action
outside of the object.
We can say that the object “knows how” to do things with its
own data, and it’s a bad idea for us to access its internals and
do things with the data ourselves. If an object doesn’t have an
interface method which does what we want to do, we should
add a new method or update an existing one.
518 | Encapsulation
property is intended to be private and is not part of the object’s
public interface: we begin its name with an underscore. Python
also supports the use of a property decorator to replace a
simple attribute with a method without changing the object’s
interface.
Key Terms
abstraction
A technique for arranging complexity of computer
systems so that functionality may be separated from
23
specific implementation details.
accessor
A method used to return the value of a private member
4
variable, also known as a getter method.
encapsulation
A language mechanism for restricting direct access to
5
some of an object’s components.
information hiding
The principle of segregation of the design decisions in a
computer program from other parts of the program. See
6
encapsulation.
mutator
A method used to control changes to a private member
7
variable, also known as a setter method.
Encapsulation | 519
private
An access modifier that restricts visibility of a property or
8
method to the class in which it is defined.
public
An access modifier that opens visibility of a property or
9
method to all other classes.
References
520 | Encapsulation
Inheritance and
Polymorphism
DAVE BRAUNSCHWEIG
Overview
Discussion
Inheritance and
Polymorphism | 521
and Student, each of which inherit from Person. When we
can describe the relationship between two objects using the
phrase is-a, that relationship is inheritance.
Key Terms
inheritance
An object or class being based on another object or class,
using the same implementation or specifying a new
2
implementation to maintain the same behavior.
References
Objects
#include <iostream>
class Temperature {
public:
double getCelsius(void);
void setCelsius(double value);
double getFahrenheit(void);
void setFahrenheit(double value);
double toCelsius(double fahrenheit);
double toFahrenheit(double celsius);
private:
double celsius;
double fahrenheit;
};
double Temperature::getFahrenheit(void) {
return fahrenheit;
}
int main() {
Temperature temp1;
Temperature temp2;
temp2.setFahrenheit(100.0);
cout << "temp2.fahrenheit = " << temp2.getFahrenheit() << e
cout << "temp2.celsius = " << temp2.getCelsius() << endl;
}
Output
temp1.celsius = 100
temp1.fahrenheit = 212
temp2.fahrenheit = 100
temp2.celsius = 37.7778
References
Objects
using System;
temp1.Celsius = 100;
Console.WriteLine("temp1.Celsius = " + temp1.Celsius.To
Console.WriteLine("temp1.Fahrenheit = " + temp1.Fahrenh
Console.WriteLine("");
C# Examples | 527
temp2.Fahrenheit = 100;
Console.WriteLine("temp2.Fahrenheit = " + temp2.Fahrenh
Console.WriteLine("temp2.Celsius = " + temp2.Celsius.To
}
}
set
{
_celsius = value;
_fahrenheit = ToFahrenheit(value);
}
}
528 | C# Examples
return _fahrenheit;
}
set
{
_fahrenheit = value;
_celsius = ToCelsius(value);
}
}
if (fahrenheit.HasValue)
{
this.Fahrenheit = Convert.ToDouble(fahrenheit);
}
}
C# Examples | 529
Output
temp1.Celsius = 0
temp1.Fahrenheit = 32
temp1.Celsius = 100
temp1.Fahrenheit = 212
temp2.Fahrenheit = 0
temp2.Celsius = -17.7777777777778
temp2.Fahrenheit = 100
temp2.Celsius = 37.7777777777778
References
530 | C# Examples
Java Examples
DAVE BRAUNSCHWEIG
Objects
import java.util.*;
class Main {
public static void main(String[] args) {
Temperature temp1 = new Temperature();
temp1.setCelsius(100.0);
System.out.println("temp1.celsius = " + temp1.getCelsiu
System.out.println("temp1.fahrenheit = " + temp1.getFah
System.out.println("");
class Temperature {
Double celsius;
Double fahrenheit;
temp1.celsius = 100.0
temp1.fahrenheit = 212.0
temp2.fahrenheit = 100.0
temp2.celsius = 37.77777777777778
References
Objects
class Temperature {
constructor() {
this._celsius = 0;
this._fahrenheit = 32;
}
get celsius() {
return this._celsius;
}
set celsius(value) {
this._celsius = value;
this._fahrenheit = this.toFahrenheit(value);
}
get fahrenheit() {
return this._fahrenheit;
}
set fahrenheit(value) {
this._fahrenheit = value;
this._celsius = this.toCelsius(value);
toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9
}
toFahrenheit(celsius) {
return celsius * 9 / 5 + 32
}
}
main()
function main() {
var temp1 = new Temperature();
temp1.celsius = 0
output("temp1.celsius = " + temp1.celsius);
output("temp1.fahrenheit = " + temp1.fahrenheit);
output("");
temp1.celsius = 100;
output("temp1.celsius = " + temp1.celsius);
output("temp1.fahrenheit = " + temp1.fahrenheit);
output("");
temp2.fahrenheit = 100;
output("temp2.fahrenheit = " + temp2.fahrenheit);
output("temp2.celsius = " + temp2.celsius);
}
function output(text) {
if (typeof document === 'object') {
document.write(text);
}
else if (typeof console === 'object') {
console.log(text);
}
else {
print(text);
}
}
Output
temp1.celsius = 0
temp1.fahrenheit = 32
temp1.celsius = 100
temp1.fahrenheit = 212
temp2.fahrenheit = 0
temp2.celsius = -17.77777777777778
temp2.fahrenheit = 100
temp2.celsius = 37.77777777777778
Objects
class Temperature:
_celsius = None
_fahrenheit = None
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
self._celsius = float(value)
self._fahrenheit = self.to_fahrenheit(self._celsius)
@property
def fahrenheit(self):
return self._fahrenheit
@fahrenheit.setter
def main():
temp1 = Temperature(celsius=0)
print("temp1.celsius =", temp1.celsius)
print("temp1.fahrenheit =", temp1.fahrenheit)
print("")
temp1.celsius = 100
print("temp1.celsius =", temp1.celsius)
print("temp1.fahrenheit =", temp1.fahrenheit)
print("")
temp2 = Temperature(fahrenheit=0)
print("temp2.fahrenheit =", temp2.fahrenheit)
temp2.fahrenheit = 100
print("temp2.fahrenheit =", temp2.fahrenheit)
print("temp2.celsius =", temp2.celsius)
main()
Output
temp1.celsius = 0
temp1.fahrenheit = 32.0
temp1.celsius = 100.0
temp1.fahrenheit = 212.0
temp2.fahrenheit = 0
temp2.celsius = -17.77777777777778
temp2.fahrenheit = 100.0
temp2.celsius = 37.77777777777778
References
Objects
class Temperature {
var _celsius:Double = 0
var _fahrenheit:Double = 32
init(celsius:Double?=nil, fahrenheit:Double?=nil) {
if celsius != nil {
self.celsius = celsius!
}
if fahrenheit != nil {
self.fahrenheit = fahrenheit!
}
}
func setCelsius(celsius:Double) {
self.celsius = celsius
self.fahrenheit = toFahrenheit(celsius:celsius)
}
func setFahrenheit(fahrenheit:Double) {
self.fahrenheit = fahrenheit
self.celsius = toCelsius(fahrenheit:fahrenheit)
}
func main() {
let temp1 = Temperature(celsius:0);
print("temp1.celsius = " + String(temp1.celsius));
print("temp1.fahrenheit = " + String(temp1.fahrenheit));
print("");
temp1.celsius = 100;
print("temp1.celsius = " + String(temp1.celsius));
print("temp1.fahrenheit = " + String(temp1.fahrenheit));
print("");
temp2.fahrenheit = 100;
print("temp2.fahrenheit = " + String(temp2.fahrenheit));
print("temp2.celsius = " + String(temp2.celsius));
}
main()
temp1.celsius = 0.0
temp1.fahrenheit = 32.0
temp1.celsius = 100.0
temp1.fahrenheit = 212.0
temp2.fahrenheit = 0.0
temp2.celsius = -17.7777777777778
temp2.fahrenheit = 100.0
temp2.celsius = 37.7777777777778
References
Review Questions
Answers:
1. false
2. true
Short Answer
Activities
Practice | 545
passing parameters and returning results. Create test data to
validate the accuracy of each program. Add comments at the
top of the program and include references to any resources
used.
546 | Practice
Tuesday, etc.). Include data validation in the class and error
handling in the main program.
References
Practice | 547