Programming Fundamentals A Modular Structured Approach
Programming Fundamentals A Modular Structured Approach
Preface
2. Author Acknowledgements
3. Orientation and Syllabus
4. Sharing/Rating Connexions Materials
5. 1. Introduction to Programming
1. Systems Development Life Cycle
2. Bloodshed Dev-C++ 5 Compiler/IDE
3. Modularization and C++ Program Layout
4. Practice 1: Introduction to Programming
6. 2. Program Planning & Design
1. Program Design
2. Pseudocode
3. Test Data
4. Practice 2: Program Planning & Design
7. 3. Data & Operators
1. Data Types in C++
2. Identifier Names
3. Constants and Variables
4. Data Manipulation
5. Assignment Operator
6. Arithmetic Operators
7. Data Type Conversions
8. Practice 3: Data & Operators
8. 4. Often Used Data Types
1. Integer Data Type
2. Floating-Point Data Type
3. String Data Type
4. Arithmetic Assignment Operators
5. Lvalue and Rvalue
6. Integer Division and Modulus
7. Practice 4: Often Used Data Types
9. 5. Integrated Development Environment
1. Integrated Development Environment
2. Standard Input and Output
3. Compiler Directives
4. Practice 5: Integrated Development Environment
10. 6. Program Control Functions
1. Pseudocode Examples for Functions
2. Hierarchy or Structure Chart
3. Program Control Functions
4. Void Data Type
5. Documentation and Making Source Code Readable
6. Practice 6: Program Control Functions
11. 7. Specific Task Functions
1. Specific Task Functions
2. Global vs Local Data Storage
3. Using a Header File for User Defined Specific Task
Functions
4. Practice 7: Specific Task Functions
12. 8. Standard Libraries
1. Standard Libraries
2. Practice 8: Standard Libraries
13. 9. Character Data, Sizeof, Typedef, Sequence
1. Character Data Type
2. Sizeof Operator
3. Typedef - An Alias
4. Sequence Operator
5. Practice 9: Character Data, Sizeof, Typedef, Sequence
14. 10. Introduction to Structured Programming
1. Structured Programming
2. Pseudocode Examples for Control Structures
3. Flowcharting
4. Practice 10: Introduction to Structured Programming
15. 11. Two Way Selection
1. If Then Else
2. Boolean Data Type
3. Relational Operators
4. Compound Statement
5. Practice 11: Two Way Selection
16. 12. Multiway Selection
1. Nested If Then Else
2. Logical Operators
3. Case Control Structure
4. Branching Control Structures
5. Practice 12: Multiway Selection
17. 13. Test After Loops
1. Do While Loop
2. Flag Concept
3. Assignment vs Equality within C++
4. Repeat Until Loop
5. Practice 13: Test After Loops
18. 14. Test Before Loops
1. Increment and Decrement Operators
2. While Loop
3. Practice 14: Test Before Loops
19. 15. Counting Loops
1. For Loop
2. Circular Nature of the Integer Data Type Family
3. Formatting Output
4. Nested For Loops
5. Practice 15: Counting Loops
20. 16. String Class, Unary Positive and Negative
1. String Class within C++
2. Unary Positive and Negative Operators
3. Practice 16: String Class, Unary Positive and Negative
21. 17. Conditional Operator and Recursion
1. Conditional Operator
2. Recursion vs Iteration
3. Practice 17: Conditional Operator and Recursion
22. 18. Introduction to Arrays
1. Array Data Type
2. Array Index Operator
3. Displaying Array Members
4. Practice 18: Introduction to Arrays
23. 19. File I/O and Array Functions
1. File Input and Output
2. Arrays and Functions
3. Loading an Array from a File
4. Math Statistics with Arrays
5. Practice 19: File I/O and Array Functions
24. 20. More Array Functions
1. Finding a Specific Member of an Array
2. Sorting an Array
3. Practice 20: More Array Functions
25. 21. More on Typedef
1. Versatile Code with Typedef
2. Practice 21: More on Typedef
26. 22. Pointers
1. Address Operator
2. Parameter Passing by Reference
3. Pointer Data Type
4. Indirection Operator
5. Practice 22: Pointers
27. 23. More Arrays & Compiler Directives
1. Multidimensional Arrays
2. Conditional Compilation
3. Practice 23: More Arrays & Compiler Directives
28. 24. OOP & HPC
1. Object Oriented Programming
2. Understanding High Performance Computing
3. Practice 24: OOP & HPC
29. Review Materials
1. Review: Foundation Topics Group: 1-5
2. Review: Modular Programming Group: 6-9
3. Review: Structured Programming Group: 10-16
4. Review: Intermediate Topics Group: 17-21
5. Review: Advanced Topics Group: 22-24
30. Appendix
1. Abbreviated Precedence Chart for C++ Operators
2. C++ Reserved Keywords
3. ASCII Character Set
4. Show Hide File Extensions
5. Academic or Scholastic Dishonesty
6. Successful Learning Skills
7. Study Habits that Build the Brain
Preface
This module introduces the Connexions online textbook/collection
"Programming Fundamentals - A Modular Structured Approach using C++"
by Kenneth Leroy Busbee.
On January 10, 2013 Version 1.22 was created with the modules that make
up the collection "fixed" to the their current versions. This will allow
Version 1.22 to remain static with the modules as of that date.
Students using this collection for a college course should note that all of the
Prerequisite links within the modules will be modules that student should
have already read and most of the Supplemental links will be modules that
the student will read shortly. Thus, students should use Prerequisite links for
review as needed and not be overly concerned about viewing all of the
Supplemental links at the first reading of this textbook/collection.
Conceptual Approach
The learning modules of this textbook/collection were, for the most part,
written without consideration of a specific programming language. In many
cases the C++ language is discussed as part of the explanation of the
concept. Often the examples used for C++ are exactly the same for the Java
programming language. However, some modules were written specifically
for the C++ programming language. This could not be avoided as the C++
language is used in conjunction with this textbook/collection by the author
in teaching college courses.
Instructor Materials
About Connexions
Read the book online, print the PDF, or buy a copy of the book.
To browse this textbook online, visit the collection home page. You will
then have three options.
1. You may view the collection modules on-line by clicking on the "Start
>>" link, which takes you to the first module in the collection. You can
then navigate to the next module using "NEXT >>" and through the
subsequent modules by using the "<< PREVIOUS | NEXT >>" button
that is towards the upper right to move forward and backward in the
collection. You can jump to any module in the collection by clicking
on that module's title in the "TABLE OF CONTENTS" box on the left
side of the window. If these contents are hidden, make them visible by
clicking on the small triangle to the right of the "TABLE OF
CONTENTS". Chapters also have a small triangle to show or hide
contents.
2. You may obtain a PDF of the entire textbook to print or view offline
by clicking on the "Download PDF" link in the "Content Actions" box.
3. You may order a bound copy of the collection (for a reasonable
printing and shipping fee) by clicking on the "Order printed copy"
button.
Connexions PDF Conversion Problems
A rating feature was added during 2009 for Connexions modules. It will not
be useful until more people rate modules within the Connexions repository.
If a module is rated by several people, it can be used as a measure of
quality. Thus, your participation in rating modules is welcomed and helps
others determine the quality of the educational materials being viewed.
In order to rate modules you must have a Connexions account. Three (3)
modules have been added to the preface series of modules for this
collection. They explain why and how to create a Connexions account and
how to rate a Connexions module.
Author Acknowledgements
This module contains the author acknowledgements for the "Programming
Fundamentals - A Modular Structured Approach using C++"
textbook/collection.
I wish to acknowledge the many people who have helped me and have
encouraged me in this project.
Orientation
Textbook/Collection Layout
Appendix N/A 7
Total Modules N/A 118
Chapter Layout
As you proceed with the Connexions modules that comprise a chapter, you
should:
Learning Objectives
Memory Building Activities aka MBAs Link – These could consist of
any of the following types of interactive computer activities: flash
card, crossword puzzle, seek a word, drag n drop, labeling, ordering or
sorting. When the materials are used as a textbook for a course, it is
imperative that students do a variety of repetitive activities in order to
memorize basic course material. Besides, have fun learning.
Exercises – In addition to any exercises within the study modules that
you completed before the practice module, there will be at least one
exercise for students to complete.
Miscellaneous Items – These will exist for some of the chapters.
Lab Assignment – Usually, completed on one's own efforts. Review
the instructions/restrictions from your professor/teacher if using this
for a high school or college credit course.
Problems – The intent of this activity is for students to formulate their
own answers. Thus, solutions to the problems will not be provided.
When the materials are used as a textbook for a course, the
professor/teacher may assign students to a "Study Group" or let
students form study groups to discuss their solutions with each other. If
you are using this for a high school or college credit course, verify that
you may work as team at solving the problems. This type of approved
activity is called "authorized collusion" and is not a violation of
"Academic or Scholastic Dishonesty" rules.
The modules in this textbook/collection have had content reviewed and are
believed to be sufficient, thus no additional textbook is required.
However, some students desire additional references or reading. The author
has used several textbooks over the years for teaching "COSC1436 –
Programming Fundamentals I" course at Houston Community College and
at the Community College of Qatar. A reading reference list has been
prepared and includes references for the following textbooks:
1. Starting Out with C++ Early Objects, by: Tony Gaddis et. al., 7th
Edition, International Edition, ISBN: 978-0-13-137714-1
2. Starting Out with C++ Early Objects, by: Tony Gaddis et. al., 6th
Edition, ISBN: 0-321-51238-3
3. Starting Out with C++ Early Objects, by: Tony Gaddis et. al., 5th
Edition, ISBN: 0-321-38348-6
4. Computer Science – A structured Approach using C++, by: Behrouz
A. Forouzan et. al., 2nd Edition, ISBN: 0-534-37480-8
Syllabus
The syllabus for a course that is for credit will be provided by your specific
course professor. If you are using this textbook/collection for non-credit as
self-study, we have some suggestions:
Pre-Chapter Items 4
Chapters 1 to 5 27
Chapters 6 to 9 17
Chapters 10 to 16 30
Chapters 17 to 21 17
Chapters 22 to 24 11
Google’s “+1”
Facebook’s “Like”
twitter’s “Tweet”
Sharing Connexions Materials
Systems Development Life Cycle
An overview of the Systems Development Life Cycle.
Discussion
The Systems Development Life Cycle is the big picture of creating an
information system that handles a major task (referred to as an application).
The applications usually consist of many programs. An example would be
the Department of Defense supply system, the customer system used at
your local bank, the repair parts inventory system used by car dealerships.
There are thousands of applications that use an information system created
just to help solve a business problem.
During the Design phase the System Analyst will document the inputs,
processing and outputs of each program within the application. During the
Implementation phase programmers would be assigned to write the
specific programs using a programming language decided by the System
Analyst. Once the system of programs is tested the new application is
installed for people to use. As time goes by, things change and a specific
part or program might need repair. During the Maintenance phase, it goes
through a mini planning, analysis, design and implementation. The
programs that need modification are identified and programmers change or
repair those programs. After several years of use, the system usually
becomes obsolete. At this point a major revision of the application is done.
Thus the cycle repeats itself.
Definitions
system analyst
Computer professional in charge of creating applications.
applications
An information system or collection of programs that handles a major
task.
life cycle
Systems Development Life Cycle: Planning - Analysis - Design -
Implementation - Maintenance
implementation
The phase of a Systems Development Life Cycle where the
programmers would be assigned to write specific programs.
Bloodshed Dev-C++ 5 Compiler/IDE
An introduction to the Bloodshed Dev-C++ 5 compiler/IDE (Integrated
Development Environment) listing the advantages of using an open source
compiler that works on a flash drive. The software along with installation
instructions and a test program are included.
Introduction
Microsoft and Borland are the two reputable names within the
programming world for compilers. They sell compiler software for many
programming languages. For the C++ programming language, the
Microsoft Visual Studio which includes C++ and Borland C++ Builder are
excellent compilers. Often with textbooks or free via the internet; you can
get Microsoft’s Visual C++ Express or Borland’s Personal Edition version
of a compiler. However, installing either of these compliers can be complex.
Microsoft’s Visual Studio compiler often creates a variety of installation
problems (such as making sure the operating system and .net components
are current) thus making it difficult for students to install at home. These
compliers require you to build a project to encompass every program. Using
a commercially sold compiler that professional programmers would
consider using for project development is fine for professionals but often
confusing to beginners. Eventually, if you are going to become a
professional programmer, you will need to become familiar with the
commercially sold compilers.
open source
Group development of source code for software that is made available
to the public at no cost.
Unique Advantage: Can be installed and run on a flash drive, thus giving
the student the ability to work on their lab assignments on any computer
that has a USB port. This can give the student portability, being able to do
lab assignments at home, work, library, open lab, classroom, friend’s house,
etc.
portability
The ability to transport software on a flash drive and thus use it on
various machines.
You need to get the software and a C++ source code program that has been
tested and is error free. You will need about 80MB of storage space. We
suggest that you create two folders on your hard drive or flash drive
depending on which installation you choose. If on a flash drive create them
at the root level of the drive. If on your home machine, you can use the
folder area set up by the operating system for you as a user. Name them:
Cpp_Software_Download
Cpp_Source_Code_Files
To help you keep files organized, you will want to create other sub-folders
for storing source code files. We suggest you create at least two other sub-
folder to be used with Connexions' related modules. Within the
Cpp_Source_Code_Files, create sub-folders named:
Demo_Programs
Monitor_Header
folder
A named area for storage of documents or other files on a disk drive or
flash drive.
source code
Any collection of statements or declarations written in some human-
readable computer programming language.
The full version of the software is named: Dev-C++ 5.0 beta 9.2 (4.9.9.2)
(9.0 MB) with Mingw/GCC 3.4.2 You can either download it from
Bloodshed or download the version as of 12/8/2008 that is stored on the
Connexions web site. Store it in the Cpp_Software_Download folder you
created. The software is approximately 9.1 MB and will take several
minutes to download if you are using a dial-up modem connection.
Note:The software has not significantly changed since 2007 and the
Connexions version will be sufficient for most users. The Bloodshed link
requires some additional navigation to get to the software download. Thus,
because it is significantly easier, we recommend that you download the
software from the Connections web site.
Link to Bloodshed: http://www.bloodshed.net/dev/devcpp.html
Listed below is a C++ source code file titled: Compiler_Test.cpp It has been
prepared for Connexions web delivery. Download and store it in the
Compiler_Test sub-folder you created. You may need to right click on the
link and select "Save Target As" in order to download the file.
Concept of Modularization
One of the most important concepts of programming is the ability to group
some lines of code into a unit that can be included in our program. The
original wording for this was a sub-program. Other names include: macro,
sub-routine, procedure, module and function. We are going to use the term
function for that is what they are called in the two predominant
programming languages of today: C++ and Java. Functions are important
because they allow us to take large complicated programs and to divide
them into smaller manageable pieces. Because the function is a smaller
piece of the overall program, we can concentrate on what we want it to do
and test it to make sure it works properly. Generally functions fall into two
categories:
The main program must establish the existence of functions used in that
program. Depending on the programming language, there is a formal way
to:
Example:
Compiler_Test.cpp source code
//************************************************
******
// Filename: Compiler_Test.cpp
// Purpose: Average the ages of two people
// Author: Ken Busbee; © Kenneth Leroy Busbee
// Date: Jan 5, 2009
// Comment: Main idea is to be able to
// debug and run a program on your
compiler.
//************************************************
******
#include <iostream>
using namespace std;
// Function Prototypes
void pause(void);
// Variables
int age1;
int age2;
double answer;
//************************************************
******
// main
//************************************************
******
int main(void)
{
// Input
cout << "\nEnter the age of the first person ---
>: ";
cin >> age1;
cout << "\nEnter the age of the second person --
>: ";
cin >> age2;
// Process
answer = (age1 + age2) / 2.0;
// Output
cout << "\nThe average of their ages is --------
>: ";
cout << answer;
pause();
return 0;
}
//************************************************
******
// pause
//************************************************
******
void pause(void)
{
cout << "\n\n";
system("PAUSE");
cout << "\n\n";
return;
}
//************************************************
******
// End of Program
//************************************************
******
This program has two functions, one from each of our categories. The
technical layout of functions are the same, it is our distinction that creates
the two categories based on how a function is being implemented.
Program Control Function
The main program piece in C++ program is a special function with the
identifier name of main. The special or uniqueness of main as a function is
that this is where the program starts executing code and this is where it
usually stops executing code. It is usually the first function defined in a
program and appears after the area used for includes, other technical items,
declaration of prototypes, the listing of global constants and variables and
any other items generally needed by the program. The code to define the
function main is provided; however, it is not prototyped or usually called
like other functions within a program. In this simple example, there are no
other program control functions.
We often have the need to perform a specific task that might be used in
many programs. In the Compile_Test.cpp source code above we have such
a task that is used to stop the execution of the code until the user hits the
enter key. The functions name is: pause. This function is not
communicating any information between the calling function and itself,
thus the use of the data type void.
Example:
general layout of a function
return <value>;
}
There is no semi-colon after the first line. Semi-colons are used at the end
of a statement in C++, but not on the first line when defining a function.
Functions have a set of braces {} used for identifying a group or block of
statements or lines of code. There are normally several lines of code within
a function. Lines of code containing the instructions end in a semi-colon.
Can you identify the definition of the pause function in the above program
example? The pause function definition is after the function main. Though
not technically required, most programs list all functions (program control
or specific task) after the function main.
Let's identify the location where the function pause is called. The calling
function is the function main and it towards the end of the function. The
line looks like:
pause();
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, and in our example there are none. A semi-colon ends the
statement or line of code. After our program is compiled and running, the
lines of code in the function main are executed and when it gets to the
calling of the pause function, the control of the program moves to the pause
function and starts executing the lines of code in the pause function. When
it’s done with the lines of code, it will return to the place in the program that
called it (in our example the function main) and continue with the code in
that function.
void pause(void);
This line of code looks exactly like the first line in our function definition
with one important addition of a semi-colon. Prototypes (or declarations to
the compiler of the communications of a function not yet defined) are
placed near the top of the program before the function main. Summary
concept: If you call a function before it is defined you must prototype it
before it is called. Looking at our list of the three things you do in
conjunction with a function in the order that they normally appear in a
program, there is a formal way to:
Definitions
modularization
The ability to group some lines of code into a unit that can be included
in our program.
function
What modules are called in the two predominant programming
languages of today: C++ and Java.
program control
Functions used to simply sub divide and control the program.
specific task
Functions designed to be used with several programs.
parameter passing
How the data is communicated in to and out of a function.
identifier name
The name given by the programmer to identify a function or other
program items such as variables.
function prototype
A function's communications declaration to a complier.
function call
A function's using or invoking of another function.
function definition
The code that defines what a function does.
braces
Used to identify a block of code in C++.
Practice 1: Introduction to Programming
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. true
3. false
4. true
5. true
Miscellaneous Items
None at this time.
Lab Assignment
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Within the variables area, change the variable names for age1 and age2
to weight1 and weight2. Add another variable of integer data type with
the identifier name of weight3.
The input area has two prompts and requests for data from the user.
They are paired up – a prompt and getting data from the keyboard. We
need to modify the prompt to ask for weight instead of age. We need to
change the variable name from age1 to weight1. Do this for the second
pair that prompts and gets the second data item. Create a third pair that
prompts and gets the third data item.
The process area has only one line of code and we need to make
changes that add the weight3 and divides by 3.0 instead of 2.0. The
code should look like this:
answer = (weight1 + weight2 + weight3) / 3.0;
The output area needs the text modified from ages to weights.
Build (compile and run) your program. You have successfully written
this program if when it run and you put in the three weights; it tells
you the correct average.
After you have successfully written this program, if you are taking this
course for college credit, follow the instructions from your
professor/instructor for submitting it for grading.
Problems
List the steps of the Systems Development Life Cycle and indicate which
step you are likely to work in as a new computer professional.
Program Design
An introduction to the computer program design process.
Topic Introduction
Program Design consists of the steps a programmer should do before they
start coding the program in a specific language. These steps when properly
documented will make the completed program easier for other programmers
to maintain in the future. There are three broad areas of activity:
Inputs
Processing
Outputs
The first modeling tool you will usually learn is pseudocode. You will
document the logic or algorithm of each function in your program. At first,
you will have only one function, and thus your pseudocode will follow
closely the IPO approach above.
There are several methods or tools for planning the logic of a program.
They include: flowcharting, hierarchy or structure charts, pseudocode,
HIPO, Nassi-Schneiderman charts, Warnier-Orr diagrams, etc.
Programmers are expected to be able to understand and do flowcharting and
pseudocode. These methods of developing the model of a program are
usually taught in most computer courses. Several standards exist for
flowcharting and pseudocode and most are very similar to each other.
However, most companies have their own documentation standards and
styles. Programmers are expected to be able to quickly adapt to any
flowcharting or pseudocode standards for the company at which they work.
The others methods that are less universal require some training which is
generally provided by the employer that chooses to use them.
Later in your programming career, you will learn about using applications
software that helps create an information system and/or programs. This type
of software is called Computer-aided Software Engineering.
Understanding the logic and planning the algorithm on paper before you
start to code is very important concept. Many students develop poor habits
and skipping this step is one of them.
Definitions
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.
Pseudocode
An introduction to pseudocode with a simple example.
Overview
Pseudocode is one method of designing or planning a program. Pseudo
means false, thus pseudocode means false code. A better translation would
be the word fake or imitation. Pseudocode is fake (not the real thing). It
looks like (imitates) real code but it is NOT real code. It uses English
statements to describe what a program is to accomplish. It is fake because
no complier exists that will translate the pseudocode to any machine
language. Pseudocode is used for documenting the program or module
design (also known as the algorithm).
Example:
Outline using Pseudocode
Input
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 dividing by two
Output
display the answer on the screen
pause so the user can see the answer
After developing the program design, we use the pseudocode to write code
in a language (like Pascal, COBOL, FORTRAN, "C", " C++", etc.) where
you must follow the rules of the language (syntax) in order to code the logic
or algorithm presented in the pseudocode. Pseudocode usually does not
include other items produced during programming design such as identifier
lists for variables or test data.
There are other methods for planning and documenting the logic for a
program. One method is HIPO. It stands for Hierarchy plus Input Process
Output and was developed by IBM in the 1960s. It involved using a
hierarchy (or structure) chart to show the relationship of the sub-routines (or
functions) in a program. Each sub-routine had an IPO piece. Since the
above problem/task was simple, we did not need to use multiple sub-
routines, thus we did not produce a hierarchy chart. We did incorporate the
IPO part of the concept for the pseudocode outline.
Definitions
pseudo
Means false and includes the concepts of fake or imitation.
Test Data
An explanation of test data with an example developed from a simple
program documented with pseudocode.
Overview
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.
Example:
Pseudocode using an IPO Outline for Painting a Rectangular Building
Input
display a message asking user for the length of
the building
get the length from the keyboard
display a message asking user for the width of
the building
get the width from the keyboard
display a message asking user for the height of
the building
get the height from the keyboard
display a message asking user for the price per
gallon of paint
get the price per gallon of paint from the
keyboard
display a message asking user for the sq ft
coverage of a gallon of paint
get the sq ft coverage of a gallon of paint from
the keyboard
Processing
calculate the total area of the building by:
multiplying the length by height by 2
then multiply the width by height by 2
then add the two results together
calculate the number of gallons of paint needed
by:
dividing the total area by the coverage per
gallon
then round up to the next whole gallon
calculate the total cost of the paint by:
multiplying the total gallons needed by the
price of one gallon of paint
Output
display the number of gallons needed on the
monitor
display the total cost of the paint on the
monitor
pause so the user can see the answer
Inputs: My building is 100 feet long by 40 feet wide and 10 feet in height
and I selected paint costing $28.49 per gallon that will cover 250 square
feet per gallon. We should verify that the pseudocode is prompting the user
for this data.
Output: Only the significant information (number of gallons to buy and the
total cost) are displayed for the user to see. We should verify that the
appropriate information is being displayed.
By developing test data we are predicting what the results should be, thus
we can verify that our program is working properly. When we run the
program we would enter the input values used in our test data. Hopefully
the program will output the predicted values. If not then our problem could
be any of the following:
1. The plan (IPO outline or other item) could be wrong
2. The conversion of the plan to code might be wrong
3. The test data results were calculated wrong
Definitions
model checking
Using test data to check the design model (usually done in
pseudocode).
code checking
Using test data to check the coded program in a specific language (like
C++).
Practice 2: Program Planning & Design
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. false
3. false
4. true
5. true
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Solution_Lab_01_Pseudocode.txt
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Problem: I have a friend who is visiting from Europe and he does not
understand exactly how much gas he is buying for his car. We need to write
a program that allows him to enter the gallons of gas and convert it to liters
(metric system). NOTE: One US gallon equals 3.7854 liters.
General Discussion
Our interactions (inputs and outputs) of a program are treated in many
languages as a stream of bytes. These bytes represent data that can be
interpreted as representing values that we understand. Additionally, within a
program we process this data in various ways such as adding them up or
sorting them. This data comes in different forms. Examples include:
yourname which is a string of characters; your age which is usually an
integer; or the amount of money in your pocket which is usually a value
measured in dollars and cents (something with a fractional part). A major
part of understanding how to design and code programs in centered in
understanding the types of data that we want to manipulate and how to
manipulate that data.
"A type defines a set of values and a set of operations that can be applied
on those values. The set of values for each type is known as the domain for
that type."[footnote] The four major families of data include:
Behrouz A. Forouzan and Richard F. Gilberg, Computer Science A
Structured Approach using C++ Second Edition (United States of America:
Thompson – Brooks/Cole, 2004) 33.
Nothing
Integer
Floating-point
Complex
The C++ programming language identifies five data types as standard data
types:
Void
Boolean
Character
Integer
Floating-point
The standard data types and the complex data types within C++ have a
series of attributes, which include:
Null or
Nothing void No data Yes
nothing
Logical
Integer Boolean bool true and Yes
false
Single
Integer Character char Yes
characters
Whole
Integer Integer int Yes
numbers
A
collection
Complex Array N/A of elements No
of the same
data type
A value
that points
to a
location
Complex Pointer N/A No
(an
address)
within the
data area
The five standard data types usually exist in most programming languages
and act or behave similarly from language to language. Most courses of
study for a programming course or language will explain the standard data
types first. After they are learned, the complex data types are introduced.
The Boolean, character and integer data types are identified as belonging to
the Integer Family. These data types are all represented by integer numbers
and thus act or behave similarly.
Definitions
data type
Defines a set of values and a set of operations that can be applied on
those values.
integer
A data type representing whole numbers.
floating point
A data type representing numbers with fractional parts.
Identifier Names
An explanation of identifier names including some common rules for the
C++ programming language.
Overview
Within programming a variety of items are given descriptive names to make
the code more meaningful to us as humans. These names are called
"Identifier Names". Constants, variables, type definitions, functions, etc.
when declared or defined are identified by a name. These names follow a
set of rules that are imposed by:
Technical to Language
Use only allowable characters (for C++ the first character alphabetic or
underscore, can continue with alphanumeric or underscore)
Can't use reserved words
Length limit
Some programming languages treat upper and lower case letters used in
identifier names as the same. Thus: pig and Pig are treated as the same
identifier name. Unknown to you the programmer, the compiler usually
forces all identifier names to upper case. Thus: pig and Pig both get
changed to PIG. However not all programming languages act this way.
Some will treat upper and lower case letters as being different things. Thus:
pig and Pig are two different identifier names. If you declare it as pig and
then reference it in your code later as Pig – you get a compiler error. To
avoid the problem altogether, we teach students to be case consistent. Use
an identifier name only once and spell it (upper and lower case) the same
way within your program.
Industry Rules
Do not start with underscore (used for technical programming)
variables in all lower case
CONSTANTS IN ALL UPPER CASE
These rules are decided by the industry (those who are using the
programming language). The above rules were commonly used within the
"C" programming language and have to large degree carried over to C++.
Definitions
reserved word
Words that cannot be used by the programmer as identifier names
because they already have a specific meaning within the programming
language.
Constants and Variables
An introductory explanation of constants and variables with examples and
how to define them within the C++ programming language.
Understanding Constants
Various textbooks describe constants using different terminology. Added to
the complexity are the explanations from various industry professionals will
vary greatly. Let's see if we can clear it up.
A constant is a data item whose value cannot change during the program's
execution. Thus, as its name implies – their value is constant.
A variable is a data item whose value can change during the program's
execution. Thus, as its name implies – their value can vary.
1. literal constant
2. defined constant
3. memory constant
Example:
Literal Constants
#define PI 3.14159
The second one is called sometimes called constant variable but that name
is contradictory all by itself. How can it be constant and vary at the same
time? The better name for the second one is a memory constant because
they have a "specific storage location in memory".
int height;
float value_coins;
height = 72;
Definitions
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.
Data Manipulation
An introduction to expressions with definitions, an example and an
explanation of precedence.
Introduction
Single values by themselves are important; however we need a method of
manipulating values (processing data). Scientists wanted an accurate
machine for manipulating values. They wanted a machine to process
numbers or calculate answers (that is compute the answer). Prior to 1950,
dictionaries listed the definition of computers as " humans that do
computations". Thus, all of the terminology for describing data
manipulation is math oriented. Additionally, the two fundamental data type
families (the integer family and floating-point family) consist entirely of
number values.
Definitions
expression
A valid sequence of operand(s) and operator(s) that reduces (or
evaluates) to a single value.
operator
A language-specific syntactical token (usually a symbol) that causes an
action to be taken on one or more operands.
operand
A value that receives the operator's action.
precedence
Determines the order in which the operators are allowed to manipulate
the operands.
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.
parentheses
Change the order of evaluation in an expression. You do what's in the
parentheses first.
Most operators are binary, that is they require two operands. Within C++
there is only one trinary operator, the conditional. All of the unary operators
are on the left side of the operand, except postfix increment and postfix
decrement. Some precedence charts indicate of which operators are unary
and trinary and thus all others are binary.
Assignment Operator
An explanation of the assignment operator with examples as used in the
C++ programming language.
Discussion
The assignment operator allows us to change the value of a modifiable data
object (for beginning programmers this typically means a variable). It is
associated with the concept of moving a value into the storage location
(again usually a variable). Within C++ programming language the symbol
used is the equal symbol. But bite your tongue, when you see the = symbol
you need to start thinking: assignment. The assignment operator has two
operands. The one to the left of the operator is usually an identifier name
for a variable. The one to the right of the operator is a value.
Example:
Simple Assignment
The value 21 is moved to the memory location for the variable named: age.
Another way to say it: age is assigned the value 21.
Example:
Assignment with an Expression
Example:
Assignment with Identifier Names in the Expression
Definitions
assignment
An operator that changes the value of a modifiable data object.
Arithmetic Operators
An overview of the arithmetic operators within the C++ programming
language.
General Discussion
An operator performs an action on one or more operands. The common
arithmetic operators are:
Addition +
Subtraction -
Multiplication *
Division /
These arithmetic operators are binary that is they have two operands. The
operands may be either constants or variables.
age + 1
This expression consists of one operator (addition) which has two operands.
The first is represented by a variable named age and the second is a literal
constant. If age had a value of 14 then the expression would evaluate (or be
equal to) 15.
These operators work as you have learned them throughout your life with
the exception of division and modulus. We normally think of division as
resulting in an answer that might have a fractional part (a floating-point
data type). However, division when both operands are of the integer data
type act differently. Please refer to the supplemental materials on "Integer
Division and Modulus".
Data Type Conversions
Implicit and explicit type conversion with both promotion and demotion is
discussed with some examples.
Overview
Changing a data type of a value is referred to as "type conversion". There
are two ways to do this:
Example:
Implicit Promotion
55 + 1.75
In this example the integer value 55 is converted to a floating-point value
(most likely double) of 55.0. It was promoted.
Example:
Implicit Demotion
Promotion
Promotion is never a problem because the lower data type (smaller range of
allowable values) is sub set of the higher data type (larger range of
allowable values). Promotion often occurs with three of the standard data
types: character, integer and floating-point. The allowable values (or
domains) progress from one type to another. That is the character data type
values are a sub set of integer values and integer values are a sub set of
floating-point values; and within the floating-point values: float values are a
sub set of double. Even though character data represent the alphabetic
letters, numeral digits (0 to 9) and other symbols (a period, $, comma, etc.)
their bit pattern also represent integer values from 0 to 255. This
progression allows us to promote them up the chain from character to
integer to float to double.
Demotion
Demotion represents a potential problem with truncation or unpredictable
results often occurring. How do you fit an integer value of 456 into a
character value? How do you fit the floating-point value of 45656.453 into
an integer value? Most compilers give a warning if it detects demotion
happening. A compiler warning does not stop the compilation process. It
does warn the programmer to check to see if the demotion is reasonable.
If I tried demoting a double that contained the number of stars in the Milky
Way galaxy into an integer, I might have a get an unpredictable result
(assuming the number of stars is larger than allowable values within the
integer domain).
Example:
Explicit Demotion with Truncation
(int) 4.234
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the soruce code file(s) in
conjunction with other learning materials.
Definitions
implicit
A value that has its data type changed automatically.
explicit
Changing a value's data type with the cast operator.
promotion
Going from a smaller domain to a larger domain.
demotion
Going from a larger domain to a smaller domain.
truncation
The fractional part of a floating-point data type that is dropped when
converted to an integer.
Practice 3: Data & Operators
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. A data type defines a set of values and the set of operations that
can be applied on those values.
2. Reserved or key words can be used as identifier names.
3. The concept of precedence says that some operators (like
multiplication and division) are to be executed before other
operators (like addition and subtraction).
4. An operator that needs two operands, will promote one of the
operands as needed to make both operands be of the same data
type.
5. Parentheses change the precedence of operators.
Solution:
Answers:
1. true
2. false
3. true
4. true
5. false – Parentheses change the order of evaluation in an
expression.
Miscellaneous Items
Link to: Manipulation of Data Part 1
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Navigate to your sub-folder: Chapter_03 and open and study the two
files.
We have learned that a fundamental concept of interaction with
computers is to divide the problem/task into three parts – input,
processing and output. This problem is simple and we will use the
IPO (input – processing – output) approach again. However this time
we are going to think about it backwards.
You can see that by working the logic backwards, we can start to
completely see what the program must do. We need to enter some data
(input), do some calculations (process) and display the results (output).
Copy into your sub-folder: Chapter_03 one of the source code listings
that we have used (we suggest the Lab 01 source code) and rename the
copy to: Lab_03.cpp
Modify the code to follow the Solution_Lab_03_Pseudocode.txt file.
I am just going to give you the line of code for rounding up to the next
whole gallon of paint (See the “Data Type Conversions” module
within Chapter 3 of the Connexions materials. Do you understand why
it works?).
total_gal_paint = total_area / coverage_gal_paint + 0.9999;
Build (compile and run) your program. You have successfully written
this program when it runs with your test data and gives the predicted
results.
After you have successfully written this program, if you are taking this
course for college credit, follow the instructions from your
professor/instructor for submitting it for grading.
Problems
General Discussion
The integer data type has two meanings:
The integer data type with its various modifiers that create different
domains
The integer family which also includes the Boolean and character data
types
The integer data type basically represents whole numbers (no fractional
parts). The integer values jump from one value to another. There is nothing
between 6 and 7. It could be asked why not make all your numbers floating
point which allow for fractional parts. The reason is twofold. First, some
things in the real world are not fractional. A dog, even with only 3 legs, is
still one (1) dog not ¾ of a dog. Second, integer data type is often used to
control program flow by counting, thus the need for a data type that jumps
from one value to another.
The integer data type has the same attributes and acts or behaves similarly
in all programming languages. The most often used integer data type in
C++ is the simple integer.
Within C++ there are various reserved words that can be used to modify the
size or signage of an integer. They include: long, short, signed and
unsigned. Signed is rarely used because integers are signed by default – you
must specify unsigned if you want integers that are only positive. Possible
combinations are:
int signed
The domain of each of the above data type options varies with the complier
being used and the computer. The domains vary because the byte size
allocated to the data varies with the compiler and computer. This effect is
known as being machine dependent. Additionally, there have been some
size changes with upgrades to the language. In "C" the int data type was
allocated 2 bytes of memory storage on an Intel compatible central
processing unit (cpu) machine. In "C++" an int is allocated 4 bytes.
These variations of the integer data type are an annoyance in C++ for a
beginning programmer. For a beginning programmer it is more important to
understand the general attributes of the integer data type that apply to most
programming languages.
Definitions
machine dependent
An attribute of a programming language that changes depending on the
computer's CPU.
Floating-Point Data Type
An explanation of the floating-point data type to include: float, double and
long double.
General Discussion
The floating-point data type is a family of data types that act alike and differ
only in the size of their domains (the allowable values). The floating-point
family of data types represent number values with fractional parts. They are
technically stored as two integer values: a mantissa and an exponent. The
floating-point family has the same attributes and acts or behaves similarly
in all programming languages. They can always store negative or positive
values thus they always are signed; unlike the integer data type that could
be unsigned. The domain for floating-point data types varies because they
could represent very large numbers or very small numbers. Rather than talk
about the actual values, we mention the precision. The more bytes of
storage the larger the mantissa and exponent, thus more precision.
The most often used floating-point family data type used in C++ is the
double. By default, most compilers convert floating-point constants into the
double data type for use in calculations. The double data type will store just
about any number most beginning programmers will ever encounter.
C++ Reserved
double
Word
Domain (Values
±1.7E-308 to ±1.7E308
Allowed)
Within C++ there are various reserved words that can be used to establish
the size in bytes of a floating-point data item. More bytes mean more
precision:
float 4 bytes
double 8 bytes
The domain of each of the above data type options varies with the complier
being used and the computer. The domains vary because the byte size
allocated to the data varies with the compiler and computer. This effect is
known as being machine dependent.
Definitions
double
The most often used floating-point family data type used in C++.
precision
The effect on the domain of floating-point values given a larger or
smaller storage area in bytes.
mantissa exponent
The two integer parts of a floating-point value.
String Data Type
An introduction to the string concept and it's use as a string constant.
General Discussion
Technically, there is no string data type in the C++ programming language.
However, the concept of a string data type makes it easy to handle strings of
character data. A single character has some limitations. Many data items are
not integers or floating-point values. The message Hi Mom! is a good
example of a string. Thus, the need to handle a series of characters as a
single piece of data (in English correctly called a datum).
Domain (Values
Extended ASCII Character Code Set
Allowed)
C++ syntax rule Double quote marks for constants
For now, we will address only the use of strings as constants. Most modern
compliers 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 the monitor. A typical line of C++ code:
would have the "Hi Mom" colored (usually red) to emphasize that the item
is a string.
Definitions
string
A series or array of characters as a single piece of data.
Arithmetic Assignment Operators
A table showing the equivalent meaning for the arithmetic assignment
operators.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the soruce code file(s) in
conjunction with other learning materials.
Discussion
They refer to on 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:
Example:
The value 39 is pulled or fetched (Rvalue) and stored into the variable
named age (Lvalue); destroying the value previously stored in that variable.
Example:
Example:
Example:
Postfix increment says to use my existing value then when you are done
with the other operators; increment me. Thus, the first use of the oldest
variable is an Rvalue context where the existing value of 55 is pulled or
fetched and then assigned to the variable age; an Lvalue context. The
second use of the oldest variable is an Lvalue context where in the value of
oldest is incremented from 55 to 56.
Definitions
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.
Integer Division and Modulus
An explanation of integer division with an example of how this was learned
in grade school as your first method of understanding division before
fractions. The modulus operator is explained.
Example:
11 / 4
Because both operands are of the integer data type the evaluation of the
expression (or answer) would be 2 with no fractional part (it gets thrown
away). Again, this type of division is call integer division and it is what
you learned in grade school the first time you learned about division.
integer division
Division with no fractional parts.
Integer division as
learned in grade
school.
In the real world of data manipulation there are some things that are always
handled in whole units or numbers (integer data type). Fractions just
don’t exist. To illustrate our example: I have 11 dollar coins to distribute
equally to my 4 children. How many do they each get? Answer is 2 with
me still having 3 left over (or with 3 still remaining in my hand). The
answer is not 2 ¾ each or 2.75 for each child. The dollar coins are not
divisible into fractional pieces. Don’t try thinking out of the box and
pretend you’re a pirate. Using an axe and chopping the 3 remaining coins
into pieces of eight. Then, giving each child 2 coins and 6 pieces of eight or
2 6/8 or 2 ¾ or 2.75. If you do think this way, I will change my example to
cans of tomato soup. I dare you to try and chop up three cans of soup and
give each kid ¾ of a can. Better yet, living things like puppy dogs. After
you divide them up with an axe, most children will not want the ¾ of a dog.
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 C++ programming language the symbol
for the modulus operator is the percent sign (%).
Example:
11 % 4
modulus
The remainder part of integer division.
Many compilers require that you have integer operands on both sides of the
modulus operator or you will get a compiler error. In other words, it does
not make sense to use the modulus operator with floating-point operands.
Example:
6 / 24 which is different from 6 % 24
How many times can you divide 24 into 6? Six divied by 24 is zero. This is
different from: What is the remainder of 6 divided by 24? Six, the
remainder part given by modulus.
Exercise:
Problem:
Evaluate the following division expressions:
1. 14 / 4
2. 5 / 13
3. 7 / 2.0
Solution:
Answers:
1. 3
2. 0
3. 3.5 because one of the operands is a floating-point value, it is not
integer division
Exercise:
Problem:
Evaluate the following modulus expressions:
1. 14 % 4
2. 5 % 13
3. 7 % 2.0
Solution:
Answers:
1. 2
2. 5
3. "error" because most compilers require both operands to be of the
integer data type
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download the Demo Program
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file. Following the methods of
your compiler/IDE, compile and run the program(s). Study the soruce code
file(s) in conjunction with other learning materials.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
Solution:
Answers:
1. false
2. false
3. true
4. true
5. false
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Within your sub-folder: Chapter_04 you will need to create three files:
Lab_04_Pseudocode.txt and Lab_04_Test_Data.txt and Lab_04.cpp
NOTE: It will be easier to copy some previous files from another
assignment and use those copies by renaming them and modifying
them as appropriate. The professor is expecting the items you create to
have a similar format to those we have been using in the course.
Create your pseudocode, test data and source code files.
Build (compile and run) your program. You have successfully written
this program when it runs with your test data and gives the predicted
results.
After you have successfully written this program, if you are taking this
course for college credit, follow the instructions from your
professor/instructor for submitting it for grading.
Problems
Decide on the data type and identifier names for the following:
Problem: A men's clothing store that caters to the very rich wants to create a
data base for its customers that records clothing measurements. They need
to record information for shoes, socks, pants, dress shirts and casual shirts.
HINT: You may need more than 5 data items.
Integrated Development Environment
An explanation of how an IDE processes a source code file into a program
that runs on the computer. Categories of errors are discussed and
demonstrated with C++ source code files that can be downloaded for
practice.
IDE Overview
High-level language programs are usually written (coded) as ASCII text
into a source code file. A unique file extension (Examples: .asm .cob .for
.pas .c .cpp) is used to identify it as a source code file. As you can guess for
our examples – Assembly, COBOL, FORTRAN, Pascal, "C" and "C++"
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
micro 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 usually called a compiler.
However, this one compiler program is really many software items that
create an environment used by programmers to develop software. Thus the
name: Integrated Development Environment or IDE.
Upon starting the IDE software the programmer usually indicates he wants
to open a file for editing as source code. As they make changes they might
either do a "save as" or "save". When they have finished entering the source
code, they usually direct the IDE to "compile & run" the program. The IDE
does the following steps:
1. If there are any unsaved changes to the source code file it has the test
editor save the changes.
2. The compiler opens the source code file and does its first step which
is executing the pre-processor compiler directives and other steps
needed to get the file ready for the second step. The #include will
insert header files into the code at this point. If it encounters an error, it
stops the process and returns the user to the source code file within the
text editor with an error message. If no problems encountered it saves
the source code to a temporary file called a translation unit.
3. The compiler opens the translation unit file and does its second step
which is converting the programming language code to machine
instructions for the CPU, a data area and a list of items to be resolved
by the linker. Any problems encounted (usually a syntax or violation
of the programming language rules) stops the process and returns the
user to the source code file within the text editor with an error
message. If no problems encountered it saves the machine instructions,
data area and linker resolution list as an object file.
4. The linker opens the program object file and links it with the library
object files as needed. Unless all linker items are resolved, the process
stops and returns the user to the source code file within the text editor
with an error message. If no problems encountered it saves the linked
objects as an executable file.
5. The IDE directs the operating system’s program called the loader to
load the executable file into the computer's memory and have the
Central Processing Unit (CPU) start processing the instructions. As the
user interacts with the program, entering his test data, he might
discover that the outputs are not correct. These types of errors are
called logic errors and would require him to return to the source code
to change the algorithm.
Resolving Errors
Despite our best efforts at becoming perfect programmers, we will create
errors. Solving these errors is known as debugging your program. The three
types of errors in the order that they occur are:
1. Compiler
2. Linker
3. Logic
There are two types of compiler errors; pre-processor (1st step) and
conversion (2nd step). A review of Figure 1 above shows the four arrows
returning to the source code so that the programmer can correct the mistake.
During the conversion (2nd step) the complier might give a warning
message which in some cases may not be a problem to worry about. For
example: Data type demotion may be exactly what you want your program
to do, but most compilers give a warning message. Warnings don't stop the
compiling process but as their name implies, they should be reviewed.
The next three figures show IDE monitor interaction for the Bloodshed
Dev-C++ 5 compiler/IDE.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download the Demo Program
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the soruce code file(s) in
conjunction with other learning materials.
Definitions
text editor
A software program for creating and editing ASCII text files.
compiler
Converts source code to object code.
pre-processor
The first step the complier does in converting source code to object
code.
linker
Connects or links object files into an executable file.
loader
Part of the operating system that loads executable files into memory
and direct the CPU to start running the program.
debugging
The process of removing errors from a program. 1) compiler 2) linker
3) logic
warning
A compiler alert that there might be a problem.
Standard Input and Output
An explanation of standard input and output as used in the computer
industry followed by examples of cin and cout as used within a C++
program.
General Discussion
Every task we have the computer do happens inside the central processing
unit (CPU) and the associated memory. Once our program is loaded into
memory and the operating system directs the CPU to start executing our
programming statements the computer looks like this:
#include <iostream>
You should think of cout and cin as being locations that you can send to or
receive data from; similar in concept to any other variable storage location
within the data area of our program. The C++ programming language has
two operators to use in conjunction with I/O devices.
Used
Action C ++ operator symbol
with
Example:
Insertion and Extraction
Using the cout the programmer displays (or inserts) a prompting message
on the monitor for the user to see. Using the cin the user types an integer
value and hits the enter key and the computer extracts the value from the
keyboard and stores it into the variable named age1. Within the computer
all data are stored as numbers and thus part of the technical code provided
by the developers of the C++ programming language that is within the
Input-Output Stream library converts data from numbers to those symbols
we are used to seeing as humans and vice versa. Example: If the user
entered the numeral digits 57 and hit the enter key – the extraction operator
would convert the 57 into a binary number and move the binary number
into the integer storage place named age1.
The cout which uses the standard output device does not format the output
into a Graphical User Interface (GUI) where you have a mouse to use. A
modern operating system using GUI normally opens a black screen output
box that would be similar to how the monitor was used when first
developed in the 1960's. That is the default of how cout is normally
implemented by most compilers.
The output message has a unique item worth mentioning. At the very front
of the message is a backslash followed by the letter n. They do not get
printed on the monitor. It is a special code (called a printer escape code)
telling the printer to go to a new line. Printer! I thought we were using a
monitor? We are but the code is a left over from the early days of printer
output. The backslash tells the printer or monitor that the next letter is a
command. The letter n is used for telling the printer or monitor to go to the
front of a new line.
Definitions
device
A piece of equipment that is electronically connected to the memory so
that data can be transferred between the memory and the device.
standard input
The keyboard.
standard output
The monitor.
insertion
Aka writing or sending data to an output device.
extraction
Aka reading or getting data from an input device.
escape code
A code directing an output device to do something.
Compiler Directives
A general explanation of pre-processor directives and how they are
evaluated by the compiler. Discussed are include and define.
General Discussion
A compiler directive is an instruction to the compiler to complete a task
before formally starting to compile the program, thus they are sometimes
called pre-processor directives. Among other items, during the pre-
processor step the compiler is looking for compiler directives and processes
them as they are encountered. After completing the tasks as directed, the
compiler proceeds to its second step where it checks for syntax errors
(violations of the rules of the language) and converts the source code into
an object code that contains machine language instructions, a data area, and
a list of items to be resolved when he object file is linked to other object
files.
Within C++ the pound symbol or # as the first character of a line indicates
that the next word is a directive (or command word) to be evaluated. The
two most common compiler directives are:
1. include – with the item following include being the name of a file that
is to be inserted at that place in the file. The files are often called
"Header Files" because the include directive is normally inserted
toward the top of the file (at the head) as one of the first items.
2. define – with the item followed by an identifier name and a value.
This identifier name and value is stored by the compiler and when it
encounters the identifier name in the program it substitutes the value
for the identifier name.
#include <iostream>
In the next example the define directive is being used to handle a constant
(called a defined constant).
Example:
Subtituting PI
#define PI 3.14159
....Later on in the program when it encounters PI
....it will replace or substitute PI with the
value 3.14159
....For example:
area_circle = radius * radius * PI;
would become:
area_circle = radius * radius * 3.14159;
Definitions
compiler directive
An instruction to the compiler to complete a task before formally
starting to compile the program.
include
A compiler directive to insert the contents of a file into the program.
Practice 5: Integrated Development Environment
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. true
3. true
4. false
5. true
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Solution_Lab_02_Pseudocode.txt
Read and follow the directions below carefully, and perform the steps in the
order listed.
Copy into your sub-folder: Chapter_05 one of the source code listings
that we have used. We suggest the Lab 01 source code and rename the
copy: Lab_05.cpp
Modify the code to follow the Solution_Lab_02_Pseudocode.txt file.
Build (compile and run) your program. You have successfully written
this program if when it runs and you use the test data [use the test data
as supplied as the solution for Lab 02] it gives the predicted results.
After you have successfully written this program, if you are taking this
course for college credit, follow the instructions from your
professor/instructor for submitting it for grading.
Problems
List and describe what might cause the four (4) types of errors encountered
in a program using an Integrated Development Environment software
product.
Identify four (4) problems with this code listing (HINT: The four (4) types
of errors encountered in a program using an Integrated Development
Environment software product).
Example:
C++ Source Code Listing
//************************************************
******
// Filename: Compiler_Test.cpp
// Purpose: Average the ages of two people
// Author: Ken Busbee; © Kenneth Leroy Busbee
// Date: Jan 5, 2009
// Comment: Main idea is to be able to
// debug and run a program on your
compiler.
//************************************************
******
#include <iostrern>
using namespace std;
// Function Prototypes
void pause(void);
// Variables
int age1;
int age2;
double answear;
//************************************************
******
// main
//************************************************
******
int main(void)
{
// Input
cout << "\nEnter the age of the first person ---
>: ";
cin >> age1;
cout << "\nEnter the age of the second person --
>: ";
cin >> age2;
// Process
answer = (age1 + age2) / 3.0;
// Output
cout << "\nThe average of their ages is --------
>: ";
cout << answer;
pause();
return 0;
}
//************************************************
******
// End of Program
//************************************************
******
Pseudocode Examples for Functions
Suggested pseudocode conventions for functions along with some
examples.
Concept
No standard for pseudocode syntax exists. However, there are some
commonly followed conventions to help make pseudocode written by one
programmer easily understood by another programmer. The following
describes a method for using pseudocode for functions that would be
understood by programmers. Five concepts are:
Examples
Here are some examples showing functions defined in pseudocode using
our conventions as described above.
Example:
pseudocode: Function with no parameter passing
Example:
pseudocode: Function with parameter passing
Function main
Pass In: nothing
Doing some lines of code
Call: clear monitor
Doing some lines of code
Pass Out: value zero to the operating system
Endfunction
Definitions
phrase word
Words used to make pseudocode logic clear to any reader.
Hierarchy or Structure Chart
An explanation of a hierarchy or structure chart with an example.
Overview
The hierarchy chart (also known as a structure chart) shows the
relationship of various units. Its name comes from its general use in
showing the organization (or structure) of a business. The President at the
top, then vice presidents on the next level, etc. Within the context of a
computer program it shows the relationship between modules (or
functions). Detail logic of the program is not presented. It does represent
the organization of the functions used within the program showing which
functions are calling on a subordinate function. Those above are calling
those on the next level down.
Definitions
hierarchy chart
Convey the relationship or big picture of the various functions in a
program.
structure chart
Another name for a hierarchy chart.
Program Control Functions
A general explanation of how functions are used to modularize a program.
Prerequisite Material
Critical to this module is the review of several Connexions modules:
You should review these materials before proceeding. If you are viewing
this module on-line, links to these items are in the "Links" box to your right.
Concept of Modularization
The concept is everywhere present in the real world about us. Simply put it
is to take a large complicated problem and to divide it into smaller
manageable pieces. The hierarchy chart of any large organization
(government unit, company, university, hospital, etc.) will show levels of
people with job titles that indicate a different area of responsibility. Each
person is a small piece of the overall workings of the organization. Each
person can concentrate on their unique talent or task to make sure it works
properly. Collectively they accomplish the goals of the organization.
Additionally, the concept has been around for a long time. A village of 300
years ago had farmers, tailors, butchers, blacksmiths, etc. Manufacturing is
a prime example of not just work being modularized but the product itself is
viewed in terms of modules or systems (Example of a automobile: engine,
steering, brakes, etc.).
The identifier names for program control functions usually imply a task to
be accomplished, such as get-data, process-data or show-results. As you
learn to write more complicated programs the number of lines of code will
increase. Prudence dictates that it would be beneficial to divide the program
into functions that perform unique tasks. The larger the program the more
need for modularization or creating of program control functions.
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on some of the links and
select "Save Target As" in order to download some of the files. Following
the methods of your compiler/IDE, compile and run the program(s). Study
the source code file(s) in conjunction with other learning materials.
The simplicity of the program should not be considered during this review.
It is obvious that the program does not need modularization. The example is
to show or demonstrate how to modularize a program for program control.
Definitions
common area
An area of the program where variables and constants are defined so
that they are available to all functions.
Void Data Type
An explanation of the void data type.
General Discussion
The void data type has no values and no operations. It's a data type that
represents the lack of a data type.
Represent Nothing
This data type was added in the transition from "C" to "C++". In "C" by
default a function returned an integer data type. Some functions don't return
a value of any kind. Thus, the need to have a data type that indicates
nothing is being returned. The void data type is mainly used in the
definition and prototyping of functions to indicate that either nothing is
being passed in and/or nothing is being passed out.
Definitions
void data type
A data type that has no values or operators and is used to represent
nothing.
Documentation and Making Source Code Readable
A source code listing and discussion of several items that make source code
easier to read and maintain.
General Discussion
We are going to consider a simple program that might be used for testing a
compiler to make sure that it is installed correctly.
Example:
Compiler_Test.cpp source code
//************************************************
******
// Filename: Compiler_Test.cpp
// Purpose: Average the ages of two people
// Author: Ken Busbee; © Kenneth Leroy Busbee
// Date: Jan 5, 2009
// Comment: Main idea is to be able to
// debug and run a program on your
compiler.
//************************************************
******
#include <iostream>
using namespace std;
// Function Prototypes
void pause(void);
// Variables
int age1;
int age2;
double answer;
//************************************************
******
// main
//************************************************
******
int main(void)
{
// Input
cout << "\nEnter the age of the first person ---
>: ";
cin >> age1;
cout << "\nEnter the age of the second person --
>: ";
cin >> age2;
// Process
answer = (age1 + age2) / 2.0;
// Output
cout << "\nThe average of their ages is --------
>: ";
cout << answer;
pause();
return 0;
}
//************************************************
******
// pause
//************************************************
******
void pause(void)
{
cout << "\n\n";
system("PAUSE");
cout << "\n\n";
return;
}
//************************************************
******
// End of Program
//************************************************
******
1. Documentation
2. Vertical Alignment
3. Appropriate use of Comments
4. Banners for Functions
5. Block Markers on Lines by Themselves
6. Indent Block Markers
7. Meaningful Identifier Names Consistently Typed
8. 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 code the way humans
read the source code. But that is exactly the point; the desire is to make the
source code easier for humans to read. You should not be confused between
what is possible (technically will compile) and what is ok (acceptable good
programming practice that leads to readable code). Let's cover each item in
more detail.
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 the
variables are defined. When declaring variable or constants many textbooks
put several items on one line; like this:
Example:
Common Textbook Defining of Variables
float length;
float width;
float height;
float price_gal_paint;
int coverage_gal_paint;
float total_area;
int total_gal_paint;
float total_cost;
This method of using one item per line is more readable by humans. It is
quicker to find an identifier name, because you can read the list vertically
faster than searching horizontally. Some programmers list them in
alphabetic order, especially when the number of variables exceeds about
twenty.
The lines of code inside either function are also aligned vertically and
indented two spaces from the left. The indentation helps set the block off
visually.
You can see through the source code short little comments that describe an
area or section. Note the use of input, processing and output which are part
of the IPO concept within the program design.
Note the use of comments in the form of a banner before each function.
Example:
Comments as a Banner
//************************************************
******
// main
//************************************************
******
As the name implies "identifier names" should clearly identify who (or
what) you are talking about. Calling you spouse "Snooky" may be
meaningful to only you. Others might need to see her full name (Jane Mary
Smith) to appropriately identify who you are talking about. The same
concept in programming is true. Variables, constants, functions, typedefs
and other items should use meaningful identifier names. Additionally, those
names should be typed consistently in terms of upper and lower case as they
are used in the program. Don't define a variable as: Pig and then type it later
on in your program as: pig.
Many programming languages have a command that allows for the creation
of an identifier name that represents a data type. The new identifier name is
described or connected to a real data type. This feature is not demonstrated
in the code above and is often a confusing concept. It is a powerful way to
help document a program so that it is meaningful, but is often used by more
experienced programmers.
Definitions
documentation
A method of preserving information useful to others in understanding
an information system or part thereof.
vertical alignment
A method of listing items vertically so that they are easier to read
quickly.
comments
Information inserted into a source code file for documentation of the
program.
banners
A set of comment lines used to help separate the functions and other
sections of a program.
braces
Used to identify a block of code in C++.
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.
consistent
A rule that says to type identifier names in upper and lower case
consistently throughout your source code.
Practice 6: Program Control Functions
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. true
3. true
4. false
5. false
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Solution_Lab_01.cpp
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Example:
pseudocode
**************************************************
****
Filename: Average_IQ.txt
Purpose: Average the IQs of two people
Author: Ken Busbee; © Kenneth Leroy Busbee
Date: Jan 17, 2009
**************************************************
****
Function main
Pass In: nothing
Call: get_iqs
Call: process_iqs
Call: show_average
Pass Out: zero to the OS
Endfunction
********************
Function get_iqs
Pass In: nothing
display a message asking user for the IQ of the
first person
get the IQ of the first person from the keyboard
display a message asking user for the IQ of the
second person
get the IQ of the second person from the
keyboard
Pass Out: nothing
Endfunction
********************
Function process_iqs
Pass In: nothing
calculate the answer by adding the two IQs and
dividing by 2.0
Pass Out: nothing
Endfunction
********************
Function show_average
Pass In: nothing
display the answer with an appropriate message
Call: pause
Pass Out: nothing
Endfunction
********************
Function pause
Pass In: nothing
direct the operating system to pause the program
Pass Out: nothing
Endfunction
**************************************************
****
Potential Variables
**************************************************
****
End of file
Example:
C++ source code
//************************************************
******
// Author: Ken Busbee; © 2009 Kenneth Leroy
Busbee
// Date: Jan 17, 2009
//************************************************
******
#include <iostream>
using namespace std;
void pause(void);
//************************************************
******
// main
//************************************************
******
int main(void)
{
// Input
cout << "\nEnter the age of the first person --->:
";
cin >> age1;
cout << "\nEnter the age of the second person
-->: ";
cin >> age2;
// Process
xx = (age1 + age2) / 2.0;
// Output
cout << "\nThe average of their ages is --------
>: ";
cout << xx;
pause();
return 0;
}
void pause(void)
{ cout << "\n\n";
system("PAUSE");
cout << "\n\n";
return; }
//************************************************
******
// End of Program
//************************************************
******
Specific Task Functions
A general explanation of specific task functions.
Prerequisite Material
Critical to this module is the review of two Connexions modules:
You should review these materials before proceeding. If you are viewing
this module on-line, links to these items are in the "Links" box to your right.
General Concept
Program Control functions which might have similar identifier names
usually perform slightly different tasks in one program to another. Looking
at the organizational chart or hierarchy chart for two companies, both might
have a vice president of production, but producing automobiles is different
than producing ice cream. Similar but different. As you go down deeper
into an organization you might find the job title of security guard. Notice
that the security guard at the automobile plant and the security guard at the
ice cream plant have exactly the same job. In fact, they are most likely
interchangeable. Within programming when a task gets specific it might be
useable in several programs. The calculation of leap year is a good
example. Needed for the verification of dates, is there or is there not a 29th
of February for this year. Needed in thousands of programs.
Definitions
user defined library
A file containing specific task functions created by individuals to be
used in many programs.
Global vs Local Data Storage
A explanation of scope and its effect on data storage and its use in
modularization.
General Discussion
The concept of global and local data storage is usually tied to the concept of
scope. Scope is the area of the program where an item (be it variable,
constant, function, etc.) that has an identifier name is recognized. In our
discussion we will use a variable and the place within a program where the
variable is defined determines its scope.
Global scope (and by extension global data storage) occurs when a variable
is defined "outside of a function". When compiling the program it creates
the storage area for the variable within the program's data area as part of
the object code. The object code has a machine code piece, a data area and
linker resolution instructions. Because the variable has global scope it is
available to all of the functions within your 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 variable 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.
Local scope (and by extension local data storage) occurs when a variable is
defined "inside of a function". When compiling, the compiler creates
machine instructions that will direct the creation of storage locations on an
area known as the stack which is part of the computer's memory. These
memory locations exist until the function completes its task and returns to
its calling function. In assembly language we talk about items being pushed
onto the stack and popped off the stack when the function terminates. Thus,
the stack is a reusable area of memory being used by all functions and
released as functions terminate. Although the variable has local scope,
technically it is available only from the point of definition to the end of
the function. The parameter passing of data items into a function
establishes them as local variables. Additionally, any other variables or
constants needed by the function usually occur near the top of the function
definition so that they are available during the entire execution of the
function's code.
Definitions
global scope
Data storage defined outside of a function.
local scope
Data storage defined inside of a function.
data area
A part of an object code file used for storage of data.
stack
A part of the computer's memory used for storage of data.
scope
The area of a source code file where an identifier name is recognized.
Using a Header File for User Defined Specific Task Functions
Concepts and an example of how to create a user library within the C++
programming language.
1. The testing shell program with the specific task functions is built and
thoroughly tested.
2. A copy of the testing shell source code is saved as the header file that
once modified will be placed in the user library. You delete the main
part of the program leaving a comments area, any needed include file
references and the specific task functions.
Header File Creation
Creating a header file from a copy of the testing shell.
4. Another copy of the testing shell source code is saved as the verify
header program. You delete the functions prototypes and definitions
then provide an include that points to the header file. This program is
compiled and run to make sure the header file is working properly.
Verify Header File Creation
Creating a verify header file from a copy of the testing shell.
A good way to understand the concept is to review the four files described
above that have been created by a programmer. We will be using the C++
programming language, however the code is easy to understand and will
serve our needs well at explaining the concepts; even if you are not familiar
with C++.
Monitor_Header
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following files to your storage device in the
appropriate folder. You may need to right click on some of the links and
select "Save Target As" in order to download some of the files.
Take a few moments to review the files in conjunction with the concept
discussion above. You should compile and run the
Monitor_Testing_Shell.cpp program.
user_library
You need to copy the udst_monitor.h file placing it into the user_library
folder just created. As you can guess the udst stands for user defined
specific task. The functions within this header file would be used to control
the interaction a user has with the monitor. The .h is a convention of the
C++ programming language and indicates a header file. Thus the identifier
name for the header file is very meaningful and descriptive.
Review the Monitor_Verify_Header.cpp source code file and note the two
include commands are different.
1. The Standard Library uses a less than and a greater than to bracket the
Standard Library name of: iostream
2. The user library uses quote marks to bracket the location of the header
file. This identifies to the complier that we are specifying the exact file
we want. We provide a complete file specification (drive, path
information, filename and extension).
3. Because this item is technically a string within C++, we must use two
back slashes between the drive, path(s) and filename. This is because
the first back slash assumes that the next character is an escape code
and if we really don't want an escape code but a back slash, the second
back slash says no I wanted a back slash.This string: "C:\\Dev-
Cpp\\user_library\\udst_monitor.h" will be interpreted to mean:
C:\Dev-Cpp\user_library\udst_monitor.h
Depending on what drive you are using, what path folder structure you are
using and what you called your folder; you may need to correct the include
reference within the source code so that it properly references the header
file.
Definitions
udst
User Defined Specific Task
testing shell
A program used to create specific task functions.
header file
A file that contains items we want to have included toward the top of
our source code.
Practice 7: Specific Task Functions
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
1. define a function
2. declare a function (a prototype is a declaration to a compiler)
3. call a function
When we use functions created by others that have been organized into
library, we include a header file in our program which contains the
prototypes for the functions. Just like functions that we create, we see them
in the following order in our source code listing:
1. declaring the function (prototype provided in the include file)
2. call the function (with parameter passing of values)
3. define the function (it is either defined in the header file or the linker
program provides the actual object code from a Standard Library
object area)
In most cases, the user can look at the prototype and understand exactly
how the communications (parameter passing) into and out of the function
will occur when the function is called. Let's look at the math example of
absolute value. The prototype is:
Not wanting to have a long function name the designers named it: abs
instead of "absolute". This might seem to violate the identifier naming rule
of using meaningful names, however when identifier names are established
for standard libraries they are often shortened to a name that is easily
understood by all who would be using them. The function is of data type
int, meaning that the function will return an integer value. It is obvious that
the integer value returned is the answer to the question, "What is the
absolute value of the integer that is being passed into the function". This
function is passed only one value; an int number. If I had two integer
variables named apple and banana; and I wanted to store the absolute value
of banana into apple; then a line of code to call this function would be:
apple = abs(banana);
Let's say it in English, pass the function absolute the value stored in
variable banana and assign the returning value from the function to the
variable apple. Thus, if you know the prototype you can usually properly
call the function and use its returning value (if it has one) without ever
seeing the definition of the code (i.e. the source code that tells the function
how to get the answer; that is written by someone else; and either included
in the header file or compiled and placed into an object library; and linked
during the linking step of the Integrated Development Environment (IDE).
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on some of the links and
select "Save Target As" in order to download some of the files. Following
the methods of your compiler/IDE, compile and run the program(s). Study
the source code and/or other file(s) in conjunction with other learning
materials.
Definitions
Standard Library
A set of specific task functions that have been added to the
programming language for universal use.
confidence
The reliance that Standard Library functions work properly.
abs
A function within the cmath standard library in C++ which stands for
absolute.
Practice 8: Standard Libraries
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
Solution:
Answers:
1. true
2. false
3. false
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Example:
pseudocode
Function area_regular_hexagon
Pass In: side
Calculate: side times side times 3 times the
square root of 0.75
Pass Out: the calculation
Endfunction
Character Data Type
An introduction to the character data type.
Most microcomputers use the ASCII (stands for American Standard Code
for Information Interchange and is pronounced "ask-key") Character Set
which has established values for 0 to 127. For the values of 128 to 255 they
usually use the Extended ASCII Character Set. When we hit the capital A
on the keyboard, the keyboard sends a byte with the bit pattern equal to an
integer 65. When the byte is sent from the memory to the monitor, the
monitor converts the integer value of 65 to into the symbol of the capital A
to display on the monitor.
C++
Reserved char
Word
Size 1 byte
C++
syntax Single quote marks – Example: 'A'
rule
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the soruce code file(s) in
conjunction with other learning materials.
Definitions
character
A data type representing single text characters like the alphabet,
numeral digits, punctuation, etc.
ASCII
American Standard Code for Information Interchange
Overview
Every data item, constants and variables, not only have a data type, but the
data type determines how many bytes the item will use in the memory of
the computer. The size of each data type varies with the complier being
used and the computer. This effect is known as being machine dependent.
Additionally, there have been some size changes with upgrades to the
language. In "C" the int data type was allocated 2 bytes of memory storage
on an Intel compatible central processing unit (cpu) machine. In "C++" an
int is allocated 4 bytes.
The compiler would determine the byte size of an integer on the specific
machine and in essence replaces the sizeof operator with a value. Integers
are usually 4 bytes long, thus the line of code would be changed to:
If you place an identifier name that represents a data storage area (variable
or memory constant), it looks at the definition for the identifier name.
NOTE: the parentheses are not needed and often not included for an
identifier name.
Example:
sizeof with a Variable
The compiler would determine the byte size of money by looking at the
definition where it indicates that the data type is double. The double data
type on the specific machine (usually 8 bytes) would replace the code and it
would become:
Definitions
sizeof
An operator that tells you how many bytes a data type occupies in
storage.
Typedef - An Alias
An explanation of typedef being used to create an alias data type.
General Discussion
The typedef statement allows the programmer to create an alias, or
synonym, for an existing data type. This can be useful in documenting a
program. The C++ programming language syntax is:
Let's say a programmer is using a double data type to store the amount of
money that is being used for various purposes in a program. He might
define the variables as follows:
Example:
Regular Definition of Variables
double income;
double rent;
double vacation;
However, he might use the typedef statement and define the variables as
follows:
Example:
Using typedef when Defining Variables
typedef double cash;
the typedef must be defined before its use
cash income;
cash rent;
cash vacation;
Definitions
typedef
Allows the programmer to create an alias, or synonym, for an existing
data type.
Sequence Operator
Outlines several uses of the sequence operator within the C++ programming
language.
General Discussion
The sequence (or comma) operator is used to separate items. It has several
uses, four of which are listed then demonstrated:
This first example is often seen in textbooks, but this method of declaring
variables is not preferred. It is difficult to quickly read the identifier names.
Example:
Preferred Vertical Method of Defining Variables
int pig;
int dog;
int cat;
int rat;
The data types and identifier names (known as parameters) are separated
from each other. This example is a function prototype.
double area_trapezoid(double base, double height,
double top);
In the syntax of a for loop you have three parts each separated by a semi-
colon. The first is the initialization area which could have more than one
initialization. The last is the update area which could have more than one
update. Mutiple initializations or updates use the comma to separate them.
This example is only the first line of a for loop.
The variable ages is an array of integers. Initial values are assigned using
block markers with the values separated from each other using a comma.
Definitions
sequence
An operator used to separate multiple occurrences of an item.
Practice 9: Character Data, Sizeof, Typedef, Sequence
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. The character data type in C++ uses the double quote marks, like:
char grade = "A";
2. Sizeof is an operator that tells you how many bytes a data type
occupies in storage.
3. Typedef helps people who can't hear and is one of the standard
accommodation features of a programming language for people
with a learning disability.
4. The sequence operator should be used when defining variables in
order to save space.
5. Programming can be both enjoyable and frustrating.
Solution:
Answers:
1. false
2. true
3. false
4. false
5. true
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Lab_09_Narrative_Description.txt
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Introduction
One of the most important concepts of programming is the ability to control
a program so that different lines of code are executed or that some lines of
code are executed many times. The mechanisms that allow us to control the
flow of execution are called control structures. Flowcharting is a method
of documenting (charting) the flow (or paths) that a program would
execute. There are four main categories of control structures:
Sequence – Very boring. Simply do one instruction then the next and
the next. Just do them in a given sequence or in order listed. Most lines
of code are this.
We have mentioned that the if then else control structure belongs to the
selection category and is a two-way selection.
Example:
if then else control structure
We have mentioned that the while control structure belongs to the iteration
category and is a test before loop.
Example:
while control structure
counter = 0;
while (counter < 5)
{
cout << "\nI love computers!";
counter ++;
}
Definitions
control structures
Mechanisms that allow us to control the flow of execution within a
program.
sequence
A control structure where you do the items in the sequence listed.
selection
A control structure where you select between two or more choices.
iteration
A control structure that allows some lines of code to be executed many
times.
branching
A control structure that allows the flow of execution to jump to a
different part of the program.
structured programming
A method of planning programs that avoids the branching category of
control structures.
Pseudocode Examples for Control Structures
Pseudocode conventions and control structure examples of: if then else,
case, while, for, do while and repeat until.
Overview
No standard for pseudocode syntax exists. However, there are some
commonly followed conventions to help make pseudocode written by one
programmer easily understood by another programmer. Most of these
conventions follow two concepts:
The sequence control structure simply lists the lines of pseudocode. The
concern is not with the sequence category but with selection and two of the
iteration control structures. The following are commonly used ending
phrase-words:
Case Endcase
While Endwhile
For Endfor
The Do While and Repeat Until iteration control structures don't need an
ending phrase-word. We simply use the first word, then the action part,
followed by the second word with the test expression. Here are some
examples:
Example:
pseudocode: If then Else
If age > 17
Display a message indicating you can vote.
Else
Display a message indicating you can't vote.
Endif
Example:
pseudocode: Case
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."
Endcase
Example:
pseudocode: For
Example:
pseudocode: Do While
Example:
pseudocode: Repeat Until
Flowcharting Symbols
Terminal
Process
Connectors
On-Page Connector
Off-Page Connector
Decision
Module Call
A program module is represented in a flowchart by rectangle with some
lines to distinguish it from process symbol. Often programmers will make a
distinction between program control and specific task modules as shown
below.
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.
Examples
We will demonstrate various flowcharting items by showing the flowchart
for some pseudocode.
Functions
Example:
pseudocode: Function with no parameter passing
Example:
pseudocode: Function main calling the clear monitor function
Function main
Pass In: nothing
Doing some lines of code
Call: clear monitor
Doing some lines of code
Pass Out: value zero to the operating system
Endfunction
Function main
Example:
pseudocode: Sequence control structure
Filename: Solution_Lab_04_Pseudocode.txt
Purpose: Convert Temperature from Fahrenheit to
Celsius
Author: Ken Busbee; © 2008 Kenneth Leroy Busbee
Date: Dec 24, 2008
Example:
pseudocode: If then Else
If age > 17
Display a message indicating you can vote.
Else
Display a message indicating you can't vote.
Endif
If then Else control structure
Example:
pseudocode: Case
Case of age
0 to 17 Display "You can't vote."
18 to 64 Display "Your in your working years."
65 + Display "You should be retired."
Endcase
Case control structure
Example:
pseudocode: While
Example:
pseudocode: For
The for loop does not have a standard flowcharting method and you will
find it done in different ways. The for loop as a counting loop can be
flowcharted similar to the while loop as a counting loop.
For control structure
Example:
pseudocode: Do While
Example:
pseudocode: Repeat Until
Definitions
flowcharting
A programming design tool that uses graphical elements to visually
depict the flow of logic within a function.
process symbol
A rectangle used in flowcharting for normal processes such as
assignment.
input/output symbol
A parallelogram used in flowcharting for input/output interactions.
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.
Practice 10: Introduction to Structured Programming
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
Solution:
Answers:
1. false
2. true
3. false
4. false
5. false
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
List the four categories of control structures and provide a brief description
of each category.
If Then Else
An introduction to the if then else control structure.
We are going to introduce the control structure from the selection category
that is available in every high level language. It is called the if then else
structure. Asking a question that has a true or false answer controls the if
then else structure. It looks like this:
if expression is true
then do this
else because it's 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."
Let's note that all of the elements are present to determine the action (or
flow) that the child will be doing. Because the question (your room is clean)
has only two possible answers (true or false) the actions are mutually
exclusive. Either the child 1) goes outside and plays or 2) sits on a chair for
five minutes. One of the actions is executed; never both of the actions.
if expression
action true
else
do nothing
Because the "else do nothing" is implied, it is usually written in short form
like:
if expression
action true
if (expression)
statement;
else
statement;
Note: The test expression is within the parentheses, but this is not a function
call. The parentheses are part of the control structure. Additionally, there is
no semicolon after the parenthesis following the expression.
Definitions
if then else
A two way selection control structure.
mutually exclusive
Items that do not overlap. Example: true and false.
Boolean Data Type
An introduction to the Boolean data type.
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. The rules within the C++ programming
language are:
C++
Reserved bool
Word
Normal
Unsigned
Signage
Domain
(Values 0 meaning false, and 1 meaning true
Allowed)
C++ syntax true and false are reserved words that can be used as
rule values in expressions
Most control structures use a test expression that executes either selection
(as in the: if then else) or iteration (as in the while; do while; or for loops)
based on the truthfulness or falseness of the expression. Thus, we often talk
about the Boolean expression that is controlling the structure. Within many
programming languages, this expression must be a Boolean expression and
is governed by a tight set of rules. However, in C++ every data type can be
used as a Boolean expression because the value of any data type within C++
can be demoted into a Boolean value.
Within most languages, expressions that yield Boolean data type values are
divided into two groups. One group uses the relational operators within
their expressions and the other group uses logical operators within their
expressions.
Within the C++ programming language the Boolean data type is one of the
standard or basic data types and is a member of the integer family.
Definitions
Boolean
A data type representing the concepts of true and false.
test expression
An expression used to control programming structures.
Relational Operators
An introduction to the six common relational operators used in
programming.
relational operator
An operator that gives a Boolean value by evaluating the relationship
between two operands.
Exercise:
Problem:
Evaluate the following Boolean expressions:
1. 9 < 25
2. 9 < 3
3. 9 > 14
4. 9 <= 17
5. 9 >= 25
6. 9 == 13
7. 9 != 13
8. 9 !< 25
Solution:
Answers:
1. 1
2. 0
3. 0
4. 1
5. 0
6. 0
7. 1
8. Error, the "not less than" is not a valid operator.
Be careful. In math you are familiar with using this symbol = to mean
equal and ≠ to mean not equal. In the C++ programming language the ≠ is
not used and the = symbol means assignment.
Demonstration Program in C++
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file. Following the methods of
your compiler/IDE, compile and run the program(s). Study the source code
file(s) in conjunction with other learning materials.
if (expression)
statement;
else
statement;
Within the C++ programming language there can be only one statement
listed as the action part of a control structure. Often, we will want to do
more than one statement. This problem is overcome by creating a
compound statement. The brace symbols – the opening { and the closing }
- are used to create a compound statement. For example:
if(expression)
{
statement;
statement;
}
else
{
statement;
statement;
}
Because programmers often forget that they can have only one statement
listed as the action part of a control structure; the C++ programming
industry encourages the use of indentation (to see the action parts clearly)
and the use of compound statements (braces), even if there is only one
action. Thus:
if(expression)
{
statement;
}
else
{
statement;
}
block
Another name for a compound statement.
Practice 11: Two Way Selection
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Evaluate the following Boolean expressions:
1. 25 < 7
2. 3 < 7
3. 14 > 7
4. 17 <= 7
5. 25 >= 7
6. 13 == 7
7. 9 != 7
8. 5 !> 7
Solution:
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.
Miscellaneous Items
Link to: Animated gif showing if then else
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Create a table with the six relational operators and their meanings.
Explain why we are using the "if then else" to manipulate the input data in
the example below.
Example:
C++ source code
cout << "\nEnter one side of the rectangle -------
-->: " ;
cin >> side1;
cout << "\nEnter the other side of the rectangle -
-->: " ;
cin >> side2;
if expression
true action
else
false action
This is the basic form of the if then else control structure. Now consider:
As you can see we simply included as part of the "true action" a statement
and another if then else control structure. We did the same (nested another if
then else) for the "false action". In our example we nested if then else
control structures. Nesting could have an if then else within a while loop.
Thus, the concept of nesting allows the mixing of the different categories of
control structures.
Multiway Selection
One of the drawbacks of two way selection is that we can only consider two
choices. But what do you do if you have more than two choices. Consider
the following which has four choices:
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
You get an appropriate message depending on the value of age. The last
item is referred to as the default. If the age is not equal to 18, 39 or 65 you
get the default message. In some situations there is no default action.
Consider:
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
The last if then else control structure has no "else". It’s implied "else do
nothing". Without the default the multiway selection could be written as a
series of "if then without the else" structures. Consider:
if age equal to 18
you can now vote
if age equal to 39
you are middle aged
if age equal to 65
you can consider retirement
Example:
C++ source code: Layout of an if then else
if (expression)
{
statement;
}
else
{
statement;
}
Note:The test expression is within the parentheses, but this is not a
function call. The parentheses are part of the control structure.
Additionally, there is no semicolon after the parenthesis following the
expression.
C++ Example
Multiway selection is often needed to cover all possibilities. Assume that
the user has been prompted for the ages of two people with the answers
stored in variables named age1 and age2. Consider:
Example:
C++ source code
What if the two persons are the same age? The program incorrectly says the
second person is older. To solve this we must handle all three possibilities.
Consider this mulitway selection example:
Example:
C++ source code
if(age1 == age2)
{
cout << "\n\nThey are the same age.";
}
else
{
if(age1 > age2)
{
cout << "\n\nThe first person is older.";
}
else
{
cout << "\n\nThe second person is older.";
}
}
Definitions
nested control structures
Placing one control structure inside of another.
multiway selection
Using control structures to be able to select from more than two
choices.
Logical Operators
An introduction to the three common logical operators used in
programming.
The logical operators are often used to help create a test expression that
controls program flow. This type of expression is also known as a Boolean
expression because they create a Boolean answer or value when evaluated.
The answers to Boolean expressions within the C++ programming language
are a value of either 1 for true or 0 for false. There are three common
logical operators that give a Boolean value by manipulating other Boolean
operand(s). Operator symbols and/or names vary with different
programming languages. The C++ programming language operators with
their meanings are:
C++
Meaning Comment Typing
Operator
Logical
&& two ampersands
and
Logical
! unary the exclamation point
not
Note:The vertical dashes or piping symbol is found on the same key as the
backslash \. You use the SHIFT key to get it. It is just above the Enter key
on most keyboards. It may be a solid vertical line on some keyboards and
show as a solid vertical line on some print fonts.
In most languages there are strict rules for forming proper logical
expressions. An example is:
This expression has two relational operators and one logical operator.
Using the precedence of operator rules the two "relational comparison"
operators will be done before the "logical and" operator. Thus:
1 && 1
or
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.
Truth Tables
A common way to show logical relationships is in truth tables.
x y x && y
x y x ||y
Logical or (||)
x !x
false true
true false
Examples
I call this example of why I hate "and" and love "or".
On Friday my mother took a more relaxed view point and when asked if I
could go outside and play she responded, "If your room is clean or your
homework is done then you may go outside and play." I learned to clean my
room quickly on Friday afternoon. Well needless to say, I loved "or".
For the next example, just imagine a teenager talking to their mother.
During the conversation mom says, "After all, your Dad is reasonable!" The
teenager says, "Reasonable. (short pause) Not."
Maybe college professors will think that all their students studied for the
exam. Ha ha! Not. Well, I hope you get the point.
Exercise:
Problem:
Evaluate the following Logical Boolean expressions:
1. 25 < 7 || 15 > 36
2. 15 > 36 || 3 < 7
3. 14 > 7 && 5 <= 5
4. 4 > 3 && 17 <= 7
5. ! false
6. ! (13 != 7)
7. 9 != 7 && ! 0
8. 5 > && 7
Solution:
Answers:
1. 0
2. 1
3. 1
4. 0
5. 1
6. 0
7. 1
8. Error, there needs to be an operand between the operators > and
&&.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Definitions
logical operator
An operator used to create complex Boolean expressions.
truth tables
A common way to show logical relationships.
Case Control Structure
An introduction to the case control structure and how it is implemented
using a switch within the C++ programming language.
One of the drawbacks of two way selection is that we can only consider two
choices. But what do you do if you have more than two choices. Consider
the following which has four choices:
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 un-important
You get an appropriate message depending on the value of age. The last
item is referred to as the default. If the age is not equal to 18, 39 or 65 you
get the default message. In some situations there is no default action.
Consider this flowchart example:
This flowchart is of the case control structure and is used for multiway
selection. The decision box holds the variable age. The logic of the case is
one of equality where in the value in the variable age is compared to the
listed values in order from left to right. Thus, the value stored in age is
compared to 18 or is "age equal to 18". If it is true, the logic flows down
through the action and drops out at the bottom of the case structure. If the
value of the test expression is false, it moves to the next listed value to the
right and makes another comparison. It works exactly the same as our
nested if then else structure.
Using the same example as above, here is the C++ code to accomplish the
case control structure.
Example:
C++ source code - case structure with integers
switch (age)
{
case 18: cout << "\nYou can vote.";
break;
case 39: cout << "\nYou're middle aged.";
break;
case 65: cout << "\nConsider retirement.";
break;
default: cout << "\nAge is un-important.";
}
The first thing you should note is that the C++ programming language does
not formally have a case control structure. It does have a switch control
structure but it acts differently than the traditional case control structure. We
use a break (which is a branching control structure) with the switch to make
it act like the traditional case structure. This is one of the few allowable
ways to use the switch with break within the C++ programming language to
simulate the traditional case structure. All other uses of the switch or break
are to be avoided if you are to stay within the bounds of good structured
programming techniques.
The value in the variable age is compared to the first "case" (note: case is
one of the C++ reserved words) which is the value 18 (also called the listed
value) using an equality comparison or is "age equal to 18". If it is true, the
cout is executed which displays “You can vote.” and the next line of code
(the break) is done (which jumps us to the end of the control structure). If it
is false, it moves on to the next case for comparison.
Most programming languages, including C++, require the listed values for
the case control structure be of the integer family of data types. This
basically means either an integer or character data type. Consider this
example that uses character data type (choice is a character variable):
Example:
C++ source code - case structure with characters
switch (choice)
{
case 'A': cout << "\nYou are an A student.";
break;
case 'B': cout << "\nYou are a B student.";
break;
case 'C': cout << "\nYou are a C student.";
break;
default: cout << "\nMaybe you should study
harder.";
}
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."
Endcase
Using the case control structure when using non integer family or ranges of
values is allowed when designing a program and documenting that design
with pseudocode or flowcharting. However, the implementation in most
languages would follow a nested if then else approach with complex
Boolean expressions. The logic of the above examples would look like this:
if age > 0 and age <= to 17
display You can’t vote.
else
if age is >= 18 and age <= 64
display You’re in your working years.
else
display You should be retired.
Definitions
case
A control structure that does mulitway selection.
switch
A C++ control structure that can be made to act like a case control
structure.
Branching Control Structures
An introduction to the common types of branching control structures and
which ones are allowed in good structured programming.
Discussion
The branching control structures allow the flow of execution to jump to a
different part of the program. The common branching control structures that
are used with other control structures are: break, continue and goto. These
are rarely used in modular structured programming with one exception.
That exception is in relation to creating the case within the selection
category of control structures. Within C++ the break is used with the switch
to create a structure that acts like the traditional case structure. There is one
other branching control structure that is often not viewed as branching
control structure. It is: return; which is used with functions. Thus, there are
two commonly used branching control reserved words used in C++; break
and return. Additionally, we will add to our list of branching items a pre-
defined function commonly used in the C++ programming language of:
exit; that is part of the C standard library (cstdlib). Some definitions:
Definitions
break
A branching control structure that terminates the existing structure.
continue
A branching control structure that causes a loop to stop its current
iteration and begin the next one.
goto
A branching control structure that causes the logic to jump to a
different place in the program.
return
A branching control structure that causes a function to jump back to
the function that called it.
exit
A pre-defined function used to prematurely stop a program and jump
to the operating system.
We will discuss each item indicating which ones are allowed or not allowed
within good structured programming practices.
Examples
break
The break is used in one of two ways; with the switch (a C++ programming
structure) to make it act like a case structure (it's more common name
within most programming languages) or as part of a looping process to
break out of the loop. The first usage is allowed in good structured
programming and the second is not allowed in good structured
programming.
Example:
C++ source code
switch (age)
{
case 18: cout << "\nYou can vote.";
break;
case 39: cout << "\nYou are middle aged.";
break;
case 65: cout << "\nYou are at retirement age.";
break;
default: cout << "\nYour current age is not
important.";
}
Example:
C++ source code
counter = 0;
while(counter < 8)
{
cout << counter << endl;
if (counter == 4)
{
break;
}
counter++;
}
continue
Example:
C++ source code
goto
Example:
C++ source code
The return is allowed in good structured programming, but only at the end
of a function. A function should not pre-maturely end by having the logic of
the function have it terminate by jumping back to the function that called it.
Example:
C++ source code
//************************************************
******
// get data
//************************************************
******
void get_data(void)
{
// Input - Test Data - 5678.9, 5432.1
cout << "\nEnter the length of the property in
feet --->: ";
cin >> property_length;
cout << "\nEnter the width of the property in
feet ---->: ";
cin >> property_width;
return;
}
exit
Example:
C++ source code
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Evaluate the following Logical Boolean expressions:
1. 25 > 39 || 15 > 36
2. 19 > 26 || 13 < 17
3. 14 < 7 && 6 <= 6
4. 4 > 3 && 17 >= 7
5. ! true
6. ! (13 == 7)
7. 9 != 7 && ! 1
8. 6 < && 8
Solution:
Answers:
1. 0
2. 1
3. 0
4. 1
5. 0
6. 1
7. 0
8. Error, there needs to be an operand between the operators < and
&&.
Miscellaneous Items
Link to: Manipulation of Data Part 3
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Compile and run the Lab_12a.cpp source code file. Understand how it
works.
Copy the source code file Lab_12a.cpp naming it: Lab_12b.cpp
Convert the nested if then else to a switch with breaks.
Build (compile and run) your program.
After you have successfully written this program, if you are taking this
course for college credit, follow the instructions from your
professor/instructor for submitting it for grading.
Problems
Case of shoe_size
4 to 6 Display "Small."
7 to 9 Display "Medium."
10 + Display "Large."
Endcase
The "Flip-Flops" is a unique shoe store that only sells flip-flops. Adult shoe
sizes less than 4 are handled in the children’s department, thus we don’t
need to concern ourselves with sizes less than 4. Half shoe sizes are to be
rounded down, thus the prompt to the user that happens before this case
structure will have addressed that issue. The variable shoe_size will be an
integer value between 4 and 1,000,000,000 (one billion).
Example:
pseudocode
Case of shoe_size
4 to 6 Display "Small."
7 to 9 Display "Medium."
10 + Display "Large."
Endcase
Problem 12c – Instructions
Example:
pseudocode
If age equal to 24
Display a message "You’re the same age as
Melinda."
Else
If age equal to 27
Display a message "You’re the same age as
Ruth."
Else
If age equal to 34
Display a message "You’re the same age as
Ben."
Else
Display a message "You’re age is un-
important."
Endif
Endif
Endif
Do While Loop
An introduction to the do while control structure with examples in the C++
programming language.
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
Within the do while control structure there are three attributes of a properly
working loop. They are:
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 is false, 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.
Syntax
The syntax for the do while control structure within the C++ programming
language is:
do
{
statement;
statement;
statement;
statement; // This statement updates the
flag;
}
while (expression);
Note:The test expression is within the parentheses, but this is not a
function call. The parentheses are part of the control structure.
Additionally, there is a semicolon after the parenthesis following the
expression.
An Example
Example:
C++ source code: do while loop
do
{
cout << "\nWhat is your age? ";
cin >> age_user;
cout << "\nWhat is your friend's age? ";
cin >> age_friend;
cout >> "\nTogether your ages add up to: ";
cout >> (age_user + age_friend);
cout << "\nDo you want to do it again? y or n ";
cin >> 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.
This type of loop control is called an event controlled loop. The flag
updating is an event where someone decides if they want the loop to
execute again.
Using indentation with the alignment of the loop actions and flag update is
normal industry practice within the C++ community.
Infinite Loops
At this point it's worth mentioning that good programming always provides
for a method to insure that the loop question will eventually be false so that
the loop will stop executing and the program continues with the next line of
code. However, if this does not happen then the program is in an infinite
loop. Infinite loops are a bad thing. Consider the following code:
Example:
C++ source code: infinite loop
loop_response = 'y';
do
{
cout << "\nWhat is your age? ";
cin >> age_user;
cout << "\nWhat is your friend's age? ";
cin >> age_friend;
cout >> "\nTogether your ages add up to: ";
cout >> (age_user + age_friend);
}
while (loop_response == 'y');
The programmer assigned a value to the flag before the loop and forgot to
update the flag. Every time the test expression is asked it will always be
true. Thus, an infinite loop because the programmer did not provide a way
to exit the loop (he forgot to update the flag).
Example:
C++ source code: infinite loop
do
{
cout << "\nWhat is your age? ";
cin >> age_user;
cout << "\nWhat is your friend's age? ";
cin >> age_friend;
cout >> "\nTogether your ages add up to: ";
cout >> (age_user + age_friend);
cout << "\nDo you want to do it again? y or n ";
cin >> loop_response;
}
while (loop_response = 'y');
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 within the Boolean concepts of the C++ programming
language, the answer to the text question is true. Viola, you have an infinite
loop.
Definitions
do while
A test after iteration control structure available in C++.
action item
An attribute of iteration control structures.
update item
An attribute of iteration control structures.
test item
An attribute of iteration control structures.
at least once
Indicating that test after loops execute the action at least once.
infinite loop
No method of exit, thus a bad thing.
Flag Concept
An explanation of how the flag concept is used within computer
programming.
Concept Discussion
For centuries flags have been used as a signal to let others know something
about the group or individual that is displaying, flying or waving the flag.
There are country flags and state flags. Ships at sea flew the flag of their
country. Pirates flew the skull and cross bones. A yellow flag was used for
quarantine, usually the plague. Even pirates stayed away. Today, some
people might recognize the flag used by scuba divers. The Presidents of
most countries have a flag. At a race car event they use the checkered flag
to indicate the race is over.
Computer programming uses the concept of a flag in the same way that
physical flags are used. A flag is anything that signals some information to
the person looking at it.
Computer Implementation
Any variable or constant that holds data can be used as a flag. You can think
of the storage location as a flag pole. The value stored within the variable
conveys some meaning and you can think of it as being the flag. An
example might be a variable named: gender which is of the character data
type. The two values normally stored in the variable are: 'F' and 'M'
meaning female and male. Then, somewhere within a program we might
look at the variable to make a decision:
Example:
flag controling an if then control structure
Looking at the flag implies comparing the value in the variable to another
value (a constant or the value in another variable) using a relational
operator (in our above example: equality).
Example:
simple flag comparison
This is fine but what if the user accidentally has on the caps lock. Then his
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:
Example:
complex flag comparison
Definitions
flag
A variable or constant used to store information that will normally be
used to control the program.
Assignment vs Equality within C++
An explanation with examples of a common mistake made by accidently
confusing the assignment operator with the equality operator within the
C++ programming language.
General Discussion
Most control structures use a test expression that executes either selection
(as in the: if then else) or iteration (as in the while; do while; or for loops)
based on the truthfulness or falseness of the expression. Thus, we often talk
about the Boolean expression that is controlling the structure. Within many
programming languages, this expression must be a Boolean expression and
is governed by a tight set of rules. However, in C++ every data type can be
used as a Boolean expression, because every data type can be demoted into
a Boolean value by using the rule/concept that zero represents false and all
non-zero values represent true.
Within C++ we have the potential added confusion of the equals symbol as
an operator that does not represent the normal math meaning of equality
that we have used for most of our life. The equals symbol with C++ means:
assignment. To get the equality concept of math within C++ we use two
equal symbols to represent the relational operator of equality. Let's
consider:
if (pig = 'y')
{
cout << "\nPigs are good";
}
else
{
cout << "\nPigs are bad.";
}
The test expression of the control structure will always be true, because the
expression is an assignment (not the relational operator of ==). It assigns
the 'y' to the variable pig, then looks at the value in pig and determines that
it is not zero; therefore the expression is true. And it will always be true and
the else part will never be executed. This is not what the programmer had
intended. Let's consider:
do
{
cout << "\nPigs are good";
cout << "\nDo it again, answer y or n: ";
cin >> do_it_again
}
while (do_it_again = 'y');
The loop's test expression will always be true, because the expression is an
assignment (not the relational operator of ==). It assigns the 'y' to the
variable do_it_again, then looks at the value in do_it_again and determines
that it is not zero; therefore the expression is true. And it will always be true
and you have just created an infinite loop. As a reminder, infinite loops are
not a good thing.
These examples are to remind you that you must be careful in creating your
test expressions so that they are indeed a question usually involving the
relational operators.
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
Within the repeat until control structure there are three attributes of a
properly working loop. They are:
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.
Definitions
repeat until
A test after iteration control structure that is not available in C++.
Practice 13: Test After Loops
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. The do while and repeat until structure act exactly the same.
2. Students sometimes confuse assignment and equality.
3. The repeat until looping control structure is available in all
programming languages.
4. Because flags are often used, they are usually a special data type.
5. The do while is a test before loop.
Solution:
Answers:
1. false
2. true
3. false
4. false
5. false
Miscellaneous Items
Link to: Animated gif showing a do while loop
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Example:
pseudocode
Do
Display "I like cheese cake!"
Display "Do it again? y or n ---> "
Get answer from keyboard
While answer is 'y'
Increment and Decrement Operators
An introduction to the increment and decrement operators used in
programming with details of C++ usage.
General Discussion
The idea of increment or decrement is to either add or subtract 1 from a
variable that is usually acting as a flag. Using a variable named counter; in
generic terms, for example:
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 type. Programmers will sometimes use inc and dec as
abbreviations for increment and decrement respectively.
Basic Concept
Within the C++ programming language the increment and decrement are
often used in this simple generic way. The operator of increment is
represented by two plus signs in a row. Examples:
counter = counter + 1;
counter += 1;
counter++;
++counter;
As C++ statements, the four examples all do the same thing. They add 1 to
the value of whatever is stored in counter. The decrement opereator is
represented by two minus signs in a row. They would subtract 1 from the
value of whatever was in the variable being decremented. The precedence
of increment and decrement depends on if the operator is attached to the
right of the operand (postfix) or to the left of the operand (prefix). Within
C++ postfix and prefix do not have the same precedence.
Postfix Increment
Postfix increment says to use my existing value then when you are done
with the other operators; increment me. An example:
Prefix Increment
Prefix increment says to increment me now and use my new value in any
calculation. An example:
The variable oldest is incremented with the new value changing it from 44
to 45; then the new value is assigned to age.
In postfix age is assigned 44 in prefix age is assigned 45. One way to help
remember the difference is to think of postfix as being polite (use my
existing value and return to increment me after the other operators are done)
where as prefix has an ego (I am important so increment me first and use
my new value for the rest of the evaluations).
Exercise:
Problem:
Evaluate the following items using increment or decrement:
Solution:
Answers:
1. true
2. y is: 18 and z is: 19
3. x is: 8.77 and y is: 8 Note: truncation of 8.77 to 8 upon demotion.
4. Not ok. Error, the item incremented must have Lvalue attributes,
usually a variable. It is an expression not a variable.
Definitions
increment
Adding one to the value of a variable.
decrement
Subtracting one from the value of a variable.
postfix
Placing the increment or decrement operator to the right of the
operand.
prefix
Placing the increment or decrement operator to the left of the operand.
While Loop
An introduction to the while control structure with examples in the C++
programming language.
Within the while control structure there are four attributes to a properly
working loop. They are:
The initialization of the flag is not technically part of the control structure,
but a necessary item to occur before the loop is started. The English
phrasing is, "While the expression is true, do the following actions". This is
looping on the true. When the test expression is false, you stop the loop and
go on with the next item in the program. Notice, because this is a test before
loop the action might not happen. It is called a test before loop because
the test comes before the action. It is also sometimes called a pre-test loop,
meaning the test is pre (or Latin for before) the action and update.
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 floor, pick it up and put it in the garbage."
Note: All of the elements are present to determine the action (or flow) that
the child will be doing (in this case repeating). Because the question (can
you see a Cheerios) has only two possible answers (true or false) the action
will continue while there are Cheerios on the floor. Either the child 1) never
picks up a Cheerio because they never spilled any or 2) picks up a Cheerio
and keeps picking up Cheerios one at a time while he can see a Cheerio on
the floor (that is until they are all picked up).
Syntax
The syntax for the while control structure within the C++ programming
language is:
An Example
Example:
C++ source code: while
loop_response = 'y';
while (loop_response == 'y')
{
cout << "\nWhat is your age? ";
cin >> age_user;
cout << "\nWhat is your friend's age? ";
cin >> age_friend;
cout >> "\nTogether your ages add up to: ";
cout >> (age_user + age_friend);
cout << "\nDo you want to do it again? y or n ";
cin >> loop_response;
}
The four attributes of a test before loop are present. The initialization of the
flag. The test is the equality relational comparison of the value in the flag
variable to the lower case character of y. 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.
This type of loop control is called an event controlled loop. The flag
updating is an event where someone decides if they want the loop to
execute again.
Using indentation with the alignment of the loop actions and flag update is
normal industry practice within the C++ community.
Infinite Loops
At this point it's worth mentioning that good programming always provides
for a method to insure that the loop question will eventually be false so that
the loop will stop executing and the program continues with the next line of
code. However, if this does not happen then the program is in an infinite
loop. Infinite loops are a bad thing. Consider the following code:
Example:
C++ source code: infinite loop
loop_response = 'y';
while (loop_response == 'y')
{
cout << "\nWhat is your age? ";
cin >> age_user;
cout << "\nWhat is your friend's age? ";
cin >> age_friend;
cout >> "\nTogether your ages add up to: ";
cout >> (age_user + age_friend);
}
The programmer assigned a value to the flag before the loop which is
correct. However, he forgot to update the flag. Every time the test
expression is asked it will always be true. Thus, an infinite loop because the
programmer did not provide a way to exit the loop (he forgot to update the
flag). Consider the following code:
Example:
C++ source code: infinite loop
loop_response = 'y';
while (loop_response = 'y')
{
cout << "\nWhat is your age? ";
cin >> age_user;
cout << "\nWhat is your friend's age? ";
cin >> age_friend;
cout >> "\nTogether your ages add up to: ";
cout >> (age_user + age_friend);
cout << "\nDo you want to do it again? y or n ";
cin >> 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 within the Boolean concepts of the C++ programming
language, the answer to the test expression is true. Viola, you have an
infinite loop.
Example:
C++ source code: infinite loop
loop_response = 'y';
while (loop_response == 'y');
{
cout << "\nWhat is your age? ";
cin >> age_user;
cout << "\nWhat is your friend's age? ";
cin >> age_friend;
cout >> "\nTogether your ages add up to: ";
cout >> (age_user + age_friend);
cout << "\nDo you want to do it again? y or n ";
cin >> loop_response;
}
The undesirable semi-colon on the end of while line causes the action of the
while loop to be the "nothingness" between the closing parenthesis and the
semi-colon. The program will infinitely loop because there is no action (that
is no action and no update). If this is the first item in your program it will
appear to start but there will be no output.
Counting Loops
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.
Example:
C++ source code: while loop that is counting
counter = 0;
while (counter < 5)
{
cout << "\nI love ice cream!";
counter++;
}
Infinite Loops
Consider:
Example:
C++ source code: infinite loop
counter = 0;
while (counter < 5)
{
cout << "\nI love ice cream!";
}
Example:
C++ source code: while as a counting loop
Consider the following variation assuming that age and counter are both
integer data type and that age has a value:
Example:
C++ source code: while as a counting loop
counter = 0;
while (counter < age)
{
cout << "\nI love corn chips!";
counter++;
}
This loop is a counting loop similar to our first counting loop example. The
only difference is instead of using a literal constant (in other words 5) in our
expression, we used the variable age (and thus the value stored in age) to
determine how many times to execute the loop. However, unlike our first
counting loop example which will always execute exactly 5 times; it is
possible that the person’s age is 0 (zero) and the first time we test the
expression it will be false and the action part of the loop would never be
executed.
Definitions
while
A test before iteration control structure available in C++.
loop attributes
Items associated with iteration or looping control structures.
initialize item
An attribute of iteration control structures.
event controlled
Using user input to control a loop.
counting controlled
Using a variable to count up or down to control a loop.
Practice 14: Test Before Loops
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Evaluate the following items using increment or decrement:
x--;
and
--x;
y = --x;
Solution:
Answers:
1. true
2. y is: 27 and z is: 26
3. x is: 3.44 and y is: 3 Note: truncation of 3.44 to 3 upon demotion
to integer data type.
4. Not ok. Error, the item incremented must have Lvalue attributes,
usually a variable. Because of the parentheses, it is an expression
not a variable.
Miscellaneous Items
Link to: Animated gif showing a while loop
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Example:
pseudocode
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
Within the for control structure there are four attributes to a properly
working loop. They are:
The initialization of the flag is not technically part of the while control
structure, but it is usually part of the for control structure. The English
phrasing is, "For x is 1; x less than 3; do the following actions; increment x;
loop back to the test expression". This is doing the action on the true. When
the test expression is false, you stop the loop and go on with the next item
in the program. Notice, because this is a test before loop the action might
not happen. It is called a test before loop because the test comes before
the action. It is also sometimes called a pre-test loop, meaning the test is pre
(or Latin for before) the action and update.
Syntax
The syntax of the for loop control structure within the C++ programming
language is:
An Example
Example:
C++ source code: for
The four attributes of a test before loop (remember the for loop is one
example of a test before loop) are present.
Using indentation with the alignment of the loop actions is normal industry
practice within the C++ community.
Infinite Loops
At this point it's worth mentioning that good programming always provides
for a method to insure that the loop question will eventually be false so that
the loop will stop executing and the program continues with the next line of
code. However, if this does not happen then the program is in an infinite
loop. Infinite loops are a bad thing. Consider the following code:
Example:
C++ source code: infinite loop
The programmer assigned a value to the flag during the initialization step
which is correct. However, he forgot to update the flag (the update step is
missing). Every time the test expression is asked it will always be true.
Thus, an infinite loop because the programmer did not provide a way to exit
the loop (he forgot to update the flag).
The following shows the use of the sequence operator to separate the
multiple initializations and multiple updates. This is not available in most
languages, thus is more unique to the C++ programming language.
Example:
C++ source code: for with multiple initializations and updates
The name for comes from mathematics’ method of writing an iteration (or
repetition). In math we would say: “For the variable i starts at a given value
and repeats an action increasing the value of i until i is executed for the
stopping value”. Usually written in math as:
Definitions
for
A test before iteration control structure typically used for counting.
Circular Nature of the Integer Data Type Family
An explanation of how modular arithmetic concepts apply to the integer
data type family and counting loops.
General 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 make all
your numbers floating-point data types. The reason is twofold. First, some
things in the real world are not fractional. A dog, even with only 3 legs, is
still one dog not three fourths of a dog. Second, the integer data type is
often used to control program flow by counting (counting loops). The
integer family has a circular wrap around feature. Using a two byte integer,
the next number bigger than 32767 is negative 32768 (character acts the
same way going from 255 to 0. We could also reverse that to be the next
smaller number than negative 32768 is positive 32767. This can be shown
by using a normal math line, limiting the domain and then connecting the
two ends to form a circle.
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.
A familiar use of modular arithmetic is its use in the 12 hour clock the
arithmetic of time-keeping in which the day is divided into two 12 hour
periods. If the time is 7:00 now, then 8 hours later it will be 3:00. Usual
addition would suggest that the later time should be 7 + 8 = 15, but this is
not the answer because clock time "wraps around" every 12 hours; there is
no "15 o'clock". Likewise, if the clock starts at 12:00 (noon) and 21 hours
elapse, then the time will be 9:00 the next day, rather than 33:00. Since the
hour number starts over when it reaches 12, this is arithmetic modulo 12.
Time-keeping on a clock gives an example of modular arithmetic."
(Modular arithmetic from Wikipedia)
The use of the modulus operator in integer division is tied to the concepts
used in modular arithmetic.
Let’s give an example of the loop executing for what appears to be for
infinity (the third item on our list).
Example:
C++ source code
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials.
Definitions
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".
Formatting Output
An explanation of formatting output (to cout) as used within a C++
program.
General Discussion
Formatting of output is handled in different ways in the various languages
used today. Many programming languages have different formatting
instructions for the standard output device which is usually the monitor
(going to a DOS black screen output box) versus using the monitor as a
Graphical User Interface (GUI). File storage output is often handled
similarly to the standard output device. All of this makes formatting of
output very machine, output device and language dependent.
There are two items used to keep output from filling up a line and
wrapping on to the next line. They are:
Using the escape code sequence of \n within your strings (text between
as set of double quote marks).
Using the item from the iostream named: endl; which is short for end
line.
Thus the programmer is responsible for making text show reasonably on the
screen. Both of the above also allow for adequate vertical spacing when
needed in your output.
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(n);
Setting the width for integer family and floating-point family data types
must be done for the output of each value. Assume in the following
example that age is an integer data type and money is a floating-point data
type.
Note that each value had to have its own setw(n) where n is an integer
number telling it how many positions to use for the output. The iomanip
header file (immediately shown) will need to be included in your program.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials.
Definitions
formatting
Modifying the way the output is displayed.
wrapping
When output is not vertically spaced properly.
Nested For Loops
An explanation of nesting with an example of nested for loops.
General Discussion
if expression
true action
else
false action
This is the basic form of the if then else control structure. Now consider:
As you can see we simply included as part of the "true action" a statement
and another if then else control structure. We did the same (nested another if
then else) for the "false action". In our example we nested if then else
control structures. Nesting could have an if then else within a while loop.
Thus, the concept of nesting allows the mixing of the different categories of
control structures.
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 |
---------------------------------------------
----------------------------
1 ! 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 |
2 ! 2 | 4 | 6 | 8 | 10 | 12 | 14 |
16 | 18 | 20 | 22 | 24 |
3 ! 3 | 6 | 9 | 12 | 15 | 18 | 21 |
24 | 27 | 30 | 33 | 36 |
4 ! 4 | 8 | 12 | 16 | 20 | 24 | 28 |
32 | 36 | 40 | 44 | 48 |
5 ! 5 | 10 | 15 | 20 | 25 | 30 | 35 |
40 | 45 | 50 | 55 | 60 |
6 ! 6 | 12 | 18 | 24 | 30 | 36 | 42 |
48 | 54 | 60 | 66 | 72 |
7 ! 7 | 14 | 21 | 28 | 35 | 42 | 49 |
56 | 63 | 70 | 77 | 84 |
8 ! 8 | 16 | 24 | 32 | 40 | 48 | 56 |
64 | 72 | 80 | 88 | 96 |
9 ! 9 | 18 | 27 | 36 | 45 | 54 | 63 |
72 | 81 | 90 | 99 | 108 |
10 ! 10 | 20 | 30 | 40 | 50 | 60 | 70 |
80 | 90 | 100 | 110 | 120 |
11 ! 11 | 22 | 33 | 44 | 55 | 66 | 77 |
88 | 99 | 110 | 121 | 132 |
12 ! 12 | 24 | 36 | 48 | 60 | 72 | 84 |
96 | 108 | 120 | 132 | 144 |
Example:
C++ source code: nested for loops - multiplication table
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials.
Definitions
complex logic
Often solved with nested control structures.
Practice 15: Counting Loops
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. true
3. true
4. false
5. true
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Lab_15a.cpp
Read and follow the directions below carefully, and perform the steps in the
order listed.
Compile and run the Lab_15a.cpp source code file. Understand how it
works.
Copy the source code file Lab_15a.cpp naming it: Lab_15b.cpp
Convert the code that is counting (all four attributes) to a for loop.
Build (compile and run) your program.
After you have successfully written this program, if you are taking this
course for college credit, follow the instructions from your
professor/instructor for submitting it for grading.
Problems
Using proper C++ syntax, convert the following for loop to a while loop.
Example:
C++ source code
General Discussion
In most programming languages a string is typically a string of characters
(string them along in a series). The rules for handling strings vary from
language to language. Technically, there is no string data type in the C++
programming language. However, the concept of a string data type makes it
easy to handle stings of character data. Associated with object oriented
programming the string class has been added to C++ as a standard part of
the programming language.
Most data is more complex than just one character, integer, etc.
Programming languages develop other methods to represent and store data
that are more complex. A complex data type of array is first most students
encounter. An array 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.
Most other operators are not allowed and basically do not make sense for a
string data type. The above items are demonstrated in the following
program.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials.
Definitions
array
A sequenced collection of elements of the same data type with a single
identifier name.
concatenation
Combining two strings into one string.
string class
A complex data item that uses object oriented programming.
class member
An operator used to invoke functions associated with a class.
Unary Positive and Negative Operators
An introduction to unary positive and unary negative operators used in
programming with details of C++ usage.
General Discussion
Unary positive also known as plus and unary negative also known as minus
are unique operators. The plus and minus when used with a constant value
represent the concept that the values are either positive or negative. Let’s
consider:
+5 + -2
We have three operators in this order: unary positive, addition, and unary
negative. The answer to this expression is a positive 3. As you can see, one
must differentiate between when the plus sign means unary positive and
when it means addition. Unary negative and subtraction have the same
problem. Let’s consider:
-2 - +5
7 - -2
First constants that do not have a unary minis in front of them are assumed
(the default) to be positive. When you subtract a negative number it is like
adding, thus the expression evaluates to positive 9.
The concept of negation is to take a value and change its sign, that is: flip it.
If it positive make it negative and if it is negative make it positive.
Mathematically, it is the following C++ code example, given that money is
an integer variable with a value of 6:
-money
money * -1
The above two expressions evaluate to the same value. In the first line, the
value in the variable money is fetched and then it’s negated to a negative 6.
In the second line, the value in the variable money is fetched and then it’s
multiplied by negative 1 making the answer a negative 6.
Simply to satisfy symmetry, the unary positive was added to the C++
programming language as on operator. However, it is a totally worthless or
useless operator and is rarely used. However don’t be confused the
following expression is completely valid:
6 + +5
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
Exercise:
Problem:
Evaluate the following items involving unary positive and unary
negative:
1. +10 - -2
2. -18 + 24
3. 4 - +3
4. +8 + - +5
5. +8 + / +5
Solution:
Answers:
1. 12
2. 6
3. 1
4. It’s 3. Surprised, but it works. The middle plus sign is addition
and the rest are unary positive or unary negative.
5. Error, no operand between addition and division.
Definitions
unary positive
A worthless operator almost never used.
unary negative
An operator that causes negation.
plus
Aka unary positive.
minus
Aka unary negative.
Practice 16: String Class, Unary Positive and Negative
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Evaluate the following items involving unary positive and unary
negative:
1. +13 - -2
2. -10 + 14
3. 4 + - 3
4. +8 - * +5
Solution:
Answers:
1. 15
2. 4
3. 1
4. Error, no operand between subtraction and multiplication.
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Problems
Describe the normal C++ operators allowed with the string data type.
Overview
The conditional operator is unique in that it has three operands separated by
two unconnected operator symbols. All other C++ operators are either
unary (one operator and one operand) or binary (one operator and two
operands). On the "Abbreviated Precedence Chart for C++ Operators" the
conditional operator has the word "trinary" in the comments column. This
prefix "tri" means three, thus three operands.
C++
Meaning Comments
Operator
Example:
if then else
Example:
conditional = option 1
age > 17 ? cout << "You can vote." : cout << "You
can’t vote.";
Example:
conditional = option 2
The first operand is a test expression similar to those that control program
flow in control structures. This type of expression is also known as a
Boolean expression because they create a Boolean answer of true or false.
If the test is true the second operand becomes the value of the expression. If
false, the third operand becomes the value of the expression. The operators
of the question mark and colon separate the three operands.
Example:
general format
Definitions
conditional
A trinary C++ operator that acts like an if then else control structure.
Recursion vs Iteration
An introduction to recursion with the alternate method of using a for loop as
the solution to a repetitive algorithm. C++ programming code for factorial
is included.
Repetitive Algorithms
"In general, there are two approaches to writing repetitive algorithms. One
uses loops; the other uses recursion. Recursion is a repetitive process in
which a function calls itself. Both approaches provide repetition, and either
can be converted to the other's approach."[footnote] Iteration is one of the
categories of control structures. It allows for the processing of some action
zero to many times. Iteration is also known as looping and repetition. The
math term "to iterate" means to perform the statement parts of the loop.
Many problems/tasks require the use of repetitive algorithms. With most
programming languages this can be done with either:
Behrouz A. Forouzan and Richard F. Gilberg, Computer Science A
Structured Approach using C++ Second Edition (United States of America:
Thompson – Brooks/Cole, 2004) 265.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials.
factorial
A math problem that often is solved using recursion.
Practice 17: Conditional Operator and Recursion
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. true
3. true
4. false
5. false
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Lab_17a.cpp
Read and follow the directions below carefully, and perform the steps in the
order listed.
Compile and run the Lab_17a.cpp source code file. Understand how it
works.
Copy the source code file Lab_17a.cpp naming it: Lab_17b.cpp
Convert the code that is using the if then else to a conditional
expression.
Convert the code that is using the conditional expression to an if then
else.
Build (compile and run) your program.
After you have successfully written this program, if you are taking this
course for college credit, follow the instructions from your
professor/instructor for submitting it for grading.
Problems
Using proper C++ syntax, convert the following if then else to a conditional
expression.
Example:
if then else
if (x == y)
{
z = 14;
}
else
{
z++;
}
Example:
conditional
Overview
An array is a sequenced collection of elements of the same data type with a
single identifier name. As such, the array data type belongs to the
"Complex" category or family of data types. 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 dimensioned arrays.
Consider a theater ticket with section, row and seat (three dimensions). This
module will only cover the single dimension array. Most single dimension
arrays are visualized vertically and are often called a list.
Most programmers are familiar with a special type of array called a string.
Strings are basically a single dimension array of characters. Unlike other
single dimension arrays, we usually envision a string as a horizontal stream
of characters and not vertically as a list. Within C++ the string data type is a
length-controlled array and is a pre-defined data class.
By leaving out the five and having initial values assigned, the compiler will
know to create the array with five storage spaces because there are five
values listed. This method is preferred because we can simply add members
to or remove members from the array by changing the items inside of the
braces. We could have also done this:
int ages[5];
This would have declared the storage space of five integers with the
identifier name of ages but their initial values would have been unknown
values (actually there would be values there but we don’t know what they
would be and thus think of the values as garbage). We could assign values
later in our program by doing this:
ages[0] = 49;
ages[1] = 48;
ages[2] = 26;
ages[3] = 19;
ages[4] = 16;
list
A single dimension array.
table
A two dimension array.
Array Index Operator
An introduction to the array index operator as used within the C++
programming language.
int my_age;
my_age = ages[2]
Miss Other
Position C++
America Contests
Saying that my cousin is the 2nd Runner Up in the Miss America contest
sounds so much better than saying that she was in 3rd Place. We would be
talking about the same position in the array of the five finalists.
ages[3] = 20;
The C++ operator name is called the array index or simply the index
operator and it uses the square brackets as the operator symbols.
Definitions
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.
Displaying Array Members
Examples of displaying members of an array with for loops and using the
sizeof operator within the C++ programming language.
Example:
accessing the members of an array
Saying that my cousin is the 2nd Runner Up in the Miss America contest
sounds so much better than saying that she was in 3rd Place. We would be
talking about the same position in the array of the five finalists.
Rather than using the for loop to display the members of the array, we could
have written five lines of code as follows:
Within the control of the for loop for the displaying of the grades, note that
we calculated the number of the members in the array by using the sizeof
operator. The expression is:
When you ask for the sizeof an array identifier name the answer is how
many total bytes long is the array (or in other words – how many bytes of
storage does this array need to store its values). This will depend on the
data type of the array and the number of elements. When you ask for the
sizeof one of its members, it tells you how many bytes one member needs.
By dividing the total number of bytes by the size of one member, we get the
answer we want: the number of members in the array. 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.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials.
Definitions
flexible coding
Using the sizeof operator to calculate the number of members in an
array.
Practice 18: Introduction to Arrays
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. The array data type is one of the standard data types in C++.
2. Arrays can have more than one dimension.
3. For loops are often used to display the members of an array.
4. When defining an array, it is preferable to specify how many
members are in the array.
5. Arrays are rarely used to represent data.
Solution:
Answers:
1. false
2. true
3. true
4. false
5. false
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Lab_18_Narrative_Description.txt
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Briefly explain what an array is and list the two common operators used
with arrays.
File Input and Output
An introduction to file input and output with examples within the C++
programming language.
Text File – A file consisting of characters from the ASCII character code
set. Text files (also know an ASCII text files) contain character data. When
we create a text file we usually think of it consisting of a series of lines. On
each line are several characters (including spaces, punctuation, etc.) and we
generally end the line with a return (this a character within the ASCII
character code set). The return is also known as the new line character. You
are most likely already familiar with the escape code of \n which is used
within C++ to indicate a return character when used with in a literal string
with the cout.
Filename – The name and its extension. Most operating systems have
restrictions on which characters can be used in filenames. Example for MS-
DOS and Windows: Lab_05.txt
Because some operating systems do not allow spaces, we suggest that you
use the underscore where needed for spacing in a filename.
Filespec – The location of a file along with its filename. It is short for file
specification. Most operating systems have a set of rules on how to specify
the drive and directory (or path through several directory levels) along with
the filename. Example for MS-DOS and Windows:
C:\myfiles\cosc_1436\Lab_05.txt
Because some operating systems do not allow spaces, we suggest that you
use the underscore where needed when creating folders or sub-directories.
Open – Your program requesting the operating system to let it have access
to an existing file or to open a new file. Within C++ this is accomplished by
including the header file: <fstream> File Input/Output is handled in C++ by
using a pre-defined class of data objects, similar to the way string data type
is handled. This class of objects has both data type names and functions
built to specifically accomplish opening and closing a file.
Within your program you create a local storage variable with the data type
of fstream like this:
fstream inData;
This variable will be used to store the device token that the operating
system assigns to the file being opened. Thus, opening a file uses a class
member function call like this:
inData.open("C:\\myfiles\\cosc_1436\\Lab_05.txt",
ios::in);
The two parameters passed to the function are the filespec and the method
that you want to use the file (in this example as input). The function
provides a returning value of a device token from the operating system and
it is stored in the variable named inData.
if (!inData)
Don’t be misled by the not operator. This reads "if it is true that the token
stored in inData is zero". If inData is zero, noting zero is 1 or true.
Read – Moving data from a device that has been opened into a memory
location defined in your program. When reading text files that have integer
or floating-point constants, the operating systems converts the text symbols
to a binary number. The operator used is the extraction or read operator. An
example of reading is:
This expression is similar to reading from the standard input device (aka the
keyboard):
The "cin" is a predefined device token associated with the Standard Input
and Output devices. For our file reading example you might say, "Go to the
device identified by the token stored in the inData variable and read in the
next value storing it in the next_number variable within my program".
This expression is similar to writing to the standard output device (aka the
monitor):
Close – Your program requesting the operating system to release a file that
was previously opened. There are two reasons to close a file. First, it
releases the file and frees up the associated operation system resources.
Second, if closing a file that was opened for output; it will clear the out the
operating system’s buffer and insure that all of the data is physically stored
in the output file. Some examples of closing files:
inData.close();
outData.close();
You need to study this module in conjunction with the demo file provided.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
After you run the program use a text editor to examine the
Demo_File_IO_Output.txt file created by the program. You should see the
output as: Total is: 33.3
Definitions
text file
A file consisting of characters from the ASCII character code set.
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.
device token
A key value provided by the operating system to associate a device to
your program.
read
Moving data from a device that has been opened into a memory
location defined in your program.
write
Moving data from a memory location defined in your program to a
device that has been opened.
close
Your program requesting the operating system to release a file that was
previously opened.
Arrays and Functions
An introduction to processing arrays with functions with an example of
displaying an array within the C++ programming language.
This module covers the displaying the array members on the monitor via
calling an array function dedicated to that task. You need to study this
module in conjunction with the demo file provided.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Definitions
array function
A user defined specific task function designed to process an array.
Loading an Array from a File
An introduction and example of loading an array from a file within the C++
programming language.
Conceptual Overview
Loading an array from a file presents an interesting dilemma. The problem
resolves around how many elements you should plan for in the array. Let’s
say 100, but what if the file has fewer or more than 100 values. How can
the program handle it correctly?
1. We can read the file once to get the element count. Thus, we will know
exactly how many members (elements) we will need.
2. We can then create an array using dynamic memory allocation by
defining the array within a function so that it has local scope. Local
scope variables are created during the execution of the program and
use the stack as the storage location instead of the data area. If you
define the array outside of a function (global scope also known as
static memory allocation) it stores it in the data area and must know
how much storage space to allocate to the array when you write the
source code. Since we don’t know how many elements will be on the
input file when we write the source code defining an array with global
scope will not work. But, we can determine exactly how many
members we need for the array by having our program count them
(step 1) so that we can then define the array with local scope to the
precise size needed.
3. We can then load the array by reading the file a second time and
storing the values read into the array just created.
This method is demonstrated in the demo file provided, thus you need to
study this material in conjunction with the demo program.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials. You may need to right click on
the link and select "Save Target As" in order to download the file.
Definitions
dynamic memory
Aka stack created memory associated with local scope.
static memory
Aka data area memory associated with global scope.
Math Statistics with Arrays
An introduction to functions performing statistical calculations on an array
within the C++ programming language.
Overview
Arrays are an important complex data type used in almost all programming.
We continue to concentrate on simple one dimension arrays also called a
list. Most programmers develop a series of user defined specific task
functions that can be used with an array for normal processing. These
functions are usually passed the array along with the number of elements
within the array. Some of functions also pass another piece of data needed
for that particular functions task.
This module covers the totaling of the members of an integer array member.
The Latin name for totaling is summa sometimes shortened to the word
sum. The array function is often called "sum" and it does some parameter
passing. It passes into the function the common two items of the array: its
name along with the number of elements; but it also returns a value
representing sum or total of the values within the array. You need to study
this module in conjunction with the demo file provided.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials. You may need to right click on
the link and select "Save Target As" in order to download the file.
Definitions
sum
Latin for summa or a total.
Practice 19: File I/O and Array Functions
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
Solution:
Answers:
1. false
2. false
3. true
4. false
5. false
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download the Lab File(s)
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Why would we open a file and count its elements and then close the file.
Finding a Specific Member of an Array
An introduction and example of searching an array within the C++
programming language.
Overview
Finding a specific member of an array means searching the array until the
member is found. It's possible that the member does not exist and the
programmer must handle that possibility within the logic of his algorithm.
Two specific searches can be made for the maximum (largest) values in the
array or the minimum (smallest) value in the array. Maximum and
minimum are also know as max and min.
1. Linear search
2. Binary search
Binary search is not cover in this module. Linear search and searching for
the maximum is demonstrated in the demo file provided, thus you need to
study this material in conjunction with the demo program.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials. You may need to right click on
the link and select "Save Target As" in order to download the file.
Definitions
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.
Sorting an Array
An introduction and example of sorting an array within the C++
programming language.
Overview
Sorting is the process through which data are arranged according to their
values. There are several sorting algorithms or methods that can be used to
sort data. Some include:
1. Bubble
2. Selection
3. Insertion
There are several different methods of bubble sorting and some methods are
more efficient than others. Most use a pair of nested loops or iteration
control structures. One method sets a flag that indicates that the array is
sorted, then does a pass and if any elements are exchanged (switched); it
sets the flag to indicate that the array is not sorted. It is executed until it
makes a pass and nothing is exchanged.
The bubble sort gets its name from the lighter bubbles that move or "bubble
up" to the top of a glass of soda pop. We move the smaller elements of the
array to the top as the larger elements move to the bottom of the array. This
can be viewed from a different perspective. Using an Italian salad dressing
with oil, water and herbs; once shaken you can either:
Either way is correct and this version of the code simply demonstrates the
sinking to the bottom the heaver or larger elements of the array.
Bubble sorting is demonstrated in the demo file provided, thus you need to
study this material in conjunction with the demo program.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials. You may need to right click on
the link and select "Save Target As" in order to download the file.
Definitions
sorting
Arranging data according to their values.
bubble sort
A method of swapping array members until they are in the desired
sequence.
Practice 20: More Array Functions
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. true
3. true
4. false
5. true
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Lab_20_Narrative_Description.txt
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Overview
Everyone seeks of ways to be more efficient in what they do. A farmer uses
a tractor instead of a horse. A construction worker uses an air powered nail
gun instead of a hammer. Programmers are no different than others, in that
they are constantly improving their ability to produce correctly working
programs. Some aspect of this is the use of modular/structured
programming, proper documentation and following industry rules for a
specific programming language. One example of efficient coding is letting
the computer count the number of elements in an array. If we define an
array:
This type of flexible coding allows us to change the members of the array
by adding or subtracting a values, like this:
Thus, we don't have to modify our code that uses the expression that
calculates the number of member in the array.
One use of the typedef is to allow us to write code that can be quickly
changed to handle different data types. There are several integer and
floating-point data types that all store number values with different
domains. If we write our code using some typedef statement, then our code
becomes versatile. By changing only our typedef commands, our code can
be used to process data of a different data type. This is demonstrated within
the demo file provided, thus you need to study this material in conjunction
with the demo program.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials. You may need to right click on
the link and select "Save Target As" in order to download the file.
Definitions
versatile
Easily modifying code to handle another data type.
flexible coding
Using the sizeof operator to calculate the number of members in an
array.
typedef
Allows the programmer to create an alias, or synonym, for an existing
data type.
Practice 21: More on Typedef
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
Solution:
Answers:
1. false – Efficiency of code execution, no; efficiency of code
production and maintenance, yes.
2. true
3. true
4. false
5. maybe true and maybe false – It does require some effort to catch
on to how it works.
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
&age
Both of these items are covered in the supplemental links to this module.
You can print out the value of the address with the following code:
cout << &age;
This will by default print the value in hexadecimal. Some people prefer an
integer value and to print it as an integer you will need to cast the address
into a long data type:
Definitions
address operator
The ampersand or &.
pointer
A variable that holds an address as its value.
Parameter Passing by Reference
An introduction and example of parameter passing by reference as used
within the C++ programming language.
Overview
When we pass parameters to functions we usually pass by value; that is the
calling function provides several values to the called function as needed.
The called function takes these values which have local scope and stores
them on the stack using them as needed for whatever processing the
functions accomplishes. This is the preferred method when calling user
defined specific task functions. The called function passes back a single
value as the return item if needed. This has the advantage of a closed
communications model with everything being neatly passed in as values
and any needed item returned back as a parameter.
Example:
parameter passing by reference
// prototype
void process_values(int qty_dimes, int
qty_quarters, double &value_dimes, double
&value_quarters);
// variable definitions
int dimes = 45;
int quarters = 33;
double value_dimes;
double value_quarters;
Note:The ampersand must appear in both the prototype and the function
definition but it does not appear in the function call.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials. You may need to right click on
the link and select "Save Target As" in order to download the file.
Definitions
reference variable
Used with parameter passing by reference.
Pointer Data Type
An introduction to the pointer data type as used within the C++
programming language.
We can create a pointer variable and establish its value which would be the
done using the address operator [which is the ampersand or &] by:
Definitions
pointer
A variable that holds an address as its value.
Indirection Operator
An introduction to the indirection operator as used within the C++
programming language.
Example:
parameter passing with pointers
// prototype
void process_values(int qty_dimes, int
qty_quarters, double * ptr_value_dimes, double *
ptr_value_quarters);
// variable definitions
int dimes = 45;
int quarters = 33;
double value_dimes;
double value_quarters;
double * ptr_value_dimes = &value_dimes;
double * ptr_value_quarters = &value_quarters;
Note:The asterisk and must appear in both the prototype and the function
definition when defining the pointer variables but it does not appear in the
function call when the pointers are passed into the function.
The above example shows the basic mechanics of the indirection operator.
The use of pointers with indirection is often preferred for processing arrays.
The array index operator is also known as the array method of
dereferencing. The following couts are equivalent:
The both say, "The name of an array is a pointer; take the pointer and
calculate a new address that points to the 3rd offset by adding the correct
number of bytes onto the pointer (integer data type is normally 4 bytes long
– 3 offsets times 4 bytes is 12 bytes); then dereference that pointer (since
this is an Rvalue context – fetch me the value that you are pointing at) and
send it to the standard output device."
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Definitions
indirection operator
The asterisk used for dereferencing a pointer.
dereferencing
The concept of using the item to which a pointer or address is pointing
at.
Practice 22: Pointers
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. false
3. true
4. true
5. true
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Lab_22_Pseudocode.txt
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Give a general explanation of the pointer data type and the use of addresses
and dereferencing. Include both the indirection operator and the index
operator in your discussion.
Multidimensional Arrays
An introduction and example of multidimensional arrays as used within the
C++ programming language.
Overview
An array is a sequenced collection of elements of the same data type with a
single identifier name. As such, the array data type belongs to the
"Complex" category or family of data types. 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 dimensioned arrays.
Consider a theater ticket with section, row and seat (three dimensions).
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials. You may need to right click on
the link and select "Save Target As" in order to download the file.
Definitions
dimension
An axis of an array.
list
A single dimension array.
table
A two dimension array.
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.
Conditional Compilation
An introduction and example of conditional compilation as used within the
C++ programming language.
Overview
As you proceed in your programming career, the problems/tasks that need
solving become more complex. The documentation of the algorithm done in
pseudo code (or some other method) will still need to be converted into a
programming solution. Inevitably, when writing that source code mistakes
will be introduced. When learning the syntax of a new programming
language, programmers sometimes automatically think in their old language
syntax, and make mistakes that are sometimes hard to detect.
#define DEBUG 1
Then using another compiler directive pair, the #if and #endif, we can have
the compiler during the pre-processor either include or not include one or
more lines of code.
#if DEBUG
cout << "\n***** DEBUG Code ** Hi mom!";
#endif
Of course saying "Hi mom!" is not very useful for debugging your code.
However, you can use test data with conditional compilation. A series of
input data values and a series of output predictors can be placed in the
program. Then you can turn on the debug feature or turn them off with your
debugging flag.
You should study the demonstration program in conjunction with this
module.
Demo_Programs
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). Following the methods of your compiler/IDE,
compile and run the program(s). Study the source code file(s) in
conjunction with other learning materials. You may need to right click on
the link and select "Save Target As" in order to download the file.
Definitions
conditional compilation
A compiler directive that includes or excludes lines of code based on a
Boolean expression.
Practice 23: More Arrays & Compiler Directives
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. true
3. true
4. true
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Read and follow the directions below carefully, and perform the steps in the
order listed.
Compile and run the Lab_23a.cpp source code file. Understand how it
works.
Copy the source code file Lab_23a.cpp naming it: Lab_23b.cpp
Add conditional compilation statements similar to the demonstration
program used in the Conditional Compilation Connexions module.
Specifically use: 157 pennies, 92 nickels, 23 dimes and 31 quarters as
your test data.
Build (compile and run) your program.
After you have successfully written this program, if you are taking this
course for college credit, follow the instructions from your
professor/instructor for submitting it for grading.
Problems
Give three examples in the real world where data might be structured into a
multidimensional array. One example (and you can’t count it) is a theatre
ticket which might have a section, row and seat number on it.
Object Oriented Programming
An overview of how object oriented programming is different from
procedural or modular structured programming.
Discussion
"In procedural programming, the programmer constructs procedures (or
functions, as they are called in C++). The procedures are collections of
programming statements that perform a specific task. The procedures each
contain their own variables and commonly share variables with other
procedures. Procedural programming is centered on the procedure or
function."[footnote] For decades (1950s to through the 1980s) most
programming was taught as procedural programming. Coupled with the
imposition of using standardized control structures in the late 1960s, we
have what is typically called modular structured programming.
Tony Gaddis, Judy Walters and Godfrey Muganda, Starting Out with C++
Early Objects Sixth Edition (United States of America: Pearson – Addison
Wesley, 2008) 22.
"The primary differences between the two approaches is their use of data. In
a procedural program, the design centers around the rules or procedures for
processing the data. The procedures, implemented as functions in C++, are
the focus of the design. The data objects are passed to the functions as
parameters. The key question is how the functions will transform the data
they receive for either storage or further processing. Procedural
programming has been the mainstay of computer science since its
beginning and is still heavily used today.
In an object-oriented program, abbreviated OOP, the design centers around
objects that contain (encapsulate) the data and the necessary functions to
process the data. In OOP, the objects own the functions that process the
data."[footnote]
Behrouz A. Forouzan and Richard F. Gilberg, Computer Science A
Structured Approach using C++ Second Edition (United States of America:
Thompson – Brooks/Cole, 2004) 156.
To help complicate the picture, the C++ programming language can be used
(and is used) to write either a procedural program (modular structured
program) or an object-oriented program. Some items used by those writing
procedural programs in C++ are in fact objects. Examples include:
1. Standard input and output items of: cout and cin; example:
cout.setf(ios::fixed)
2. Strings; calculating the length with: identifier_name.length()
3. File input/output; example: inData.open(filespec, ios::in)
Transition
Many students will learn modular structured programming before learning
object-oriented programming. The common way of teaching programming
fundamentals is to cover them or divide them into three courses, usually
covered in this order:
1. Modular structured
2. Object-oriented
3. Data structures
Definitions
procedural programming
Aka modular structured programming.
object oriented
A programming approach that encapsulates data with functions.
Understanding High Performance Computing
An explanation of the difference between sequential programming and
parallel programming concepts with examples of each. A historical sketch
of computers with examples of high performance computing solving
problems using parallel programming concepts. Suggestions for various
groups of learners to explore high performance computing. Includes
software programs, source code files and several Internet links.
This module received the "Best Module" award for the "Parallel
Algorithms and Applications" category which included a US $500 prize.
Those who reviewed the entries for the competition made some suggestions
for improvement and most have been incorporated into this revised edition
of the module. As always; my thanks to them and all others who make
suggestions for improving educational materials.
Example:
After eating all you can, you toss your chicken leg bone out of the car
window (shame on you for trashing up the highway), but in short order an
ant finds your tossed chicken bone. One single ant could bite off the left
over on the bone and transport it to the colony, one bite at a time; but, it
might take him 1 whole day (24 hours) of work. But, what if he gets help?
He signals some buddies and being a small colony of ants they allocate a
total of 10 ants to do the task. Ten times the workers take one tenth the
time. The ten ants do the task in 2 hours and 24 minutes.
I toss another bone out the window. An ant finds it and the colony allocates
50 ants to do the task of picking the bone clean. In less than 30 minutes
(28.8 to be exact) the 50 ants working in parallel complete the task.
Example:
One painter might take 8 hours to paint the exterior of an average sized
house. But, if he can put a crew of 10 painters working simultaneously (or
in other words in parallel) it takes only 48 munities. What about a crew of
50 painters assuming that they can do work and not get in the way of each
other; well how about less than 10 minutes (9.6 to be exact).
Now let's make sure we understand that the same amount of work was done
in the examples given. The work was only completed in a shorter amount of
time because we put more workers on the task. Not all tasks can be divided
up in this way, but when it can be divided between multiple workers, we
can take advantage of the workers doing their sub part of the task in
parallel. Let’s look at another example.
Example:
I want to drive from Houston, Texas to Dallas, Texas; a distance of about
250 miles. For easy calculations let's say I can travel 50 miles in one hour.
It would take me 5 hours. Well, I could divide the task between 5 cars and
have each car travel 50 miles and arrive in Dallas in 1 hour. Right?
Well, wrong. The task of driving from Houston to Dallas cannot be divided
into tasks that can be done in parallel. The task can only be done by one
person driving in a line from Houston to Dallas in 5 hours. I used the word
"line" because it helps connect us to the word: linear. A linear task cannot
be broken-up into smaller tasks to be done in parallel by multiple workers.
Within the computer world, the word associated with linear concept is
sequential processing. I must drive one mile at a time in sequence to get to
Dallas.
"ENIAC, short for Electronic Numerical Integrator And Computer, was the
first general-purpose electronic computer (July 1946). It was the first
Turing-complete, digital computer capable of being reprogrammed to solve
a full range of computing problems. ENIAC had twenty ten-digit signed
accumulators which used ten's complement representation and could
perform 5,000 simple addition or subtraction operations between any of
them and a source (e.g., another accumulator, or a constant transmitter)
every second. It was possible to connect several accumulators to run
simultaneously, so the peak speed of operation was potentially much higher
due to parallel operation." (ENIAC from Wikipedia)
Often not understood by many today, the first computer used base 10
arithmetic in the electronics and was a parallel processing machine by
using several accumulators to improve the speed. However, this did not last
for long. During its construction:
Von Neumann also proposed using a binary (base 2) numbering system for
the electronics. One of the characteristics of the von Neumann architecture
was the trade off of multiple processors using base 10 electronics to a single
central processor using base 2 (or digital) electronics. To compare to our ant
example, the idea was to use one real fast ant versus 10 slow ants. If one
real fast ant can do 1,000 tasks in an hour; it would be more powerful (be
able to do more tasks) than 10 ants doing 10 tasks an hour or the equivalent
of 100 tasks per hour.
The rest is history – most commercially built computers for about the first
forty years (1951 to 1991) followed the von Neumann architecture. The
electronic engineers keep building more reliable and faster electronics.
From vacuum tube, to transistor, to integrated circuit to what we call today
"chip" technology. This transformation made computers break down less
frequently (they were more reliable), physically smaller, needing less
electric power and faster. Personal computers were introduced in the late
1970's and within ten years became more commonly available and used.
One short coming was that most programming efforts were towards
improving the linear (or sequential) way of thinking or solving a problem.
After all, the computer electronic engineers would be making a faster
computer next year. Everyone understood that the computer had only one
central processing unit (CPU). Right?
Example:
The circus traveling by train from one city to the next has an elephant that
dies. They decide to toss the elephant off the train (shame on them for
trashing up the country side), but in short order a "super" ant (faster than
most regular ants) finds the elephant. This project is much larger than your
tossed chicken bone. One single "super" ant could do the task (bite off a
piece of the elephant and transport it to the colony, one bite at a time); but,
it might take one whole year. After all this requires a lot more work than a
chicken bone. But, what if he gets help? He signals some buddies and
being a large colony of "super" ants they allocate a total of 2,190 ants to do
the task. Wow, they devour the elephant in six hours.
This elephant example is exactly where the computer scientists had arrived.
The electronic engineers were going to continue to make improvements in
the speed of a single central processing unit computer, but not soon enough
to satisfy the "need for power" to be able to solve tasks requiring immense
computing power. Some of the new tasks that would require immense
computer power included the human genome project, searching for oil and
gas by creating 3 dimensional images of geological formations and the
study of gravitational forces in the universe; just to mention a few. The
solution: parallel processing to the rescue. Basically the only way to get this
immense computer power was to implement parallel processing techniques.
During the late 1970's and early 1980's scientists saw the need to explore
the parallel processing paradigm more fully and thus the birth of High
Performance Computing. Various national and international conferences
started during the 1980's to be able to further the cause of High
Performance Computing. For example in November of 2008 the "SC08"
supercomputing conference celebrated their 20th anniversary.
The predicting of the weather is a good example for the need of High
Performance Computing. Using the fastest central processing unit computer
it might take a year to predict tomorrow's weather. The information would
be correct but 365 days late. Using parallel processing techniques and a
powerful "high performance computer", we might be able to predict
tomorrow’s weather in 6 hours. Not only correct, but in time to be useful.
Most people are familiar with the giga hertz (billions of instructions per
second) measure to describe how fast a single CPU's processor is running.
Most microcomputers of today are running around 3 GHz or 3 billion
instructions a second. Although 3 billion sounds fast, many of these
instructions are simple operations.
You also should realize that your personal computer is not doing 3 gigafolp
worth of calculations, but something slower when using the FLOPS
measurement.
It took several years (about 30) to get computers to a personal level (1951
to 1981). It took about twenty years (late 1980’s to present 2009) to get
multi-processor computers to the personal level. Currently available to the
general public are computers with "duo core" and "quad core" processors.
In the near future, micro computers will have 8 to 16 core processors.
People ask, "Why would I need that much computer power?" There are
dozens of applications, but I can think of a least one item that almost
everyone wants: high quality voice recognition. That's right! I want to talk
to my computer. Toss your mouse, toss your keyboard, no more touch pad –
talk to it.
Again, one short coming is that most programming efforts have been
towards teaching and learning the sequential processing way of thinking or
solving a problem. Educators will now need to teach and programmers will
now need to develop skills in programming using parallel concepts and
algorithms.
Summary
We have bounced you back and forth between sequential and parallel
concepts. We covered our natural tendency to do work in parallel. But with
the birth of computers the parallel concepts were set to the side and the
computer industry implemented a faster single processor approach
(sequential). We explained the limitations of sequential processing and the
need for computing power. Thus, the birth of High Performance
Computing. Parallel processing computers are migrating into our homes.
With that migration, there is a great need to educate the existing generation
and develop the next generation of scientists and programmers to be able to
take advantage of High Performance Computing.
We have provided two computer programs that help students see the impact
of parallel processing. The first is a "Linear to Parallel Calculator" where
the student enters how long it would take one person to complete a task,
asks how many people will work as a group on the task, then calculates how
long it will take the group to complete the task. The second is a "Parallel
Speed Demonstration Program" that simulates parallel processing. It
displays to the monitor the first 60 factorial numbers in 60 seconds, then
shows as if 10 processors are doing it in 6 seconds, then as if 100
processors are doing it in less than 1 second. Both are compiled and ready
for use on an Intel CPU machine (compiled for use on Windows OS).
You may need to right click on the link and select "Save Target As" in order
to download these source code files.
Look at the source code listings provided in the next section, but remember,
you cannot compile or run these on your normal computer.
The challenge is to try parallel computing, not just talk about it.
During the week of May 21st to May 26th in 2006, this author attended a
workshop on Parallel and Distributed Computing. The workshop was given
by the National Computational Science Institute and introduced parallel
programming using multiple computers (a group of micro computers
grouped or clustered into a super-micro computer). The conference
emphasized several important points related to the computer industry:
1. During the past few years super-micro computers have become more
powerful and more available.
2. Desk top computers are starting to be built with multiple processors (or
cores) and we will have multiple (10 to 30) core processors within a
few years.
3. Use of super-micro computing power is wide spread and growing in all
areas: scientific research, engineering applications, 3D animation for
computer games and education, etc.
4. There is a shortage of educators, scientific researchers, and computer
professionals that know how to manage and utilize this developing
resource. Computer professionals needed include: Technicians that
know how to create and maintain a super-micro computer; and
Programmers that know how to create computer applications that
use parallel programming concepts.
This last item was emphasized to those of you beginning a career in
computer programming that as you progress in your education, you should
be aware of the changing nature of computer programming as a profession.
Within a few years all professional programmers will have to be familiar
with parallel programming.
During the conference this author wrote a program that sorts an array of
150,000 integers using two different approaches. The first way was without
parallel processing. When it was compiled and executed using a single
machine, it took 120.324 seconds to run (2 minutes). The second way was
to redesign the program so parts of it could be run on several processors at
the same time. When it was compiled and executed using 11 machines
within a cluster of micro-computers, it took 20.974 seconds to run. That’s
approximately 6 times faster. Thus, parallel programming will become a
necessity to be able to utilize the multi-processor hardware of the near
future.
The source code files used during the above workshop were modified to a
version 8, thus an 8 is in the filename. The non-parallel processing "super"
code was named: nonps8.cpp with the parallel processing "super" code
named: ps8.cpp (Note: The parallel processing code contains some
comments that describe that part of the code being run by a machine
identified as the "SERVER_NODE" with a part of the code being run by
the 10 other machines (the Clients). The client machines communicate
critical information to the server node using "Message Passing Interface" or
MPI commands.)
You may need to right click on the link and select "Save Target As" in order
to download these source code files.
Download the source code file from Connexions: nonps8.cpp
You can also "Google" the topic's key words and spend several days reading
and experimenting with High Performance Computing.
Educator Resources
There are many sites that provide materials and assistance to those teaching
the many aspects of High Performance Computing. A few of them are:
sequential processing
Using only one processor and completing the tasks in a sequential
order.
parallel processing
Dividing a task into parts that can utilize more than one processor.
parallel programming
Involves developing programs that utilize parallel processing
algorithms that take advantage of multiple processors.
Practice 24: OOP & HPC
Questions, exercises, problems, etc. that support this chapter in the
"Programming Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Learning Objectives
With 100% accuracy during a: memory building activity, exercises, lab
assignment, problems, or timed quiz/exam; the student is expected to:
Exercises
Exercise:
Problem:
Answer the following statements as either true or false:
1. false
2. true
3. false
4. false
5. true
Miscellaneous Items
None at this time.
Lab Assignment
If you have not done so, please create the folder(s) and/or sub-folder(s) as
appropriate.
Download and store the following file(s) to your storage device in the
appropriate folder(s). You may need to right click on the link and select
"Save Target As" in order to download the file.
Download from Connexions: Lab_24_Narrative_Description.txt
Read and follow the directions below carefully, and perform the steps in the
order listed.
Problems
Strategy Discussion
Exams vary depending on your instructor. Many will use the following:
1. Definitions
2. Self-grading questions including true/false, multiple choice, short
answer, etc.
3. Problems
Miscellaneous Items
Link to: Manipulation of Data Part 1
Review: Modular Programming Group: 6-9
Review materials that support a group of chapters in the "Programming
Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Strategy Discussion
Exams vary depending on your instructor. Many will use the following:
1. Definitions
2. Self-grading questions including true/false, multiple choice, short
answer, etc.
3. Problems
Miscellaneous Items
None at this time.
Review: Structured Programming Group: 10-16
Review materials that support a group of chapters in the "Programming
Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Strategy Discussion
Exams vary depending on your instructor. Many will use the following:
1. Definitions
2. Self-grading questions including true/false, multiple choice, short
answer, etc.
3. Problems
Miscellaneous Items
Link to: Animated gif showing an if then else
Strategy Discussion
Exams vary depending on your instructor. Many will use the following:
1. Definitions
2. Self-grading questions including true/false, multiple choice, short
answer, etc.
3. Problems
Miscellaneous Items
None at this time.
Review: Advanced Topics Group: 22-24
Review materials that support a group of chapters in the "Programming
Fundamentals - A Modular Structured Approach using C++"
collection/textbook.
Strategy Discussion
Exams vary depending on your instructor. Many will use the following:
1. Definitions
2. Self-grading questions including true/false, multiple choice, short
answer, etc.
3. Problems
Miscellaneous Items
None at this time.
Abbreviated Precedence Chart for C++ Operators
An abbreviated precedence chart for C++ operators typically used in a modular structured programming
fundamentals course.
An operator is a language-specific syntactical token (one or more symbols) that causes an action to be taken on
one or more operands. The following item provides an abbreviated list of those C++ operators that are typically
taught in a programming fundamentals course that teaches modular structured programming concepts.
The first column shows the precedence (the higher precedence is 1 or it goes first) and operators that have the
same precedence also have the same associativity (the associativity is only listed once for the group of operators).
Decrement is two minus signs, but some word processing software programs might have problems printing two
minus signs and convert it to a double dash. Insertion (two < signs) and extraction (two > signs) might also have
printing problems. These printing problems are noted in the comments with emphasized text.
OPERATOR CONNEXIONS
PR SYMBOL(S) COMMENTS ASSOICIATIVITY
NAME MODULE
aka array
1 index [] m21316
index
postfix
2 ++ unary m20499
increment
unary, aka
3 indirection * Right to Left m22152
dereference
prefix
3 ++ unary m20499
increment
4 divide / m18706
5 subtract - m18706
writing, two
6 insertion << less than Left to Right m18835
signs
reading, two
6 extraction >> greater than m18835
signs
less than or
7 <= m19549
equal to
greater than
7 >= m19549
or equal to
addition
12 += m18743
assignment
subtraction
12 -= m18743
assignment
multiplication
12 *= m18743
assignment
division
12 /= m18743
assignment
12 modulus %= m18743
assignment
sequence or
13 , Left to Right m18690
comma
C++ Reserved Keywords
A brief explanation and list of C++ reserved keywords for use in a
programming fundamentals course.
All programming languages have "reserved words". There are usually less
than 50 of these reserved words in any given programming language. They
are reserved because they have been pre-assigned a specific meaning within
that programming language, thus the compiler recognizes those words to
mean a specific thing or action. Within C++ the reserved words are also
known as "keywords".
For the C++ language all "reserved keywords" are typed in lower case. The
list that follows includes the American National Standards Institute (ANSI)
and the International Organization for Standardization (ISO) lists of
reserved words for the C++ programming language. The ISO reserved
words may not be implemented in the compiler that you are using, however
they may be adopted in future releases of C++ compilers. Wisdom dictates
to avoid using them at this point so that there will not be a problem
compiling your source code in future releases of compilers. There has been
no distinction made in the ANSI or ISO reserved word lists. A search of the
Internet for C++ reserved words will reveal several different lists. Some are
more unique to a specific compiler. Some will be incomplete because the
list has been enlarged. The talbe that follows should work for any beginning
programming course using C++. The reserved keywords are:
do not this
ASCII Character Set
Brief explanation of ASCII character set with web links to more
information and tables.
The following web links provide more information and tables listing the
ASCII Character Set:
http://asciiset.com/
http://www.asciitable.com/
http://en.wikipedia.org/wiki/ASCII
Show Hide File Extensions
General instructions on how to show or hide file extensions. Specific
instructions and web page links for Windows XP, Windows Vista and
Windows 7 operating systems.
By default, file extensions for known file types are hidden in Windows
operating systems. However, you can change this setting so that file
extensions are shown for all file types. Being able to see file extensions can
be very helpful for students taking computer courses because those course
instructions often refer to file extensions.
Windows XP
With the Windows Explorer open, slect the “Tools” tab and then “Folder
Options”.
Windows Vista
Select the “Start” button, then “Control Panel”, then “Appearance and
Personalization” and then “Folder Options”.
Windows 7
Select the “Start” button, then “Control Panel” and then “Folder Options”.
Introduction
The relationship between faculty and students has always been one of open
and honest communication. The faculty member carries the responsibility
of presenting course materials via reading assignments, lectures, labs, etc.
The student is to learn and understand these materials. Additionally, the
faculty members employ various methods to assess the student’s mastery of
the course materials. Frequently this is done via quizzes, tests, writing
assignments, the completion of lab materials, etc. Academic dishonesty
(sometimes called “Scholastic Dishonesty”) is the violation of that trust.
Collusion
Another category of academic dishonesty is collusion which is the
unauthorized collaboration with another person in preparing written work
(including lab assignments) offered for credit (counting towards your grade
calculation). To better understand collusion, students need to realize that as
part of the learning and evaluation of that learning, many professors use
group projects; a directed or authorized collaboration. Often students are
encouraged to form study groups to help discuss the course materials thus
improving the learning process. These authorized and sometimes directed
activities are not collusion.
Type it Yourself
Lab assignments are to be your own personal typing efforts. That is you are
to type them or make the modifications yourself to the files (documents,
spreadsheets, databases, programming source code, etc.) If your course is a
programming subject, you are to run the source code file on your compiler,
making corrections as need to complete the lab assignment. If the directions
for an assignment include starting a new file then don’t use an existing file
and modify it to complete the assignment. Unless specifically authorized
by your professor, students should not complete computerized course
work as a team or group and then share the final completed product.
Students have said that they worked as a team or group and that all
participated and all learned the materials. Don’t try this excuse because
professors don’t buy it. Here is the problem: Part of the learning process is
in you doing it yourself. Example: I ask two students to make me some
pancakes for breakfast; I expect two individually prepared plates of
pancakes (one from each of them) for my breakfast. The professor really
does not want to eat two plates of pancakes (or 50 to 100 plates of
pancakes, depending on how many students they are teaching), but part of
your directed learning activity for the course is to demonstrate that you can
make pancakes (not watch someone else make pancakes or participate as a
group to make pancakes).
Students have said that they shared the file so they the other student could
see how the completed assignment should look. Don’t try this excuse
because professors don’t buy it. Here is the problem: When you share the
file you share your typing efforts (or your original work and your efforts to
create that original work). Back to our pancake example: “I only gave the
other student a plate of completed pancakes, so he could see what the end
product should be.” All the other student does is add some blue berries and
whip cream. If a student makes minor modifications to your work (changes
the spots where his name is at) and turns it in as his work – you will be
included in the charge of academic dishonesty. Unless specifically
authorized by your professor, don’t share any files that you create or
modify with another student – ever, not now and not in the future.
Don’t leave your files on a machine where others may have access to them.
If multiple students are using or have access to the same machine (often
happens with students living in the same household – husband/wife,
siblings or roommates) or in an on-campus course where many students will
have access to the machine – store your files on a flash drive. Physically
control who gets access to your flash drive.
Students have said that they did not think they could be detected or that
academic dishonesty could not be proved. Don’t try this approach because
professors believe that they are slightly smarter. Actually, we know that we
are a lot smarter. It amazes us that student don’t realize that professors are a
formidable force. Don’t gamble that you can beat us at the “Academic
Dishonesty Game”. Please don’t take this as a challenge and use it as an
excuse to see if you can be academically dishonest and not get caught. We
are warning you, not challenging you.
Serious Consequences
The consequences will vary from instructor to instructor and from
institution to institution. They range from a simple slap on the hand (don’t
do it again) to complete explusion from the institution (expelled from all of
your courses). Because the bond of trust is broken, many instructors will
simply expel you from the course you are taking. As an example: Within
the BCIS1405 course at Houston Community College, we expelled 8
students (along with giving them the grade of “F”) from Distance
Educations sections during the Spring 2008 term for Academic Dishonesty.
Be ready for what ever the consequences your instructor will deliver if you
are dishonest.
Summary
The ethics of academic honesty; there is a bond of trust that whatever
the student does in relationship to the evaluation process are their own
work and efforts.
Seek clarification from your professor if you have any doubt that the
collaborative activity might be considered collusion.
The normal rule of thumb is 1 to 1.5 hours out of class studying for every
hour in class and for computer courses this normally means both the lecture
and lab hours. Students with learning disabilities or those whose primary
language is not English will want to plan for more study time and should
use a larger ratio. Thus, you should calculate the weekly hours of
commitment needed for a course depending on your circumstances.
Example:
But many students take courses at a faster pace by either taking a course
between semesters in a very concentrated mode, starting a course after the
regular start of a semester or during the summer. To calculate the weekly
study time needed you will need to calculate the total regular semester
instructional time and divide by the number of weeks in the faster pace
delivery. Example:
Our 4 credit hour course is to be taken during a summer term that has 9
weeks of instruction time. The total regular semester time would be 15
times the normal semester commitment (180 to 225 hours). Dividing it by 9
would mean 20 to 25 hours per week.
If taking a course via distance education, students need to plan for all of the
course time, thus during a regular semester term, our 4 credit hour course
example would require 3 to 4 study periods with 3 to 4 hours for each study
period per week. If taking the course at faster pace (9 week summer term)
you will need to schedule more study times. This may mean a 3 to 4 hour
study period daily for 6 days a week (with only one day off as a day of
rest).
If you are taking a distance education course, you need to regularly enter
the learning management system (such as Blackboard Vista) and review the
announcements, discussion list postings and read (and answer if
appropriate) email. Most distance education professors assume that
anything he has communicated via these tools will have been read by the
student within 3 days. In short this means you are responsible for having
read the items and completing any action requested.
Study Habits that Build the Brain
Several PowerPoint presentations on how our study habits effect our
learning. A main presentation with additional presentations on reading the
textbook, taking lecture notes, using 3x5 cards and using flash cards to
study.
Introduction
During the spring of 2008 the author, Kenneth Leroy Busbee, did some
research with students taking a computer programming fundamentals
course to determine if using 3x5 cards would improve student performance
on exams. In short, it did! This was not a surprise, but it became obvious
that most of us (faculty at all levels of education as well as students) have
little understanding of how are brain builds understanding and long term
memory.
Main Presentation
Link to: Study Habits that Build the Brain
Specific Topics
Link to: Reading the Textbook