Programming Fundamentals/Printable version

From Wikibooks, open books for an open world
Jump to navigation Jump to search


Programming Fundamentals

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Programming_Fundamentals

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.

Preface

A Note to Readers[edit | edit source]

Welcome to Programming Fundamentals – A Modular Structured Approach, 2nd Edition!

The original content for this book was created by Kenneth Leroy Busbee and written specifically for his course based on C++. The goal for this second edition is to make it programming-language neutral, so that it may serve as an introductory programming textbook for students using any of a variety of programming languages, including C++, C#, Java, JavaScript, Python, and Swift. Other languages will be considered upon request.

Programming concepts are introduced generically, with logic demonstrated in pseudocode and flowchart form, followed by examples for different programming languages. Emphasis is placed on a modular, structured approach that supports reuse, maintenance, and self-documenting code.

As you begin to review this edition, please keep the audience in mind. If something is missing, think about whether that concept applies to programming in general or only to certain programming languages, and whether it is a fundamental, first-semester programming concept or something better addressed in a more advanced textbook.

You are encouraged to make use of the Comments page at the end of the book whenever you have suggestions or concerns regarding content or approach. All suggestions will be reviewed and considered.

Dave Braunschweig

About this Book[edit | edit source]

Programming Fundamentals – A Modular Structured Approach, 2nd Edition is an adaptation of “Programming Fundamentals – A Modular Structured Approach using C++“, written by Kenneth Leroy Busbee, a faculty member at Houston Community College in Houston, Texas. The materials used in the first edition were originally developed by Busbee and others as independent modules for publication within the Connexions environment. The original source is available at https://cnx.org/contents/MDgA8wfz@22.2:YzfkjC2r@17/ .

This second edition, adapted by Dave Braunschweig, expands on the original vision by supporting multiple programming languages with pseudocode and flowcharts, and includes example code in C++, C#, Java, JavaScript, Python, and Swift.

Programming fundamentals are often divided into three college courses: Modular/Structured, Object Oriented and Data Structures. This textbook/collection covers the first of those three courses.

Learning Modules[edit | edit source]

The learning modules of this textbook were written as standalone modules. Students using a collection of modules as a textbook will usually view its contents by reading the modules sequentially as presented by the author of the collection.

However, many readers of these modules may find them as a result of an Internet search. The textbook design allows the author of a module to create web links to other modules and Internet locations and designate any necessary prerequisites.

Conceptual Approach[edit | edit source]

The learning modules of this textbook were, for the most part, written without consideration of a specific programming language. Concepts are presented generically, with program logic demonstrated first in pseudocode and flowchart format. Language-specific examples follow the general overview.

Re-use and Customization[edit | edit source]

The Creative Commons (CC) Attribution-ShareAlike license applies to all modules in this textbook. Under this license, any module may be used or modified for any purpose as long as proper attribution to the original author(s) is maintained and you distribute your contributions under the same license.

PDF Conversion Problems[edit | edit source]

There are several known PDF printing problems. A description of the known problems are:

  1. When it converts an “Example” the PDF displays the first line of an example properly but indents the remaining lines of the example. This problem occurs for the printing of a book (because it prints a PDF) and downloading either a module or a textbook/collection as a PDF.
  2. Within C++ there are three operators that do not convert properly into PDF format.
decrement which is two minus signs
insertion << which is two less than signs
extraction >> which is two greater than signs

References[edit | edit source]


Author Acknowledgements

1st Edition Acknowledgements[edit | edit source]

I wish to acknowledge the many people who have helped me and have encouraged me in this project.

  1. Mr. Abass Alamnehe, who is a fellow faculty member at Houston Community College. He has encouraged the use of Connexions as an “open source” publishing concept. His comments on several modules have led directly to the improvement of the materials in this textbook/collection.
  2. The hundreds (most likely a thousand plus) students that I have taken programming courses that I have taught since 1984. The languages include: COBOL, mainframe IBM assembly, Intel assembly, Pascal, “C” and “C++”. They have often suggested that I write my own book because they thought that I was explaining the subject matter better than the author of the textbook that we were using. Little did my students understand that directly or indirectly they aided in the improvement of the materials from which I taught as well as improving me as a teacher.
  3. To my future students and all those that will use this textbook/collection. They will provide suggestions for improvement as well as being the thousand eyes identifying the hard to find typos, etc.
  4. My wife, Carol, who supports me in all that I do. She has tolerated the many hours that I have spent in concentration on developing the modules that comprise this work. Without her support, this work would not have happened.

Kenneth Leroy Busbee

2nd Edition Acknowledgements[edit | edit source]

I wish to acknowledge the many people who have helped make this edition possible, including:

  • Kenneth Leroy Busbee for his initial vision and willingness to share Programming Fundamentals – A Modular Structured Approach using C++ as CC-BY, making it possible to build on his success.
  • University of Cape Town for likewise sharing Object-Oriented Programming in Pythonas CC-BY-SA and making it possible to build on their efforts.
  • Jay Singelmann and Jean Longhurst, who first taught me structured programming.
  • Joyce Farrell, whose Programming Logic and Design book I have used for several years and has no doubt influenced my approach.
  • Devin Cook for developing Flowgorithm, releasing it as free software, and graciously allowing its use to generate most of the pseudocode and flowcharts used in this edition of the book.
  • Zoe Wake Hyde and the staff and volunteers at Rebus Community for providing a community and platform to create and collaborate on open content.
  • April Browne, Carol Potaczek, and Maisie Sparks for providing subject matter expertise and recommendations for content improvement.
  • My wife and family for accepting my dedication to open educational resources and loving me anyway.

Dave Braunschweig

References[edit | edit source]


Introduction to Programming

Overview[edit | edit source]

This chapter introduces programming, the software development process, tools and methods used to develop and test programs. These include integrated development environments (IDEs), version control, input and output, and a Hello World program in pseudocode and flowchart format. The programming languages C++, C#, Java, JavaScript, Python, and Swift are introduced with example code.

Chapter Outline[edit | edit source]

Learning Objectives[edit | edit source]

  1. Understand key terms and definitions.
  2. Create pseudocode for a programming problem.
  3. Create a flowchart for a programming problem.
  4. Perform software testing for a programming problem.
  5. List the four categories and give examples of errors that may be encountered when using an Integrated Development Environment (IDE).
  6. Test an Integrated Development Environment using a Hello World program.
  7. Modify an existing program to meet given requirements.


Systems Development Life Cycle

Overview[edit | edit source]

Systems Development Life Cycle

The Systems Development Life Cycle (SDLC) describes a process for planning, creating, testing, and deploying an information system. A number of SDLC models or methodologies have been implemented to address different system needs, including waterfall, spiral, Agile software development, rapid prototyping, and incremental.[1]

Discussion[edit | edit source]

The steps within the Systems Development Life Cycle (SDLC) explain how a computer information system that handles a major task is typically created. Information systems can be hardware based, software based (referred to as application software or applications), or a combination of both. Application software usually consists of many programs.

There are thousands of uses for an application to help improve and hasten a business, school, etc.. Real world deployment examples include: the Department of Defense supply system, the customer system used at your local bank, and the repair parts inventory system used by car dealerships. Another example would be the "101 Computer Games" available at some retail stores. This would be considered an entertainment application since the software actually consists of many different gaming programs (checkers, chess, tic-tac-toe, etc.). The code for each game was likely written by different programmers. Application generators are software that help programmers develop applications. These development tools have not been available until recently; they are helpful tools, especially for embedded software.

Computer professionals that are in charge of creating applications often have the job title of System Analyst. The major steps in creating an application include the following: planning, analysis, design, implementation, and maintenance. In the first step, the Planning phase, the System Analyst will identify if there is a demand for replacing or creating a new application. This is where a feasibility test is conducted to determine the success of the new application. During the Analysis phase, the desired operations of the application must be stated. This helps verify that the needs of the end-user are satisfied.[2] 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 cycle. 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.

Key Terms[edit | edit source]

applications
An information system or collection of programs that handles a major task.
embedded software
Software that is used for specialized technology that is typically not a computer, examples of this are the electronics of cars, telephones, modems, robots, appliances, toys, security systems, pacemakers, and electronic watches.
implementation
The phase of a Systems Development Life Cycle where the programmers would be assigned to write specific programs.
life cycle
How long an application lasts before it is replaced.
system analyst
Computer professional in charge of creating applications.
Systems Development Life Cycle (SDLC)
Planning – Analysis – Design – Implementation – Maintenance

References[edit | edit source]


Program Design

Overview[edit | edit source]

Program design consists of the steps a programmer should take before they start coding a program. 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:

  • Understanding the Program
  • Using Design Tools to Create a Model
  • Developing Test Data

Understanding the Program[edit | edit source]

If you are working on a project as one of many programmers, the system analyst may have created a variety of documentation items that will help you understand what the program does. These could include screen layouts, narrative descriptions, documentation showing the processing steps, etc. If you are not on a project and are only creating a simple program, you will likely have only a brief description of the program’s purpose. Understanding a program's purpose usually involves understanding its:

  • Inputs
  • Processing
  • Outputs

This IPO approach works well for beginner programmers. It might help to visualize the program running on a computer: You can imagine what the monitor will look like, what the user must enter with the keyboard, and what processing or changes will be made.

Algorithm[edit | edit source]

An algorithm is a series of specific and finite instructions that produce a result (output), Algorithms are everywhere. For example, in a recipe, directions of a GPS, how to tie a tie, etc. Flowcharts and pseudocode are very useful tools to organize and design algorithms. However, in order to develop a useful algorithm, it is necessary to:

  1. Understand the problem
  2. Define an input
  3. Process the input data
  4. Expect output
  5. Test and analyze data

Algorithms are the basis of any computer program. Before writing a single line of code it is necessary to design an algorithm that solves the problem. Therefore, a good programmer must be a good problem solver and be knowledgeable of their own inputs.

Using Design Tools to Create a Model[edit | edit source]

At first, you will not need a hierarchy chart because your first programs will not be complex. But as they grow and become more complex, you will divide your programs into several modules (or functions).

The first modeling tool you 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 understand and create flowcharts and pseudocode. These methods of developing a program's model are usually taught in computer courses. Several standards exist for flowcharting and pseudocode and most are very similar. However, most companies have their own documentation standards and styles. Programmers are expected to quickly adapt to any flowcharting or pseudocode standards for the company at which they work. The other methods that are less universal require some training which is generally provided by the employer.

Later in your programming career, you will learn about using application software that helps create an information system and/or programs. This type of software is called Computer-Aided Software Engineering (CASE).

Understanding the logic and planning the algorithm on paper, before you start to code, is a very important concept. Many students develop poor habits and skipping this step is one of them.

Develop Test Data[edit | edit source]

Test data consists of the programmer providing some input values and predicting the outputs. This can be quite easy for a simple program and the test data can be used to check the model to see if it produces the correct results.

Key Terms[edit | edit source]

algorithm
Series of specific and finite instructions that produce a result.
Computer-Aided Software Engineering (CASE)
Application software that helps create an information system and/or programs.
IPO
Inputs – Processing – Outputs
pseudocode
Written statements used to convey the steps of an algorithm or function, not actual code.
test data
Providing input values and predicting the outputs.

References[edit | edit source]


Program Quality

Overview[edit | edit source]

Program quality describes basic properties of the program’s source code and executable code, including reliability, robustness, usability, portability, maintainability, efficiency, and readability.

Discussion[edit | edit source]

Whatever the approach to development may be, the finished program should perform well in the following properties:

  • Reliability: how often the results of a program are correct. This depends on the conceptual correctness of algorithms, and minimization of programming mistakes, such as mistakes in resource management (e.g., buffer overflows and race conditions) and logic errors (such as division by zero or off-by-one errors).
  • Robustness: how well a program anticipates problems due to errors (not bugs). This includes situations such as incorrect, inappropriate or corrupt data, unavailability of needed resources such as memory, operating system services, network connections, user error, and unexpected power outages.
  • Usability: the ergonomics of a program: the ease with which a person can use the program for its intended purpose or in some cases even unanticipated purposes. Such issues can make or break its success, regardless of other issues. This involves a wide range of textual, graphical and sometimes hardware elements that improve the clarity, intuitiveness, cohesiveness, and completeness of a program’s user interface.
  • Portability: the range of computer hardware and operating system platforms on which the source code of a program can be compiled/interpreted and run. This depends on differences in the programming facilities provided by the different platforms, including hardware and operating system resources, expected behavior of the hardware and operating system, and availability of platform specific compilers (and sometimes libraries) for the language of the source code.
  • Maintainability: the ease with which a program can be modified by its present or future developers in order to make improvements or customizations, fix bugs and security holes, or adapt it to new environments. Good practices during initial development make the difference in this regard. This quality may not be directly apparent to the end user but it can significantly affect the fate of a program over the long term.
  • Efficiency/performance: the measure of system resources a program consumes (processor time, memory space, slow devices such as disks, network bandwidth and to some extent even user interaction): the less, the better. This also includes careful management of resources, for example cleaning up temporary files and eliminating memory leaks.
  • Readability: the ease with which a human reader can comprehend the purpose, control flow, and operation of source code. It affects the aspects of quality above, including portability, usability and most importantly maintainability. Readability is important because programmers spend the majority of their time reading, trying to understand, and modifying existing source code, rather than writing new source code. Unreadable code often leads to bugs, inefficiencies, and duplicated code.
  • It is crucial to note that there is no single property that is more important than the rest. The properties are best viewed as a system, each being just as important as the next. These properties support the program and if one is weak or fails, it will affect the entire program.

Key Terms[edit | edit source]

efficiency
The measure of system resources a program consumes.
maintainability
The ease with which a program can be modified by its present or future developers.
portability
The range of computer hardware and operating system platforms on which the source code of a program can be compiled/interpreted and run.
readability
The ease with which a human reader can comprehend the purpose, control flow, and operation of source code.
reliability
How often the results of a program are correct.
robustness
How well a program anticipates problems due to errors.
usability
The ease with which a person can use the program.

References[edit | edit source]


Pseudocode

Overview[edit | edit source]

Pseudocode is an informal high-level description of the operating principle of a computer program or other algorithm.[1]

Discussion[edit | edit source]

Pseudocode is one method of designing or planning a program. Pseudo means false. Thus, pseudocode means false code. Pseudocode is a simplified programming language that describes a program in lay terms. It uses English statements to describe what a program is to accomplish. Pseudocode is used for documenting the program or module design (also known as the algorithm).

The following outline of a simple program illustrates pseudocode. We want to be able to enter the ages of two people and have the computer calculate their average age and display the answer.

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 C++, Java, Python, etc.) where you must follow the rules of the language (syntax) 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 of 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.

Key Terms[edit | edit source]

pseudo
Means false and includes the concepts of fake or imitation.

References[edit | edit source]


Flowcharts

Overview[edit | edit source]

Flowchart displaying "Hello world!"

A flowchart is a type of diagram that represents an algorithm, workflow or process. The flowchart shows the steps as boxes of various kinds, and their order by connecting the boxes with arrows. This diagrammatic representation illustrates a solution model to a given problem. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields.[1]

Discussion[edit | edit source]

Flowcharts display the steps in code as shapes connected together with arrows. The main goal is to create a rough draft of a solution to a coding problem. The type of shapes seen in the flowchart depends on what statements the programmer wants to create. For example, an “if” statement (a part of the code that only works if a certain condition is true) is represented by a diamond, while the looping statements (ones that allow a section of code to repeat itself as needed) are represented by hexagons. Flowcharts may also color code the different types of statements as well, making the code easier to read.

Common flowcharting symbols and examples follow. When first reading this section, focus on the simple symbols and examples. Return to this section in later chapters to review the advanced symbols and examples.

Simple Flowcharting Symbols[edit | edit source]

Terminal[edit | edit source]

The rounded rectangles, or terminal points, indicate the flowchart's starting and ending points.

Terminal

Flow Lines[edit | edit source]

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.

Line

Input/Output[edit | edit source]

The parallelograms designate input or output operations.

Input/Output

Process[edit | edit source]

The rectangle depicts a process such as a mathematical computation, or a variable assignment.

Process

Decision[edit | edit source]

The diamond is used to represent the true/false statement being tested in a decision symbol.

Decision

Advanced Flowcharting Symbols[edit | edit source]

Module Call[edit | edit source]

A program module is represented in a flowchart by a rectangle with some lines to distinguish it from process symbol. Often programmers will make a distinction between program control and specific task modules or between local functions and library functions.

Predefined Process

Connectors[edit | edit source]

Sometimes a flowchart is broken into two or more smaller flowcharts. This is usually done when a flowchart does not fit on a single page, or must be divided into sections. A connector symbol, which is a small circle with a letter or number inside it, allows you to connect two flowcharts on the same page. A connector symbol that looks like a pocket on a shirt, allows you to connect to a flowchart on a different page.

On-page Connector Off-page connector

Simple Examples[edit | edit source]


Simple Examples[edit | edit source]

We will demonstrate various flowcharting items by showing the flowchart for some pseudocode.

Functions[edit | edit source]

pseudocode: Function with no parameter passing

Function clear monitor
    Pass In: nothing
    Direct the operating system to clear the monitor
    Pass Out: nothing
End function

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
End function

Sequence Control Structures[edit | edit source]

The next item is pseudocode for a simple temperature conversion program. This demonstrates the use of both the on-page and off-page connectors. It also illustrates the sequence control structure where nothing unusual happens. Just do one instruction after another in the sequence listed.

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

Pseudocode = IPO Outline

input
    display a message asking the user for the temperature in Fahrenheit
    get the temperature from the keyboard

processing
    calculate the Celsius by subtracting 32 from the Fahrenheit temperature then multiply the result by 5 then divide the result by 9. Round up or down to the whole number.
    HINT: Use 32.0 when subtracting to ensure floating-point accuracy.

output
    display the Celsius with an appropriate message
    pause so the user can see the answer 

Advanced Examples[edit | edit source]

Selection Control Structures[edit | edit source]

pseudocode: If then Else

If age > 17
    Display a message indicating you can vote.
Else
    Display a message indicating you can't vote.
Endif

pseudocode: Case

Case of age
    0 to 17   Display "You can't vote."
    18 to 64  Display "You are in your working years."
    65 +      Display "You should be retired."
End case

Iteration (Repetition) Control Structures[edit | edit source]

pseudocode: While

count assigned zero
While count < 5
    Display "I love computers!"
    Increment count
End while

pseudocode: For

For x starts at 0, x < 5, increment x
    Display "Are we having fun?"
End 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.

pseudocode: Do While

count assigned five
Do
    Display "Blast off is soon!"
    Decrement count
While count > zero

pseudocode: Repeat Until

count assigned five
Repeat
    Display "Blast off is soon!"
    Decrement count
Until count < one

Key Terms[edit | edit source]

decision symbol
A diamond used in flowcharting for asking a question and making a decision.
flow lines
Lines (sometimes with arrows) that connect the various flowcharting symbols.
flowcharting
A programming design tool that uses graphical elements to visually depict the flow of logic within a function.
input/output symbol
A parallelogram used in flowcharting for input/output interactions.
process symbol
A rectangle used in flowcharting for normal processes such as assignment.

References[edit | edit source]


Software Testing

Overview[edit | edit source]

Software testing involves the execution of a software component or system component to evaluate one or more properties of interest. In general, these properties indicate the extent to which the component, or system, under test:[1]

  • meets the requirements that guided its design and development
  • responds correctly to all kinds of inputs
  • performs its functions within an acceptable time
  • is sufficiently usable
  • can be installed and run in its intended environments
  • achieves the general result its stakeholders desire

Discussion[edit | edit source]

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.

  1. to check the model to see if it produces the correct results (model checking)
  2. to check the coded program to see if it produces the correct results (code checking)

Test data is developed by using the algorithm of the program. This algorithm is usually documented during the program design with either flowcharting or pseudocode. Here is the pseudocode in outline form describing the inputs, processing, and outputs for a program used to calculate gross pay for hourly work.

Pseudocode using an IPO Outline for Calculating Gross Pay

Input
    display a message asking user for their hours worked
    get the hours from the keyboard
    display a message asking user for their pay rate
    get the rate from the keyboard
    
Processing
    calculate the gross pay by:
        multiplying the hours worked by the hourly rate

Output
    display the gross pay on the monitor
    pause so the user can see the answer

Creating Test Data and Model Checking[edit | edit source]

Test data is used to verify that the inputs, processing, and outputs are working correctly. As test data is initially developed it can verify that the documented algorithm (pseudocode in the example we are doing) is correct. It helps us understand and even visualize the inputs, processing, and outputs of the program.

Inputs: I worked 37.5 hours this week and my hourly rate is $15.50 per hour. We should verify that the pseudocode is asking the user for this data.

Processing: Using my solar powered handheld calculator, I can calculate the gross pay would be: 37.5 * 15.50 or $581.25. We should verify that the pseudocode is performing the correct calculations.

Output: Only the significant information (total gross pay) is displayed for the user to see. We should verify that the appropriate information is being displayed.

Testing the Coded Program – Code Checking[edit | edit source]

The test data can be developed and used to test the algorithm that is documented (in our case our pseudocode) during the program design phase. Once the program is code with compiler and linker errors resolved, the programmer gets to play user and should test the program using the test data developed. When you run your program, how will you know that it is working properly? Did you properly plan your logic to accomplish your purpose? Even if your plan was correct, did it get converted correctly (coded) into the chosen programming language? The answer (or solution) to all of these questions is our test data.

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 another item) could be wrong
  2. The conversion of the plan to code might be wrong
  3. The test data results were calculated wrong

Resolving problems of this nature can be the most difficult problems a programmer encounters. You must review each of the above to determine where the error is lies. Fix the error and re-test your program.

Key Terms[edit | edit source]

code checking
Using test data to check the coded program in a specific language (like C++).
model checking
Using test data to check the design model (usually done in pseudocode).

References[edit | edit source]


Integrated Development Environment

Overview[edit | edit source]

An integrated development environment (IDE) is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of a source code editor, build automation tools, and a debugger. Most modern IDEs have intelligent code completion. Some IDEs contain a compiler, interpreter, or both. The boundary between an integrated development environment and other parts of the broader software development environment is not well-defined. Sometimes a version control system, or various tools to simplify the construction of a graphical user interface (GUI), are integrated. Many modern IDEs also have a class browser, an object browser, and a class hierarchy diagram, for use in object-oriented software development.[1]

Discussion[edit | edit source]

High-level language programs are usually written (coded) as ASCII text into a source code file. A unique file extension (Examples: .asm .c .cpp .java .js .py) is used to identify it as a source code file. As you might guess from our examples – Assembly, “C”, “C++”, Java, JavaScript, and Python, however, they are just ASCII text files (other text files usually use the extension of .txt). The source code produced by the programmer must be converted to an executable machine code file specifically for the computer’s CPU (usually an Intel or Intel-compatible CPU within today’s world of computers). There are several steps in getting a program from its source code stage to running the program on your computer. Historically, we had to use several software programs (a text editor, a compiler, a linker, and operating system commands) to make the conversion and run our program. However, today all those software programs with their associated tasks have been integrated into one program. However, this one program is really many software items that create an environment used by programmers to develop software. Thus the name: Integrated Development Environment or IDE.

Integrated Development Environment or IDE

Programs written in a high-level language are either directly executed by some kind of interpreter or converted into machine code by a compiler (and assembler and linker) for the CPU to execute. JavaScript, Perl, Python, and Ruby are examples of interpreted programming languages. C, C++, C#, Java, and Swift are examples of compiled programming languages.[2] The figure shows the progression of activity in an IDE as a programmer enters the source code and then directs the IDE to compile and run the program.

Upon starting the IDE software the programmer usually indicates the file he or she wants to open 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 performs the 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 are encountered, it saves the source code to a temporary file called a translation unit.
  3. The compiler opens the translation unit file and performs the 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 encountered (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 are 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 are 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 test data, he or she might discover that the outputs are not correct. These types of errors are called logic errors and would require the user to return to the source code to change the algorithm.

Resolving Errors[edit | edit source]

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 - A program that turns programming language code into machine code.
  2. Linker - A program that takes files and combines them into a singular file. (Examples include .exe, .lib, etc.)
  3. Logic - The computing part of a program, where for example, can use data and included formulas to give a set data point.

There are two types of compiler errors; pre-processor (1st step) and conversion (2nd step).

During the conversion (2nd step) the compiler 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.

Key Terms[edit | edit source]

compiler
Converts source code to object code.
debugging
The process of removing errors from a program. 1) compiler 2) linker 3) logic
integrated development environment (IDE)
A software application that provides comprehensive facilities to computer programmers for software development.
linker
Connects or links object files into an executable file.
loader
Part of the operating system that loads executable files into memory and directs the CPU to start running the program.
pre-processor
The first step the compiler does in converting source code to object code.
text editor
A software program for creating and editing ASCII text files.
warning
A compiler alert that there might be a problem.

References[edit | edit source]


Version Control

Overview[edit | edit source]

Version control, also known as revision control or source control, is the management of changes to documents, computer programs, large websites, and other collections of information. Each revision is associated with a timestamp and the person making the change. Revisions can be compared, restored, and with some types of files, merged.[1]

Version control systems (VCS) most commonly run as stand-alone applications, but may also be embedded in various types of software, including integrated development environments (IDEs).

Discussion[edit | edit source]

Version control implements a systematic approach to recording and managing changes in files. At its simplest, version control involves taking ‘snapshots’ of your file at different stages. This snapshot records information about when the snapshot was made, and also about what changes occurred between different snapshots. This allows you to ‘rewind’ your file to an older version. From this basic aim of version control, a range of other possibilities is made available.[2]

Version control allows you to:[3]

  • Track developments and changes in your files
  • Record the changes you made to your file in a way that you will be able to understand later
  • Experiment with different versions of a file while maintaining the original version
  • ‘Merge’ two versions of a file and manage conflicts between versions
  • Revert changes, moving ‘backward’ through your history to previous versions of your file

Version control is particularly useful for facilitating collaboration. One of the original motivations behind version control systems was to allow different people to work on large projects together. Using version control to collaborate allows for a greater deal of flexibility and control than many other solutions. As an example, it would be possible for two people to work on a file at the same time and then merge these together. If there were ‘conflicts’ between the two versions, the version control system would allow you to see these conflicts and make an active decision about how to ‘merge’ these different versions into a new ‘third’ document. With this approach you would also retain a ‘history’ of the previous version should you wish to revert back to one of these later on.[4]

Popular version control systems include:[5]

  • Git
  • Helix VCS
  • Microsoft Team Foundation Server
  • Subversion

The remainder of this lesson focuses on using the Git version control system.

Git[edit | edit source]

Git is a version control system for tracking changes in computer files and coordinating work on those files among multiple people. It is primarily used for source code management in software development, but it can be used to keep track of changes in any set of files. Git was created by Linus Torvalds in 2005 for development of the Linux kernel and is free and open source software.[6]

Free public git repositories are available from:

  • Bitbucket
  • GitHub

Initializes a new Git repository by creating a .git subdirectory in the current working directory:

  • git init

Cloning an existing repository requires only a URL to the repository and the following git command:

  • git clone <url>

Once cloned, repositories are synchronized by pushing and pulling changes. If the original source repository has been modified, the following git command is used to pull those changes to the local repository:

  • git pull

Local changes must be added and committed, and then pushed to the remote repository. Note the period (dot) at the end of the first command.

  • git add .
  • git commit -m "reason for commit"
  • git push

If there are conflicts between the local and remote repositories, the changes should be merged and then pushed. If necessary, local changes may be forced upon the remote server using:

  • git push --force

Key Terms[edit | edit source]

branch
A separate working copy of files under version control which may be developed independently from the origin.
clone
Create a new repository containing the revisions from another repository.
commit
To write or merge the changes made in the working copy back to the repository.
merge
An operation in which two sets of changes are applied to a file or set of files.
push
Copy revisions from the current repository to a remote repository.
pull
Copy revisions from a remote repository to the current repository.
version control
The management of changes to documents, computer programs, large websites, and other collections of information.
version control systems
Most commonly run as stand-alone applications, but may also be embedded in various types of software, including integrated development environments

References[edit | edit source]


Input and Output

Overview[edit | edit source]

Input and output, or I/O are how an information processing system communicates with the outside world, a human, or another information processing system. Inputs are the signals or data received by the system and outputs are the signals or data sent from it.[1]

Discussion[edit | edit source]

CPU – Memory – Input/Output Devices

Every task done on the computer 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:

Our program, now loaded into memory, has basically two areas:

  • Machine instructions – our instructions for what we want done
  • Data storage – our variables that we're using in our program

Often our program contains instructions to interact with the input/output devices. We need to move data into (write) and/or out of (read) the memory data area. A device is a piece of equipment that is electronically connected to the memory so that data can be transferred between the memory and the device. Historically this was done with punched cards and printouts. Tape drives were used for electronic storage. With time we migrated to using disk drives for storage with keyboards and monitors (with monitor output called soft copy) replacing punch cards and printouts (called hard copy).

Most computer operating systems and by extension programming languages have identified the keyboard as the standard input device and the monitor as the standard output device. Often the keyboard and monitor are treated as the default device when no other specific device is indicated.

Key Terms[edit | edit source]

default device
The device the computer sends information to if none is specified.
device
A piece of equipment that is electronically connected to the memory so that data can be transferred between the memory and the device.
escape code
A code directing an output device to do something.
extraction
Aka reading or getting data from an input device.
insertion
Aka writing or sending data to an output device.
standard input
The keyboard.
standard output
The monitor.

References[edit | edit source]


Hello World

Overview[edit | edit source]

A “Hello, world!” program is a computer program that outputs or displays “Hello, world!” to a user. Being a very simple program in most programming languages, it is often used to illustrate the basic syntax of a programming language for a working program, and as such is often the very first program people write.[1]

Discussion[edit | edit source]

A “Hello, world!” program is traditionally used to introduce novice programmers to a programming language. “Hello, world!” is also traditionally used in a sanity test to make sure that a computer language is correctly installed, and that the operator understands how it works.[2]

The tradition of using the phrase “Hello, world!” as a test message was influenced by an example program in the seminal book The C Programming Language. The example program from that book prints “hello, world” (without capital letters or exclamation mark), and was inherited from a 1974 Bell Laboratories internal memorandum by Brian Kernighan.[3]

In addition to displaying “Hello, world!”, a “Hello, world!” program might include comments. A comment is a programmer-readable explanation or annotation in the source code of a computer program. They are added with the purpose of making the source code easier for humans to understand, and are generally ignored by compilers and interpreters. The syntax of comments in various programming languages varies considerably.[4]

Pseudocode[edit | edit source]

Function Main
    ... This program displays "Hello world!"
    Output "Hello world!"
End

Function Main ... This program displays "Hello World" Output "Hello World" End

Output[edit | edit source]

Hello world!

Each code element represents:[5]

  • Function Main begins the main function
  • ... begins a comment
  • Output indicates the following value(s) will be displayed or printed
  • "Hello world!" is the literal string to be displayed
  • End ends a block of code

Flowchart[edit | edit source]

Examples[edit | edit source]

The following pages provide examples of “Hello, world!” programs in different programming languages. Each page includes an explanation of the code elements that comprise the program and links to IDEs you can use to test the program.

Key Terms[edit | edit source]

comment
A programmer-readable explanation or annotation in the source code of a computer program.

References[edit | edit source]


Introduction Examples C++

Overview[edit | edit source]

C++ is a general-purpose programming language. It has imperative, object-oriented and generic programming features, while also providing facilities for low-level memory manipulation. C++ was developed by Bjarne Stroustrup at Bell Labs starting in 1979 as an extension of the C language. The C++ programming language was initially standardized in 1998.[1]

C++ is one of the most popular current programming languages[2] and is often used in computer science courses.

Example[edit | edit source]

Hello World[edit | edit source]

 // This program displays "Hello world!"
 //
 // References:
 // http://www.cplusplus.com/doc/tutorial/program_structure/
 #include <iostream>
 
 int main()
 {
     std::cout << "Hello world!";
 }

Output[edit | edit source]

Hello world!

Discussion[edit | edit source]

Each code element represents:[3]

  • // begins a comment
  • #include <iostream> includes standard input and output streams
  • int main() begins the main function, which returns an integer value
  • { begins a block of code
  • std::cout is standard output
  • << directs the next element to standard output
  • "Hello world!" is the literal string to be displayed
  • ; ends each line of C++ code
  • } ends a block of code

C++ IDEs[edit | edit source]

There are many free cloud-based and local IDEs available to begin coding in C++. Check with your instructor or do your own research for recommendations.

Cloud-Based IDEs[edit | edit source]

Local IDEs[edit | edit source]

References[edit | edit source]


Introduction Examples CSharp

Overview[edit | edit source]

C# is a general-purpose, object-oriented programming language encompassing strong typing, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed around 2000 by Microsoft within its .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2006). C# is one of the programming languages designed for the Common Language Infrastructure.[1]

C# is one of the most popular current programming languages[2], is the primary language for Windows application development and is often used in computer science and gaming courses.

Example[edit | edit source]

Input: Hello World[edit | edit source]

 // This program displays "Hello world!"
 //
 // References:
 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/hello-world-your-first-program
 
 public class Hello
 {
     public static void Main()
     {
         System.Console.WriteLine("Hello world!");
     }
 }

Output[edit | edit source]

Hello world!

Discussion[edit | edit source]

Each code element represents:Programming Fundamentals/Hello World

  • // begins a comment
  • public class Hello begins the Hello World program
  • { begins a block of code
  • public static void Main() begins the main function
  • System.Console.WriteLine() calls the standard output write line function
  • "Hello world!" is the literal string to be displayed
  • ; ends each line of C# code
  • } ends a block of code

C# IDEs[edit | edit source]

There are many free cloud-based and local IDEs available to begin coding in C#. Check with your instructor or do your own research for recommendations.

Cloud-Based IDEs[edit | edit source]

Local IDEs[edit | edit source]

References[edit | edit source]


Introduction Examples Java

Overview[edit | edit source]

Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers “write once, run anywhere” (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. Java was originally developed by James Gosling at Sun Microsystems and released in 1995.[1]

Java is one of the most popular current programming languages[2] and is often used in computer science courses.

Example[edit | edit source]

Hello World[edit | edit source]

 // This program displays "Hello world!"
 //
 // References:
 // https://introcs.cs.princeton.edu/java/11hello/HelloWorld.java.html
 
 class Main {
     public static void main(String[] args) {
         System.out.println("Hello world!");
     }
 }

Output[edit | edit source]

Hello world!

Discussion[edit | edit source]

Each code element represents:Programming Fundamentals/Hello World

  • // begins a comment
  • class Main begins the Hello World program
  • { begins a block of code
  • public static void main(String[] args) begins the main function
  • System.out.println() calls the standard output print line function
  • "Hello world!" is the literal string to be displayed
  • ; ends each line of Java code
  • } ends a block of code

Java IDEs[edit | edit source]

There are many free cloud-based and local IDEs available to begin coding in Java. Check with your instructor or do your own research for recommendations.

Cloud-Based IDEs[edit | edit source]

Local IDEs[edit | edit source]

References[edit | edit source]


Introduction Examples JavaScript

Overview[edit | edit source]

JavaScript, often abbreviated as JS, is a high-level, interpreted programming language. Alongside HTML and CSS, JavaScript is one of the three core technologies of the World Wide Web. JavaScript enables interactive web pages and therefore is an essential part of web applications. The vast majority of websites use it, and all major web browsers have a dedicated JavaScript engine to execute it.[1]

JavaScript is one of the most popular current programming languages[2], and is the primary programming language for front-end web development. JavaScript files have a .js file extension. JavaScript has been implemented in multiple platforms with different I/O commands. Several examples follow.

Example[edit | edit source]

Hello World – Console Log[edit | edit source]

 // This script displays "Hello world!".
 //
 // References:
 // https://www.digitalocean.com/community/tutorials/how-to-write-your-first-javascript-program
 
 console.log("Hello world!")

Output[edit | edit source]

Hello world!

Discussion[edit | edit source]

Each code element represents:

  • // begins a comment
  • console.log() writes to the JavaScript console output log
  • "Hello world!" is the literal string to be displayed

Hello World – Window Alert[edit | edit source]

 // This script displays "Hello world!".
 //
 // References:
 // https://www.digitalocean.com/community/tutorials/how-to-write-your-first-javascript-program
 
 alert("Hello world!")

Output[edit | edit source]

Hello world!

Discussion[edit | edit source]

Each code element represents:

  • // begins a comment
  • alert() calls the window alert function to display a message
  • "Hello world!" is the literal string to be displayed

Hello World – Document Write[edit | edit source]

 // This script displays "Hello world!".
 //
 // References:
 // https://www.w3schools.com/jsref/met_doc_write.asp
 document.write("Hello world!")

Output[edit | edit source]

Hello world!

Discussion[edit | edit source]

Each code element represents:

  • // begins a comment
  • document.write() writes output to the current document
  • "Hello world!" is the literal string to be displayed

JavaScript IDEs[edit | edit source]

There are many free cloud-based and local IDEs available to begin coding in JavaScript. Check with your instructor or do your own research for recommendations.

Cloud-Based IDEs[edit | edit source]

Local IDEs[edit | edit source]

References[edit | edit source]


Introduction Examples Python

Overview[edit | edit source]

Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales.[1]

Python is one of the most popular current programming languages[2], is frequently recommended as a first programming language, and often used in information systems and data science courses.

Example[edit | edit source]

Input: Hello World[edit | edit source]

 # This program displays "Hello world!"
 #
 # References:
 # https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Hello,_World
 
 print("Hello world!")

Output[edit | edit source]

Hello world!

Discussion[edit | edit source]

Each code element represents:Programming Fundamentals/Hello World

  • # begins a comment
  • print() calls the print function
  • "Hello world!" is the literal string to be displayed

Python IDEs[edit | edit source]

There are many free cloud-based and local IDEs available to begin coding in Python. Check with your instructor or do your own research for recommendations.

Cloud-Based IDEs[edit | edit source]

Local IDEs[edit | edit source]

References[edit | edit source]


Introduction Examples Swift

Overview[edit | edit source]

Swift is a general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. for iOS, macOS, watchOS, tvOS, and Linux. Apple intended Swift to support many core concepts associated with Objective-C, but in a “safer” way, making it easier to catch software bugs. Swift was introduced in 2014.[1]

Swift is a popular programming language for the Apple platforms it supports, but it lacks support for Microsoft Windows environments.TIOBE: Index.

Example[edit | edit source]

Hello World[edit | edit source]

 // This program displays "Hello world!"
 //
 // References:
 // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html
 
 print("Hello world!")

Output[edit | edit source]

Hello world!

Discussion[edit | edit source]

Each code element represents:Programming Fundamentals/Hello World

  • // begins a comment
  • print() calls the print function
  • "Hello world!" is the literal string to be displayed

Swift IDEs[edit | edit source]

There are several free cloud-based and local IDEs available to begin coding in Swift. Check with your instructor or do your own research for recommendations.

Cloud-Based IDEs[edit | edit source]

Local IDEs[edit | edit source]

References[edit | edit source]


Practice: Introduction to Programming

Chapter Summary[edit | edit source]

  • Systems Development Life Cycle - a process for planning, creating, testing, and deploying an information system.
  • Program Design - consists of the steps a programmer should take before they start coding a program.
  • Program Quality - describes basic properties of the program’s source code and executable code
  • Pseudocode- modeling/planning tool written in English statements to convey the steps of an algorithm
  • Flowcharts- are a type of diagram that represents an algorithm, workflow, or process.
  • Software Testing - involves the execution of a software component or system component to evaluate one or more properties of interest.
  • Integrated Development Environment - is a software application that provides comprehensive facilities to computer programmers for software development.
  • Version Control - is the management of changes to documents, computer programs, large websites, and other collections of information.
  • Input and Output - are how an information processing system communicates with the outside world, a human, or another information processing system.
  • Hello World - is a computer program that outputs or displays “Hello, world!” to a user.

Review Questions[edit | edit source]

True / False:

  1. Coding the program in a language like C++ is the first task of planning. You plan as you code.
  2. Usability is the single most important fundamental property in the development process of a new program.
  3. Pseudocode has a strict set of rules and is the same everywhere in the computer programming industry.
  4. Test data is developed for testing the program once it is coded into a language like C++.
  5. Commit is to write or merge the changes made in the working copy back to the repository.
  6. Not writing down your vision of a program could lead to problems further down the coding process.
  7. IDE "compile and run" is a five (5) step process.
  8. Git is a version control system for tracking changes in computer files and coordinating work on those files among multiple people.
  9.  Printing "Hello World" on screen is the same for Python as is in Pseudocode.   
  10. The robustness of a program is its ability to work around bugs in the code and still function as intended.
  11. Psuedocode can help increase the maintainability of a program.
  12. The reliability of a program refers to how often the results of a program are correct.

Answers:

  1. False - It is important to plan out your code first before jumping into the act of coding, especially when you are starting out in a new language you aren't fully familiar with.
  2. False
  3. False
  4. False
  5. True
  6. True
  7. True
  8. True
  9. False - Although they may seem similar no two programming languages are exactly the same.
  10. False
  11. True
  12. True

Short Answer:

  1. List the steps of the Systems Development Life Cycle and indicate which step you are likely to work in as a new computer professional.
  2. List and describe what might cause the four (4) types of errors encountered in a program using a compiler and an Integrated Development Environment software product.
  3. List and describe seven (7) properties that are evaluated when determining the quality of a program's source code.
  4. List three (3) errors that you may encounter when testing a coded program using test data that outputs the wrong values.
  5. List the elements which determine a program's quality.

Activities[edit | edit source]

Pseudocode and Flowcharts[edit | edit source]

The following activities focus on software planning and testing using pseudocode and / or flowcharts.

  1. Search the Internet for pseudocode for making a peanut butter and jelly sandwich. Based on the examples you find, create pseudocode to make your own favorite sandwich or other non-prepackaged meal. Note: Because peanut butter and jelly sandwich examples are already available, you must select something else for your pseudocode. Test your pseudocode by reading the instructions out loud as someone else follows your directions.
  2. Search the Internet for a flowchart for making a peanut butter and jelly sandwich. Use a free online or downloadable flowchart tool to create a flowchart that describes how to make your favorite sandwich or other non-prepackaged meal. Note: Because peanut butter and jelly sandwich examples are already available, you must select something else for your flowchart. Test your flowchart by reading the instructions out loud while someone else follows your directions.
  3. Create pseudocode or a flowchart for a program that would interact with bank customers and help them determine the value of a bag or jar of coins brought in for deposit. Include counts for pennies, nickels, dimes and quarters and calculate the total value of all of the coins deposited. Test your program by having someone else follow the instructions and guide them as they use your program.
  4. Create pseudocode or a flowchart for a program that allows the user to enter gallons of gas and converts it to liters (metric system). NOTE: One US gallon equals 3.7854 liters. Test your program by having someone else follow the instructions and guide them as they use your program.
  5. A major restaurant sends a chef to purchase fruits and vegetables every day. Upon returning to the store the chef must enter two pieces of data for each item purchased: the quantity (Example: 2 cases) and the price paid (Example: $4.67). The program has a list of 20 items and after the chef enters the information, the program provides a total for the purchases for that day. Prepare test data for five (5) items: apples, oranges, bananas, lettuce, and tomatoes.

Programming Languages and Integrated Development Environments[edit | edit source]

The following activities focus on selecting a programming language and testing integrated development environments.

  1. Research different programming languages and select a programming language to use with this textbook. Copy the Hello World example code for your selected programming language and use one of the free cloud-based IDEs to try running the Hello World program.
  2. Modify the example Hello World program to instead display Hello <name>!, where <name> is your name. Include comments at the top of the program and test the program to verify that it works correctly.
  3. Research free downloadable tools for your selected programming language (interpreter/compiler, IDE, etc.). Consider downloading and installing a development environment on your system. If you set up your own development environment, test the environment using your Hello Name program written above.

References[edit | edit source]


Data and Operators

Overview[edit | edit source]

This chapter introduces constants and variables, data types, and operators.

Chapter Outline[edit | edit source]

Learning Objectives[edit | edit source]

  1. Understand key terms and definitions.
  2. Understand basic data types and how operators manipulate data.
  3. Given example pseudocode, flowcharts, and source code, create a program that uses appropriate data types and operators to solve a given problem.


Constants and Variables

Overview[edit | edit source]

A constant is a value that cannot be changed by the program during normal execution, in other words, the value is constant. When associated with an identifier, a constant is said to be “named,” although the terms “constant” and “named constant” are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution, in other words, the value is variable.

Discussion[edit | edit source]

Understanding Constants[edit | edit source]

A constant is a data item whose value cannot change during the program’s execution. Thus, as its name implies – the value is constant.

A variable is a data item whose value can change during the program’s execution. Thus, as its name implies – the value can vary.

Constants are used in two ways. They are:

  1. literal constant
  2. defined constant

A literal constant is a value you type into your program wherever it is needed. Examples include the constants used for initializing a variable and constants used in lines of code:

21
12.34
'A'
"Hello world!"
false
null

In addition to literal constants, most textbooks refer to symbolic constants or named constants as a constant represented by a name. Many programming languages use ALL CAPS to define named constants.

Language Example
C++ #define PI 3.14159or

const double PI = 3.14159;

C# const double PI = 3.14159;
Java const double PI = 3.14159;
JavaScript const PI = 3.14159;
Python PI = 3.14159
Swift let pi = 3.14159

Technically, Python does not support named constants, meaning that it is possible (but never good practice) to change the value of a constant later. There are workarounds for creating constants in Python, but they are beyond the scope of a first-semester textbook.

Defining Constants and Variables[edit | edit source]

Named constants must be assigned a value when they are defined. Variables do not have to be assigned initial values. Variables once defined may be assigned a value within the instructions of the program.

Language Example
C++ double value = 3;
C# double value = 3;
Java double value = 3;
JavaScript var value = 3;let value = 3;
Python value = 3
Swift var value:Int = 3

Key Terms[edit | edit source]

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.

References[edit | edit source]


Identifier Names

Overview[edit | edit source]

Within programming, a variety of items are given descriptive names to make the code more meaningful to the programmer. These are called "Identifier Names." When an item is declared or defined, it is identified by a name. Some examples of items that can be named are constants, variables, type definitions, and functions. These names help identify the function of the item. These names follow a set of rules that are imposed by:

  1. the language's technical limitations
  2. good programming practices
  3. common industry standards for the language

Discussion[edit | edit source]

Language Technical Limitations[edit | edit source]

  • Must use only allowable characters: in many languages, the first character must be alphabetic or an underscore. The next character can be alphanumeric or an underscore
  • Can't use reserved words
  • Length limit

These attributes vary from one programming language to another. The allowable characters and reserved words will be different. The length limit refers to how many characters are allowed in an identifier name and is often compiler dependent and may vary from compiler to compiler for the same language. However, all programming languages have some form of the technical rules listed here.

Good Programming Techniques[edit | edit source]

  • Meaningful
  • Be case consistent

Meaningful identifier names make your code easier to understand for other programmers. After all, what does “p” mean? Obviously, "p" could stand for anything. Because of this, avoid abbreviations and don't use cryptic, or hard to understand identifier names.

Some programming languages treat upper and lower case letters used in identifier names as the same (ex. pig and Pig are treated as the same identifier name). The compiler usually changes all identifier names to upper case (ex. pig and Pig are now both changed to PIG), unbeknownst to the programmer. However, not all programming languages act this way. Some will treat upper and lower case letters as being different things (ex. 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 will get a different variable or perhaps a compiler error. To avoid this problem altogether, we teach students to be case consistent. Use an identifier name only one way and spell it (upper and lower case) the same way every time within your program.

Industry Rules[edit | edit source]

Almost all programming languages and most coding shops have a standard code formatting style guide programmers are expected to follow. Among these are three common identifier casing standards:

  • camelCase – each word is capitalized except the first word, with no intervening spaces
  • PascalCase – each word is capitalized including the first word, with no intervening spaces
  • snake_case – each word is lowercase with underscores separating words

C++, Java, and JavaScript typically use camelCase, with PascalCase reserved for libraries and classes. C# uses primarily PascalCase with camelCase parameters. Python uses snake_case for most identifiers. In addition, the following rules apply:

  • Do not start with an underscore (used for technical programming)
  • CONSTANTS IN ALL UPPER CASE (often UPPER_SNAKE_CASE)

These rules are decided on by the industry (those who are using the programming language).

Key Terms[edit | edit source]

Camel case
The practice of writing compound words or phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation.
Pascal case
The practice of writing compound words or phrases such that each word or abbreviation in the phrase begins with a capital letter, including the first letter, with no intervening spaces or punctuation.
Reserved word
Words that cannot be used by the programmer as identifier names because they already have a specific meaning within the programming language. (ie. if, then, else, while, for and case)
Snake case
The practice of writing compound words or phrases in which the elements are separated with one underscore character (_) and no spaces, with each element’s initial letter usually lowercased within the compound and the first letter either upper or lower case.

References[edit | edit source]


Data Types

Overview[edit | edit source]

A data type is a classification of data which tells the compiler or interpreter how the programmer intends to use the data. Most programming languages support various types of data, including integer, real, character or string, and Boolean.

Discussion[edit | edit source]

Our interactions (inputs and outputs) with 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:

  • your name – a string of characters
  • your age – usually an integer
  • the amount of money in your pocket – usually a value measured in dollars and cents (something with a fractional part)

A major part of understanding how to design and code programs is centered in understanding the types of data that we want to manipulate and how to manipulate that data.

Common data types include:

Data Type Represents Examples
integer whole numbers -5, 0, 123
floating point (real) fractional numbers -87.5, 0.0, 3.14159
string A sequence of characters "Hello world!"
Boolean logical true or false true, false
nothing no data null

The common data types usually exist in most programming languages and act or behave similarly from language to language. Additional complex and/or composite data types may exist and vary from language to language.

Pseudocode[edit | edit source]

Function Main
    ... This program demonstrates variables, literal constants, and data types.

    Declare Integer i
    Declare Real r
    Declare String s
    Declare Boolean b
    
    Assign i = 1234567890
    Assign r = 1.23456789012345
    Assign s = "string"
    Assign b = true

    Output "Integer i = " & i
    Output "Real r = " & r
    Output "String s = " & s
    Output "Boolean b = " & b
End

Output[edit | edit source]

Integer i = 1234567890
Real r = 1.23456789012345
String s = string
Boolean b = true

Flowchart[edit | edit source]

Data types flowchart

Key Terms[edit | edit source]

Boolean
A data type representing logical true or false.
Data types
Defines a set of values and a set of operations that can be applied on those values.
Floating point
A data type representing numbers with fractional parts.
Integer
A data type representing whole numbers.
String
A data type representing a sequence of characters.

References[edit | edit source]


Integer Data Type

Overview[edit | edit source]

An integer data type represents some range of mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values. Integers are commonly represented in a computer as a group of binary digits (bits). The size of the grouping varies so the set of integer sizes available varies between different types of computers and different programming languages.[1]

Discussion[edit | edit source]

The integer data type 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 threefold. 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, the 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. Third, integer processing is significantly faster within the CPU than is floating point processing.

The integer data type has similar attributes and acts or behaves similarly in all programming languages that support it.

Language Reserved Word Size Range
C++ short 16 bits / 2 bytes -32,768 to 32,767
C++ int varies depends on compiler
C++ long 32 bits / 4 bytes -2,147,483,648 to 2, 147,483,647
C++ long long 64 bits / 8 bytes −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
C# short 16 bits / 2 bytes -32,768 to32,767
C# int 32 bits / 4 bytes -2,147,483,648 to 2, 147,483,647
C# long 64 bits / 8 bytes −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Java short 16 bits / 2 bytes -32,768 to32,767
Java int 32 bits / 4 bytes -2,147,483,648 to 2, 147,483,647
Java long 64 bits / 8 bytes −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
JavaScript N/A
Python int() no limit
Swift Int varies depends on platform
Swift Int32 32 bits / 4 bytes -2,147,483,648 to 2, 147,483,647
Swift Int64 64 bits / 8 bytes −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

For C++ and Swift the size of a default integer varies with the compiler being used and the computer. This effect is known as being machine dependent. These variations of the integer data type are an annoyance for a beginning programmer. For a beginning programmer, it is more important to understand the general attributes of the integer data type that apply to most programming languages.

JavaScript does not support an integer data type, but the Math.round() function may be used to return the value of a number rounded to the nearest integer.[2]

Python 3 integers are not limited in size, however, sys.maxsize may be used to determine the maximum practical size of a list or string index.[3]

Key Terms[edit | edit source]

machine dependent
An attribute of a programming language that changes depending on the computer’s CPU.

References[edit | edit source]


Floating-Point Data Type

Overview[edit | edit source]

A floating-point data type uses a common representation of real numbers as an approximation, which is essentially a trade-off between range and precision. For this reason, floating-point computation is often found in systems that include very small and very large real numbers, which require fast processing times. A number is, in general, represented approximately to a fixed number of significant digits and scaled using an exponent in some fixed base such as 10.[1]

Discussion[edit | edit source]

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 represents 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.

Language Reserved Word Size Precision Range
C++ float 32 bits / 4 bytes 7 decimal digits ±3.40282347E+38
C++ double 64 bits / 8 bytes 15 decimal digits ±1.79769313486231570E+308
C# float 32 bits / 4 bytes 7 decimal digits ±3.40282347E+38
C# double 64 bits / 8 bytes 15 decimal digits ±1.79769313486231570E+308
Java float 32 bits / 4 bytes 7 decimal digits ±3.40282347E+38
Java double 64 bits / 8 bytes 15 decimal digits ±1.79769313486231570E+308
JavaScript Number 64 bits / 8 bytes 15 decimal digits ±1.79769313486231570E+308
Python float() 64 bits / 8 bytes 15 decimal digits ±1.79769313486231570E+308
Swift Float 32 bits / 4 bytes 7 decimal digits ±3.40282347E+38
Swift Double 64 bits / 8 bytes 15 decimal digits ±1.79769313486231570E+308

When converting operations with floating-point values, there may be more decimal places than you want. We can use the round function to limit the number of decimal places displayed. For example, round(1.12356,2) gives 1.12.[2]

Key Terms[edit | edit source]

double
The most often used floating-point family data type used.
mantissa exponent
The two integer parts of a floating-point value.
precision
The effect on the domain of floating-point values given a larger or smaller storage area in bytes.

References[edit | edit source]


String Data Type

Overview[edit | edit source]

A string data type is commonly a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation). A string is generally considered a data type and is often implemented as an array data structure of bytes (or words) that stores a sequence of elements, typically characters, using some character encoding.[1]

Discussion[edit | edit source]

Depending on the programming language and precise data type used, a variable declared to be a string may either cause storage in memory to be statically allocated for a predetermined maximum length or employ dynamic allocation to allow it to hold a variable number of elements. When a string appears literally in source code, it is known as a string literal or an anonymous string.[2]

The character data type represents individual or single characters. Characters comprise a variety of symbols such as the alphabet (both upper and lower case) the numeral digits (0 to 9), punctuation, etc. All computers store character data in a one-byte field as an integer value. Because a byte consists of 8 bits, this one-byte field has 28 or 256 possibilities using the positive values of 0 to 255.

C++, C#, and Java differentiate between single characters and strings using single quotes and double quotes, respectively. JavaScript, Python, and Swift do not differentiate between characters and strings and use either single quotes or double quotes to define string literals.

Language Reserved Word Example
C++ char 'A'
C++ string "Hello world!"
C# char 'A'
C# String "Hello world!"
Java char 'A'
Java String "Hello world!"
JavaScript String 'Hello world!', "Hello world!"
Python str() 'Hello world!', "Hello world!"
Swift Character "A"
Swift String "Hello world!"

Most computing devices 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.

For now, we will address only the use of strings and characters as constants. Most modern compilers that are part of an Integrated Development Environment (IDE) will color the source code to help the programmer see different features more readily. Beginning programmers will use string constants to send messages to standard output.

Key Terms[edit | edit source]

ASCII
American Standard Code for Information Interchange
Character
A data type representing single text characters like the alphabet, numeral digits, punctuation, etc.
Double quote marks
Used to create string type data within most programming languages.
Single quote marks
Used to create character type data within languages that differentiate between string and character data types.
String
A series or array of characters as a single piece of data.

References[edit | edit source]


Boolean Data Type

Overview[edit | edit source]

A Boolean data type has one of two possible values (usually denoted true and false), intended to represent the two truth values of logic and Boolean algebra. It is named after George Boole, who first defined an algebraic system of logic in the mid 19th century. The Boolean data type is primarily associated with conditional statements, which allow different actions by changing control flow depending on whether a programmer-specified Boolean condition evaluates to true or false.[1]

Discussion[edit | edit source]

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.

When implemented in hardware, the 0 and 1 are switches, where 0 is open and 1 is close. The Boolean data type has the same attributes and acts or behaves similarly in all programming languages. However, while all languages recognize false as 0, some languages define true as -1 rather than 1. This is the result of storing the Boolean values as an integer and using a one’s complement representation that negates all bits rather than only the rightmost bit. To simplify processing, most programming languages recognize any non-zero value as being true.

Language Reserved Word True False
C++ bool true false
C# bool or Boolean true false
Java bool true false
JavaScript Boolean() true false
Python bool() True False
Swift Bool true false

Key Terms[edit | edit source]

Boolean
A data type representing the concepts of true or false.
Ones' complement
The value obtained by inverting all the bits in the binary representation of a number (swapping 0s for 1s and vice versa).

References[edit | edit source]


Nothing Data Type

Overview[edit | edit source]

A nothing data type is a feature of some programming languages which allow the setting of a special value to indicate a missing or uninitialized value rather than using the value 0 (zero).[1]

Discussion[edit | edit source]

Most programming languages support the use of a reserved word or words to represent missing, uninitialized, or invalid values.

Language Reserved Word Meaning
C++ null no value
C# null no value
Java null no value
JavaScript null no value
JavaScript NaN Not a Number
Python None no value
Swift nil no value

Key Terms[edit | edit source]

NaN
Reserved word used to indicate a non-numeric value in a numeric variable.
Null
Reserved word used to represent a missing value or invalid value.

References[edit | edit source]


Order of Operations

Overview[edit | edit source]

The order of operations (or operator precedence) is a collection of rules that reflect which procedures to perform first in order to evaluate a given mathematical expression.[1]

Discussion[edit | edit source]

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.

An Expression Example with Evaluation[edit | edit source]

Let’s look at an example: 2 + 3 * 4 + 5 is our expression but what does it equal?

  1. the symbols of + meaning addition and * meaning multiplication are our operators
  2. the values 2, 3, 4 and 5 are our operands
  3. precedence says that multiplication is higher than addition
  4. thus, we evaluate the 3 * 4 to get 12
  5. now we have: 2 + 12 + 5
  6. the associativity rules say that addition goes left to right, thus we evaluate the 2 +12 to get 14
  7. now we have: 14 + 5
  8. finally, we evaluate the 14 + 5 to get 19; which is the value of the expression

Parentheses would change the outcome. (2 + 3) * (4 + 5) evaluates to 45.

Parentheses would change the outcome. (2 + 3) * 4 + 5 evaluates to 25.

Operator Precedence Chart[edit | edit source]

Each computer language has some rules that define precedence and associativity. They often follow rules we may have already learned. Multiplication and division come before addition and subtraction is a rule we learned in grade school. This rule still works.

Order of Operations[2]

  • Parentheses
  • Exponents
  • Multiplication / Division
  • Addition / Subtraction

A common mnemonic to remember this rule is PEMDAS, or Please Excuse My Dear Aunt Sally. Precedence rules may vary from one programming language to another. You should refer to the reference sheet that summarizes the rules for the language that you are using. It is often called an Operator Precedence, Precedence of Operators, or Order of Operations chart. You should review this chart as needed when evaluating expressions.

A valid expression consists of operand(s) and operator(s) that are put together properly. Why the (s)? Some operators are:

  1. Unary – only have one operand
  2. Binary – have two operands, one on each side of the operator
  3. Trinary – have two operator symbols that separate three operands

Most operators are binary, that is they require two operands. Some precedence charts indicate of which operators are unary and trinary and thus all others are binary.

Key Terms[edit | edit source]

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.
expression
A valid sequence of operand(s) and operator(s) that reduces (or evaluates) to a single value.
operand
A value that receives the operator’s action.
operator
A language-specific syntactical token (usually a symbol) that causes an action to be taken on one or more operands.
parentheses
Change the order of evaluation in an expression. You do what’s in the parentheses first.
precedence
Determines the order in which the operators are allowed to manipulate the operands.

References[edit | edit source]


Assignment

Overview[edit | edit source]

An assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable.[1]

Discussion[edit | edit source]

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 most programming languages the symbol used for assignment 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.

Simple Assignment

age = 21

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.

Assignment with an Expression

total_cousins = 4 + 3 + 5 + 2

The item to the right of the assignment operator is an expression. The expression will be evaluated and the answer is 14. The value 14 would be assigned to the variable named: total_cousins.

Assignment with Identifier Names in the Expression

students_period_1 = 25
students_period_2 = 19
total_students = students_period_1 + students_period_2;

The expression to the right of the assignment operator contains some identifier names. The program would fetch the values stored in those variables; add them together and get a value of 44; then assign the 44 to the total_students variable.

Key Terms[edit | edit source]

assignment
An operator that changes the value of a modifiable data object.

Multimedia[edit | edit source]

  1. Flowgorithm: Declare Assign and Output A Value https://www.youtube.com/watch?v=HNCqFvzo9uo

References[edit | edit source]


Arithmetic Operators

Overview[edit | edit source]

The basic arithmetic operations are addition, subtraction, multiplication, and division. Arithmetic is performed according to an order of operations.[1]

Discussion[edit | edit source]

An operator performs an action on one or more operands. The common arithmetic operators are:

Action Common Symbol
Addition +
Subtraction -
Multiplication *
Division /
Modulus (associated with integers) %

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, may act differently. Please refer to the next section on “Integer Division and Modulus”.

Arithmetic Assignment Operators[edit | edit source]

Many programming languages support a combination of the assignment (=) and arithmetic operators (+, -, *, /, %). Various textbooks call them “compound assignment operators” or “combined assignment operators." Their usage can be explained in terms of the assignment operator and the arithmetic operators. In the table, we will use the variable age and you can assume that it is of integer data type.

Arithmetic assignment examples: Equivalent code:
age += 14; age = age + 14;
age -= 14; age = age - 14;
age *= 14; age = age * 14;
age /= 14; age = age / 14;
age %= 14; age = age % 14;

Pseudocode[edit | edit source]

Function Main
    ... This program demonstrates arithmetic operations.
    Declare Integer a
    Declare Integer b
    
    Assign a = 3
    Assign b = 2
    Output "a = " & a
    Output "b = " & b
    Output "a + b = " & a + b
    Output "a - b = " & a - b
    Output "a * b = " & a * b
    Output "a / b = " & a / b
    Output "a % b = " & a % b
End

Output[edit | edit source]

a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1.5
a % b = 1

Flowchart[edit | edit source]

Arithmetic operations flowchart

References[edit | edit source]


Integer Division and Modulus

Overview[edit | edit source]

In integer division and modulus, the dividend is divided by the divisor into an integer quotient and a remainder. The integer quotient operation is referred to as integer division, and the integer remainder operation is the modulus.[1][2]

Discussion[edit | edit source]

By the time we reach adulthood, we normally think of division as resulting in an answer that might have a fractional part (a floating-point data type). This type of division is known as floating-point division. However, when both operands are of the integer data type, division may act differently, depending on the programming language, and is called: integer division. Consider:

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 called integer division and it is what you learned in grade school the first time you learned about division.

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? The 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.

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 many programming languages, the symbol for the modulus operator is the percent sign (%).

11 % 4

Thus, the answer or value of this expression is 3 or 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.

Don’t let the following items confuse you.

6 / 24 which is different from 6 % 24

How many times can you divide 24 into 6? Six divided by 24 is zero. This is different from: What is the remainder of 6 divided by 24? Six, the remainder part is given by modulus.

Evaluate the following division expressions:

  1. 14 / 4
  2. 5 / 13
  3. 7 / 2.0

Evaluate the following modulus expressions:

  1. 14 % 4
  2. 5 % 13
  3. 7 % 2.0

Solutions

  1. 14 % 4 = 2
  2. 5 % 13 = 5
  3. 7 % 2.0 = 1.0

Key Terms[edit | edit source]

integer division
Division with no fractional parts- giving “quotient” as an answer.
modulus
The remainder part of integer division.

References[edit | edit source]


Unary Operations

A unary operation is an operation with only one operand. As unary operations have only one operand, they are evaluated before other operations containing them.[1] Common unary operators include Positive (+) and Negative (-).

Discussion[edit | edit source]

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

The expression evaluates to negative 7. Let's consider:

7 - -2

First constants that do not have a unary minus 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.

Negation – Unary Negative[edit | edit source]

The concept of negation is to take a value and change its sign, that is: flip it. If it is 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.

Unary Positive – Worthless[edit | edit source]

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

The second + sign is interpreted as unary positive. The first + sign is interpreted as addition.

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[edit | edit source]

Do not confuse the unary negative operator with decrement. Decrement changes the value in the variable and thus is an Lvalue concept. Unary negative does not change the value of the variable but uses it in an Rvalue context. It fetches the value and then negates that value. The original value in the variable does not change.

Because there is no changing of the value associated with the identifier name, the identifier name could represent a variable or named constant.

Exercises[edit | edit source]

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

Key Terms[edit | edit source]

minus
Aka unary negative.
plus
Aka unary positive.
unary negative
An operator that causes negation.
unary positive
A worthless operator almost never used.

References[edit | edit source]


Lvalue and Rvalue

Overview[edit | edit source]

Some programming languages use the idea of L-values and R-values, deriving from the typical mode of evaluation on the left and right-hand side of an assignment statement. An L-value refers to an object that persists beyond a single expression. An R-value is a temporary value that does not persist beyond the expression that uses it.[1]

Discussion[edit | edit source]

L-value and R-value refer to the left and right side of the assignment operator. The L-value (pronounced: L value) concept refers to the requirement that the operand on the left side of the assignment operator is modifiable, usually a variable. R-value concept pulls or fetches the value of the expression or operand on the right side of the assignment operator. Some examples:

age = 39

The value 39 is pulled or fetched (R-value) and stored into the variable named age (L-value); destroying the value previously stored in that variable.

voting_age = 18
age = voting_age

If the expression has a variable or named constant on the right side of the assignment operator, it would pull or fetch the value stored in the variable or constant. The value 18 is pulled or fetched from the variable named voting_age and stored into the variable named age.

age < 17

If the expression is a test expression or Boolean expression, the concept is still an R-value. The value in the identifier named age is pulled or fetched and used in the relational comparison of less than.

JACK_BENNYS_AGE = 39
JACK_BENNYS_AGE = 65;

This is illegal because the identifier JACK_BENNYS_AGE does not have L-value properties. It is not a modifiable data object, because it is a constant.

Some uses of the L-value and R-value can be confusing in languages that support increment and decrement operators. Consider:

oldest = 55
age = oldest++

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 R-value context where the existing value of 55 is pulled or fetched and then assigned to the variable age; an L-value context. The second use of the oldest variable is an L-value context wherein the value of the oldest is incremented from 55 to 56.

Key Terms[edit | edit source]

Lvalue
The requirement that the operand on the left side of the assignment operator is modifiable, usually a variable.
Rvalue
Pulls or fetches the value stored in a variable or constant.

References[edit | edit source]


Data Type Conversions

Overview[edit | edit source]

Changing a data type of a value is referred to as “type conversion”. There are two ways to do this:

  1. Implicit – the change is implied
  2. Explicit – the change is explicitly done with an operator or function

The value being changed may be:

  1. Promotion – going from a smaller domain to a larger domain
  2. Demotion – going from a larger domain to a smaller domain

Discussion[edit | edit source]

Implicit Type Conversion[edit | edit source]

Automatic conversion of a value from one data type to another by a programming language, without the programmer specifically doing so, is called implicit type conversion.  It happens whenever a binary operator has two operands of different data types. Depending on the operator, one of the operands is going to be converted to the data type of the other. It could be promoted or demoted depending on the operator.

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.

Implicit Demotion

In programming languages that have explicit integer data types (C++, C#, Java), care must be taken to avoid implicit demotion. For example:

int money;

money = 23.16;

In this example, the variable money is an integer. We are trying to move a floating-point value 23.16 into an integer storage location. This is demotion and the floating-point value usually gets truncated to 23.

Promotion[edit | edit source]

Promotion is never a problem because the lower data type (smaller range of allowable values) is a subset 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 subset of integer values and integer values are a subset of floating-point values; and within the floating-point values, float values are a subset 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[edit | edit source]

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 calculate the number of cans of soup to buy based on the number of people I am serving (say 8) and the servings per can (say 2.3), I would need 18.4 cans. I might want to demote the 18.4 into an integer. It would truncate the 18.4 into 18 and because the value 18 is within the domain of an integer data type, it should demote with the truncation side effect.

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).

Explicit Type Conversion[edit | edit source]

Most languages have a method for the programmer to change or cast a value from one data type to another; called explicit type conversion. Some languages support a cast operator. The cast operator is a unary operator; it only has one operand and the operand is to the right of the operator. The operator is a set of parentheses surrounding the new data type. Other languages have functions that perform explicit type conversion. In each of the following examples, the expression value would be 3.

Language Floating-Point to Integer Type Conversion Example
C++ (int) 3.14
C# Convert.ToInt32(3.14)
Java Math.floor(3.14)
JavaScript Math.floor(3.14)
Python int(3.14)
Swift Int(3.14)

In each of the following examples, the expression value would be 3.14.

Language String to Floating-Point Type Conversion Example
C++ #include <string.h>std::stod("3.14")
C# Convert.ToDouble("3.14")
Java Double.parseDouble("3.14")
JavaScript parseFloat("3.14")
Python float("3.14")
Swift Double("3.14")

Key Terms[edit | edit source]

demotion
Going from a larger domain to a smaller domain.
explicit
Changing a value’s data type with the cast operator.
implicit
A value that has its data type changed automatically.
promotion
Going from a smaller domain to a larger domain.
truncation
The fractional part of a floating-point data type that is dropped when converted to an integer.

References[edit | edit source]


Input-Process-Output Model

Overview[edit | edit source]

The input–process–output (IPO) model is a widely used approach in systems analysis and software engineering for describing the structure of an information processing program or another process. The IPO model is the most basic structure for describing a process.[1]

Discussion[edit | edit source]

A computer program or any other sort of process using the input-process-output model receives inputs from a user or other source, does some computations on the inputs, and returns the results of the computations. The system divides the work into three categories:[2]

  • A requirement from the environment (input)
  • A computation based on the requirement (process)
  • A provision for the environment (output)

For example, a program might be written to convert Fahrenheit temperatures into Celsius temperatures. Following the IPO model, the program must:

  • Ask the user for the Fahrenheit temperature (input)
  • Perform a calculation to convert the Fahrenheit temperature into the corresponding Celsius temperature (process)
  • Display the Celsius temperature (output)

Pseudocode[edit | edit source]

Function Main
    ... This program converts an input Fahrenheit temperature to Celsius.

    Declare Real fahrenheit
    Declare Real celsius
    
    Output "Enter Fahrenheit temperature:"
    Input fahrenheit

    Assign celsius = (fahrenheit - 32) * 5 / 9

    Output fahrenheit & "° Fahrenheit is " & celsius & "° Celsius"
End

Output[edit | edit source]

Enter Fahrenheit temperature:
100
100° Fahrenheit is 37.7777777777778° Celsius

Flowchart[edit | edit source]

Fahrenheit to Celsius flowchart

References[edit | edit source]


Variable Examples C++

Overview[edit | edit source]

The following examples demonstrate data types, arithmetic operations, and input in C++.

Data Types[edit | edit source]

 // This program demonstrates variables, literal constants, and data types.
 
 #include <iostream>
 #include <sstream>
 
 using namespace std;
 
 int main() {
     int i;
     double d;
     string s;
     bool b;
     
     i = 1234567890;
     d = 1.23456789012345;
     s = "string";
     b = true;
     cout << "Integer i = " << i << endl;
     cout << "Double d = " << d << endl;
     cout << "String s = " << s << endl;
     cout << "Boolean b = " << b << endl;
     return 0;
 }

Output[edit | edit source]

Integer i = 1234567890
Real r = 1.23457
String s = string
Boolean b = 1

Discussion[edit | edit source]

Each code element represents:

  • // begins a comment
  • #include <iostream> includes standard input and output streams//
  • #include <sstream> includes standard string streams//
  • using namespace std allows reference to string, cout, and endl without writing std::string, std::cout, and std::endl.
  • int main() begins the main function, which returns an integer value
  • { begins a block of code
  • int i defines an integer variable named i
  • ; ends each line of C++ code
  • double d defines a double floating-point variable named d
  • string s defines a string variable named s
  • bool b defines a Boolean variable named b
  • i = , d = , s =, b = assign literal values to the corresponding variables
  • cout is standard output
  • << directs the next element to standard output
  • endl ends the current line
  • return 0 returns the value 0 from main, indicating the main function completed successfully
  • } ends a block of code

Arithmetic[edit | edit source]

 // This program demonstrates arithmetic operations.
 
 #include <iostream>
 #include <sstream>
 
 using namespace std;
 
 int main() {
     int a;
     int b;
     
     a = 3;
     b = 2;
     
     cout << "a = " << a << endl;
     cout << "b = " << b << endl;
     cout << "a + b = " << a + b << endl;
     cout << "a - b = " << a - b << endl;
     cout << "a * b = " << a * b << endl;
     cout << "a / b = " << a / b << endl;
     cout << "a % b = " << a + b << endl;
     return 0;
 }

Output[edit | edit source]

a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1
a % b = 5

Discussion[edit | edit source]

Each new code element represents:

  • +, -, *, /, and % represent addition, subtraction, multiplication, division, and modulus, respectively.

Temperature[edit | edit source]

 // This program converts an input Fahrenheit temperature to Celsius.
 //
 // References:
 // https://www.mathsisfun.com/temperature-conversion.html
 // https://en.wikibooks.org/wiki/C%2B%2B_Programming
 #include <iostream>
 
 using namespace std;
 
 int main() {
     double fahrenheit;
     double celsius;
     
     cout << "Enter Fahrenheit temperature:" << endl;
     cin >> fahrenheit;
 
     celsius = (fahrenheit - 32) * 5 / 9;
 
     cout << fahrenheit << "° Fahrenheit is " << celsius << "° Celsius" << endl;
 
     return 0;
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7778° Celsius

Discussion[edit | edit source]

Each new code element represents:

  • cin >> fahrenheit reads the next integer from standard input and assigns the value to the fahrenheit variable

References[edit | edit source]


Variable Examples CSharp

Overview[edit | edit source]

The following examples demonstrate data types, arithmetic operations, and input in C#.

Data Types[edit | edit source]

 // This program demonstrates variables, literal constants, and data types.
 
 using System;
 
 public class DataTypes
 {
     public static void Main(string[] args)
     {
         int i;
         double d;
         string s;
         Boolean b;
         
         i = 1234567890;
         d = 1.23456789012345;
         s = "string";
         b = true;
 
         Console.WriteLine("Integer i = " + i);
         Console.WriteLine("Double d = " + d);
         Console.WriteLine("String s = " + s);
         Console.WriteLine("Boolean b = " + b);
     }
 }

Output[edit | edit source]

Integer i = 1234567890
Double d = 1.23456789012345
String s = string
Boolean b = True

Discussion[edit | edit source]

Each code element represents:

  • // begins a comment
  • using System allows references to Boolean and Console without writing System.Boolean and System.Console
  • public class DataTypes begins the Data Types program
  • { begins a block of code
  • public static void Main() begins the main function
  • int i defines an integer variable named i
  • ; ends each line of C# code
  • double d defines a double floating-point variable named d
  • string s defines a string variable named s
  • Boolean b defines a Boolean variable named b
  • i = , d = , s =, b = assign literal values to the corresponding variables
  • Console.WriteLine() calls the standard output write line function
  • } ends a block of code

Arithmetic[edit | edit source]

 // This program demonstrates arithmetic operations.
 
 using System;
 
 public class Arithmetic
 {
     public static void Main(string[] args)
     {
         int a;
         int b;
         
         a = 3;
         b = 2;
 
         Console.WriteLine("a = " + a);
         Console.WriteLine("b = " + b);
         Console.WriteLine("a + b = " + (a + b));
         Console.WriteLine("a - b = " + (a - b));
         Console.WriteLine("a * b = " + a * b);
         Console.WriteLine("a / b = " + a / b);
         Console.WriteLine("a % b = " + (a + b));
     }
 }

Output[edit | edit source]

a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1
a % b = 5

Discussion[edit | edit source]

Each new code element represents:

  • +, -, *, /, and % represent addition, subtraction, multiplication, division, and modulus, respectively.

Temperature[edit | edit source]

 // This program converts an input Fahrenheit temperature to Celsius.
 
 using System;
 
 public class Temperature
 {
     public static void Main(string[] args)
     {
         double fahrenheit;
         double celsius;
         
         Console.WriteLine("Enter Fahrenheit temperature:");
         fahrenheit = Convert.ToDouble(Console.ReadLine());
 
         celsius = (fahrenheit - 32) * 5 / 9;
 
         Console.WriteLine(
             fahrenheit.ToString() + "° Fahrenheit is " + 
             celsius.ToString() + "° Celsius" + "\n");
     }
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

Discussion[edit | edit source]

Each new code element represents:

  • Console.ReadLine() reads the next line from standard input
  • Convert.ToDouble converts the input to a double floating-point value

References[edit | edit source]


Variable Examples Java

Overview[edit | edit source]

The following examples demonstrate data types, arithmetic operations, and input in Java.

Data Types[edit | edit source]

 // This program demonstrates variables, literal constants, and data types.
 
 public class Main {
     public static void main(String[] args) {
         int i;
         double d;
         String s;
         boolean b;
         
         i = 1234567890;
         d = 1.23456789012345;
         s = "string";
         b = true;
 
         System.out.println("Integer i = " + i);
         System.out.println("Double d = " + d);
         System.out.println("String s = " + s);
         System.out.println("Boolean b = " + b);
     }
 }

Output[edit | edit source]

Integer i = 1234567890
Double d = 1.23456789012345
String s = string
Boolean b = true

Discussion[edit | edit source]

Each code element represents:

  • // begins a comment
  • public class DataTypes begins the Data Types program
  • { begins a block of code
  • public static void main(String[] args) begins the main function
  • int i defines an integer variable named i
  • ; ends each line of Java code
  • double d defines a double floating-point variable named d
  • string s defines a string variable named s
  • boolean b defines a Boolean variable named b
  • i = , d = , s =, b = assign literal values to the corresponding variables
  • System.out.println calls the  standard output print line function
  • } ends a block of code

Arithmetic[edit | edit source]

 // This program demonstrates arithmetic operations.
 
 public class Main {
     public static void main(String[] args) {
         int a;
         int b;
         
         a = 3;
         b = 2;
 
         System.out.println("a = " + a);
         System.out.println("b = " + b);
         System.out.println("a + b = " + (a + b));
         System.out.println("a - b = " + (a - b));
         System.out.println("a * b = " + a * b);
         System.out.println("a / b = " + a / b);
         System.out.println("a % b = " + (a % b));
     }
 }

Output[edit | edit source]

a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1
a % b = 1

Discussion[edit | edit source]

Each new code element represents:

  • +, -, *, /, and % represent addition, subtraction, multiplication, division, and modulus, respectively.

Temperature[edit | edit source]

 // This program converts an input Fahrenheit temperature to Celsius.
 
 import java.util.*;
 
 public class Main {
     private static Scanner input = new Scanner(System.in);
 
     public static void main(String[] args) {
         double fahrenheit;
         double celsius;
         
         System.out.println("Enter Fahrenheit temperature:");
         fahrenheit = input.nextDouble();
 
         celsius = (fahrenheit - 32) * 5 / 9;
         
         System.out.println(Double.toString(fahrenheit) + "° Fahrenheit is " + celsius + "° Celsius");
     }
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

Discussion[edit | edit source]

Each new code element represents:

  • private static Scanner input ... defines an object to read from standard input
  • input.nextDouble() reads input as a double floating-point value

References[edit | edit source]


Variable Examples JavaScript

Overview[edit | edit source]

The following examples demonstrate data types, arithmetic operations, and input in JavaScript.

Data Types[edit | edit source]

 // This program demonstrates variables, literal constants, and data types.
 
 var n;
 var s;
 var b;
     
 n = 1.23456789012345;
 s = "string";
 b = true;
     
 output("Number n = " + n);
 output("String s = " + s);
 output("Boolean b = " + b);
 
 function output(text) {
   if (typeof document === 'object') {
     document.write(text);
   } 
   else if (typeof console === 'object') {
     console.log(text);
   } 
   else {
     print(text);
   }
 }

Output[edit | edit source]

Number n = 1.23456789012345
String s = string
Boolean b = true

Discussion[edit | edit source]

Each code element represents:

    • // begins a comment
    • var n, s, and b define variables
    • ; ends each line of JavaScript code
    • i = , d = , s =, b = assign literal values to the corresponding variables
    • output() calls the output function
    • function output(text) defines a output function that checks the JavaScript environment and writes to the current document, the console, or standard output as appropriate.

Arithmetic[edit | edit source]

 // This program demonstrates arithmetic operations.
 
 var a;
 var b;
     
 a = 3;
 b = 2;
 output("a = " + a);
 output("b = " + b);
 output("a + b = " + (a + b));
 output("a - b = " + (a - b));
 output("a * b = " + a * b);
 output("a / b = " + a / b);
 output("a % b = " + (a % b));
 
 function output(text) {
   if (typeof document === 'object') {
     document.write(text);
   } 
   else if (typeof console === 'object') {
     console.log(text);
   } 
   else {
     print(text);
   }
 }

Output[edit | edit source]

a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1.5
a % b = 1

Discussion[edit | edit source]

Each new code element represents:

  • +, -, *, /, and % represent addition, subtraction, multiplication, division, and modulus, respectively.

Temperature[edit | edit source]

 // This program converts an input Fahrenheit temperature to Celsius.
 
 var fahrenheit;
 var celsius;
     
 output("Enter Fahrenheit temperature:");
 fahrenheit = input();
 
 celsius = (fahrenheit - 32) * 5 / 9;
 
 output(fahrenheit.toString() + "° Fahrenheit is " + celsius + "° Celsius");
 
 function input(text) {
   if (typeof window === 'object') {
     return prompt(text)
   }
   else if (typeof console === 'object') {
     const rls = require('readline-sync');
     var value = rls.question(text);
     return value;
   }
   else {
     output(text);
     var isr = new java.io.InputStreamReader(java.lang.System.in); 
     var br = new java.io.BufferedReader(isr); 
     var line = br.readLine();
     return line.trim();
   }
 }
 
 function output(text) {
   if (typeof document === 'object') {
     document.write(text);
   } 
   else if (typeof console === 'object') {
     console.log(text);
   } 
   else {
     print(text);
   }
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

Discussion[edit | edit source]

Each new code element represents:

  • function input(text) defines a function that checks the JavaScript environment and reads from the current window, the console, or standard input as appropriate.

References[edit | edit source]


Variable Examples Python

Overview[edit | edit source]

The following examples demonstrate data types, arithmetic operations, and input in Python.

Data Types[edit | edit source]

 # This program demonstrates variables, literal constants, and data types.
 
 i = 1234567890
 f = 1.23456789012345
 s = "string"
 b = True
 
 print("Integer i =", i)
 print("Float f =", f)
 print("String s =", s)
 print("Boolean b =", b)

Output[edit | edit source]

Integer i = 1234567890
Float f = 1.23456789012345
String s = string
Boolean b = true

Discussion[edit | edit source]

Each code element represents:

  • # begins a comment
  • i = , d = , s =, b = assign literal values to the corresponding variables
  • print() calls the print function

Arithmetic[edit | edit source]

 # This program demonstrates arithmetic operations.
 
 a = 3
 b = 2
 
 print("a =", a)
 print("b =", b)
 print("a + b =", (a + b))
 print("a - b =", (a - b))
 print("a * b =", a * b)
 print("a / b =", a / b)
 print("a % b =", (a % b))

Output[edit | edit source]

a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1.5
a % b = 1

Discussion[edit | edit source]

Each new code element represents:

  • +, -, *, /, and % represent addition, subtraction, multiplication, division, and modulus, respectively.

Temperature[edit | edit source]

 # This program converts an input Fahrenheit temperature to Celsius.
 
 print("Enter Fahrenheit temperature:")
 fahrenheit = float(input())
 
 celsius = (fahrenheit - 32) * 5 / 9
 
 print(str(fahrenheit) + "° Fahrenheit is " + str(celsius) + "° Celsius")

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100.0° Fahrenheit is 37.77777777777778° Celsius

Discussion[edit | edit source]

Each new code element represents:

  • input() reads the next line from standard input
  • float() converts the input to a floating-point value

References[edit | edit source]


Variable Examples Swift

Overview[edit | edit source]

The following examples demonstrate data types, arithmetic operations, and input in Swift.

Data Types[edit | edit source]

 // This program demonstrates variables, literal constants, and data types.
 
 var i: Int
 var d: Double
 var s: String
 var b: Bool
 
 i = 1234567890
 d = 1.23456789012345
 s = "string"
 b = true
 
 print("Integer i =", i)
 print("Double d =", d)
 print("String s =", s)
 print("Boolean b =", b)

Output[edit | edit source]

Integer i = 1234567890
Double d = 1.23456789012345
String s = string
Boolean b = true

Discussion[edit | edit source]

Each code element represents:

  • // begins a comment
  • var i: Int defines an integer variable named i
  • var d: Double defines a double floating-point variable named d
  • var s: String defines a string variable named s
  • var b: Bool defines a Boolean variable named b
  • i = , d = , s =, b = assign literal values to the corresponding variables
  • print() calls the print function

Arithmetic[edit | edit source]

 // This program demonstrates arithmetic operations.
 
 var a: Int
 var b: Int
 
 a = 3
 b = 2
 
 print("a =", a)
 print("b =", b)
 print("a + b =", (a + b))
 print("a - b =", (a - b))
 print("a * b =", a * b)
 print("a / b =", a / b)
 print("a % b =", (a % b))

Output[edit | edit source]

a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1
a % b = 1

Discussion[edit | edit source]

Each new code element represents:

  • +, -, *, /, and % represent addition, subtraction, multiplication, division, and modulus, respectively.

Temperature[edit | edit source]

 // This program converts a Fahrenheit temperature to Celsius.
 //
 // References:
 //    https://www.mathsisfun.com/temperature-conversion.html
 //    https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
 
 var fahrenheit: Double
 var celsius: Double
 
 print("Enter Fahrenheit temperature:")
 fahrenheit = Double(readLine()!)!
 
 celsius = (fahrenheit - 32) * 5 / 9
 
 print(String(fahrenheit) + "° Fahrenheit is " + String(celsius) + "° Celsius")

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100.0° Fahrenheit is 37.7777777777778° Celsius

Discussion[edit | edit source]

Each new code element represents:

  • readline()! reads the next line from standard input
  • Double()! converts the input to a double floating-point value
  • String() converts the output numeric value to a string

References[edit | edit source]


Practice: Data and Operators

Chapter Summary[edit | edit source]

  • Constants and Variables: In a program, a constant is a value that cannot be changed during the execution of the program. With the addition of an identifier, it can become a "named" constant. "Constant" and "Named constant" can often be used interchangeably. Example: const float PI = 3.1415927 in the program PI will always be that value no matter what the user inputs. On the other hand, you have a variable, which is a value that can be changed during the execution of the program. Example: yard = mile * 1760 in this program the output for "yard" will change depending on what the user inputs for "mile" which makes it a variable.
  • Identifier Names: When an item is declared or defined, it is identified by a name. Some examples of items that can be named are constants, variables, type definitions, and functions. These names help identify the function of the item.
  • Data Types: A data type is a classification of data that tells the compiler or interpreter how the programmer intends to use the data. There are five types:
    • Integer Data Type - Whole numbers with no fractional parts
    • Floating-Point Data - Formulaic representation of real numbers (scientific notation)
    • String Data Type - a string of characters being either a literal constant or a variable
    • Boolean Data Type - has one of two possible values (true or false)
    • Nothing Data Type - a feature of some programming languages which allows the setting of special values to indicate a missing or uninitialized value rather than using the value 0
  • Order of Operations: Mathematical rules that govern the order in which procedures (addition, multiplication, etc.) are carried out in a term.
  • Assignment: The assignment operator, which is typically an equals symbol (=), sets or changes the value of a modifiable data object, usually a variable. The operand on the left (Lvalue) of the assignment operator is the modifiable object and the operand on the right (Rvalue) is typically the value that is assigned to the modifiable object. For novice programmers, the assignment operator (=) is often confused with the relational operator (==) which is used for comparison or as a test expression. [1]

Arithmetic Operators: Arithmetic operations are functions that represent basic arithmetic. The basic arithmetic operations are addition, subtraction, multiplication, and division. All operations also follow the order of operations as well.

Integer Division and Modulus: Integer division and Modulus are when the dividend is divided by the divisor and turned into a quotient. The modulus is the remainder of the integer operation. This is because, in programs, integer values are always handled in whole units.

Unary Operations: Unary operations are operations with only one operand. The most common values of the operand are negative and positive, also known as Unary positive and Unary Negative. Unary Negative is a value that can change a sign and flip it, while Unary positive isn't able to change any values and considered worthless.

Lvalue and Rvalue: Lvalue and Rvalue are the left and right side of the assignment operator, where the Lvalue is considered to be the expression that can be modified, and the right side is a temporary expression value that can change.

Data Type Conversions: Data type conversions are when you change the value of a data type, also referred to as "type conversion". There are two types of type conversions, Implicit and Explicit. Implicit is when the change is simply implied, whereas Explicit is when a change is done with an operator or function. The value can have a Promotion when the smaller domain is changed to a bigger domain, or Demotion, where the larger domain is changed to a smaller domain.

Input-Process-Output Model: IPO(Input-Process-Output) model is a widely used approach for describing the structure of multiple programs in system analysis and software engineering. The model is designed to detect inputs and outputs and specific processing tasks that are required to turn inputs into outputs in these programs.

Review Questions[edit | edit source]

True or false:

  1. A data type defines a set of values and the set of operations that can be applied to those values.
  2. Reserved or keywords 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.
  6. Integer data types are stored with a mantissa and an exponent.
  7. Strings are identified by single quote marks in most programming languages.
  8. An operand is a value that receives the operator’s action.
  9. Arithmetic assignment is a shorter way to write some expressions.
  10. Integer division is rarely used in computer programming.
  11. The Nothing data type is the same as the value 0 (zero).
  12. A boolean data type has two or more possible values. One possibility can be a null data type.
  13. A constant can change its value.
  14. The Pascal case standard uses all lowercase letters with underscores separating words.

Answers:

  1. true
  2. false
  3. true
  4. true
  5. false – Parentheses change the order of evaluation in an expression.
  6. false
  7. false - Strings can be identified by double quotation marks as well.
  8. true
  9. true
  10. false
  11. false
  12. false - Boolean is a binary variable, only having two possible values, such as true/false.
  13. false
  14. false

Variables:
In each of the following, determine appropriate identifier names and data types:

  1. You are buying paint for a mural project in your neighborhood, so you must calculate how many gallons of paint you'll need.
  2. You want to open a savings account at a bank, but you are not sure which bank is best for you. You decide to compare each bank's interest rate to see where you'll get the most money.
  3. There is a sale at your local supermarket, and you want to know how much you saved on your purchase.
  4. You are taking a poll to see which flavor of ice cream people like most at your school.
  5. A condominium complex decides to open a pool and wants to know how many cubic feet of space they need to dig out.

Short Answer:

  1. A men’s clothing store that caters to the very rich wants to create a database for its customers that records clothing measurements. They need to record information for shoes, socks, pants, dress shirts and casual shirts. Explain how you would create a program that records this information using your new knowledge of assigning values and data types. List the steps you would take and why you would take them. HINT: You may need more than 5 data items.
  2. The sequence operator can be used when declaring multiple identifier names for variables or constants of the same data type. Is this a good or bad programming habit and why?
  3. Explain how you would correctly display something that includes two different types of data. For example, how would you display something that says "John is" + (integer variable with Johns age) " years old"?
  4. You are creating a program that converts inches to centimeters. Using the input-process-output model, list the steps required to carry out the operation.
  5. What is the correct order of operations using these 6 terms: Addition, Subtraction, Multiplication, Division, Parentheses, and Exponents?

Activities[edit | edit source]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use appropriate data types for each variable, and include separate statements for input, processing, and output. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a program to prompt the user for hours and rate per hour and then calculate and display their weekly, monthly, and annual gross pay (hours * rate).[2]
  2. Create a program that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds. For example, a person 1 year old is 12 months old, 365 days old, etc.
  3. Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then calculate and display the distance in yards, feet, and inches, or ask the user for a distance in miles, and then calculate and display the distance in kilometers, meters, and centimeters.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
  5. Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet (9 square feet) to a yard.
  6. Create a program that helps the user determine how much paint is required to paint a room and how much it will cost. Ask the user for the length, width, and height of a room, the price of a gallon of paint, and the number of square feet that a gallon of paint will cover. Calculate the total area of the four walls as 2 * length * height + 2 * width * height Calculate the number of gallons as: total area / square feet per gallon Note: You must round up to the next full gallon. To round up, add 0.9999 and then convert the resulting value to an integer. Calculate the total cost of the paint as: gallons * price per gallon.
  7. Review Wikipedia: Aging in dogs. Create a program to prompt the user for the name of their dog and its age in human years. Calculate and display the age of their dog in dog years, based on the popular myth that one human year equals seven dog years. Be sure to include the dog's name in the output, such as:
        Spike is 14 years old in dog years.

References[edit | edit source]

See Also[edit | edit source]

  1. http://flowgorithm.org/documentation/operators.htm
  2. http://flowgorithm.org/documentation/declare.htm
  3. http://flowgorithm.org/documentation/output.htm
  4. http://flowgorithm.org/documentation/types.htm
  5. http://flowgorithm.org/documentation/input.htm



Functions

Overview[edit | edit source]

This chapter introduces modular programming, functions, parameters, return values, and scope.

Chapter Outline[edit | edit source]

Learning Objectives[edit | edit source]

  1. Understand key terms and definitions.
  2. Given example pseudocode, flowcharts, and source code, create a program that uses functions, parameters, and return values to solve a given problem.


Modular Programming

Overview[edit | edit source]

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.[1]

Concept of Modularization[edit | edit source]

One of the most important concepts of programming is modularization- grouping lines of code together to create an interchangeable piece that can be used and removed from our program as needed. The original wording for this was a sub-program. Other names include: macro, sub-routine, procedure, module and function. 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 each piece (function) to do and perform tests and edit code. In this way, functions help to organize code. Generally, functions fall into two categories:

  1. Program Control – Functions used to simply sub-divide and control the program. These functions are unique to the program being written. Other programs may use similar functions, maybe even functions with the same name, but the content of the functions are almost always very different.
  2. Specific Task – Functions designed to be used with several programs. These functions perform a specific task and thus are usable in many different programs because the other programs also need to do the specific task. Specific task functions are sometimes referred to as building blocks. Because they are already coded and tested, we can use them with confidence to more efficiently write a large program.

The main program must establish the existence of functions used in that program. Depending on the programming language, there is a formal way to:

  1. define a function (its definition or the code it will execute)
  2. call a function
  3. declare a function (a prototype is a declaration to a compiler)

Note: Defining and calling functions are common activities across programming languages. Declaring functions with prototypes is specific to certain programming languages, including C and C++.

Program Control functions normally do not communicate information to each other but use a common area for variable storage. Specific Task functions are constructed so that data can be communicated between the calling program piece (which is usually another function) and the function being called. This ability to communicate data is what allows us to build a specific task function that may be used in many programs. The rules for how the data is communicated in and out of a function vary greatly by programming language, but the concept is the same. The data items passed (or communicated) are called parameters. Thus the wording: parameter passing. The four data communication options include:

  1. no communication in with no communication out
  2. no communication in with some communication out
  3. some communication in with some communication out
  4. some communication in with no communication out

Program Control Function[edit | edit source]

The main program piece in many programming languages is a special function with the identifier name of main. Function control programs are unique to one program. "Main" is a special area of the program where code execution begins, where functions are called, and where the program's execution ends. It is often the first function defined in a program, and it is the area where many of the program's important settings are defined. These settings include items such as declaration of prototypes, listing global constants and variables, as well as many other technical items. The code to define the function main is provided; however, it is not prototyped or usually called like other functions within a program.

Specific Task Function[edit | edit source]

We often have the need to perform a specific task that might be used in many programs. Specific task functions are designed to be used in many programs.

General layout of a function in a statically-typed language such as C++, C#, and Java:

<return value data type> function identifier name(<data type> <identifier name for input value>) {
    //lines of code;
    return <value>;
}

General layout of a function in a dynamically typed language such as JavaScript and Python:

function identifier name(<identifier name for input value>) {
    //lines of code;
    return <value>;
}

def function identifier name(<identifier name for input value>):
    //lines of code
    return <value>

In some programming languages, functions have a set of braces {} used for identifying a group or block of statements or lines of code. Other languages use indenting or some type of begin and end statements to identify a code block. There are normally several lines of code within a function.

Programming languages will either have specific task functions defined before or after the main function, depending on coding conventions for the given language.

When you call a function you use its identifier name and a set of parentheses. You place any data items you are passing inside the parentheses. After our program is compiled and running, the lines of code in the main function are executed, and when it gets to the calling of a specific task function, the control of the program moves to the function and starts executing the lines of code in the function. When it’s done with the lines of 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.

Program Layout[edit | edit source]

Most programs have several items before the functions, including:

  1. Documentation – Most programs have a comment area at the start of the program with a variety of comments pertinent to the program.
  2. Include or import statements used to access standard library functions.
  3. Language-specific code such as namespace references or function prototypes.
  4. Global or module-level constants and variables, when required.

Key Terms[edit | edit source]

braces
Used to identify a block of code in languages such as C++, C#, Java, and JavaScript.
function
What modules are called in many predominant programming languages of today.
function call
A function’s using or invoking of another function.
function definition
The code that defines what a function does.
function prototype
A function’s communications declaration to a compiler.
identifier name
The name given by the programmer to identify a function or other program items such as variables.
modularization
The ability to group some lines of code into a unit that can be included in our program.
parameter passing
How the data is communicated in to and out of a function.
program control
Functions used to subdivide and control the program.
specific task
Functions designed to be used with several programs.

References[edit | edit source]


Hierarchy or Structure Chart

Overview[edit | edit source]

Hierarchy or Structure chart for a program that has five functions.

The hierarchy chart (also known as a structure chart) shows the relationship between various modules. Its name mostly comes from showing the organization (or structure) of a business, with the president of the business at the top, followed by the vice president etc., continuing down until the lowest level workers are reached. Within the context of a computer program, it shows the relationship between modules (or functions). Detailed 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, almost like how a manager orders an employee to complete a task.

Hierarchy charts are created by the programmer to help document a program. They convey the big picture of the modules (or functions) used in a program.

Key Terms[edit | edit source]

hierarchy chart
Conveys the relationship or big picture of the various functions in a program.
structure chart
Another name for a hierarchy chart.

References[edit | edit source]


Function Examples

Overview[edit | edit source]

The following pseudocode and flowchart examples take the Temperature program from the previous chapter and separate the functionality into independent functions for input, processing, and output, as GetFahrenheit, CalculateCelsius, and DisplayResult, respectively.

Discussion[edit | edit source]

As independent functions, each function acts as a miniature program, with its own input, processing, and output. As you review the following code, note which functions have parameters (input) and which functions have return values (output). Parameters and return values will be discussed in the next few pages.

Function Purpose Parameters (input) Return Value (output)
Main main program none none
GetFahrenheit input none fahrenheit
CalculateCelsius processing fahrenheit celsius
DisplayResult output fahrenheit, celsius none

Pseudocode[edit | edit source]

Function Main
    ... This program asks the user for a Fahrenheit temperature, 
    ... converts the given temperature to Celsius,
    ... and displays the results.

    Declare Real fahrenheit
    Declare Real celsius
    
    Assign fahrenheit = GetFahrenheit()
    Assign celsius = CalculateCelsius(fahrenheit)
    Call DisplayResult(fahrenheit, celsius)
End

Function GetFahrenheit
    Declare Real fahrenheit
    
    Output "Enter Fahrenheit temperature:"
    Input fahrenheit
Return Real fahrenheit

Function CalculateCelsius (Real fahrenheit)
    Declare Real celsius
    
    Assign celsius = (fahrenheit - 32) * 5 / 9
Return Real celsius

Function DisplayResult (Real fahrenheit, Real celsius)
    Output fahrenheit & "° Fahrenheit is " & celsius & "° Celsius"
End

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

Flowchart[edit | edit source]

Main function flowchart GetFahrenheit function flowchart CalculateCelsius function flowchart DisplayResult function flowchart

References[edit | edit source]


Parameters and Arguments

Overview[edit | edit source]

A parameter is a special kind of variable used in a function to refer to one of the pieces of data provided as input to the function. These pieces of data are the values of the arguments with which the function is going to be called/invoked. An ordered list of parameters is usually included in the definition of a function, so that, each time the function is called, its arguments for that call are evaluated, and the resulting values can be assigned to the corresponding parameters.[1]

Discussion[edit | edit source]

Recall that the modular programming approach separates the functionality of a program into independent modules. To separate the functionality of one function from another, each function is given its own unique input variables, called parameters. The parameter values, called arguments, are passed to the function when the function is called. Consider the following function pseudocode:

Function CalculateCelsius (Real fahrenheit)
    Declare Real celsius
    
    Assign celsius = (fahrenheit - 32) * 5 / 9
Return Real celsius

If the CalculateCelsius function is called passing in the value 100, as in CalculateCelsius(100), the parameter is fahrenheit and the argument is 100. The terms parameter and argument are often used interchangeably. However, parameter refers to the variable identifier (fahrenheit) while argument refers to the variable value (100).

Functions may have no parameters or multiple parameters. Consider the following function pseudocode:

Function DisplayResult (Real fahrenheit, Real celsius)
    Output fahrenheit & "° Fahrenheit is " & celsius & "° Celsius"
End

If the DisplayResult function is called passing in the values 98.6 and 37.0, as in DisplayResults(98.6, 37.0), the argument or value for the fahrenheit parameter is 98.6 and the argument or value for the celsius parameter is 37.0. Note that the arguments are passed positionally. Calling DisplayResults(37.0, 98.6)would result in incorrect output, as the value of fahrenheit would be 37.0 and the value of celsius would be 98.6.

Some programming languages, such as Python, support named parameters. When calling functions using named parameters, parameter names and values are used, and positions are ignored. When names are not used, arguments are identified by position. For example, any of the following function calls would be valid:

CalculateCelsius(98.6, 37.0)
CalculateCelsius(fahrenheit=98.6, celsius=37.0)
CalculateCelsius(celsius=37.0, fahrenheit=98.6)

Key Terms[edit | edit source]

argument
A value provided as input to a function.
parameter
A variable identifier provided as input to a function.
A local variable in that function that will receive the value that was passed as argument when the function was called.
return
The value that a function return after it was executed, that value is stored in the variable that made the call to the function

References[edit | edit source]


Call by Value vs Call by Reference

Overview[edit | edit source]

In call by value, a parameter acts within the function as a new local variable initialized to the value of the argument (a local (isolated) copy of the argument). In call by reference, the argument variable supplied by the caller can be affected by actions within the called function.[1]

Discussion[edit | edit source]

Call by Value[edit | edit source]

Within most current programming languages, parameters are passed by value by default, with the argument as a copy of the calling value. Arguments are isolated, and functions are free to make changes to parameter values without any risk of impact to the calling function. Consider the following pseudocode:

Function Main
    Declare Real fahrenheit

    Assign fahrenheit = 100
    Output "Main fahrenheit = " & fahrenheit
    Call ChangeFahrenheit(fahrenheit)
    Output "Main fahrenheit = " & fahrenheit
End

Function ChangeFahrenheit (Real fahrenheit)
    Output "ChangeFahrenheit fahrenheit = " & fahrenheit
    Assign fahrenheit = 0
    Output "ChangeFahrenheit fahrenheit = " & fahrenheit
End

Output[edit | edit source]

Main fahrenheit = 100
ChangeFahrenheit fahrenheit = 100
ChangeFahrenheit fahrenheit = 0
Main fahrenheit = 100

In English, the Main function assigns the value 100 to the variable fahrenheit, displays that value, and then calls ChangeFahrenheit passing a copy of that value. The called function displays the argument, changes it, and displays it again. Execution returns to the calling function, and Main displays the value of the original variable. With call by value, the variable fahrenheit in the calling function and the parameter fahrenheit in the called function refer to different memory addresses, and the called function cannot change the value of the variable in the calling function.

Call by Reference[edit | edit source]

If a programming language uses or supports call by reference, the variable in the calling function and the parameter in the called function refer to the same memory address, and the called function may change the value of the variable in the calling function. Using the same code example as above, call by reference output would change to:

Main fahrenheit = 100
ChangeFahrenheit fahrenheit = 100
ChangeFahrenheit fahrenheit = 0
Main fahrenheit = 0

Programming languages that support both call by value and call by reference use some type of key word or symbol to indicate which parameter passing method is being used.

Language Call By Value Call by Reference
C++ default use &parameter in called function
C# default use ref parameter in calling and called functions
Java default applies to arrays and objects
JavaScript default applies to arrays and objects
Python default applies to arrays (lists) and mutable objects

Arrays and objects are covered in later chapters.

Key Terms[edit | edit source]

call by reference
Parameters passed by calling functions may be modified by called functions.
call by value
Parameters passed by calling functions cannot be modified by called functions.

References[edit | edit source]


Return Statement

Overview[edit | edit source]

A return statement causes execution to leave the current function and resume at the point in the code immediately after where the function was called. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.[1]

Discussion[edit | edit source]

The return statement exits a function and returns to the statement where the function was called. Most programming languages support optionally returning a single value to the calling function. Consider the following pseudocode:

Function Main
    ...
    Assign fahrenheit = GetFahrenheit()
    ...
End

Function GetFahrenheit
    Declare Real fahrenheit
    
    Output "Enter Fahrenheit temperature:"
    Input fahrenheit
Return Real fahrenheit

In English, the Main function calls the GetFahrenheit function, passing in no parameters. The GetFahrenheit function retrieves input from the user and returns that input back to the main function, where it is assigned to the variable fahrenheit. In this example, the Main function has no return value.

Note that functions are independent, and each function must declare its own variables. While both functions have a variable named fahrenheit, they are not the same variable. Each variable refers to a different location in memory. Just as parameters by default are passed by position rather than by name, return values are also passed by position rather than by name. The following code would generate the same results.

Function Main
    ...
    Assign fahrenheit = GetTemperature()
    ...
End

Function GetTemperature
    Declare Real temperature
    
    Output "Enter Fahrenheit temperature:"
    Input temperature
Return Real temperature

Most programming languages support either zero or one return value from a function. There are some older programming languages where return values are not supported. In those languages, the modules are often referred to as subroutines rather than functions. There are also programming languages that support multiple return values in a single return statement, however, only single return values or no return value will be used in this book.

Key Terms[edit | edit source]

return
A branching control structure that causes a function to jump back to the function that called it.

References[edit | edit source]


Void Data Type

Overview[edit | edit source]

The void data type, similar to the Nothing data type described earlier, is the data type for the result of a function that returns normally, but does not provide a result value to its caller. Void is not the same as zero, void is not a number and cannot be in calculations.[1]

Discussion[edit | edit source]

The void data type has no values and no operations. It’s a data type that represents the lack of a data type.

Language Reserved Word
C++ void
C# void
Java void
JavaScript void
Python N/A
Swift Void

Many programming languages need a data type to define the lack of return value to indicate that nothing is being returned. The void data type is typically used in the definition and prototyping of functions to indicate that either nothing is being passed in and/or nothing is being returned.

In C and Java[2], the void data type is required. In C++, the void can be used in a function's parameter list if it does not need to return a value.

Key Terms[edit | edit source]

void data type
A data type that has no values or operators and is used to represent nothing.

References[edit | edit source]


Scope

Overview[edit | edit source]

The scope of an identifier name binding – an association of a name to an entity, such as a variable – is the region of a computer program where the binding is valid: where the name can be used to refer to the entity. Such a region is referred to as a scope block. In other parts of the program, the name may refer to a different entity (it may have a different binding), or to nothing at all (it may be unbound).[1]

Discussion[edit | edit source]

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 variables with global scope are placed near the top of the source code before any functions. This way they are available to all of the functions.

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.

Scope is an important concept for modularization. Program control functions may use global scope for variables and constants placing them near the top of the program before any functions. Specific task functions use only local scope variables by passing data as needed into the function with parameter passing and creating local variables and constants as needed. Any information that needs to be communicated back to the calling function is again done via parameter passing. This closed communications model that passes all data into and out of a function creates an important predecessor concept for encapsulation which is used in object-oriented programming.

Key Terms[edit | edit source]

data area
A part of an object code file used for storage of data.
global scope
Data storage defined outside of a function.
local scope
Data storage defined inside of a function.
scope
The area of a source code file where an identifier name is recognized.
stack
A part of the computer’s memory used for storage of data.

References[edit | edit source]


Programming Style

Credit: https://www.python-course.eu/python3_blocks.php Python Indent Coding
Python Indent Coding[1]

Overview[edit | edit source]

Programming style is a set of rules or guidelines used when writing the source code for a computer program. Following a particular programming style will help programmers read and understand source code conforming to the style, and help to avoid introducing errors.[2] Each language has its own set of rules. It is important to follow the correct guidelines to make sure the code functions properly. For example, Javascript doesn't necessarily need an indent inside of a function. It is good practice to indent so it is visible to the user. In python, code must be indented for the program to run.

Discussion[edit | edit source]

Within the programming industry there is a desire to make software programs easy to maintain. The desire centers on money. Simply put, it costs less money to maintain a well written program. One important aspect of program maintenance is making source code listings clear and as easy to read as possible. To that end we will consider the following:

  1. Documentation
  2. Vertical Alignment
  3. Comments
  4. Indentation
  5. Meaningful Identifier Names Consistently Typed
  6. Appropriate use of Typedef

The above items are not needed in order for the source code to compile. Technically the compiler does not read the source 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 run) and what is okay (acceptable good programming practice that leads to readable code).

For each of these items, check style guides for your selected programming language to determine standards and best practices. The following are general guidelines to consider.

Documentation[edit | edit source]

Documentation is usually placed at the top of the program using several comment lines. The amount of information would vary based on the requirements or standards of the company who is paying its employees or independent contractors to write the code.

Vertical Alignment[edit | edit source]

You see this within the documentation area. All of the items are aligned up within the same column. This vertical alignment occurs again when variables are defined. When declaring variables or constants many textbooks put several items on one line; like this:

float  length, width, height;

However common this is in textbooks, it would generally not be acceptable to standards used in most companies. You should declare each item on its own line; like this:

float  length;
float  width;
float  height;

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.

The lines of code inside functions are also aligned vertically and typically indented two or four spaces from the left. The indentation helps set the block off visually.

Comments[edit | edit source]

Experts have varying viewpoints on whether, and when, comments are appropriate in source code. Some assert that source code should be written with few comments, on the basis that the source code should be self-explanatory or self-documenting. Others suggest code should be extensively commented, with over 50% of the non-whitespace characters in source code being contained within comments).[3]

In between these views is the assertion that comments are neither beneficial nor harmful by themselves, and what matters is that they are correct and kept in sync with the source code, and omitted if they are superfluous, excessive, difficult to maintain or otherwise unhelpful.[4]

In addition comments are not supposed to be to long. You can change the length by having the comment in several lines or create multi line comments by adding adding a delimiter.

All comments should be specific about what a certain part of a program is supposed to do. It is important that you comment is understandable and simple to anyone who reads to make it easier for yourself or others.

Indentation[edit | edit source]

For languages that use curly braces, there are two common indentation styles:

function(parameters) {
    // code
}
function(parameters)
{
    // code
}

In either case, it is important to maintain vertical alignment between the start of the code block and the closing curly brace.

The number of spaces used for indenting blocks of code is typically two or four spaces. Care should be taken to ensure that the IDE or code editor inserts spaces rather than tab characters for indents.

Meaningful Identifier Names Consistently Typed[edit | edit source]

As the name implies “identifier names” should clearly identify who (or what) you are talking about. Calling your spouse “Snooky” may be meaningful only to you. It’s why referring to your spouse as “Snooky” to other people like interviewers at a potential place of employment could lead to confusion, questions and even the false rumor you’re in love with Nicki Minaj. If you don't say a name that has meaning to people, everyone will come up with their own idea of what the name refers too whenever that idea is true or not. This is why most people 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, and other identifiers should use meaningful 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.

A good rule of thumb for identifiers in procedural programs (as opposed to object-oriented programs) is to use verb-noun combinations for function identifiers and use noun or adjective-noun combinations for constant and variable identifiers. If a function name requires two verbs or two nouns to fully describe the function, it should probably be split into separate functions.

Key Terms[edit | edit source]

braces
Used to identify a block of code in languages such as C++, C#, Java, and JavaScript.
consistent
A rule that says to type identifier names in upper and lower case consistently throughout your source code.
comments
Information inserted into a source code file for documentation of the program.
documentation
A method of preserving information useful to others in understanding an information system or part thereof.
indention
A method used to make sections of source code more visible.
meaningful
A rule that says identifier names must be easily understood by another reading the source code.
vertical alignment
A method of listing items vertically so that they are easier to read quickly.

References[edit | edit source]


Standard Libraries

Overview[edit | edit source]

Many common or standard functions, whose definitions have already been written, are ready to be used in any program. They are organized into a group of functions (think of them as several books) and are collectively called a standard library. There are many functions organized into several libraries For example, within most programming languages many math functions exist and have been coded (and placed into libraries). These functions were written by programmers and tested to ensure that they work properly. In most cases, the functions were reviewed by several people to double and triple check to ensure that they did what was expected. We have the advantage of using these functions with confidence that they will work properly in our programs, thus saving us time and money.

Discussion[edit | edit source]

The main program must establish the existence of functions used in that program. Depending on the programming language, there is a formal way to:

  1. define a function
  2. declare a function (a prototype is a declaration to a compiler)
  3. call a function

When we create functions in our program, we usually see them in the following order in our source code listing:

  1. declare the function (prototype)
  2. call the function
  3. define the function

When we use functions created by others that have been organized into a 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. calling the function (with parameter passing of values)
  3. defining 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.

Language Example
C++ #include <cmath>std::abs(number);
C# Math.Abs(number);
Java Java.lang.Math.abs(number)
JavaScript Math.abs(number);
Python abs(number)
Swift abs(number)

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. 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).

Key Terms[edit | edit source]

abs
A function within a standard library which stands for absolute value.
confidence
The reliance that Standard Library functions work properly.
standard library
A set of specific task functions that have been added to the programming language for universal use.

References[edit | edit source]


Function Examples C++

Temperature[edit | edit source]

 // This program asks the user for a Fahrenheit temperature, 
 // converts the given temperature to Celsius,
 // and displays the results.
 //
 // References:
 // https://www.mathsisfun.com/temperature-conversion.html
 // https://en.wikibooks.org/wiki/C%2B%2B_Programming
 
 #include <iostream>
 
 using namespace std;
 
 double getFahrenheit();
 double calculateCelsius(double);
 void displayResult(double, double);
 
 int main() {
     double fahrenheit;
     double celsius;
     
     fahrenheit = getFahrenheit();
     celsius = calculateCelsius(fahrenheit);
     displayResult(fahrenheit, celsius);
     
     return 0;
 }
 
 double getFahrenheit() {
     double fahrenheit;
     
     cout << "Enter Fahrenheit temperature:" << endl; 
     cin >> fahrenheit;
     
     return fahrenheit;
 }
 
 double calculateCelsius(double fahrenheit) {
     double celsius;
     
     celsius = (fahrenheit - 32) * 5 / 9;
     
     return celsius;
 }
 
 void displayResult(double fahrenheit, double celsius) {
     cout << fahrenheit << "° Fahrenheit is " 
         << celsius << "° Celsius" << endl;
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7778° Celsius

References[edit | edit source]


Function Examples CSharp

Temperature[edit | edit source]

 // This program asks the user for a Fahrenheit temperature, 
 // converts the given temperature to Celsius,
 // and displays the results.
 //
 // References:
 // https://www.mathsisfun.com/temperature-conversion.html
 // https://en.wikibooks.org/wiki/C_Sharp_Programming
 
 using System;
 
 class Temperature 
 {
     public static void Main (string[] args) 
     {
         double fahrenheit;
         double celsius;
         
         fahrenheit = GetFahrenheit();
         celsius = CalculateCelsius(fahrenheit);
         DisplayResult(fahrenheit, celsius);
     }
 
     private static double GetFahrenheit()
     {
         string input;
         double fahrenheit;
         
         Console.WriteLine("Enter Fahrenheit temperature:");
         input = Console.ReadLine();
         fahrenheit = Convert.ToDouble(input);
 
         return fahrenheit;
     }
 
     private static double CalculateCelsius(double fahrenheit)
     {
         double celsius;
         
         celsius = (fahrenheit - 32) * 5 / 9;
         
         return celsius;
     }
 
     private static void DisplayResult(double fahrenheit, double celsius)
     {
         Console.WriteLine(fahrenheit.ToString() + "° Fahrenheit is " +
             celsius.ToString() + "° Celsius");
     }
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

References[edit | edit source]


Function Examples Java

Temperature[edit | edit source]

 // This program asks the user for a Fahrenheit temperature, 
 // converts the given temperature to Celsius,
 // and displays the results.
 //
 // References:
 // https://www.mathsisfun.com/temperature-conversion.html
 // https://en.wikibooks.org/wiki/Java_Programming
 
 import java.util.*;
 
 class Main {
     private static Scanner input = new Scanner(System.in);
 
     public static void main(String[] args) {
         double fahrenheit;
         double celsius;
         
         fahrenheit = getFahrenheit();
         celsius = calculateCelsius(fahrenheit);
         displayResult(fahrenheit, celsius);
     }
 
     private static double getFahrenheit() {
         double fahrenheit;
         
         System.out.println("Enter Fahrenheit temperature:");
         fahrenheit = input.nextDouble();
         
         return fahrenheit;
     }
 
     private static double calculateCelsius(double fahrenheit) {
         double celsius;
         
         celsius = (fahrenheit - 32) * 5 / 9;
         
         return celsius;
     }
 
     private static void displayResult(double fahrenheit, double celsius) {
         System.out.println(fahrenheit + "° Fahrenheit is " + 
             celsius + "° Celsius");
     }
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

References[edit | edit source]


Function Examples JavaScript

Temperature[edit | edit source]

 // This program asks the user for a Fahrenheit temperature,
 // converts the given temperature to Celsius,
 // and displays the results.
 //
 // References:
 // https://www.mathsisfun.com/temperature-conversion.html
 // https://en.wikibooks.org/wiki/JavaScript
 
 main();
 
 function main() {
   var fahrenheit = getFahrenheit();
   var celsius = calculateCelsius(fahrenheit);
   displayResult(fahrenheit, celsius);
 }
 
 function getFahrenheit() {
   var fahrenheit = input("Enter Fahrenheit temperature:");
   return fahrenheit;
 }
 
 function calculateCelsius(fahrenheit) {
   var celsius = (fahrenheit - 32) * 5 / 9;
   return celsius;
 }
 
 function displayResult(fahrenheit, celsius) {
   output(fahrenheit + "° Fahrenheit is " + 
     celsius + "° Celsius");
 }
 
 function input(text) {
   if (typeof window === 'object') {
     return prompt(text)
   }
   else if (typeof console === 'object') {
     const rls = require('readline-sync');
     var value = rls.question(text);
     return value;
   }
   else {
     output(text);
     var isr = new java.io.InputStreamReader(java.lang.System.in); 
     var br = new java.io.BufferedReader(isr); 
     var line = br.readLine();
     return line.trim();
   }
 }
 
 function output(text) {
   if (typeof document === 'object') {
     document.write(text);
   } 
   else if (typeof console === 'object') {
     console.log(text);
   } 
   else {
     print(text);
   }
 }

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

References[edit | edit source]


Function Examples Python

Temperature[edit | edit source]

 # This program asks the user for a Fahrenheit temperature, 
 # converts the given temperature to Celsius,
 # and displays the results.
 #
 # References:
 # https://www.mathsisfun.com/temperature-conversion.html
 # https://en.wikibooks.org/wiki/Python_Programming
 
 
 def get_fahrenheit():
     print("Enter Fahrenheit temperature:")
     fahrenheit = float(input())
     return fahrenheit
 
 
 def calculate_celsius(fahrenheit):
     celsius = (fahrenheit - 32) * 5 / 9
     return celsius
 
 
 def display_result(fahrenheit, celsius):
     print(str(fahrenheit) + "° Fahrenheit is " + 
         str(celsius) + "° Celsius")
 
 
 def main():
     fahrenheit = get_fahrenheit()
     celsius = calculate_celsius(fahrenheit)
     display_result(fahrenheit, celsius)
 
 
 main()

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100.0° Fahrenheit is 37.77777777777778° Celsius

References[edit | edit source]


Function Examples Swift

Temperature[edit | edit source]

 // This program asks the user for a Fahrenheit temperature, 
 // converts the given temperature to Celsius,
 // and displays the results.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
 
 func getFahrenheit() -> Double {
     var fahrenheit: Double
     
     print("Enter Fahrenheit temperature:")
     fahrenheit = Double(readLine(strippingNewline: true)!)!
     
     return fahrenheit
 }
 
 func calculateCelsius(fahrenheit: Double) -> Double {
     var celsius: Double
     
     celsius = (fahrenheit - 32) * 5 / 9
     
     return celsius
 }
 
 func displayResult(fahrenheit: Double, celsius: Double) {
     print(String(fahrenheit) + "° Fahrenheit is " + String(celsius) + "° Celsius")
 }
 
 func main() {
     var fahrenheit: Double
     var celsius: Double
     
     fahrenheit = getFahrenheit()
     celsius = calculateCelsius(fahrenheit:fahrenheit)
     displayResult(fahrenheit:fahrenheit, celsius:celsius)
 }
 
 main()

Output[edit | edit source]

Enter Fahrenheit temperature:
 100
100.0° Fahrenheit is 37.7777777777778° Celsius

References[edit | edit source]


Practice: Functions

Chapter Summary[edit | edit source]

  • Modular Programming - A software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.[1]
  • Hierarchy or Structure Chart - Conveys the relationship or big picture of the various functions in a program.
  • Function Examples
  • Parameters and Arguments - A parameter is a special kind of variable used in a function to refer to one of the pieces of data provided as input to the function. These pieces of data are the values of the arguments with which the function is going to be called/invoked.
  • Call by Value vs Call by Reference - Parameters can be passed by two different methods depending on the language.
    • Call by Value passes parameters as copies of the original value creating a second location in memory, which is essentially a new local variable. Any changes made to a Call by Value parameter only affect the passed in value and not the value passed in by the caller. This is the most common method that is used by most modern programming languages.
    • Call by Reference passes in the parameter using a single memory location which essentially passes in the original parameter from the calling function. Any changes made to a Call by Reference parameter by the called function also changes the value of that parameter in the calling function.[2]
  • Return Statement - Causes the result of a function to leave the current function and resume at the point in the code immediately after where the function was called.
  • Void Data Type - A data type that has no values or operators and is used to represent nothing.
  • Scope - The area of a source code file where an identifier name is recognized.
  • Programming Style - A set of rules or guidelines used when writing the source code for a computer program.
  • Standard Libraries - Common functions whose definitions have already been written that are ready to be used in any program.

Review Questions[edit | edit source]

True / False[edit | edit source]

  1. In addition to the term function as the name of a subprogram, the computer industry also uses macro, procedure and module.
  2. Generally, functions fall into two categories: Program Control and Specific Task.
  3. Functions must always have a return value.
  4. Hierarchy Charts and Structure Charts are basically the same thing.
  5. Program Control functions are used to simply subdivide and control the program.
  6. The void data type is rarely used in C++.
  7. Making source code readable is only used by beginning programmers.
  8. User-defined specific task functions are usually placed into a user-defined library.
  9. Local and global data storage is associated with the concept of scope.
  10. Creating a header file for user-defined specific task functions is a difficult task.
  11. The stack is part of the computer’s memory used for storage of data.
  12. The standard library is a set of specific task functions that have been added to the programming language for universal use.
  13. Programmers should have confidence that standard library functions work properly.
  14. It would be easier to write programs without using specific task functions.
  15. In order to separate the functionality of one function from another, you need to give each function its own parameters.
  16. Call-by-value evaluates arguments and passes a copy of the value to the subroutine.
  17. All functions should be called from "Output" because "Output" needs to call information from the other functions to get the correct output.
  18. Functions can only return 1 output.

Answers:

  1. true
  2. true
  3. false - Functions do not always need a return value, if the function is not going to jump back to the function that called it, then there is no need for a return value.
  4. true - Both names come from showing the organization / structure of a business, or the relationship between various modules.
  5. true
  6. false - The void can be used in a function's parameter list if it does not feed to return a value in C++.
  7. false - Making source code readable should be a priority for all programmers.
  8. true
  9. true
  10. false – It may seem difficult at first, but with a little practice it is really quite easy.
  11. true
  12. true
  13. true
  14. false - That may be the case in very simple code, but when the programs becomes complicated it becomes crucial to use functions.
  15. true
  16. true
  17. false - All functions should be called from main, because main is in charge of the other functions.
  18. true - only Python has the ability to return multiple variables from a single function.

Short Answer[edit | edit source]

  1. Create a hierarchy chart for the function example program found in this chapter.
  2. Review the programs you have already created for this course. Based on coding standards for your selected programming language, identify some problems that make your code “undocumented”, “unreadable” or wrong in some other way.
  3. Describe the differences between the local scope and the global scope.
  4. Think about when you are creating a function that requires more than one parameter to be passed in. Then when calling that function, in what order do you place those parameters and why?
  5. In your own words describe the difference between calling by value and calling by reference.
  6. Explain the differences between the void data type and the Nothing data type.
  7. Explain why having multiple functions in a program is more useful than having everything in the Main() function.

Activities[edit | edit source]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a program to prompt the user for hours and rate per hour and then calculate and display their weekly, monthly, and annual gross pay (hours * rate). Base monthly and annual calculations on 12 months per year and 52 weeks per year.[3]
  2. Create a program that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds. For example, a person 1 year old is 12 months old, 365 days old, etc.
  3. Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then calculate and display the distance in yards, feet, and inches, or ask the user for a distance in miles, and then calculate and display the distance in kilometers, meters, and centimeters.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
  5. Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet (9 square feet) to a yard.
  6. Create a program that helps the user determine how much paint is required to paint a room and how much it will cost. Ask the user for the length, width, and height of a room, the price of a gallon of paint, and the number of square feet that a gallon of paint will cover. Calculate the total area of the four walls as 2 * length * height + 2 * width * height Calculate the number of gallons as: total area / square feet per gallon Note: You must round up to the next full gallon. To round up, add 0.9999 and then convert the resulting value to an integer. Calculate the total cost of the paint as: gallons * price per gallon.
  7. Review Wikipedia: Aging in dogs. Create a program to prompt the user for the name of their dog and its age in human years. Calculate and display the age of their dog in dog years, based on the popular myth that one human year equals seven dog years. Be sure to include the dog's name in the output, such as:
        Spike is 14 years old in dog years.

References[edit | edit source]


Conditions

Overview[edit | edit source]

This chapter introduces conditions and selection control structures.

Chapter Outline[edit | edit source]

Learning Objectives[edit | edit source]

  1. Understand key terms and definitions.
  2. Given example pseudocode, flowcharts, and source code, create a program that uses conditions and selection control structures to solve a given problem.


Structured Programming

Overview[edit | edit source]

Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of:

This is in contrast to using simple tests and jumps such as the "go to" statement, which can lead to “spaghetti code”; code that is potentially difficult to follow and maintain.[1]

Discussion[edit | edit source]

One of the most important concepts of programming is the ability to control a program so that different lines of code are executed. 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 three main categories of control structures:

Sequence – Sequence is code that is the most familiar and easiest to read. The code is read in an a to z order. Think of reading a book. You read chapter to chapter in sequential order.

<script>
    var a = 1;
    var b = 2;
    var c = 3;
    a = b;
    c = a;
<script>

Selection – Select between two or more conditions. The choice is decided by asking a question. The answer determines the path to be executed.

<script>
    var a = 1;
    var b = 2;
    if (a         {
        var text = I know a < b, its a bit obvious;
        document.getElementById(demo).innerHTML =text;
        }
</script>

Iteration – Also known as repetition, it allows some code s) to be executed or repeated several times. The code might not be executed at all, executed a fixed number of times or executed indefinitely until some condition has been met. Iteration is also known as looping because the code shows the flow looping back to repeat the task. For example, a while loop is used to repeat back based on what condition is asked.

<script>
    var a = 0;
    var b = 10;
    result = a < b;
    text =  ;
    while(a < b)
        {
        text += result + <br>;
        a++;
        }
    document.getElementById(demo).innerHTML = text;
</script>

Branching – An uncontrolled structure that allows the flow of execution to jump to a different part of the program. This category is rarely used in modular structured programming. For example, and if/else statement depending on the condition.

<script>
var x="";
var time=new Date().getHours();
if (time<20)
  {x="Have Good day";
  }
else
  {x="Have Good evening";
  }
document.write(x);
</script>

All high-level programming languages have control structures. All languages have the first three categories of control structures (sequence, selection, and iteration). Most have the if then else structure (which belongs to the selection category) and the while structure (which belongs to the iteration category). After these two basic structures, there are usually language variations.

The concept of structured programming started in the late 1960’s with an article by Edsger Dijkstra. He proposed a “go to less” method of planning programming logic that eliminated the need for the branching category of control structures. The topic was debated for about 20 years. But ultimately – “By the end of the 20th century nearly all computer scientists were convinced that it is useful to learn and apply the concepts of structured programming.”[2]

Key Terms[edit | edit source]

branching
An uncontrolled structure that allows the flow of execution to jump to a different part of the program.
control structures
Mechanisms that allow us to control the flow of execution within a program.
iteration
A control structure that allows some lines of code to be executed many times.
selection
A control structure where the program chooses between two or more options.
sequence
A control structure where the program executes the items in the order listed.
spaghetti code
A phrase that is used to express disapproval for source code that is unstructured and difficult to maintain.[3]
structured programming
A method of planning programs that avoids the branching category of control structures.

References[edit | edit source]


Selection Control Structures

Overview[edit | edit source]

In selection control structures, conditional statements perform different computations or actions depending on whether a programmer-specified Boolean condition evaluates to true or false.[1]

Discussion[edit | edit source]

The basic attribute of a selection control structure is to be able to select between two or more alternate paths. This is described as either two-way selection or multi-way selection. A question using Boolean concepts usually controls which path is selected. All of the paths from a selection control structure join back up at the end of the control structure, before moving on to the next lines of code in a program.

If Then Else Control Structure[edit | edit source]

The if then else control structure is a two-way selection.

If age > 17
    Output "You can vote."
False:
    Output "You can't vote."
End
Language Reserved Words
C++ if, else
C# if, else
Java if, else
JavaScript if, else
Python if, elif, else
Swift if, else

Case Control Structure[edit | edit source]

The case control structure is a multi-way selection. Case control structures compare a given value with specified constants and take action according to the first expression to match.[2]

Case of age
    0 to 17   Display "You can't vote."
    18 to 64  Display "You're in your working years."
    65 +      Display "You should be retired."
End
Language Reserved Words
C++ switch, case, break, default
C# switch, case, break, default
Java switch, case, break, default
JavaScript switch, case, break, default
Python N/A
Swift switch, case, break (optional), default

Python does not support a case control structure. There are workarounds, but they are beyond the scope of this book.

Key Terms[edit | edit source]

if then else
A two-way selection control structure.
case
A multi-way selection control structure.

References[edit | edit source]


If Then Else

Overview[edit | edit source]

The if–then–else construct, sometimes called if-then, is a two-way selection structure common across many programming languages. Although the syntax varies from language to language, the basic structure looks like:[1]

If (boolean condition) Then
    (consequent)
Else
    (alternative)
End If

Discussion[edit | edit source]

The "if then else' control structure, from the selection category, is available in every high level language. The structure is controlled by asking a question that has a true or false answer. Review the example below:

if the answer to the question is true
    then do this
else because it is false
    do this

In most languages, the question (called a test expression) is a Boolean expression. The Boolean data type has two values – true and false. Let’s rewrite the structure to consider this:

if expression is true
    then do this
else because it is false
    do this

Some languages use reserved words of: “if”, “then” and “else”. Many eliminate the “then”. Additionally the “do this” can be tied to true and false. You might see it as:

if expression is true
    action true
else
    action false

And most languages infer the “is true” you might see it as:

if expression
    action true
else
    action false

The above four forms of the control structure are saying the same thing. The else word is often not used in our English speaking today. However, consider the following conversation between a mother and her child.

Child asks, “Mommy, may I go outside and play?”

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.

One Choice – Implied Two-Way Selection[edit | edit source]

Often the programmer will want to do something only if the expression is true, that is with no false action. The lack of a false action is also referred to as a “null else” and would be written as:

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

Key Terms[edit | edit source]

if then else
A two-way selection control structure.
mutually exclusive
Items that do not overlap. Example: true or false.

References[edit | edit source]


Code Blocks

Overview[edit | edit source]

A code block, sometimes referred to as a compound statement, is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements. A programming language that permits the creation of blocks, including blocks nested within other blocks, is called a block-structured programming language. Blocks are fundamental to structured programming, where control structures are formed from blocks.[1]

Discussion[edit | edit source]

The Need for a Compound Statement[edit | edit source]

Within many programming languages, there can be only one statement listed as the action part of a control structure:

if (expression)
    statement
else
    statement

Often, we will want to do more than one statement. This problem is overcome by creating a code block or compound statement. For programming languages that use curly braces {} to designate code blocks, a compound if-then-else statement would be similar to:

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 programming industry encourages the use of indentation (to see the action parts clearly) and the use of compound statements (braces) always, even when there is only one statement. Thus:

if(expression)
{
    statement;
}
else
{
    statement;
}

By writing code in this manner, if the programmer modifies the code by adding more statements to either the action true or the action false; they will not introduce either compiler or logic errors. Using indentation and braces should become standard practice in any language that requires the use of compound statements with control structures.

Indentation and End Block[edit | edit source]

Other programming languages require explicit designation of code blocks through either indentation or some type of end block statement. For example, Python uses indentation to indicate the statements in a code block:

if expression:
    statement
    statement
else:
    statement
    statement

Lua uses an end block reserved word:

if expression then
    statement
    statement
else
    statement
    statement
end

The general if-then-else structure in each of these programming languages is similar, as is the required or expected indentation. The difference is in the syntax used to designate the code blocks.

Key Terms[edit | edit source]

block
Another name for a compound statement.
compound statement
A unit of code consisting of one or more statements.

References[edit | edit source]


Relational Operators

Overview[edit | edit source]

A relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality (e.g., 5 = 5) and inequalities (e.g., 4 ≥ 3).[1]

Discussion[edit | edit source]

Relational operators give a Boolean value (data type that has one of two possible values to represent the two truths of logic) by evaluating the relationship between two operands.

Operator symbols and/or names can vary with different programming languages. Most programming languages use relational operators similar to the following:

Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equality (equal to)
!= or <> inequality (not equal to)

Examples:

  • 9 < 25
  • 9 < 3
  • 9 > 14
  • 9 <= 17
  • 9 >= 25
  • 9 == 13
  • 9 != 13
  • 9 !< 25
  • 9 <> 25

Note: Be careful. In math you are familiar with using the symbol = to mean equal and ≠ to mean not equal, but in many programming languages the ≠ is not used and the = symbol means assignment.

Key Terms[edit | edit source]

relational operator
An operator that gives a Boolean value by evaluating the relationship between two operands.

References[edit | edit source]


Assignment vs Equality

Overview[edit | edit source]

Assignment sets and/or re-sets the value stored in the storage location denoted by a variable name.[1] Equality is a relational operator that tests or defines the relationship between two entities.[2]

Discussion[edit | edit source]

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 many programming languages, each data type can be used as a Boolean expression because each data type can be demoted into a Boolean value by using the rule/concept that zero and nothing represent false and all non-zero values represent true.

Within various languages, 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 typically means assignment. To get the equality concept of math we often use two equal symbols to represent the relational operator of equality. Let’s consider:

If (pig = 'y')
    Output "Pigs are good"
Else
    Output "Pigs 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. The correct syntax for a Boolean expression is:

If (pig == 'y')
    Output "Pigs are good"
Else
    Output "Pigs are bad."

This example reminds you that you must be careful in creating your test expressions so that they are indeed a question, usually involving the relational operators. Some programming languages will generate a warning or an error when an assignment is used in a Boolean expression, and some do not.

Don’t get caught using assignment for equality.

Key Terms[edit | edit source]

assignment
Sets or resets the value of a variable.
equality
Tests or defines the relationship between values.

References[edit | edit source]


Logical Operators

Overview[edit | edit source]

A logical operator is a symbol or word used to connect two or more expressions such that the value of the compound expression produced depends only on that of the original expressions and on the meaning of the operator.[1] Common logical operators include AND, OR, and NOT.

Discussion[edit | edit source]

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.

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. 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:

Language AND OR NOT
C++ && || !
C# && || !
Java && || !
JavaScript && || !
Python and or not
Swift && || !

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:

6 > 4 && 2 <= 14

6 > 4 and 2 <= 14

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:

true && true

True and True

The final evaluation of the expression is: true.

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.

When forming logical expressions programmers often use parentheses (even when not technically needed) to make the logic of the expression very clear. Consider the above complex Boolean expression rewritten:

(6 > 4) && (2 <= 14)

(6 > 4) and (2 <= 14)

Most programming languages recognize any non-zero value as true. This makes the following a valid expression:

6 > 4 && 8

6 > 4 and 8

But remember the order of operations. In English, this is six is greater than four and eight is not zero. Thus:

true && true

True and True

To compare 6 to both 4 and 8 would instead be written as:

6 > 4 && 6 > 8

6 > 4 and 6 > 8

This would evaluate to false as:

true && false

True and False

Truth Tables[edit | edit source]

A common way to show logical relationships is in truth tables.

Logical AND
x y x and y
false false false
false true false
true false false
true true true
Logical OR
x y x or y
false false false
false true true
true false true
true true true
Logical NOT
x not x
false true
true false

Examples[edit | edit source]

Take a look at the following hypothetical scenarios:

AND:

A mother tells her son, he must clean his room AND do his homework to go outside. If the son only does one of the tasks his mother asks of him, he will not be allowed outside because he has failed to complete the other task. 

Remember from this lesson that when using an 'AND' statement the same logic applies, the program will not run the statement associated with the true condition, unless all conditions in an 'AND' statement are true.

OR:

Karen is told she can get an 'A' if she writes an essay OR successfully hacks into the class gradebook. By saying OR the teacher has given Karen two possible ways to get an 'A'. Each way is entirely independent from the other so she does not have to do both tasks to get an 'A' only one. 

Remember from this lesson that when using an 'OR' statement only one of the conditions listed in the statement has to be true in order to get the statement associated with the true condition to run.

NOT:

Mark is told he can only go to the club if he's NOT Steve. This is due to Steve being banned from the club for rowdy behavior. While Mark and Steve look a like, they are not the same person. Mark proves this by showing the bouncer his 'I.D.'. Since Mark is NOT Steve the bouncer lets him in and for the rest of the night he has a great time.

Remember from this lesson that when using a 'NOT' statement the program will consider any value that is equal to the value of the listed statement as false. Only conditions that do 'NOT' equal, the statements value will run as true.


Makes sense right? Hopefully you can apply this to the following expression examples listed below.

Examples:

  • 25 < 7 || 15 > 36
  • 15 > 36 || 3 < 7
  • 14 > 7 && 5 <= 5
  • 4 > 3 && 17 <= 7
  • ! false
  • ! (13 != 7)
  • 9 != 7 && ! 0
  • 5 > 1 && 7

More examples:

  • 25 < 7 or 15 > 36
  • 15 > 36 or 3 < 7
  • 14 > 7 and 5 <= 5
  • 4 > 3 and 17 <= 7
  • not False
  • not (13 != 7)
  • 9 != 7 and not 0
  • 5 > 1 and 7


Key Terms[edit | edit source]

logical operator
An operator used to create complex Boolean expressions.
test expression
Also known as a Boolean expression.
truth tables
A common way to show logical relationships.

References[edit | edit source]


Nested If Then Else

Overview[edit | edit source]

Two-way selection structures may be nested inside other two-way selection structures, resulting in multi-way selection.

Discussion[edit | edit source]

We are going to first introduce the concept of nested control structures. Nesting is a concept that places one item inside of another. Consider:

if expression
    true action
else 
    false action

This is the basic form of the if then else control structure. Now consider:

if age is less than 18
    you can't vote
    if age is less than 16
        you can't drive
    else
        you can drive
else 
    you can vote
    if age is less than 21
        you can't drink 
    else
        you can drink

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[edit | edit source]

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. To simplify the code structure, this is most often written as:

if age equal to 18
    you can now vote
else if age equal to 39
    you are middle-aged 
else if age equal to 65
    you can consider retirement
else
    your age is unimportant

Key Terms[edit | edit source]

multiway selection
Using control structures to be able to select from more than two choices.
nested control structures
Placing one control structure inside of another.

References[edit | edit source]


Case Control Structure

Overview[edit | edit source]

A case or switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.[1]

Discussion[edit | edit source]

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 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 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 wherein 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.

Code to Accomplish Multiway Selection[edit | edit source]

Python does not support a case control structure. But using the same example as above, here is C++ / C# / Java / JavaScript / Swift code to accomplish the case control structure.

switch (age)
{
    case 18:
        message = "You can vote.";
        break;
    case 39:
        message = "You're middle-aged.";
        break;
    case 65:
        message = "Consider retirement.";
        break;
    default:
        message = "Age is unimportant.";
        break;
}

The value in the variable age is compared to the first “case," 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 message is assigned the value “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.

Many programming languages 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):

switch (choice)
{
    case 'A':
        message = "You are an A student.";
        break;
    case 'B':
        message = "You are a B student.";
        break;
    case 'C':
        message = "You are a C student.";
        break;
    default:
        message = "Maybe you should study harder.";
        break;
}

Limitations of the Case Control Structure[edit | edit source]

Most programming languages do not allow ranges of values for case-like structures. Consider this flowcharting example that used ranges:

Consider also the following pseudocode for the same logic:

Case of age
  0 to 17    Display "You can't vote."
  18 to 64   Display "You’re in your working years."
  65 +       Display "You should be retired."
End

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.

Good Structured Programming Methods[edit | edit source]

Most textbook authors confirm that good structured programming techniques and habits are more important than concentrating on the technical possibilities and capabilities of the language that you are using to learn programming skills. Remember, this module is concentrating on programming fundamentals and concepts to build our initial programming skills. It is not a created with the intent to cover programming languages in detail, despite the fact that at times we have to cover language mechanics.

Key Terms[edit | edit source]

case
A control structure that does multiway selection.
switch
A control structure that can be made to act like a case control structure.

References[edit | edit source]


Condition Examples

Temperature[edit | edit source]

Pseudocode[edit | edit source]

Function Main
    Declare String choice
    
    Assign choice = GetChoice()
    If Choice = "C" Or Choice = "c"
        Call ProcessCelsius()
    False:
        If Choice = "F" Or Choice = "f"
            Call ProcessFahrenheit()
        False:
            Output "You must enter C to convert to Celsius or F to convert to Fahrenheit!"
        End
    End
End

Function CalculateCelsius (Real fahrenheit)
    Declare Real celsius
    
    Assign celsius = (fahrenheit - 32) * 5 / 9
Return Real celsius

Function CalculateFahrenheit (Real celsius)
    Declare Real fahrenheit
    
    Assign fahrenheit = celsius * 9 / 5 + 32
Return Real fahrenheit

Function DisplayResult (Real temperature, String fromScale, Real result, String toScale)
    Output temperature & "° " & fromScale & " is " & result & "° " & toScale
End

Function GetChoice
    Declare String choice
    
    Output "Enter F to convert to Fahrenheit or C to convert to Celsius:"
    Input Choice
Return String choice

Function GetTemperature (String scale)
    Declare Real temperature
    
    Output "Enter " & scale & " temperature:"
    Input temperature
Return Real temperature

Function ProcessCelsius
    Declare Real temperature
    Declare Real result
    
    Assign temperature = GetTemperature("Celsius")
    Assign result = CalculateCelsius(temperature)
    Call DisplayResult(temperature, "Fahrenheit", result, "Celsius")
End

Function ProcessFahrenheit
    Declare Real temperature
    Declare Real result
    
    Assign temperature = GetTemperature("Fahrenheit")
    Assign result = CalculateFahrenheit(temperature)
    Call DisplayResult(temperature, "Celsius", result, "Fahrenheit")
End

Output[edit | edit source]

Enter C to convert to Celsius or F to convert to Fahrenheit:
 c
Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

Enter C to convert to Celsius or F to convert to Fahrenheit:
 f
Enter Celsius temperature:
 100
100° Celsius is 212° Fahrenheit

Enter C to convert to Celsius or F to convert to Fahrenheit:
 x
You must enter C to convert to Celsius or F to convert to Fahrenheit.

Flowchart[edit | edit source]

Conditions flowchart Conditions ProcessCelsius flowchart Conditions ProcessFahrenheit flowchart Conditions GetChoice flowchart Conditions GetTemperature flowchart Conditions CalculateCelsius flowchart Conditions CalculateFahrenheit flowchart Conditions DisplayResult flowchart

References[edit | edit source]


Condition Examples C++

Temperature[edit | edit source]

// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given 
// temperature and displays the result.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C%2B%2B_Programming

#include <iostream>

using namespace std;

double getTemperature(string label);
double calculateCelsius(double fahrenheit);
double calculateFahrenheit(double celsius);
void displayResult(double temperature, string fromLabel, double result, string toLabel);

int main() {
    // main could either be an if-else structure or a switch-case structure

    char choice;
    double temperature;
    double result;
    
    cout << "Enter F to convert to Fahrenheit or C to convert to Celsius:" << endl;
    cin >> choice;

    // if-else approach
    if (choice == 'C' || choice == 'c') {
        temperature = getTemperature("Fahrenheit");
        result = calculateCelsius(temperature);
        displayResult(temperature, "Fahrenheit", result, "Celsius");
    }
    else if (choice == 'F' || choice == 'f') {
        temperature = getTemperature("Celsius");
        result = calculateFahrenheit(temperature);
        displayResult(temperature, "Celsius", result, "Fahrenheit");
    }
    else {
        cout << "You must enter C to convert to Celsius or F to convert to Fahrenheit!" << endl;
    }

    // switch-case approach
    switch(choice) {
        case 'C':
        case 'c':
            temperature = getTemperature("Fahrenheit");
            result = calculateCelsius(temperature);
            displayResult(temperature, "Fahrenheit", result, "Celsius");
            break;
        case 'F':
        case 'f':
            temperature = getTemperature("Celsius");
            result = calculateFahrenheit(temperature);
            displayResult(temperature, "Celsius", result, "Fahrenheit");
            break;
        default:
            cout << "You must enter C to convert to Celsius or F to convert to Fahrenheit!" << endl;
    }
}

double getTemperature(string label) {
    double temperature;
    
    cout << "Enter " << label << " temperature:" << endl;
    cin >> temperature;
    
    return temperature;
}

double calculateCelsius(double fahrenheit) {
    double celsius;
    
    celsius = (fahrenheit - 32) * 5 / 9;
    
    return celsius;
}

double calculateFahrenheit(double celsius) {
    double fahrenheit;
    
    fahrenheit = celsius * 9 / 5 + 32;
    
    return fahrenheit;
}

void displayResult(double temperature, string fromLabel, double result, string toLabel) {
    cout << temperature << "° " << fromLabel << " is " << result << "° " << toLabel << endl;
}

Output[edit | edit source]

Enter C to convert to Celsius or F to convert to Fahrenheit:
 c
Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7778° Celsius

Enter C to convert to Celsius or F to convert to Fahrenheit:
 f
Enter Celsius temperature:
 100
100° Celsius is 212° Fahrenheit

Enter C to convert to Celsius or F to convert to Fahrenheit:
 x
You must enter C to convert to Celsius or F to convert to Fahrenheit.

References[edit | edit source]


Condition Examples CSharp

Temperature[edit | edit source]

// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given 
// temperature and displays the result.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C_Sharp_Programming

using System;

public class MainClass
{
    public static void Main(String[] args)
    {
        // main could either be an if-else structure or a switch-case structure

        string choice;
        double temperature;
        double result;
                
        Console.WriteLine("Enter F to convert to Fahrenheit or C to convert to Celsius:");
        choice = Console.ReadLine();

        // if-else approach
        if (choice == "C" || choice == "c")
        {
            temperature = GetTemperature("Fahrenheit");
            result = CalculateCelsius(temperature);
            DisplayResult(temperature, "Fahrenheit", result, "Celsius");
        }
        else if (choice == "F" || choice == "f")
        {
            temperature = GetTemperature("Celsius");
            result = CalculateFahrenheit(temperature);
            DisplayResult(temperature, "Celsius", result, "Fahrenheit");
        }
        else
        {
            Console.WriteLine("You must enter C to convert to Celsius or F to convert to Fahrenheit!");
        }

        // switch-case approach
        switch(choice)
        {
            case "C":
            case "c":
                temperature = GetTemperature("Fahrenheit");
                result = CalculateCelsius(temperature);
                DisplayResult(temperature, "Fahrenheit", result, "Celsius");
                break;
            case "F":
            case "f":
                temperature = GetTemperature("Celsius");
                result = CalculateFahrenheit(temperature);
                DisplayResult(temperature, "Celsius", result, "Fahrenheit");
                break;
            default:
                Console.WriteLine("You must enter C to convert to Celsius or F to convert to Fahrenheit!");
                break;
        }
    }

    private static double GetTemperature(string label)
    {
        string input;
        double temperature;
        
        Console.WriteLine("Enter " + label + " temperature:");
        input = Console.ReadLine();
        temperature = Convert.ToDouble(input);

        return temperature;
    }

    private static double CalculateCelsius(double fahrenheit)
    {
        double celsius;
        
        celsius = (fahrenheit - 32) * 5 / 9;
        
        return celsius;
    }

    private static double CalculateFahrenheit(double celsius)
    {
        double fahrenheit;
        
        fahrenheit = celsius * 9 / 5 + 32;
        
        return fahrenheit;
    }

    private static void DisplayResult(double fahrenheit, string fromLabel, double celsius, string toLabel)
    {
        Console.WriteLine(fahrenheit.ToString() + "° " + fromLabel + " is " + celsius.ToString() + "° " + toLabel);
    }
}

Output[edit | edit source]

Enter C to convert to Celsius or F to convert to Fahrenheit:
 c
Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7777777777778° Celsius

Enter C to convert to Celsius or F to convert to Fahrenheit:
 f
Enter Celsius temperature:
 100
100° Celsius is 212° Fahrenheit

Enter C to convert to Celsius or F to convert to Fahrenheit:
 x
You must enter C to convert to Celsius or F to convert to Fahrenheit.

References[edit | edit source]


Condition Examples Java

Temperature[edit | edit source]

// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given 
// temperature and displays the result.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/Java_Programming

import java.util.*;

class Main {
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        // main could either be an if-else structure or a switch-case structure

        String choice;
        double temperature;
        double result;
        
        choice = getChoice();

        // if-else approach
        if (choice.equals("C") || choice.equals("c")) {
            temperature = getTemperature("Fahrenheit");
            result = calculateCelsius(temperature);
            displayResult(temperature, "Fahrenheit", result, "Celsius");
        } else if (choice.equals("F") || choice.equals("f")) {
            temperature = getTemperature("Celsius");
            result = calculateFahrenheit(temperature);
            displayResult(temperature, "Celsius", result, "Fahrenheit");
        } else {
            System.out.println("You must enter C to convert to Celsius or F to convert to Fahrenheit!");
        }

        // switch-case approach
        switch (choice) {
            case "C":
            case "c":
                temperature = getTemperature("Fahrenheit");
                result = calculateCelsius(temperature);
                displayResult(temperature, "Fahrenheit", result, "Celsius");
                break;
            case "F":
            case "f":
                temperature = getTemperature("Celsius");
                result = calculateFahrenheit(temperature);
                displayResult(temperature, "Celsius", result, "Fahrenheit");
                break;
            default:
                System.out.println("You must enter C to convert to Celsius or F to convert to Fahrenheit!");
        }
    }

    public static String getChoice() {
        String choice;
        
        System.out.println("Enter C to convert to Celsius or F to convert to Fahrenheit:");
        choice = input.nextLine();
        
        return choice;
    }
    
    public static double getTemperature(String label) {
        double temperature;
        
        System.out.println("Enter " + label + " temperature:");
        temperature = input.nextDouble();
        
        return temperature;
    }

    public static double calculateCelsius(double fahrenheit) {
        double celsius;
        
        celsius = (fahrenheit - 32) * 5 / 9;
        
        return celsius;
    }
    
    public static double calculateFahrenheit(double celsius) {
        double fahrenheit;
        
        fahrenheit = celsius * 9 / 5 + 32;
        
        return fahrenheit;
    }
    
    public static void displayResult(double temperature, String fromLabel, double result, String toLabel) {
        System.out.println(Double.toString(temperature) + "° " + fromLabel + " is " + result + "° " + toLabel);
    }
}

Output[edit | edit source]

Enter C to convert to Celsius or F to convert to Fahrenheit:
 c
Enter Fahrenheit temperature:
 100
100.0° Fahrenheit is 37.77777777777778° Celsius

Enter C to convert to Celsius or F to convert to Fahrenheit:
 f
Enter Celsius temperature:
 100
100.0° Celsius is 212.0° Fahrenheit

Enter C to convert to Celsius or F to convert to Fahrenheit:
 x
You must enter C to convert to Celsius or F to convert to Fahrenheit.

References[edit | edit source]


Condition Examples JavaScript

Temperature[edit | edit source]

// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given 
// temperature and displays the result.
//
// References:
//   https://www.mathsisfun.com/temperature-conversion.html
//   https://en.wikibooks.org/wiki/JavaScript

main();

function main() 
{
    // main could either be an if-else structure or a switch-case structure

    var choice;
    var temperature;
    var result;
    
    choice = getChoice();

    // if-else approach
    if (choice == "C" || choice == "c") {
        temperature = getTemperature("Fahrenheit");
        result = calculateCelsius(temperature);
        displayResult(temperature, "Fahrenheit", result, "Celsius");
    } 
    else if (choice == "F" || choice == "f") {
        temperature = getTemperature("Celsius");
        result = calculateFahrenheit(temperature);
        displayResult(temperature, "Celsius", result, "Fahrenheit");
    } 
    else {
        output("You must enter C to convert to Celsius or F to convert to Fahrenheit!");
    }

    // switch-case approach
    switch(choice) {
        case 'C':
        case 'c':
            temperature = getTemperature("Fahrenheit");
            result = calculateCelsius(temperature);
            displayResult(temperature, "Fahrenheit", result, "Celsius");
            break;
        case 'F':
        case 'f':
            temperature = getTemperature("Celsius");
            result = calculateFahrenheit(temperature);
            displayResult(temperature, "Celsius", result, "Fahrenheit");
            break;
        default:
            output("You must enter C to convert to Celsius or F to convert to Fahrenheit!");
    }
}

function getChoice() {
    var choice;
    
    output("Enter C to convert to Celsius or F to convert to Fahrenheit:");
    choice = input();
    
    return choice;
}

function getTemperature(label) {
    var temperature;
    
    output("Enter " + label + " temperature:");
    temperature = input();
    
    return temperature;
}

function calculateCelsius(fahrenheit) {
    var celsius;
    
    celsius = (fahrenheit - 32) * 5 / 9;
    
    return celsius;
}

function calculateFahrenheit(celsius) {
    var fahrenheit;
    
    fahrenheit = celsius * 9 / 5 + 32;
    
    return fahrenheit;
}

function displayResult(temperature, fromLabel, result, toLabel) {
    output(temperature.toString() + "° " + fromLabel + " is " + result + "° " + toLabel);
}

function input(text) {
  if (typeof window === 'object') {
    return prompt(text)
  }
  else if (typeof console === 'object') {
    const rls = require('readline-sync');
    var value = rls.question(text);
    return value;
  }
  else {
    output(text);
    var isr = new java.io.InputStreamReader(java.lang.System.in); 
    var br = new java.io.BufferedReader(isr); 
    var line = br.readLine();
    return line.trim();
  }
}

function output(text) {
  if (typeof document === 'object') {
    document.write(text);
  } 
  else if (typeof console === 'object') {
    console.log(text);
  } 
  else {
    print(text);
  }
}

Output[edit | edit source]

Enter C to convert to Celsius or F to convert to Fahrenheit:
 c
Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.77777777777778° Celsius

Enter C to convert to Celsius or F to convert to Fahrenheit:
 f
Enter Celsius temperature:
 100
100° Celsius is 212° Fahrenheit

Enter C to convert to Celsius or F to convert to Fahrenheit:
 x
You must enter C to convert to Celsius or F to convert to Fahrenheit.

References[edit | edit source]


Condition Examples Python

Temperature[edit | edit source]

# This program asks the user to select Fahrenheit or Celsius conversion
# and input a given temperature. Then the program converts the given 
# temperature and displays the result.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Python_Programming


def get_choice():
    print("Enter C to convert to Celsius or F to convert to Fahrenheit:")
    choice = input()    
    return choice


def get_temperature(label):
    print(f"Enter {label} temperature:")
    temperature = float(input())    
    return temperature


def calculate_celsius(fahrenheit):
    celsius = (fahrenheit - 32) * 5 / 9    
    return celsius


def calculate_fahrenheit(celsius):
    fahrenheit = celsius * 9 / 5 + 32
    return fahrenheit


def display_result(temperature, from_label, result, to_label):
    print(f"{temperature}° {from_label} is {result}° {to_label}")


def main():
    choice = get_choice()
    if choice == "C" or choice == "c":
        temperature = get_temperature("Fahrenheit")
        result = calculate_celsius(temperature)
        display_result (temperature, "Fahrenheit", result, "Celsius")
    elif choice == "F" or choice == "f":
        temperature = get_temperature("Celsius")
        result = calculate_fahrenheit(temperature)
        display_result (temperature, "Celsius", result, "Fahrenheit")
    else:
        print("You must enter C to convert to Celsius or F to convert to Fahrenheit.")


main()

Output[edit | edit source]

Enter C to convert to Celsius or F to convert to Fahrenheit:
 c
Enter Fahrenheit temperature:
 100
100.0° Fahrenheit is 37.77777777777778° Celsius

Enter C to convert to Celsius or F to convert to Fahrenheit:
 f
Enter Celsius temperature:
 100
100.0° Celsius is 212.0° Fahrenheit

Enter C to convert to Celsius or F to convert to Fahrenheit:
 x
You must enter C to convert to Celsius or F to convert to Fahrenheit.

References[edit | edit source]


Condition Examples Swift

Temperature[edit | edit source]

// This program asks the user for a Fahrenheit temperature, 
// converts the given temperature to Celsius,
// and displays the results.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

func getChoice() -> String {
    var choice: String

    print("Enter C to convert to Celsius or F to convert to Fahrenheit:")
    choice = readLine(strippingNewline: true)!

    return choice
}

func getTemperature(label: String) -> Double {
    var temperature: Double
    
    print("Enter " + label + " temperature:")
    temperature = Double(readLine(strippingNewline: true)!)!
    
    return temperature
}

func calculateCelsius(fahrenheit: Double) -> Double {
    var celsius: Double
    
    celsius = (fahrenheit - 32) * 5 / 9
    
    return celsius
}

func calculateFahrenheit(celsius: Double) -> Double {
    var fahrenheit: Double
    
    fahrenheit = celsius * 9 / 5 + 32
    
    return fahrenheit
}

func displayResult(temperature: Double, fromLabel: String, result: Double, toLabel: String) {
    print(String(temperature) + "° " + fromLabel + " is " + String(result) + "° " +  toLabel)
}

func main() {
    // main could either be an if-else structure or a switch-case structure

    var choice: String
    var temperature: Double
    var result: Double

    choice = getChoice()

    // if-else approach    
    if choice == "C" || choice == "c" {
        temperature = getTemperature(label:"Fahrenheit")
        result = calculateCelsius(fahrenheit:temperature)
        displayResult(temperature:temperature, fromLabel:"Fahrenheit", result:result, toLabel:"Celsius")    } 
    else if choice == "F" || choice == "f" {
        temperature = getTemperature(label:"Celsius")
        result = calculateFahrenheit(celsius:temperature)
        displayResult(temperature:temperature, fromLabel:"Celsius", result:result, toLabel:"Fahrenheit")
    } 
    else {
        print("You must enter C to convert to Celsius or F to convert to Fahrenheit.")
    }

    // switch-case approach
    switch choice {
        case "C", "c":
            temperature = getTemperature(label:"Fahrenheit")
            result = calculateCelsius(fahrenheit:temperature)
            displayResult(temperature:temperature, fromLabel:"Fahrenheit", result:result, toLabel:"Celsius")
        case "F", "f":
            temperature = getTemperature(label:"Celsius")
            result = calculateFahrenheit(celsius:temperature)
            displayResult(temperature:temperature, fromLabel:"Celsius", result:result, toLabel:"Fahrenheit")
        default:
            print("You must enter C to convert to Celsius or F to convert to Fahrenheit.")
    }
}

main()

Output[edit | edit source]

Enter C to convert to Celsius or F to convert to Fahrenheit:
 c
Enter Fahrenheit temperature:
 100
100.0° Fahrenheit is 37.77777777777778° Celsius

Enter C to convert to Celsius or F to convert to Fahrenheit:
 f
Enter Celsius temperature:
 100
100.0° Celsius is 212.0° Fahrenheit

Enter C to convert to Celsius or F to convert to Fahrenheit:
 x
You must enter C to convert to Celsius or F to convert to Fahrenheit.

References[edit | edit source]


Practice: Conditions

Chapter Summary[edit | edit source]

  • Structured Programming - Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection, repetition, block structures, and subroutines.
  • Selection Control Structures - Conditional statements perform different computations or actions depending on whether a programmer-specified Boolean condition evaluates to true or false.
  • If Then Else - A two-way selection structure common across many programming languages.
  • Code Blocks - A lexical structure of source code which is grouped together.
  • Relational Operators - Tests or defines some kind of relation between two entities.
  • Assignment vs Equality - Assignment sets a value to the memory address location of a variable. The left operand is set to the value of the right operand and is denoted with a single equals sign (=). Equality is a relational operator used to compare or test two operands and is often denoted with two or three equals signs (==, ===). The result of such a comparisons returns true or false.[1] [2]
  • Logical Operators - Symbol or word used to connect two or more expressions such that the value of the compound expression produced depends only on that of the original expressions and on the meaning of the operator.
  • Nested If Then Else - Two-way selection structures may be nested inside other two-way selection structures, resulting in multi-way selection.
  • Case Control Structure - A case or switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.

Review Questions[edit | edit source]

True / False[edit | edit source]

  1. There are only two categories of control structures.
  2. Branching control structures are rarely used in good structured programming.
  3. If then else is a multiway selection control structure.
  4. The while control structure is part of the branching category.
  5. Pseudocode is better than flowcharting.
  6. In a sequence control structure, the program executed path is chosen by options prompted by questions.
  7. An iteration control structure allows some lines of code to be executed many times.
  8. A relational operator is an operator used to create complex Boolean expressions.
  9. The best way to structure an if-then-else statement is to check if a statement is True.
  10. The value of the statement "True and False" is 'True'.
  11. To initialize or set the value of a variable, you should use the equality operator (==)

Answers:

  1. false - There are three.
  2. true
  3. false - It is part of the selection structure.
  4. false - It is part of the repetition category.
  5. false - While pseudocode may be very useful, it does not have the same clarity as flowcharting.
  6. false - Sequence structure programs execute items in the order listed.
  7. true
  8. false - They are used to test relationships between values.
  9. false - In general, it is better to test for False or not False rather than True or not True.
  10. false - The statement's value is 'False'.
  11. false - Use the assignment operator (=)

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
  9. 25 > 39 || 15 > 36
  10. 19 > 26 || 13 < 17
  11. 14 < 7 && 6 <= 6
  12. 4 > 3 && 17 >= 7
  13. ! true
  14. ! (13 == 7)
  15. 9 != 7 && ! 1
  16. 6 < && 8

Answers:

  1. 0
  2. 1
  3. 1
  4. 0
  5. 1
  6. 0
  7. 1
  8. Error, the “not greater than” is not a valid operator.
  9. 0
  10. 1
  11. 0
  12. 1
  13. 0
  14. 1
  15. 0
  16. Error, there needs to be an operand between the operators < and &&.

Short Answer[edit | edit source]

  1. List the four categories of control structures and provide a brief description of each category.
  2. Create a table with the six relational operators and their meanings.
  3. Provide examples of when it is appropriate to use "if" vs. "if-else" vs. "if-else if-else".
  4. Describe the differences between Assignment and Equality and provide examples of each being used properly.

Activities[edit | edit source]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Create a program to prompt the user for hours and rate per hour and then compute gross pay (hours * rate). Include a calculation to give 1.5 times the hourly rate for any overtime (hours worked above 40 hours).[3] For example, 50 hours worked at $10 per hour with overtime is $550.
  2. Create a program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in (M)onths, (D)ays, (H)ours, or (S)econds. Use if/else conditional statements to calculate and display their approximate age in the selected timeframe. Do not perform any unnecessary calculations.
  3. Review MathsIsFun: US Standard Lengths. Create a program that asks the user for a distance in miles, and then ask the user if they want the distance in US measurements (yards, feet, and inches) or in metric measurements (kilometers, meters, and centimeters). Use if/else conditional statements to determine their selection and then calculate and display the results.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user what shape they would like to calculate the area for. Use if/else conditional statements to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  5. Review Wikipedia: Aging in dogs. Create a program to prompt the user for the name of their dog and its age in human years. Calculate and display the age of their dog in dog years, assuming the first two years equal 10.5 years each, with subsequent years equaling four human years. Be sure to include the dog's name in the output, such as:
        Spike is 14.0 years old in dog years.
  6. Create a program that helps the user determine what sock size to order based on their shoe size:
        < 4 = extra small
        4 to 6 = small
        7 to 9 = medium
        10 to 12 = large
        13+ = extra large
    Use if/else conditional statements to determine their selection and then display the results. Round half-sizes up to the next whole size. One option for rounding is to add 0.5 and then convert to an integer.
  7. If your programming language supports it, update one or more of the programs above to replace the if/else conditional statements with case/select conditional statements.
  8. Review Wikipedia: Is functions. If your programming language supports it, update one or more of the programs above to include input validation for all numeric input.
  9. If your programming language supports it, extend one or more of the programs above by adding structured exception handling statements (try-catch, try-except, etc.) to handle any runtime errors caused by the user entering invalid values for the input.

References[edit | edit source]


Loops

Overview[edit | edit source]

This chapter introduces loops and iteration control structures.

Chapter Outline[edit | edit source]

Learning Objectives[edit | edit source]

  1. Understand key terms and definitions.
  2. Identify control structures based on test before iteration, test after iteration, and counting, and when to use each type.
  3. Given example pseudocode, flowcharts, and source code, create a program that uses loops and iteration control structures to solve a given problem.


Iteration Control Structures

Overview[edit | edit source]

In iteration control structures, a statement or block is executed until the program reaches a certain state, or operations have been applied to every element of a collection. This is usually expressed with keywords such as while, repeat, for, or do..until.[1]

Discussion[edit | edit source]

The basic attribute of an iteration control structure is to be able to repeat some lines of code. The visual display of iteration creates a circular loop pattern when flowcharted, thus the word “loop” is associated with iteration control structures. Iteration can be accomplished with "test before" loops, "test after" loops, and counting loops. A question using Boolean concepts usually controls how often the loop will execute.

Pseudocode: Iteration (Repetition) Control Structures[edit | edit source]

While Loop

count assigned zero
While count < 5
    Display "I love computers!"
    Increment count
End

Do-While Loop

count assigned five
Do
    Display "Blast off is soon!"
    Decrement count
While count > zero

Repeat-Until Loop

count assigned five
Repeat
    Display "Blast off is soon!"
    Decrement count
Until count < one

For Loop

For x starts at 0, x < 5, increment x
    Display "Are we having fun?"
End

References[edit | edit source]


While Loop

Overview[edit | edit source]

A "while" loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The "while" loop can be thought of as a repeating "if" statement.[1]

Discussion[edit | edit source]

Introduction to "Test Before" Loops[edit | edit source]

There are two commonly used "test before" loops in the iteration (or repetition) category of control structures. They are "while" and "for"; this module covers the "while" loop.

Understanding Iteration in General – "While"[edit | edit source]

The concept of iteration is connected to possibly wanting to repeat an action. Like all control structures we ask a question to control the execution of the loop. The term "loop" comes from the circular looping motion that occurs when using flowcharting. The basic form of the while loop is as follows:

initialization of the flag 
while the answer to the question is true then do
    some statements or action
    some statements or action
    some statements or action
    update the flag

In most programming languages the question (called a test expression) is a Boolean expression. The Boolean data type has two values – true and false. Let’s rewrite the structure to consider this:

initialization of the flag 
while the expression is true then do
    some statements or action
    some statements or action
    some statements or action
    update the flag

Within the "while" control structure there are four attributes to a properly working loop. They are:

  • Initializing the flag
  • Test expression
  • Action or actions
  • Update of the flag

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.

Human Example of the "While" Loop[edit | edit source]

Consider the following one-way conversation between a parent and their child.

It's just after breakfast and the parent knows their child had Cheerios. Past experience has taught them that their child usually spills Cheerios on the floor.

The parent tells their child: “While it is true that there is a Cheerio on the floor, pick it up and put it in the garbage.”

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 (Is there a Cheerio on the floor?) has only two possible answers (true or false), the action will continue while there are Cheerios on the floor. Therefore, 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 until they are all picked up.

Infinite Loops[edit | edit source]

At this point, it is worth mentioning that good programming always provides for a method to ensure 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 and will not stop until the program is terminated externally or the computer is restarted. Consider the following code:

Pseudocode infinite loop

loop_response = 'y'
While loop_response == 'y'
    Output "What is your age?"
    Input user_age
    Output "What is your friend's age?"
    Input friend_age
    Output "Together your ages add up to: "
    Output user_age + friend_age

The programmer assigned a value to the flag before the loop which is correct. However, they forgot to update the flag. Every time the test expression is asked it will always be true. Thus, it's 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:

loop_response = 'y';
While loop_response = 'y'
    Output "What is your age?"
    Input user_age
    Output "What is your friend's age?"
    Input friend_age
    Output "Together your ages add up to: "
    Output user_age + friend_age
    Output "Do you want to try again? y or n"
    Input loop_response

No matter what the user replies during the flag update, the test expression does not do a relational comparison but does an assignment. It assigns ‘y’ to the variable and asks if ‘y’ is true? Since all non-zero values are treated as representing true, the answer to the test expression is true. Viola, you have an infinite loop.

Counting Loops[edit | edit source]

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.

Another common usage of the while loop is as a counting loop. Consider:

counter = 0
While counter < 5
    Output "I love ice cream!"
    counter += 1

The variable counter is said to be controlling the loop.  It is set to zero (called initialization) before entering the while loop structure and as long as it is less than 5 (five); the loop action will be executed.  But part of the loop action uses the increment operator to increase counter’s value by one.  After executing the loop five times (once for counter’s values of: 0, 1, 2, 3 and 4) the expression will be false and the next line of code in the program will execute. A counting loop is designed to execute the action (which could be more than one statement) a set of given number of times. In our example, the message is displayed five times on the monitor. It is accomplished by making sure all four attributes of the while control structure are present and working properly. The attributes are:

  • Initializing the flag
  • Test expression
  • Action or actions
  • Update of the flag

Missing an attribute might cause an infinite loop or give undesired results (does not work properly).

Infinite Loops[edit | edit source]

Consider:

counter = 0;
while counter < 5
    Output "I love ice cream!"

Missing the flag update usually causes an infinite loop.

Variations on Counting[edit | edit source]

In the following example, the integer variable age is said to be controlling the loop (that is the flag). We can assume that age has a value provided earlier in the program. Because the while structure is a test before loop; 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.

While 0 < age
    Output "I love candy!"
    age -= 1

Consider the following variation assuming that age and counter are both integer data type and that age has a value:

counter = 0;
While counter < age
    Output "I love corn chips!"
    counter += 1

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.

Key Terms[edit | edit source]

counting controlled
Using a variable to count up or down to control a loop.
infinite loop
A sequence of instructions which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.
initialize item
An attribute of iteration control structures.
loop attributes
Items associated with iteration or looping control structures.
might not happen
Indicating that test before loops might not execute the action.
while
A test before iteration control structure.

References[edit | edit source]


Do While Loop

Overview[edit | edit source]

A do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block.[1]

Some languages may use a different naming convention for this type of loop. For example, the Pascal language has a repeat until loop, which continues to run until the control expression is true (and then terminates) — whereas a “while” loop runs while the control expression is true (and terminates once the expression becomes false).[2]

Discussion[edit | edit source]

Introduction to Test After Loops[edit | edit source]

There are two commonly used test after loops in the iteration (or repetition) category of control structures. They are: do while and repeat until. This module covers both.

Understanding Iteration in General – do while[edit | edit source]

The concept of iteration is connected to possibly wanting to repeat an action. Like all control structures, we ask a question to control the execution of the loop. The term loop comes from the circular looping motion that occurs when using flowcharting. The basic form of the do while loop is as follows:

do
    some statements or action
    some statements or action
    some statements or action
    update the flag
while the answer to the question is true

In most programming languages the question (called a test expression) is a Boolean expression. The Boolean data type has two values – true and false. Let’s rewrite the structure to consider this:

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.

Understanding Iteration in General – repeat until[edit | edit source]

The concept of iteration is connected to possibly wanting to repeat an action. Like all control structures, we ask a question to control the execution of the loop. The term loop comes from the circular looping motion that occurs when using flowcharting. The basic form of the repeat until loop is as follows:

repeat
    some statements or action
    some statements or action
    some statements or action
    update the flag
until the answer to the question becomes true

In most programming languages the question (called a test expression) is a Boolean expression. The Boolean data type has two values – true and false. Let’s rewrite the structure to consider this:

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.

An Example[edit | edit source]

Do
    Output "What is your age?"
    Input user_age
    Output "What is your friend's age?"
    Input friend_age
    Output "Together your ages add up to: "
    Output age_user + friend_age
    Output "Do you want to try it again? y or n"
    Input loop_response
While loop_response == 'y'

The three attributes of a test after loop are present. The action part consists of the 6 lines that prompt for data and then displays the total of the two ages. The update of the flag is the displaying the question and getting the answer for the variable loop_response. The test is the equality relational comparison of the value in the flag variable to the lower case character of y. The loop will continue processing while loop_response is "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 the normal industry practice.

Infinite Loops[edit | edit source]

At this point, it is worth mentioning that good programming always provides for a method to ensure 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 and will not stop until the program is terminated externally or the computer is restarted. Consider the following code:

loop_response = 'y'
Do
    Output "What is your age?"
    Input user_age
    Output "What is your friend's age?"
    Input friend_age
    Output "Together your ages add up to: "
    Output user_age + friend_age
While loop_response == 'y'

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, it's 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:

do
    Output "What is your age?"
    Input user_age
    Output "What is your friend's age?"
    Input friend_age
    Output "Together your ages add up to: "
    Output age_user + friend_age
    Output "Do you want to try it again? y or n"
    Input loop_response
While loop_response = 'y'

No matter what the user replies during the flag update, the test expression does not do a relational comparison but does an assignment. It assigns ‘y’ to the variable and asks if ‘y’ is true? Since all non-zero values are treated as representing true, the answer to the text question is true. Viola, you have an infinite loop.

Key Terms[edit | edit source]

action item
An attribute of iteration control structures.
at least once
Indicating that test after loops execute the action at least once.
do while
A test after iteration control structure.
infinite loop
A sequence of instructions which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.[3]
event controlled loop
Where user input is used to control a loop.[4]
repeat until
A test after iteration control structure alternative available in some programming languages.
test item
An attribute of iteration control structures.
update item
An attribute of iteration control structures.

References[edit | edit source]


Flag Concept

Overview[edit | edit source]

Checkered flags

Flags are commonly used to control or to indicate the intermediate state or outcome of particular operations.[1]

Discussion[edit | edit source]

A flag reveals whether a data structure is in a possible state range and may indicate a bit field attribute, which a user needs special permission to access. A processor has many states that store multiple flag values that may help with post-processing. One example is arithmetic overflow. If the memory exceeds the limit like dividing by 0, the flag jump in to help out.

An example of the flag concept is a switch in which a parser is set at the beginning of a command line program. These switches are turned into flags which are then processed.

Computer Implementation =[edit | edit source]

Any variable or constant that holds data can be used as a flag. You can think of the storage location as a flagpole. 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: marital_status which is of the character data type. The two values commonly stored in the variable are: ‘S’ and ‘M’, meaning single and married. Then, somewhere within a program we might look at the variable to make a decision:

flag controlling an if then control structure

if marital_status equals 'M'
    display "Are you filing your taxes jointly?"
    get answer from user store in filing_jointly variable

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).

Control structures are “controlled” by using a test expression which is usually a Boolean expression. Thus, the flag concept of “looking” at the value in the variable and comparing it to another value is fundamental to understanding how all control structures work.

Two Flags with the Same Meaning[edit | edit source]

Sometimes we will use an iteration control structure of do while to allow us to decide if we want to do the loop action again. A variable might be named “loop_response” with the user prompted for their answer of ‘y’ for yes or ‘n’ for no. Once the answer is retrieved from the keyboard and stored in our flag variable of “loop_response” the test expression to control the loop might be:

simple flag comparison

loop_response equals 'y'

This is fine but what if the user accidentally has on the caps lock. Then the response of ‘Y’ would not have the control structure loop and perform the action again. The solution lies in looking at the flag twice. Consider:

complex flag comparison

loop_response equals 'y' or loop_response equals 'Y'

We look to see if the flag is either a lower case y or an upper case Y by using a more complex Boolean expression with both relational and logical operators.

Multiple Flags in One Byte[edit | edit source]

Within assembly language programming and in many technical programs that control special devices; the use of a single byte to represent several flags is common. This is accomplished by having each one of the 8 bits that make up the byte represent a flag. Each bit has a value of either 1 or 0 and can represent true and false, on or off, yes or no, etc.

Key Terms[edit | edit source]

flag
A variable used to store information that will normally be used to control the program.
Flag of Oceania

References[edit | edit source]


For Loop

Overview[edit | edit source]

A for loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly. A for loop has two parts: a header specifying the iteration, and a body which is executed once per iteration. The header often declares an explicit loop counter or loop variable, which allows the body to know which iteration is being executed. For loops are typically used when the number of iterations is known before entering the loop. For loops can be thought of as shorthands for while loops which increment and test a loop variable.[1][1]

Discussion[edit | edit source]

Introduction to Test Before Loops[edit | edit source]

There are two commonly used test before loops in the iteration (or repetition) category of control structures. They are: while and for. This module covers the: for.

Understanding Iteration in General – for[edit | edit source]

In many programming languages, the for loop is used exclusively for counting; that is to repeat a loop action as it either counts up or counts down. There is a starting value and a stopping value. The question that controls the loop is a test expression that compares the starting value to the stopping value. This expression is a Boolean expression and is usually using the relational operators of either less than (for counting up) or greater than (for counting down). The term loop comes from the circular looping motion that occurs when using flowcharting. The basic form of the for loop (counting up) is as follows:

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

It might be best to understand the for loop by understanding a while loop acting like a counting loop. Let’s consider;

initialization of the starting value 
while the 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:

  • Initializing the flag – done once
  • Test expression
  • Action or actions
  • Update of the flag

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.

An Example[edit | edit source]

For counter = 0, counter < 5, counter += 1
    Output "I love ice cream!"

The four attributes of a test before loop (remember the for loop is one example of a test before loop) are present.

  • The initialization of the flag to a value of 0.
  • The test is the less than relational comparison of the value in the flag variable to the constant value of 5.
  • The action part consists of the 1 line of output.
  • The update of the flag is done with the increment operator.

Using indentation with the alignment of the loop actions is the normal industry practice.

Infinite Loops[edit | edit source]

At this point, it is worth mentioning that good programming always provides for a method to ensure 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 and will not stop until the program is terminated externally or the computer is restarted. Consider the following code:

For counter = 0, counter < 5
    Output "I love ice cream!"

The programmer assigned a value to the flag during the initialization step which is correct. However, they forgot to update the flag (the update step is missing). Every time the test expression is asked it will always be true. Thus, it's an infinite loop because the programmer did not provide a way to exit the loop (he forgot to update the flag).

Key Terms[edit | edit source]

for loop
A test before iteration control structure typically used for counting.
infinite loop
A loop that goes on forever since no stop value was given.

References[edit | edit source]


Branching Statements

Overview[edit | edit source]

A branch is an instruction in a computer program that can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order.[1] Common branching statements include break, continue, return, and goto.

Discussion[edit | edit source]

Branching statements allow the flow of execution to jump to a different part of the program. The common branching statements used within other control structures include: break, continue, return, and goto. The goto is rarely used in modular structured programming. Additionally, we will add to our list of branching items a pre-defined function commonly used in programming languages of: exit.

Examples[edit | edit source]

break[edit | edit source]

Break terminates the existing structure. Break is used in one of two ways; with a switch to make it act like a case structure or as part of a looping process to break out of the loop. The following gives the appearance that the loop will execute 8 times, but the break statement causes it to stop during the fifth iteration.

counter = 0;
While counter < 8
    Output counter
    If counter == 4
        break
    counter += 1

continue[edit | edit source]

Continue causes the loop to stop its current iteration and begin the next one. The following gives the appearance that the loop will print to the monitor 8 times, but the continue statement causes it not to print number 4.

For counter = 0, counter < 8, counter += 1
    If counter == 4
        continue
    Output counter

return[edit | edit source]

Return causes the function to jump back to the function that called it. The return statement exits a function and returns to the statement where the function was called.

Function DoSometing
    statements
Return <optional return value>

goto[edit | edit source]

Goto causes logic to jump to a different place. The goto structure is typically not accepted in good structured programming. However, some programming languages allow you to create a label with an identifier name followed by a colon. You use the command word goto followed by the label.

some lines of code; 
goto label;                // jumps to the label
some lines of code; 
some lines of code; 
some lines of code; 
label: some statement;     // Declared label
some lines of code;

exit[edit | edit source]

Exit is a pre-defined function which prematurely stops the execution of the program and causes it to jump to another place in the program. A good example is the opening a file and then testing to see if the file was actually opened. If not, we have an error that usually indicates that we want to prematurely stop the execution of the program. The exit function terminates the running of the program and in the process returns an integer value back to the operating system.

Key Terms[edit | edit source]

branching statements
Allow the flow of execution to jump to a different part of the program.
break
A branching statement that terminates the existing structure.
continue
A branching statement that causes a loop to stop its current iteration and begin the next one.
exit
A predefined function used to prematurely stop a program and return to the operating system.
goto
An unstructured branching statement that causes the logic to jump to a different place in the program.
return
A branching statement that causes a function to jump back to the function that called it.

References[edit | edit source]


Increment and Decrement Operators

Overview[edit | edit source]

Increment and decrement operators are unary operators that add or subtract one from their operand, respectively. They are commonly implemented in imperative programming languages.[1]

Discussion[edit | edit source]

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:

increment the counter

The concept is:

counter is assigned counter + 1

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.

Operator symbols and/or names vary with different programming languages. Several programming languages support increment and decrement operators:

Operator Meaning
++ increment, two plus signs
-- decrement, two minus signs

Code Examples[edit | edit source]

Basic Concept[edit | edit source]

Within C++, C#, Java, and JavaScript programming languages, the increment and decrement operators are often used in this simple generic way. The increment operator is represented by two plus signs in a row. Examples:

counter = counter + 1;

counter += 1;

counter++;

++counter;

As statements, the four examples all do the same thing. They add 1 to the value of whatever is stored in counter. The decrement operator 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). Note that postfix and prefix do not have the same precedence.

Postfix Increment[edit | edit source]

Postfix increment says to use my existing value then when you are done with the other operators; increment me. An example:

int oldest = 44;
age = oldest++;

The first use of the oldest variable is an Rvalue context where the existing value of 44 is pulled or fetched and then assigned to the variable age; then the variable oldest is incremented with its value changing from 44 to 45. This seems to be a violation of precedence because increment is higher precedence than assignment. But that is how postfix increment works.

Prefix Increment[edit | edit source]

Prefix increment says to increment me now and use my new value in any calculation. An example:

int oldest = 44;
age = ++oldest;

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) whereas prefix has an ego (I am important so increment me first and use my new value for the rest of the evaluations).

Allowable Data Types[edit | edit source]

Within some programming languages, increment and decrement can be used only on the integer data type. Other languages expand this not only to all of the integer family but also to the floating-point family (float and double). Incrementing 3.87 will change the value to 4.87. Decrementing ‘C’ will change the value to ‘B’. Remember the ASCII character values are really one-byte unsigned integers (domain from 0 to 255).

Exercises[edit | edit source]

Evaluate the following items using increment or decrement:

  1. True or false: x = x +1 and x+=1 and x++ all accomplish increment?
  2. Given: int y = 19; and int z; what values will y and z have after: z = y–;
  3. Given: double x = 7.77; and int y; what values will x and y have after: y = ++x;
  4. Is this ok? Why or why not? 6 * ++(age -3)

Key Terms[edit | edit source]

decrement
Subtracting one from the value of a variable.
increment
Adding one to 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.

References[edit | edit source]


Integer Overflow

Overview[edit | edit source]

Integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.[1]

The most common result of an overflow is that the least significant representable bits of the result are stored; the result is said to wrap around the maximum (i.e. modulo power of two). An overflow condition may give results leading to unintended behavior. In particular, if the possibility has not been anticipated, overflow can compromise a program’s reliability and security.[2]

Discussion[edit | edit source]

There are times when character and integer data types are lumped together because they both act the same (often called the integer family). It would be better to say they act differently than 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.

“In mathematics, modular arithmetic (sometimes called clock arithmetic) is a system of arithmetic for integers where numbers “wrap around” after they reach a certain value — the modulus. …

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. Regular 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.

Implications When Executing Loops[edit | edit source]

If a programmer sets up a counting loop incorrectly, usually one of three things happen:

  • Infinite loop – usually caused by missing update attribute.
  • Loop never executes – usually, the text expression is wrong with the direction of the less than or greater than relationship needing to be switched.
  • Loop executes more times than desired – update not properly handled. Usually, the direction of counting (increment or decrement) needs to be switched.

Let’s give an example of the loop executing for what appears to be infinity (the third item on our list).

for int x = 0, x < 10, x--
    Output x

The above code accidentally decrements and the value of x goes in a negative way towards -2147483648 (the largest negative value in a normal four-byte signed integer data type). It might take a while (thus it might appear to be in an infinite loop) for it to reach the negative 2 billion-plus value, before finally decrementing to positive 2147483647. Which would, incidentally, stop the loop execution.

Key Terms[edit | edit source]

circular nature
Connecting the negative and positive ends of the domain of an integer family data type.
loop control
Making sure the attributes of a loop are properly handled.
modular arithmetic
A system of arithmetic for integers where numbers “wrap around”.

References[edit | edit source]


Nested Loops

Overview[edit | edit source]

Nested for loops places one for loop inside another for loop. The inner loop is repeated for each iteration of the outer loop.

Discussion[edit | edit source]

Nested Control Structures[edit | edit source]

We are going to first introduce the concept of nested control structures. Nesting is a concept that places one item inside of another. Consider:

if expression
    true action
else 
    false action

This is the basic form of the if then else control structure. Now consider:

if age is less than 18
    you can't vote
    if age is less than 16
        you can't drive
    else
        you can drive
else
    you can vote
    if age is less than 21
        you can't drink 
    else
        you can drink

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.

Many complex logic problems require using nested control structures. By nesting control structures (or placing one inside another) we can accomplish almost any complex logic problem.

An Example – Nested for loops[edit | edit source]

Here is an example of a 10 by 10 multiplication table:

         1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10 |
     -------------------------------------------------------------
   1 !   1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10 |
   2 !   2 |   4 |   6 |   8 |  10 |  12 |  14 |  16 |  18 |  20 |
   3 !   3 |   6 |   9 |  12 |  15 |  18 |  21 |  24 |  27 |  30 |
   4 !   4 |   8 |  12 |  16 |  20 |  24 |  28 |  32 |  36 |  40 |
   5 !   5 |  10 |  15 |  20 |  25 |  30 |  35 |  40 |  45 |  50 |
   6 !   6 |  12 |  18 |  24 |  30 |  36 |  42 |  48 |  54 |  60 |
   7 !   7 |  14 |  21 |  28 |  35 |  42 |  49 |  56 |  63 |  70 |
   8 !   8 |  16 |  24 |  32 |  40 |  48 |  56 |  64 |  72 |  80 |
   9 !   9 |  18 |  27 |  36 |  45 |  54 |  63 |  72 |  81 |  90 |
  10 !  10 |  20 |  30 |  40 |  50 |  60 |  70 |  80 |  90 | 100 |

We might also see that the answers could be designed as a collection of cells (each cell being exactly six spaces wide). The pseudocode to produce part of the table is:

For row = 1, row <= 3, row += 1
    For column = 1, column <= 3, column += 1
        Output row * column
        Output "\t"
    Output "\n"

An Example - Nested Do While For Loops[edit | edit source]

Please input what number you want to multiply 3 What number do you want constant 2 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 Would you like another set? Type yes no Ok bye

Here is a pseudo code for the example above

Function Main
    Declare Integer answer
    Declare Integer multiply
    Declare Integer constant
    Declare String choice
    
    Loop
        Output "Please input what number you want to multiply"
        Input multiply
        Output "What number do you want constant"
        Input constant
        Declare Integer i
        
        Assign i = 0
        For i = 1 to multiply
            Assign answer = i * constant
            Output constant & " x " & i & " = " & answer
        End
        Output "Would you like another set? Type yes"
        Input choice
    Do choice == "Yes"
    Output "Ok bye"
End

Key Terms[edit | edit source]

complex logic
Often solved with nested control structures.

References[edit | edit source]


Loop Examples

Counting[edit | edit source]

Pseudocode[edit | edit source]

... This program demonstrates While, Do, and For loop counting using user-designated start, stop, and increment values.

Function Main
    Declare Integer start
    Declare Integer stop
    Declare Integer increment
    
    Assign start = GetValue("starting")
    Assign stop = GetValue("ending")
    Assign increment = GetValue("increment")
    Call WhileLoop(start, stop, increment)
    Call DoLoop(start, stop, increment)
    Call ForLoop(start, stop, increment)
End

Function GetValue (String name)
    Declare Integer value
    
    Output "Enter " & name & " value:"
    Input value
Return Integer value

Function WhileLoop (Integer start, Integer stop, Integer increment)
    Output "While loop counting from " & start & " to " & stop & " by " & increment & ":"
    Declare Integer count
    
    Assign count = start
    While count <= stop
        Output count
        Assign count = count + increment
    End
End

Function DoLoop (Integer start, Integer stop, Integer increment)
    Output "Do loop counting from " & start & " to " & stop & " by " & increment & ":"
    Declare Integer count
    
    Assign count = start
    Loop
        Output count
        Assign count = count + increment
    Do count <= stop
End

Function ForLoop (Integer start, Integer stop, Integer increment)
    Output "For loop counting from " & start & " to " & stop & " by " & increment & ":"
    Declare Integer count
    
    For count = start to stop step increment
        Output count
    End
End

Output[edit | edit source]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

Flowchart[edit | edit source]

Loops main flowchart Loops Get Value flowchart Loops While Loop flowchart Loops Do Loop flowchart Loops For Loop flowchart

References[edit | edit source]


Loop Examples C++

Counting[edit | edit source]

// This program demonstrates While, Do, and For loop counting using 
// user-designated start, stop, and increment values.
//
// References:
//     https://en.wikibooks.org/wiki/C%2B%2B_Programming

#include 

using namespace std;

int getValue(string name);
void whileLoop(int start, int stop, int increment);
void doLoop(int start, int stop, int increment);
void forLoop(int start, int stop, int increment);

int main() {
    int start = getValue("starting");
    int stop = getValue("ending");
    int increment = getValue("increment");

    whileLoop(start, stop, increment);
    doLoop(start, stop, increment);
    forLoop(start, stop, increment);

    return 0;
}

int getValue(string name) {
    int value;
    
    cout << "Enter " << name << " value:" <> value;
    
    return value;
}

void whileLoop(int start, int stop, int increment) {
    cout << "While loop counting from " << start << " to " << 
        stop << " by " << increment << ":" << endl;
    
    int count = start;
    while (count <= stop) {
        cout << count << endl;
        count = count + increment;
    }
}

void doLoop(int start, int stop, int increment) {
    cout << "Do loop counting from " << start << " to " << 
        stop << " by " << increment << ":" << endl;
    
    int count = start;
    do {
        cout << count << endl;
        count = count + increment;
    } while (count <= stop);
}

void forLoop(int start, int stop, int increment) {
    cout << "For loop counting from " << start << " to " << 
        stop << " by " << increment << ":" << endl;
    
    for (int count = start; count <= stop; count += increment) {
        cout << count << endl;
    }
}

Output[edit | edit source]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References[edit | edit source]


Loop Examples CSharp

Counting[edit | edit source]

// This program demonstrates While, Do, and For loop counting using 
// user-designated start, stop, and increment values.
//
// References:
//     https://en.wikibooks.org/wiki/C_Sharp_Programming

using System;

public class Loops
{
    public static void Main(string[] args)
    {
        int start = GetValue("starting");
        int stop = GetValue("ending");
        int increment = GetValue("increment");
        
        WhileLoop(start, stop, increment);
        DoLoop(start, stop, increment);
        ForLoop(start, stop, increment);
    }
    
    public static int GetValue(string name)
    {
        Console.WriteLine("Enter " + name + " value:");
        string input = Console.ReadLine();
        int value = Convert.ToInt32(input);
        
        return value;
    }
    
    public static void WhileLoop(int start, int stop, int increment)
    {
        Console.WriteLine("While loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        int count = start;
        while (count &lt;= stop)
        {
            Console.WriteLine(count);
            count = count + increment;
        }
    }
    
    public static void DoLoop(int start, int stop, int increment)
    {
        Console.WriteLine(&quot;Do loop counting from &quot; + start + &quot; to &quot; + 
            stop + &quot; by &quot; + increment + &quot;:&quot;);
        
        int count = start;
        do
        {
            Console.WriteLine(count);
            count = count + increment;
        }
        while (count &lt;= stop);
    }
    
    public static void ForLoop(int start, int stop, int increment)
    {
        Console.WriteLine(&quot;For loop counting from &quot; + start + &quot; to &quot; + 
            stop + &quot; by &quot; + increment + &quot;:&quot;);
        
        for (int count = start; count &lt;= stop; count += increment)
        {
            Console.WriteLine(count);
        }
    }
}

Output[edit | edit source]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References[edit | edit source]


Loop Examples Java

Counting[edit | edit source]

// This program demonstrates While, Do, and For loop counting using 
// user-designated start, stop, and increment values.
//
// References:
//     https://en.wikibooks.org/wiki/Java_Programming

import java.util.*;

public class Main {
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        int start = getValue("starting");
        int stop = getValue("ending");
        int increment = getValue("increment");

        whileLoop(start, stop, increment);
        doLoop(start, stop, increment);
        forLoop(start, stop, increment);
    }
    
    public static int getValue(String name) {
        System.out.println("Enter " + name + " value:");
        int value = input.nextInt();
        
        return value;
    }
    
    public static void whileLoop(int start, int stop, int increment) {
        System.out.println("While loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        int count = start;
        while (count &lt;= stop) {
            System.out.println(count);
            count = count + increment;
        }
    }
    
    public static void doLoop(int start, int stop, int increment) {
        System.out.println(&quot;Do loop counting from &quot; + start + &quot; to &quot; + 
            stop + &quot; by &quot; + increment + &quot;:&quot;);
        
        int count = start;
        do {
            System.out.println(count);
            count = count + increment;
        } while (count &lt;= stop);
    }
    
    public static void forLoop(int start, int stop, int increment) {
        System.out.println(&quot;For loop counting from &quot; + start + &quot; to &quot; + 
            stop + &quot; by &quot; + increment + &quot;:&quot;);
        
        for (int count = start; count &lt;= stop; count += increment) {
            System.out.println(count);
        }
    }
}

Output[edit | edit source]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References[edit | edit source]


Loop Examples JavaScript

Counting[edit | edit source]

// This program demonstrates While, Do, and For loop counting using 
// user-designated start, stop, and increment values.
//
// References:
//   https://en.wikibooks.org/wiki/JavaScript

main()

function main() {
    var start = getValue("starting");
    var stop = getValue("ending");
    var increment = getValue("increment");

    whileLoop(start, stop, increment);
    doLoop(start, stop, increment);
    forLoop(start, stop, increment);
}

function getValue(name) {
    output("Enter " + name + " value:");
    var value = Number(input());
    return value;
}

function whileLoop(start, stop, increment) {
    output("While loop counting from " + start + " to " + stop + 
        " by " + increment + ":");

    var count = start;
    while (count &lt;= stop) {
        output(count);
        count = count + increment;
    }
}

function doLoop(start, stop, increment) {
    output(&quot;Do loop counting from &quot; + start + &quot; to &quot; + stop + 
        &quot; by &quot; + increment + &quot;:&quot;);
    
    var count = start;
    do {
        output(count);
        count = count + increment;
    } while (count &lt;= stop);
}

function forLoop(start, stop, increment) {
    output(&quot;For loop counting from &quot; + start + &quot; to &quot; + stop + 
        &quot; by &quot; + increment + &quot;:&quot;);
    
    for (var count = start; count &lt;= stop; count += increment) {
        output(count);
    }
}

function input(text) {
  if (typeof window === &#039;object&#039;) {
    return prompt(text)
  }
  else if (typeof console === &#039;object&#039;) {
    const rls = require(&#039;readline-sync&#039;);
    var value = rls.question(text);
    return value;
  }
  else {
    output(text);
    var isr = new java.io.InputStreamReader(java.lang.System.in); 
    var br = new java.io.BufferedReader(isr); 
    var line = br.readLine();
    return line.trim();
  }
}

function output(text) {
  if (typeof document === &#039;object&#039;) {
    document.write(text);
  } 
  else if (typeof console === &#039;object&#039;) {
    console.log(text);
  } 
  else {
    print(text);
  }
}

Output[edit | edit source]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References[edit | edit source]


Loop Examples Python

Counting[edit | edit source]

# This program demonstrates While, Do, and For loop counting using
# user-designated start, stop, and increment values.
#
# References:
#     https://en.wikibooks.org/wiki/Python_Programming


def get_value(name):
    print("Enter " + name + " value:")
    value = int(input())    
    return value


def while_loop(start, stop, increment):
    print("While loop counting from " + str(start) + " to " + 
        str(stop) + " by " + str(increment) + ":")
    count = start
    while count <= stop:
        print(count)
        count = count + increment


def do_loop(start, stop, increment):
    print("Do loop counting from " + str(start) + " to " + 
        str(stop) + " by " + str(increment) + ":")
    count = start
    while True:    #This simulates a Do Loop
        print(count)
        count = count + increment
        if not(count <= stop): break   #Exit loop


def for_loop(start, stop, increment):
    print("For loop counting from " + str(start) + " to " + 
        str(stop) + " by " + str(increment) + ":")
    for count in range(start, stop + increment, increment):
        print(count)


def main():
    start = get_value("starting")
    stop = get_value("ending")
    increment = get_value("increment")
    while_loop(start, stop, increment)
    do_loop(start, stop, increment)
    for_loop(start, stop, increment)


main()

Output[edit | edit source]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References[edit | edit source]


Loop Examples Swift

Counting[edit | edit source]

// This program demonstrates While, Do, and For loop counting using
// user-designated start, stop, and increment values.
//
// References:
//     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

import Foundation

func getValue(name: String) -> Int {
    var value : Int
    
    print("Enter " + name + " value:")
    value = Int(readLine()!)!
    return value
}

func whileLoop(start: Int, stop: Int, increment: Int) {
    print("While loop counting from " + String(start) + " to " + 
        String(stop) + " by " + String(increment) + ":")
    
    var count : Int
    
    count = start
    while count <= stop {
        print(count)
        count = count + increment
    }
}

func doLoop(start: Int, stop: Int, increment: Int) {
    print("Do loop counting from " + String(start) + " to " + 
        String(stop) + " by " + String(increment) + ":")
    
    var count : Int
    
    count = start
    repeat {
        print(count)
        count = count + increment
    } while count <= stop
}

func forLoop(start: Int, stop: Int, increment: Int) {
    print("For loop counting from " + String(start) + " to " + 
        String(stop) + " by " + String(increment) + ":")
    
    for count in stride(from: start, through: stop, by: increment) {
        print(count)
    }
}

func main() {
    var start : Int
    var stop : Int
    var increment : Int

    start = getValue(name: "starting")
    stop = getValue(name: "ending")
    increment = getValue(name: "increment")

    whileLoop(start: start, stop: stop, increment: increment)
    doLoop(start: start, stop: stop, increment: increment)
    forLoop(start: start, stop: stop, increment: increment)
}

main()

Output[edit | edit source]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References[edit | edit source]


Practice: Loops

Chapter Summary[edit | edit source]

  • Iteration Control Structures - A statement or block is executed until the program reaches a certain state, or operations have been applied to every element of a collection.
  • While Loop - A control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
  • Do While Loop - A control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given Boolean condition at the end of the block.
  • Flag Concept - A flag is a variable used to store information that will normally be used to control the program.
  • For Loop - A pretest loop that executes code repetitively until the condition evaluates to false. For loops are definite loops which are generally used as a counting loop when the number of iterations is known.
  • Branching Statements - Instructions in a computer program that can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order.
  • Increment and Decrement Operators - Unary operators that add or subtract one from their operand, respectively.
  • Integer Overflow - When an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.
  • Nested Loops - Nested loops place one for loop inside another for loop. The inner loop is repeated for each iteration of the outer loop.

Review Questions[edit | edit source]

True / False[edit | edit source]

  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 the loop.
  6. Only for loops can be counting loops.
  7. The integer data type has modular arithmetic attributes.
  8. The escape code of \n is part of the formatting output.
  9. Nested for loops is not allowed in the C++ programming language.
  10. Counting loops use all four of the loop attributes.
  11. A Do While Loop is a block of statements that are executed one or more times before the expression is checked.
  12. In Python, While loops and Do While loops both use the While statement.
  13. Decrement is adding one to the value of a variable.
  14. a break is a predefined function used to prematurely stop a program and return to the operating system.
  15. A while loop will repeat a block of code indefinitely or until an exit command.
  16. The best loop for restarting your program is a While loop because the While loop will run through all the statements at least once before checking if the expression is true or not.
  17. a prefix increment adds one to the operator to the left of the operand.

Answers:

  1. false - The difference is that where the condition is checked
  2. true - Typically equality uses two equal signs instead of one.
  3. false - It is available in older languages more commonly than newer ones.
  4. false - Flags are used to control or indicate the intermediate state or outcome of particular operations.
  5. false - Do While loops are a test after iteration control structure, meaning they test after the loop has run at least once.
  6. false - Any kind of loop can be a counting loop.
  7. true
  8. true
  9. false - Nested loops involve a loop in another loop. They can be used in any language.
  10. true
  11. true
  12. true - The difference between the two is where the condition is checked.
  13. false - Increment is adding to the value of a variable.
  14. false - A break is a branching statement that terminates the existing structure.
  15. false - A Do While loop will repeat a block of code while true and exit with an exit command. While loop will loop indefinitely or condition is met.
  16. false - The While loop always checks the expression to see if it's true or not before running the associated statements, making it a terrible loop for restarting your program. The best loop for restarting your program is actually a Do While loop since it always runs the statement's in the loop once before checking if the expression is true or not.
  17. true

Short Answer:

  1. In your own words describe the difference between a Do and a Do While loop.
  2. If you wanted to create a program that asked for a name on startup, and wouldn't advance until given one, what type of loop would you use and why?

Fill in the blank: Practicing Truth Tables[edit | edit source]

  1. True AND False = _____
  2. False AND NOT False = _____
  3. True OR True = _____
  4. True AND False = _____
  5. False OR NOT True = _____
  6. True AND True = _____
  7. False OR True = _____
  8. False AND False = _____

Activities[edit | edit source]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

While Loops[edit | edit source]

Complete the following using a while loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
    1 * 1 = 1
    1 * 2 = 2
    1 * 3 = 3
    A list of five expressions for the value 3 would be:
    3 * 1 = 3
    3 * 2 = 6
    3 * 3 = 9
    3 * 4 = 12
    3 * 5 = 15
  2. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores.
  3. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.

Do While / Repeat Until Loops[edit | edit source]

Complete the following using a do while / repeat until loop structure.

  1. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Use a loop to request each score and add it to a total. Continue accepting scores until the user enters either a negative value or no value (your choice). Finally, calculate and display the average for the entered scores.
  2. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess the user’s number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Continue efficiently guessing higher or lower until they indicate equal, then print the number of guesses required to guess their number and end the program.
  3. Add a do while / repeat until loop to any activity from a previous chapter. Continue running the program while the user wants to continue or until the user wants to stop.
  4. Add an input validation loop to any activity from a previous chapter. Verify that the input is valid before returning the value. Ask the user to input the value again while the input is invalid.

For Loops[edit | edit source]

Complete the following using a for loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
    1 * 1 = 1
    1 * 2 = 2
    1 * 3 = 3
    A list of five expressions for the value 3 would be:
    3 * 1 = 3
    3 * 2 = 6
    3 * 3 = 9
    3 * 4 = 12
    3 * 5 = 15
  2. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores.
  3. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.

Nested Loops[edit | edit source]

Complete the following using a nested loop structure.

  1. Review MathsIsFun: 10x Printable Multiplication Table. Create a program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Include row and column labels. For example, the output from 1 to 3 might look like:
        1   2   3
    1   1   2   3
    2   2   4   6
    3   3   6   9
    The output from 3 to 5 might look like:
        3   4   5
    3   9  12  15
    4  12  16  20
    5  15  20  25
  2. Add a do while / repeat until loop to any activity from this chapter. Continue running the program while the user wants to continue or until the user wants to stop.

References[edit | edit source]


Arrays

Overview[edit | edit source]

This chapter introduces arrays, which may be referred to as lists in some programming languages. Arrays are used for data structures and are able to store an arrangement of elements. Various versions of arrays will be introduced for use in different scenarios. All arrays will be the same data type and capable of working with functions and other variables, as we will learn throughout the chapter.

Chapter Outline[edit | edit source]

Learning Objectives[edit | edit source]

  1. Understand key terms and definitions.
  2. Identify static and dynamic arrays and the code structures necessary to process each type.
  3. Identify single-dimension arrays and multi-dimensional arrays and the code structures necessary to process each type.
  4. Given example pseudocode, flowcharts, and source code, create a program that uses arrays or lists to solve a given problem.


Arrays and Lists

Overview[edit | edit source]

An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.[1]

Depending on the language, array types may overlap (or be identified with) other data types that describe aggregates of values, such as lists and strings. Array types are often implemented by array data structures, but sometimes by other means, such as hash tables, linked lists, or search trees.[2] In Python, the built-in array data structure is a list.

Static arrays have a fixed size. Their length cannot be changed. On the other hand, dynamic array lengths can be altered. According to geeksforgees.org, dynamic arrays are described as a simple dynamic array that can be constructed by allocating an array of fixed-size, typically the number of elements immediately required. The elements of the dynamic array are stored contiguously at the start of the underlying array. Elements can be added at the end of a dynamic array in real time by using reserved memory space until this space is completely consumed.[3][4]

Discussion[edit | edit source]

An array is a data structure consisting of a collection of elements, each identified by an 'array index' or 'key'. Each axis of an array is called a dimension. A 'list' is a single dimension array. A 'table' is a 2 dimensional array. The index notation specifies elements of an array, using brackets [] or {} depending on the programming language, to store the elements into the array. A string is 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.

Individual values of the array are called members or elements. The operators allow us to reference or access the individual members. The operator commonly associated with referencing array members is the index operator.

Defining an Array[edit | edit source]

Language Example
C++ int ages[] = {49, 48, 26, 19, 16};
C# int[] ages = {49, 48, 26, 19, 16};
Java int[] ages = {49, 48, 26, 19, 16};
JavaScript var ages = [49, 48, 26, 19, 16];
Python ages = [49, 48, 26, 19, 16]
Swift var ages:[Int] = [49, 48, 26, 19, 16]

This process is known as the defining of storage space. The square brackets [] are used here to create the array with five integer members and the identifier name of ages. The assignment with braces (that is a block) establishes the initial values assigned to the members of the array. Note the use of the sequence or comma operator. We could have also done something similar to:

Language Example Initial Values
C++ int ages[5]; undefined
C# int[] ages = new int[5]; 0
Java int[] ages = new int[5]; 0
JavaScript var ages = Array(5); undefined
Python ages = [None] * 5 None

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 or initialized as indicated, depending on the programming language. We could assign values later in our program by doing the following (leaving off the semicolons in Python):

ages[0] = 49;
ages[1] = 48;
ages[2] = 26;
ages[3] = 19;
ages[4] = 16;

Note: The members of the array go from 0 to 4; NOT 1 to 5. This is explained in more detail on the next page.

Key Terms[edit | edit source]

array
is a data structure consisting of a collection of elements (values or variables).
dimension
An axis of an array.
index notation
Specifies elements of an array, using brackets [] or {} depending on the programming language
list
A single dimension array.
table
A two-dimension array.

References[edit | edit source]


Index Notation

Overview[edit | edit source]

Index notation is used to specify the elements of an array.[1] Most current programming languages use square brackets [] as the array index operator. Older programming languages, such as FORTRAN, COBOL, and BASIC, often use parentheses () as the array index operator.

Discussion[edit | edit source]

Example:

Language Example
C++ int ages[] = {49, 48, 26, 19, 16};
int myAge = ages[2];
C# int[] ages = {49, 48, 26, 19, 16};
int myAge = ages[2];
Java int[] ages = {49, 48, 26, 19, 16};
int myAge = ages[2];
JavaScript var ages = [49, 48, 26, 19, 16];
int myAge = ages[2];
Python ages = [49, 48, 26, 19, 16]
my_age = ages[2]
Swift var ages:[Int] = [49, 48, 26, 19, 16]
var my_age = ages[2]

As an operator, square brackets either provide the value held by the member of the array (Rvalue) or change the value of member (Lvalue). In the above example, the member that is two offsets from the front of the array (the value 26) is assigned to the variable named myAge. The dereference operator of [2] tells the computer, go to the 2nd offset from the front of the ages array and get the value stored there. In this case, the value would be 26. In most current programming languages, the array members (or elements) are referenced starting at zero. The more common way for people to reference a list is by starting with position one. Consider:

Position Index Miss America Other Contests
zero offsets from the front ages[0] Winner 1st Place
one offset from the front ages[1] 1st Runner Up 2nd Place
two offsets from the front ages[2] 2nd Runner Up 3rd Place
three offsets from the front ages[3] 3rd Runner Up 4th Place
four offsets from the front ages[4] 4th Runner Up 5th Place

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;

This is an example of changing an array’s value by assigning 20 to the 4th member of the array and replacing the value 19 with 20. This is an Lvalue context because the array is on the left side of the assignment operator.

Key Terms[edit | edit source]

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.

References[edit | edit source]


Displaying Array Members

Overview[edit | edit source]

To display all array members, get the value of each element using a for loop and output the element using index notation and the loop control variable.

Discussion[edit | edit source]

Accessing Array Members[edit | edit source]

Let's say we want to create an integer array named "ages" with five values of 49, 48, 26, 19, and 16. In pseudocode, this might be written as:

Declare Integer Array ages[5]

Assign ages = [49, 48, 26, 19, 16]

To display all elements of the array in order, we might write:

Output ages[0]

Output ages[1]

Output ages[2]

Output ages[3]

Output ages[4]

While this works for short arrays, it is a terrible method for arrays that contain hundreds or thousands of values due to having to type out each element. One of the principles of software development is don’t repeat yourself (DRY). Violations of the DRY principle are typically referred to as WET solutions, which is commonly taken to stand for either “write everything twice”, “we enjoy typing” or “waste everyone’s time."[1]

Rather than repeating ourselves, we can use a "for" loop to get the value of each element of the array and use the loop control variable as the array index. Consider the following pseudocode:

Declare Integer Array ages[5]
Declare Integer index
    
Assign ages = [49, 48, 26, 19, 16]

For index = 0 to 4
    Output ages[index]
End

This approach is much more efficient from a programming perspective, and also results in a smaller program. But there is still one more opportunity for improvement. Most programming languages support a built-in method for determining the size of an array. To reduce potential errors and required maintenance, the loop control should be based on the size of the array rather than a hard-coded value. Consider:

Declare Integer Array ages[5]
Declare Integer index
    
Assign ages = [49, 48, 26, 19, 16]

For index = 0 to Size(ages) - 1
    Output ages[index]
End

This method allows for flexible coding.  By writing the "for" loop in this fashion, we can change the declaration of the array by adding or subtracting members and we don’t need to change our for loop code.

Key Terms[edit | edit source]

don’t repeat yourself
A principle of software development aimed at reducing repetition of software patterns, replacing repetition with abstractions, or repetition of the same data. Instead, programmers should use data normalization to avoid redundancy.[2]
flexible coding
Using the size of an array to determine the number of loop iterations required.

References[edit | edit source]


Arrays and Functions

Overview[edit | edit source]

In modular programming, specific task functions are often created and used/reused for array processing. Array processing functions are usually passed with the array and any data necessary to process the array for the given task.

It should be noted that arrays are passed by reference in most current programming languages. Array processing functions must take care not to alter the array unless intended.

Discussion[edit | edit source]

Arrays are an important complex data type. 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 either passed with the array along with the number of elements within the array, or just the array itself if the programming language has functions to determine current array size. Some functions also accept additional parameters necessary for that particular function’s task.

This module covers displaying array members by calling an array function dedicated to that task.

Pseudocode[edit | edit source]

Function Main
    Declare Integer Array ages[5]
    
    Assign ages = [49, 48, 26, 19, 16]
    Call DisplayArray(ages)
End

Function DisplayArray (Integer Array array)
    Declare Integer index
    
    For index = 0 to Size(array) - 1
        Output array[index]
    End
End

Output[edit | edit source]

49
48
26
19
16

Key Terms[edit | edit source]

array function
A user-defined specific task function designed to process an array.

References[edit | edit source]


Math Statistics with Arrays

Overview[edit | edit source]

Statistics is a branch of mathematics dealing with the collection, organization, analysis, interpretation, and presentation of data. Common statistical methods include mean (or average) and standard deviation.[1]

Discussion[edit | edit source]

Arrays can store words, letters/characters (strings) and numbers (integers/floats). Any type of array containing words, numbers or a combination can use a built-in function like len(Python exclusive) to find the number of elements in an array to help display output and parse lines. All arrays can also handle functions that allow the user to sort array values from highest to lowest (or vice versa). Other functions are only intended to handle arrays with numbers. For example, When arrays contain numbers, the elements of the array can be added together using the sum function. Since the built-in sum function cannot handle strings without producing an unsupported operand type error, we use this function only to add numbers, rather than join strings together.

We will continue learning about the sum function (also known as totaling) in this module. In the example below, the sum function totals the array passed to it. Other mathematical functions often associated with statistics such as: average, count, minimum, maximum, standard deviation, etc. are often developed for processing arrays.

Pseudocode[edit | edit source]

Function Main
    Declare Integer Array ages[5]
    Declare Integer total
    
    Assign ages = [49, 48, 26, 19, 16]

    Assign total = sum(ages)

    Output "Total age is: " & total
End

Function sum (Integer Array array)
    Declare Integer total
    Declare Integer index
    
    Assign total = 0
    For index = 0 to Size(array) - 1
        Assign total = total + array[index]
    End
Return Integer total

Output[edit | edit source]

Total age is: 158

Key Terms[edit | edit source]

sum
is a built-in function, which adds the elements of an array together.
len
is a built-in function and it returns the number of items in an object.

References[edit | edit source]


Searching Arrays

Overview[edit | edit source]

Linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.[1]

Discussion[edit | edit source]

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 or her algorithm.

“The linear search is a very simple algorithm. Sometimes called a sequential search, it uses a loop to sequentially step through an array, starting with the first element. It compares each element with the value being searched for and stops when either the value is found or the end of the array is encountered. If the value being searched for is not in the array, the algorithm will search to the end of the array.”[2]

Two specific linear searches can be made for the maximum (largest) value in the array or the minimum (smallest) value in the array. Maximum and minimum are also known as max and min. Note that the following max and min functions assume an array size >= 1.

Pseudocode[edit | edit source]

Function Main
    Declare Integer Array ages[5]
    Declare Integer maximum
    Declare Integer minimum
    
    Assign ages = [49, 48, 26, 19, 16]

    Assign maximum = max(ages)
    Assign minimum = min(ages)

    Output "Maximum age is: " & maximum
    Output "Minimum age is: " & minimum
End

Function max (Integer Array array)
    Declare Integer maximum
    Declare Integer index
    
    Assign maximum = array[0]
    For index = 1 to Size(array) - 1
        If maximum < array[index] 
            Assign maximum = array[index] 
        End 
    End 
Return Integer maximum 

Function min (Integer Array array) 
    Declare Integer minimum 
    Declare Integer index 

    Assign minimum = array[0] 
    For index = 1 to Size(array) - 1 
        If minimum > array[index]
            Assign minimum = array[index]
        End
    End
Return Integer minimum

Output[edit | edit source]

Maximum age is: 49
Minimum age is: 16

Key Terms[edit | edit source]

linear search
Using a loop to sequentially step through an array.
maximum
"max" is an abbreviation for maximum, which means the largest member of an array.
minimum
"min" is an abbreviation for minimum, which means the smallest member of an array.

References[edit | edit source]

  1. Wikipedia: Linear search
  2. Tony Gaddis, Judy Walters, and Godfrey Muganda, Starting Out with C++ Early Objects Sixth Edition (United States of America: Pearson – Addison Wesley, 2008) 559.


Sorting Arrays

Overview[edit | edit source]

A sorting algorithm is an algorithm that puts elements of a list in a certain order. The most frequently used orders are numerical order and lexicographical order.[1] Most current programming languages include built-in or standard library functions for sorting arrays.

Discussion[edit | edit source]

Sorting is the process through which data are arranged according to their values. The following examples show standard library and/or built-in array sorting methods for different programming languages.

Language Sort Example
C++ #include <algorithm>
sort(array, array + sizeof(array) / sizeof(int));
C# System.Array.Sort(array);
Java import java.util.Arrays;
Arrays.sort(array);
JavaScript array.sort();
Python array.sort()
Swift array.sort()
Language Reverse Sort Example
C++ #include <algorithm>
sort(array, array + sizeof(array) / sizeof(int), greater <int>());
C# System.Array.Sort(array);
System.Array.Reverse(array);
Java import java.util.Arrays;
Arrays.sort(array, Collections.reverseOrder());
JavaScript array.sort;
array.reverse();
Python array.sort(reverse=True)
Swift array.sort(>)

Key Terms[edit | edit source]

sorting
Arranging data according to their values.

References[edit | edit source]


Parallel Arrays

Overview[edit | edit source]

A group of parallel arrays is a form of implicit data structure that uses multiple arrays to represent a singular array of records. It keeps a separate, homogeneous data array for each field of the record, each having the same number of elements. Then, objects located at the same index in each array are implicitly the fields of a single record.[1]

Discussion[edit | edit source]

A data structure is a data organization and storage format that enables efficient access and modification. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data. Data structure options include arrays, linked lists, records, and classes.[2]

Parallel arrays use two or more arrays to represent a collection of data where each corresponding array index is a matching field for a given record. For example, if there are two arrays, one for names and one for ages, the array elements at index [2] for arrays "names" and "ages" would describe the name and age of the third person. This is because arrays begin counting at 0.

Pseudocode[edit | edit source]

Function Main
    Declare String Array names[5]
    Declare Integer Array ages[5]
    
    Assign names = ["Lisa", "Michael", "Ashley", "Jacob", "Emily"]
    Assign ages = [49, 48, 26, 19, 16]

    DisplayArrays(names, ages)
End

Function DisplayArrays (String Array names, Integer Array ages)
    Declare Integer index
    
    For index = 0 to Size(name) - 1
        Output names[index] & " is " & ages[index] & " years old"
    End
End

Output[edit | edit source]

Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old

Key Terms[edit | edit source]

parallel array
An implicit data structure that uses multiple arrays to represent a singular array of records.

References[edit | edit source]


Multidimensional Arrays

Overview[edit | edit source]

The number of indices needed to specify an element is called the dimension or dimensionality of the array. A two-dimensional array, or table, may be stored as a one-dimensional array of one-dimensional arrays (rows of columns) and accessed with double indexing (array[row][column] in typical notation).[1]

Discussion[edit | edit source]

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 a section, row, and seat (three dimensions).

We refer to the individual values as members (or elements) of the array. Multidimensional arrays use one set of square brackets per dimension or axis of the array. For example, a table that has two dimensions would use two sets of square brackets to define the array variable and two sets of square brackets for the index operators to access the members of the array. Programming languages implement the details of arrays differently. The total number of dimensions allowed in an array is language-specific and also limited by available memory.

Pseudocode[edit | edit source]

Function Main
    Declare String Array game[3][3]
    
    Assign game = [ ["X", "O", "X"], ["O", "O", "O"], ["X", "O", "X"] ]

    DisplayGame(game)
End

Function DisplayGame (String Array game)
    Declare Integer row
    Declare Integer column
    
    Output "Tic-Tac-Toe"
    For row = 0 to 2
        For column = 0 to 2
            Output game[row][column]
            If column < 2 Then
                Output " | "
            End
        End
    End
End

Output[edit | edit source]

Tic-Tac-Toe
X | O | X
O | O | O
X | O | X

Key Terms[edit | edit source]

array member
An element or value in an array.
dimension
An axis of an array.
index
An operator that allows us to reference a member of an array.
list
A single dimension array.
offset
The method of referencing array members by starting at zero.
table
A two-dimension array.

References[edit | edit source]


Fixed and Dynamic Arrays

Overview[edit | edit source]

A fixed array is an array for which the size or length is determined when the array is created and/or allocated.[1]

A dynamic array is a random access, a variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern programming languages. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that needs to be specified at allocation.[2]

Discussion[edit | edit source]

Static arrays have their size or length determined when the array is created and/or allocated. For this reason, they may also be referred to as fixed-length arrays or fixed arrays. Array values may be specified when the array is defined, or the array size may be defined without specifying array contents. Depending on the programming language, an uninitialized array may contain default values, or it may contain whatever values were left in memory from previous allocation.

Language Defined Values Fixed-Length with Undefined or Default Values
C++ int values[] = {0, 1, 2}; int values[3];
C# int[] values = {0, 1, 2}; int[] values = = new int[3];
Java int[] values = {0, 1, 2}; int[] values = = new int[3];
JavaScript var values = [0, 1, 2]; var values = new Array(3);
Python values = [0, 1, 2] values = [None] * 3
Swift var values:[Int] = [0, 1, 2] var values: [Int] = [Int](repeating: 0, count: 3)

Dynamic arrays allow elements to be added and removed at runtime. Most current programming languages include built-in or standard library functions for creating and managing dynamic arrays.

Language Class Add Remove
C++ #include <list>
std::list
insert erase
C# System.Collections.Generic.List Add Remove
Java java.util.ArrayList add remove
JavaScript Array push, splice pop, splice
Python List append remove
Swift Array append remove

Key Terms[edit | edit source]

dynamic array
A data structure consisting of a collection of elements that allows individual elements to be added or removed.
fixed array
A data structure consisting of a collection of elements for which the size or length is determined when the data structure is defined or allocated.

References[edit | edit source]


Array Examples C++

Arrays[edit | edit source]

// This program demonstrates array processing, including:
// display, total, max, min, parallel arrays, sort,
// fixed arrays, dynamic arrays, and multidimensional arrays.

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

void displayArray(int [], int);
int sum(int [], int);
int max(int [], int);
int min(int [], int);
void displayParallel(string [], int [], int);
void fixedArray();
void dynamicArray();
void displayMultidimensional();

int main() {
    string names[] = {"Lisa", "Michael", "Ashley", "Jacob", "Emily"};
    int ages[] = {49, 48, 26, 19, 16};

    displayArray(ages, sizeof(ages) / sizeof(int));

    int total = sum(ages, sizeof(ages) / sizeof(int));
    int maximum = max(ages, sizeof(ages) / sizeof(int));
    int minimum = min(ages, sizeof(ages) / sizeof(int));

    cout << "total: " << total << endl;
    cout << "maximum: " << maximum << endl;
    cout << "minimum: " << minimum << endl;

    displayParallel(names, ages, sizeof(ages) / sizeof(int));

    sort(ages, ages + sizeof(ages) / sizeof(int));
    displayArray(ages, sizeof(ages) / sizeof(int));

    fixedArray();
    dynamicArray();
    displayMultidimensional();

    return 0;
}

void displayArray(int arry[], int size) {
    for (int index = 0; index < size; index++) {
        cout << "array[" << index << "] = " << arry[index] << endl;
    }
}

int sum(int arry[], int size) {
    int total = 0;
    for (int index = 0; index < size; index++) {
        total += arry[index];
    }
    return total;
}

int max(int arry[], int size) {
    int maximum = arry[0];
    for (int index = 1; index < size; index++) {
        if (maximum < arry[index]) {
            maximum = arry[index];
        }
    }
    return maximum;
}

int min(int arry[], int size) {
    int minimum = arry[0];
    for (int index = 1; index  arry[index]) {
            minimum = arry[index];
        }
    }
    return minimum;
}

void displayParallel(string names[], int ages[], int size) {
    for (int index = 0; index < size; index++) {
        cout << names[index] << " is " << ages[index] << " years old" << endl;
    }
}

void fixedArray() {
    int arry[5];
    srand (time(NULL));
    for (int index = 0; index < 5; index++) {
        int number = rand() % 100;
        arry[index] = number;
    }

    displayArray(arry, 5);
}

void dynamicArray() {
    list arry;
    srand (time(NULL));
    for (int index = 0; index < 5; index++) {
        int number = rand() % 100;
        arry.push_back(number);
    }

    for (list::iterator it = arry.begin(); it != arry.end(); it++) {
        cout << *it << endl;
    }
}

void displayMultidimensional() {
    string game[3][3] = {
        {"X", "O", "X"}, 
        {"O", "O", "O"}, 
        {"X", "O", "X"} };

    for (int row = 0; row < 3; row++) {
        for (int column = 0; column < 3; column++) {
            cout << (game[row][column]);
            if (column < 2) {
                cout << " | ";
            }
        }
        cout << endl;
    }    
}

Output[edit | edit source]

array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
array[0] = 30
array[1] = 14
array[2] = 67
array[3] = 59
array[4] = 96
30
14
67
59
96
X | O | X
O | O | O
X | O | X

References[edit | edit source]


Array Examples CSharp

Arrays[edit | edit source]

// This program demonstrates array processing, including:
// display, total, max, min, parallel arrays, sort,
// fixed arrays, dynamic arrays, and multidimensional arrays.

using System;
using System.Collections.Generic;

class Arrays {
    public static void Main (string[] args) 
    {
        String[] names = {"Lisa", "Michael", "Ashley", "Jacob", "Emily"};
        int[] ages = {49, 48, 26, 19, 16};

        DisplayArray(ages);

        int total = sum(ages);
        int maximum = max(ages);
        int minimum = min(ages);

        Console.WriteLine("total: " + total);
        Console.WriteLine("maximum: " + maximum);
        Console.WriteLine("minimum: " + minimum);

        DisplayParallel(names, ages);

        System.Array.Sort(ages);
        DisplayArray(ages);

        FixedArray();
        DynamicArray();
        DisplayMultidimensional();
    }

    public static void DisplayArray(int[] array) 
    {
        for (int index = 0; index < array.Length; index++) 
        {
            Console.WriteLine("array[" + index + "] = " + array[index]);
        }
    }

    public static int sum(int[] array) 
    {
        int total = 0;
        for (int index = 0; index < array.Length; index++) 
        {
            total += array[index];
        }
        return total;
    }

    public static int max(int[] array) 
    {
        int maximum = array[0];
        for (int index = 1; index < array.Length; index++) 
        {
            if (maximum < array[index]) 
            {
                maximum = array[index];
            }
        }
        return maximum;
    }

    public static int min(int[] array) 
    {
        int minimum = array[0];
        for (int index = 1; index  array[index]) 
            {
                minimum = array[index];
            }
        }
        return minimum;
    }

    public static void DisplayParallel(String[] names, int[] ages) 
    {
        for (int index = 0; index < names.Length; index++) 
        {
            Console.WriteLine(names[index] + " is " + 
                ages[index] + " years old");
        }
    }

    public static void FixedArray() 
    {
        int[] array = new int[5];

        Random random = new Random();
        for (int index = 0; index < array.Length; index++) 
        {
            int number = random.Next(0, 100);
            array[index] = number;
        }
        DisplayArray(array);
    }

    public static void DynamicArray() 
    {
        List array = new List();

        Random random = new Random();
        for (int index = 0; index < 5; index++) 
        {
            int number = random.Next(0, 100);
            array.Add(number);
        }
        for (int index = 0; index < array.Count; index++) 
        {
            Console.WriteLine("array[" + index + "] = " + array[index]);
        }
    }

    public static void DisplayMultidimensional() 
    {
        String[,] game = new String[,] 
        {
            {"X", "O", "X"}, 
            {"O", "O", "O"}, 
            {"X", "O", "X"} 
        };

        for (int row = 0; row < 3; row++) 
        {
            for (int column = 0; column < 3; column++) 
            {
                Console.Write(game[row, column]);
                if (column < 2) 
                {
                    Console.Write(" | ");
                }
            }
            Console.WriteLine();
        }
    }
}

Output[edit | edit source]

array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
array[0] = 65
array[1] = 45
array[2] = 78
array[3] = 32
array[4] = 4
array[0] = 24
array[1] = 62
array[2] = 97
array[3] = 40
array[4] = 82
X | O | X
O | O | O
X | O | X

References[edit | edit source]


Array Examples Java

Arrays[edit | edit source]

// This program demonstrates array processing, including:
// display, total, max, min, parallel arrays, sort,
// fixed arrays, dynamic arrays, and multidimensional arrays.

import java.util.*;

class Main {
    public static void main(String[] args) {
        String[] names = {"Lisa", "Michael", "Ashley", "Jacob", "Emily"};
        int[] ages = {49, 48, 26, 19, 16};

        displayArray(ages);

        int total = sum(ages);
        int maximum = max(ages);
        int minimum = min(ages);

        System.out.println("total: " + total);
        System.out.println("maximum: " + maximum);
        System.out.println("minimum: " + minimum);

        displayParallel(names, ages);

        Arrays.sort(ages);
        displayArray(ages);

        fixedArray();
        dynamicArray();
        displayMultidimensional();
    }

    public static void displayArray(int[] array) {
        for (int index = 0; index < array.length; index++) {
            System.out.println("array[" + index + "] = " + array[index]);
        }
    }

    public static int sum(int[] array) {
        int total = 0;
        for (int index = 0; index < array.length; index++) {
            total += array[index];
        }
        return total;
    }

    public static int max(int[] array) {
        int maximum = array[0];
        for (int index = 1; index < array.length; index++) {
            if (maximum < array[index]) {
                maximum = array[index];
            }
        }
        return maximum;
    }

    public static int min(int[] array) {
        int minimum = array[0];
        for (int index = 1; index  array[index]) {
                minimum = array[index];
            }
        }
        return minimum;
    }

    public static void displayParallel(String[] names, int[] ages) {
        for (int index = 0; index < names.length; index++) {
            System.out.println(names[index] + " is " + 
                ages[index] + " years old");
        }
    }

    public static void fixedArray() {
        int[] array = new int[5];

        for (int index = 0; index < array.length; index++) {
            int number = (int) Math.floor(Math.random() * 100);
            array[index] = number;
        }
        displayArray(array);
    }

    public static void dynamicArray() {
        ArrayList array = new ArrayList();

        for (int index = 0; index < 5; index++) {
            int number = (int) Math.floor(Math.random() * 100);
            array.add(number);
        }
        System.out.println(array);
    }

    public static void displayMultidimensional() {
        String[][] game = {
            {"X", "O", "X"}, 
            {"O", "O", "O"}, 
            {"X", "O", "X"} };

        for (int row = 0; row < 3; row++) {
            for (int column = 0; column < 3; column++) {
                System.out.print(game[row][column]);
                if (column < 2) {
                    System.out.print(" | ");
                }
            }
            System.out.println();
        }
    }
}

Output[edit | edit source]

array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
array[0] = 28
array[1] = 30
array[2] = 28
array[3] = 75
array[4] = 21
[56, 50, 63, 82, 15]
X | O | X
O | O | O
X | O | X

References[edit | edit source]


Array Examples JavaScript

Arrays[edit | edit source]

// This program demonstrates array processing, including:
// display, total, max, min, parallel arrays, sort,
// fixed arrays, dynamic arrays, and multidimensional arrays.

main()

function main() {
    var names = ['Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily'];
    var ages = [49, 48, 26, 19, 16];

    displayArray(names);
    displayArray(ages);

    var total = sum(ages);
    var maximum = max(ages);
    var minimum = min(ages);

    output('total: ' + total);
    output('maximum: ' + maximum);
    output('minimum: ' + minimum);

    displayParallel(names, ages);

    ages.sort();
    displayArray(ages);

    fixedArray();
    dynamicArray();
    displayMultidimensional();
}

function displayArray(array) {
    for (var index = 0; index < array.length; index++) {
        output('array[' + index + '] = ' + array[index]);
    }
}

function sum(array) {
    var total = 0;
    for (var index = 0; index < array.length; index++) {
        total += array[index];
    }
    return total;
}

function max(array) {
    var maximum = array[0];
    for (var index = 1; index < array.length; index++) {
        if (maximum < array[index]) {
            maximum = array[index];
        }
    }
    return maximum;
}

function min(array) {
    var minimum = array[0];
    for (var index = 1; index  array[index]) {
            minimum = array[index];
        }
    }
    return minimum;
}

function displayParallel(names, ages) {
    for (var index = 0; index < names.length; index++) {
        output(names[index] + ' is ' + ages[index] + ' years old');
    }
}

function fixedArray() {
    var array = new Array(5);

    for (var index = 0; index < array.length; index++) {
        var number = Math.floor(Math.random() * 100);
        array[index] = number;
    }
    displayArray(array);
}

function dynamicArray() {
    var array = [];

    for (var index = 0; index < 5; index++) {
        var number = Math.floor(Math.random() * 100);
        array.push(number);
    }
    displayArray(array);
}

function displayMultidimensional() {
    var game = [
        ['X', 'O', 'X'], 
        ['O', 'O', 'O'], 
        ['X', 'O', 'X'] ];

    for (var row = 0; row < 3; row++) {
        var line = '';
        for (var column = 0; column < 3; column++) {
            line += game[row][column];
            if (column < 2) {
                line += ' | ';
            }
        }
        output(line);
    }
}

function output(text) {
  if (typeof document === 'object') {
    document.write(text);
  } 
  else if (typeof console === 'object') {
    console.log(text);
  } 
  else {
    print(text);
  }
}

Output[edit | edit source]

array[0] = Lisa
array[1] = Michael
array[2] = Ashley
array[3] = Jacob
array[4] = Emily
array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
array[0] = 55
array[1] = 4
array[2] = 46
array[3] = 88
array[4] = 49
array[0] = 28
array[1] = 95
array[2] = 13
array[3] = 60
array[4] = 60
X | O | X
O | O | O
X | O | X

References[edit | edit source]


Array Examples Python

Arrays[edit | edit source]

# This program demonstrates array processing, including:
# display, total, max, min, parallel arrays, sort,
# fixed arrays, dynamic arrays, and multidimensional arrays.


def display_array(array):
    for index in range(len(array)):
        print('array[' + str(index) + '] = ' + 
            str(array[index]))


def sum(array):
    total = 0
    for index in range(len(array)):
        total += array[index]
    return total


def max(array):
    maximum = array[0]
    for index in range(1, len(array)):
        if maximum < array[index]:
            maximum = array[index]
    return maximum


def min(array):
    minimum = array[0]
    for index in range(1, len(array)):
        if minimum > array[index]:
            minimum = array[index]
    return minimum


def display_parallel(names, ages):
    for index in range(len(names)):
        print(names[index] + ' is ' + 
            str(ages[index]) + ' years old')
    

def fixed_array():
    import random

    array = [None] * 5
    for index in range(len(array)):
        array[index] = random.randint(0, 100)
    display_array(array)


def dynamic_array():
    import random

    array = []
    for index in range(5):
        array.append(random.randint(0, 100))
    display_array(array)


def display_multidimensional():
    game = [
        ['X', 'O', 'X'], 
        ['O', 'O', 'O'], 
        ['X', 'O', 'X'] ]

    for row in range (0, 3):
        for column in range(0, 3):
            print(game[row][column], end='')
            if column < 2:
                print(' | ', end='')
        print()


def main():
    names = ['Lisa', 'Michael', 'Ashley', 'Jacob', 'Emily']
    ages = [49, 48, 26, 19, 16]

    display_array(names)
    display_array(ages)

    total = sum(ages)
    maximum = max(ages)
    minimum = min(ages)

    print('total: ' + str(total))
    print('maximum: ' + str(maximum))
    print('minimum: ' + str(minimum))

    display_parallel(names, ages)
    
    ages.sort()
    display_array(ages)

    fixed_array()
    dynamic_array()
    display_multidimensional()


main()

Output[edit | edit source]

array[0] = Lisa
array[1] = Michael
array[2] = Ashley
array[3] = Jacob
array[4] = Emily
array[0] = 49
array[0] = Lisa
array[1] = Michael
array[2] = Ashley
array[3] = Jacob
array[4] = Emily
array[0] = 49
array[1] = 48
array[2] = 26
array[3] = 19
array[4] = 16
total: 158
maximum: 49
minimum: 16
Lisa is 49 years old
Michael is 48 years old
Ashley is 26 years old
Jacob is 19 years old
Emily is 16 years old
array[0] = 16
array[1] = 19
array[2] = 26
array[3] = 48
array[4] = 49
array[0] = 18
array[1] = 14
array[2] = 59
array[3] = 99
array[4] = 61
array[0] = 85
array[1] = 4
array[2] = 35
array[3] = 45
array[4] = 93
X | O | X
O | O | O
X | O | X

References[edit | edit source]


Array Examples Swift

Arrays[edit | edit source]

// This program demonstrates array processing, including: 
// display, total, max, min, parallel arrays, sort // multidimensional arrays, and dynamic arrays. 
// 
// References: 
//     https://www.mathsisfun.com/temperature-conversion.html 
//     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

import Foundation

func displayArray(array: [Int]) {
    for index in 0...array.count - 1 {
        print("array[" + String(index) + "] = " + String(array[index]))
    }
}

func displayParallel(names:[String], ages:[Int]) {
    for index in 0...names.count - 1 {
        print(names[index] + " is " + String(ages[index]))
    }
}

func displayMultidimensional() {
    var game: [[String]]
    
    game = [
        ["X", "O", "X"],
        ["O", "X", "O"],
        ["X", "O", "X"]
    ]

    for row in 0...2 {
        for column in 0...2 {
            print(game[row][column], terminator:"")
            if column < 2 {
                print(" | ", terminator:"")
            }
        }
        print()
    }
}

func dynamicArray() {
    var array: [Int] = []

    srand(UInt32(time(nil)))
    for _ in 0...4 {
        array.append(random() % 100)
    }
    print(array)
}

func main() {
    var names: [String]
    var ages: [Int]
    var total: Int
    var maximum: Int
    var minimum: Int

    names = ["Lisa", "Michael", "Ashley", "Jacob", "Emily"]
    ages = [49, 48, 26, 19, 16]

    displayArray(array:ages)
    total = ages.reduce(0, +)
    maximum = ages.max()!
    minimum = ages.min()!

    print("total:", total)
    print("maximum:", maximum)
    print("minimum:", minimum)

    displayParallel(names:names, ages:ages)

    ages.sort()
    displayArray(array:ages)

    displayMultidimensional()
    dynamicArray()
}

main()

Output[edit | edit source]

array[0] = 49 
array[1] = 48 
array[2] = 26 
array[3] = 19 
array[4] = 16 
total: 158 
maximum: 49 
minimum: 16 
Lisa is 49 
Michael is 48 
Ashley is 26 
Jacob is 19 
Emily is 16 
array[0] = 16 
array[1] = 19 
array[2] = 26 
array[3] = 48 
array[4] = 49 
X | O | X 
O | X | O 
X | O | X 
[93, 3, 7, 35, 59]

References[edit | edit source]


Practice: Arrays

Chapter Summary[edit | edit source]

  • Arrays and Lists - Data structures consisting of collections of elements (values or variables).
  • Index Notation - Typically indicated by brackets [] or parenthesis (), index notation is used to identify the location or numeric value of an element of an array. [1]
  • Displaying Array Members - To display all array members, get the value of each element using a for loop and output the element using index notation and the loop control variable.
  • Arrays and Functions - Array processing functions are usually passed with the array and any data necessary to process the array for the given task.
  • Math Statistics with Arrays - Statistics is a branch of mathematics dealing with the collection, organization, analysis, interpretation, and presentation of data. Arrays can store words, letters/characters (strings) and numbers (integers/floats), therefor the arrays and statistics go hand in hand.
  • Searching Arrays - Linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.
  • Sorting Arrays - A sorting algorithm is an algorithm that puts elements of a list in a certain order.
  • Parallel Arrays - A group of parallel arrays is a form of implicit data structure that uses multiple arrays to represent a singular array of records.
  • Multidimensional Arrays - The number of indices needed to specify an element is called the dimension or dimensionality of the array.
  • Dynamic Arrays - A dynamic array is random access, a variable-size list data structure that allows elements to be added or removed.

Review Questions[edit | edit source]

True / False[edit | edit source]

  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.
  6. Linear searches require complex algorithms.
  7. Functions are often created for searching for the max and min values in an array.
  8. The bubble sort is an easy way to arrange data an array.
  9. There is only one method of bubble sorting.
  10. Sorting an array is frequently done.
  11. A single-dimensional array is also called a table.
  12. Array members are referenced starting with one.
  13. If you don't know how many elements are going to go in a certain array, you should create a static array.
  14. It is better to use a list if you want to perform arithmetic functions on the data elements as opposed to a traditional array.
  15. it is impossible for an array to have an empty value in the middle of the array.
  16. You can subtract values from an array.

Answers:

  1. false
  2. true
  3. true
  4. false
  5. false
  6. false
  7. true
  8. true
  9. false
  10. true
  11. false - A single-dimensional array is known as a list.
  12. false - Some programming languages may start at one, but for others, such as Python, the array members start at 0.
  13. false
  14. false
  15. false - A dynamic array can have empty values, where elements can be added or removed.
  16. true

Short Answer[edit | edit source]

  1. Briefly explain what an array is and list the two common operators used with arrays.
  2. Give a short explanation of bubble sorting.
  3. Explain the difference between array push and array pop.
  4. Describe the difference between a static array and a dynamic array. Also, include why you would choose one instead of the other.
  5. Briefly explain the differences between a variable and an array.
  6. explain why sorting arrays is used so often.

Activities[edit | edit source]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

Defined-Value Arrays[edit | edit source]

  1. Review MathsIsFun: Leap Years. Create a program with a defined array where each entry is the number of days in the corresponding month (January = 31, February = 28 or 29 depending on year, March = 31, etc.). Build a parallel string array with the names of each month. Ask the user to enter a year and month number and then look up the corresponding month name and number of days and display the information. Continue accepting input until the user enters an invalid year or invalid month number.[2]
  2. Review Wikipedia: Zeller’s congruence. Create a program that asks the user for their birthday (year, month, and day) and then calculates and displays the day of the week on which they were born. Use an array lookup to convert the numeric day of the week to the correct string representation (Monday, Tuesday, Wednesday, etc.).

Fixed-Length Arrays[edit | edit source]

  1. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a static (fixed-size) array. After the scores are entered, calculate and display the high, low, and average for the entered scores.
  2. Review Wikipedia: Monty Hall problem. Create a program that uses an array to simulate the three doors. Use 0 (zero) to indicate goats and 1 (one) to indicate the car. Clear each “door” and then use a random number function to put the number 1 in one of the array elements. Then use the random number function to randomly select one of the three elements. Run the simulation in a loop 100 times to confirm a 1/3 chance of winning. Then run the simulation again, this time switching the selection after a 0 (goat) is removed from the remaining choices. Run the simulation in a loop 100 times to confirm a 2/3 chance of winning by switching.
  3. If your programming language supports it, use a built-in sort function to sort the grade scores from the activity above and display the array in order from highest score to lowest score.

Dynamic Arrays / Lists[edit | edit source]

  1. If your programming language supports it, update the grade score program above to replace the static array with a dynamic array, and extend the array as each item is added to the array. Continue accepting scores until the user enters a negative value.
  2. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Record each guess in an an array and continue efficiently guessing higher or lower until they indicate equal, then display the list of guesses required to guess their number and end the program.
  3. If your programming language supports it, use a built-in sort function to sort the grade scores from the activity above and display the array in order from highest score to lowest score.

References[edit | edit source]

  1. https://en.wikibooks.org/wiki/Programming_Fundamentals/Index_Notation
  2. Farrell, J. (2015). Programming Logic and Design, Introductory, 8th Edition. Cengage. ISBN 9781285845777


Strings and Files

Overview[edit | edit source]

This chapter introduces string and file processing.

Chapter Outline[edit | edit source]

Learning Objectives[edit | edit source]

  1. Understand key terms and definitions.
  2. Given example pseudocode, flowcharts, and source code, create a program that processes strings to solve a given problem.
  3. Given example pseudocode, flowcharts, and source code, create a program that processes a text file to solve a given problem.
  4. Understand how to replace, add or remove strings into a file.
  5. Be able to read and understand a given file and string program.
  6. Be able to organize a file from any given format.
  7. Understand how to use outside functions within a file and string program.
  8. Understand how to delete, read, or create a file.


Strings

Overview[edit | edit source]

A string is a sequence of characters, as a literal constant or variable. A variable may be fixed or dynamic. A string is considered a data type which is implemented as an array data structure of bytes that stores a sequence of elements using character encoding. [1]

Discussion[edit | edit source]

A variable declared to be a string may either cause storage in memory to be statically or dynamically allocated. When a string appears literally in the source code, it is known as a string literal or an anonymous string.[2]

Most data is more complex than just one character, integer, etc. An array is a sequenced collection of elements of the same data type with a single identifier name. A one-dimensional array(list) lists elements vertically. Strings are viewed as a one-dimensional array that is displayed horizontally.

In the “C” programming language, all strings were handled as an array of characters that ended in an ASCII null character (the value 0 or the first character in the ASCII character code set). This approach required programmers to manually process string length and manage string storage. Buffer overflows were common. A buffer overflow, or buffer overrun, is an anomaly where a program, while writing data to a buffer, overruns the buffer’s boundary and overwrites adjacent memory locations.[3]

The "Javascript" programming language JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third and so on. There are many string functions most important being lastIndexOf(). This searches and (if found) returns the index number of the searched character or substring within the string. Searches the string from end to the beginning. If not found, -1 is returned. “Start” is an optional argument specifying the position within string to begin the search. Default is string.length -1. Slice(start, [end]) returns a substring of the string based on the “start” and “end” index arguments, NOT including the “end” index itself. “End” is optional, and if none is specified, the slice includes all characters from “start” to the end of the string. Split(delimiter, [limit]) Splits a string into many according to the specified delimiter and returns an array containing each element. The optional “limit” is an integer that lets you specify the maximum number of elements to return. There are many more functions that are just as important but these are just an example of what string functions can do in Javascript.

Most current programming languages implement strings as a data type or class where strings are stored as a length controlled array. String length and storage are handled by the compiler or interpreter, reducing program errors.

Language Reserved Word
C++ string
C# String
Java String
JavaScript String
Python str()
Swift String

Key Terms[edit | edit source]

array
A sequenced collection of elements of the same data type with a single identifier name.
buffer overflow
An anomaly where a program overruns a memory storage location and overwrites adjacent memory locations.
concatenation
Combining two strings into one string.
string
An array of single digits or letters that is typically used to display to the user or is the user's input.
string class
A complex data item that uses object oriented programming.
empty string
It is a unique string of length zero

References[edit | edit source]


String Functions

Overview[edit | edit source]

String functions are used in computer programming languages to manipulate a string or query information about a string.[1]

Discussion[edit | edit source]

Most current programming languages include built-in or library functions to process strings. Common examples include case conversion, comparison, concatenation, find, join, length, reverse, split, substring, and trim.

Function C++ C# Java
case tolower(), toupper(), etc. ToLower(), ToUpper(), etc. toLowerCase(), toUpperCase(), etc.
comparison <, >, ==, etc. <, >, ==, etc. <, >, ==, etc.
concatenation +, += +, += +, +=
find find() IndexOf() indexOf()
join N/A Join() join()
length length() Length length()
replace replace() Replace() replace()
reverse reverse() Reverse() N/A
split strtok() Split() split()
substring substr() Substring() substring()
trim N/A Trim() trim()
Function JavaScript Python Swift
case toLowerCase(), toUpperCase(), etc. lower(), upper(), etc. lowercased(), uppercased()
comparison <, >, ==, etc. <, >, ==, etc. <, >, ==, etc.
concatenation +, += +, += +, +=
find indexOf() find() firstIndex()
join join() join() joined()
length length len() count
replace replace() replace() replacingOccurrences()
reverse N/A string[::-1] reversed()
split split() split() split()
substring substring() string[start:end] string[start...end]
trim trim() strip() trimmingCharacters()

Key Terms[edit | edit source]

case
A function that either makes a string all uppercase or lowercase depending on which mode is used.
comparison
Determines if the value (string or non-string), is less than, greater than, or equal to the value it's being compared to.
concatenate
Join character strings end-to-end.[2]
find
Checks if a character in a string exists and if it does, finds the location of that character in the string.
join
Joins strings together using a character of the person's choosing.
length
Finds how many characters are in a string, or the number of elements in an array.
replace
Replaces all instances of one character in a string with another.
reverse
Places all characters of a string or elements in an array in reverse order.
split
Divides a string's content onto separate lines based off a chosen character.
substring
Creates a smaller string by using characters from a bigger string.[3]
trim
Remove leading and trailing spaces from a string.[4]

References[edit | edit source]


String Formatting

Overview[edit | edit source]

String formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.[1]

Discussion[edit | edit source]

Most current programming languages provide one or more string formatting functions that use a template string with placeholders and optional alignment, width, and precision indicators to generate formatted output.

Language Function Examples
C++ snprintf() snprintf(str, sizeof(str), "Hello %s!", name);
snprintf(str, sizeof(str), "$%.2f", value);
C# Format() String.Format("Hello {0}!", name);
String.Format("{0:$0.00}", value);
Java format() String.format("Hello %s!", name);
String.format("$%.2f", value);
JavaScript template literal `Hello ${name}`;
`$${value.toFixed(2)}`;
Python format() "Hello {}!".format(name)
"${:.2f}".format(value)
Swift interpolation
String()
"Hello \(name)!"
String(format:"%.2f", value)

String interpolation, like string concatenation, may lead to security problems. If user input data is improperly escaped or filtered, the system may be exposed to code injection.[2]

Key Terms[edit | edit source]

code injection
The exploitation of a computer bug that is caused by processing invalid data.[3]
formatting
Modifying the way the output is displayed.
interpolation
Variable substitution
string interpolation
Evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

References[edit | edit source]


File Input and Output

Overview[edit | edit source]

A computer file is a computer resource for recording data discretely in a computer storage device. Just as words can be written to paper, so can information be written to a computer file.

There are different types of computer files, designed for different purposes. A file may be designed to store a picture, a written message, a video, a computer program, or a wide variety of other kinds of data. Some types of files can store several types of information at once.

A filename extension is often used to indicate a characteristic of the file contents or its intended use. A file extension is typically delimited from the filename with a full stop (period), but in some systems it is separated with spaces.[1]

By using computer programs, a person can open, read, change, and close a computer file. Computer files may be reopened, modified, and copied an arbitrary number of times.[2]

Discussion[edit | edit source]

In computer programming, standard streams are pre-connected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin – keyboard), standard output (stdout – originally a printer) and standard error (stderr – monitor). Streams may be redirected to other devices and/or files. In current environments, stdout is usually redirected to the monitor.[3]

Computer files are stored on secondary storage devices and used to maintain program data over time. Most programming languages have built-in functions or libraries to support processing files as text streams. We need to understand how to open, read, write and close text files. The following File Input/Output terms are explained:

Text File – A file consisting of characters from the ASCII character code set. Text files (also known as 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 (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 many programming languages to indicate a return character when used within a literal string.

A typical text file consisting of lines can be created by text editors (Notepad) or word processing programs (Microsoft Word). When using a word processor you must usually specify the output file as text (.txt) when saving it. Most source code files are ASCII text files with a unique file extension; such as C++ using .cpp, C# using .cs, Python using .py, etc.. Thus, most compiler/Integrated Development Environment software packages can be used to create ASCII text files.

For example, just as we create a text file on our PC by right clicking and creating a new text document. The same is being done but in code.

Filename – The name and its extension. Most operating systems have restrictions on which characters can be used in filenames. Example 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.

Path (Filespec) – The location of a file along with its filename. Filespec 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: 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. In most current programming languages, a file data type exists and is used for file processing. A file variable will be used to store the device token that the operating system assigns to the file being opened. An open function or method is used to retrieve the device token and typically requires at least two parameters: the path and the mode (read, write, append, or a combination thereof). Corresponding pseudocode would be:

Declare File datafile

datafile = open(filespec, mode)

The open function provides a return value of a device token from the operating system and it is stored in the variable named data.

It is considered good programming practice to determine if the file was opened properly. The reason the operating system usually can’t open a file is because the filespec is wrong (misspelled or not typed case consistent in some operating systems) or the file is not stored in the location specified. Accessing files stored on a network or the Internet may fail due to a network error.

Verifying that a file was opened properly is processed with a condition control structure. That structure may be either be an if-then-else statement or a try-catch / try-except error handler, depending on the programming language used.

Read – Moving data from a device that has been opened into a memory location defined in your program. For example:

text = read(datafile)

or

text = datafile.read()

Write – Moving data from a memory location defined in your program to a device that has been opened. For example:

write(datafile, text)

or

datafile.write(text)

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 ensure that all of the data is physically stored in the output file. For example:

close(datafile)

or

datafile.close()

Key Terms[edit | edit source]

close
Your program requesting the operating system to release a file that was previously opened.
device token
A key value provided by the operating system to associate a device to your program.
filename
The name and its extension.
filespec
The location of a file along with its filename.
open
Your program requesting the operating system to let it have access to an existing file or to open a new file.
read
Moving data from a device that has been opened into a memory location defined in your program.
stream
A sequence of data elements made available over time.[4]
stdin
Standard input stream, typically the keyboard.[5]
stderr
Standard output error stream, typically the monitor.[6]
stdout
Standard output stream, originally a printer, but now typically the monitor.[7]
text file
A file consisting of characters from the ASCII character code set.
write
Moving data from a memory location defined in your program to a device that has been opened.

References[edit | edit source]


Loading an Array from a Text File

Overview[edit | edit source]

Loading an array from a text file requires several steps, including: opening the file, reading the records, parsing (splitting) the records into fields, adding the fields to an array, and closing the file. The file may be read all at once and then parsed or processed line by line. The array must be as large as the number of records in the file or must be generated dynamically.

Discussion[edit | edit source]

Loading an array from a file presents an interesting dilemma. The problem revolves 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?

Either:

  1. Read the file and count the number of records.
  2. Create a static array of that size.
  3. Read the file again and add each record to the array.

Or:

  1. Read the file and dynamically add the records to the array.

Processing Records[edit | edit source]

There are two options for file processing:

  1. Read the entire file into memory, split the records and then process each record.
  2. Read the file line by line and process one record at a time.

Which of these approaches is better will depend on the size of the file and the types of file and string processing supported by your programming language. Reading the entire file at once may be faster for small files. Very large files must be processed line by line.

Processing Fields[edit | edit source]

Processing fields require splitting records based on the given file format. For example, a comma-separated-values file might be formatted as:

Celsius, Fahrenheit
0.0,32.0
1.0,33.8
2.0,35.6

The first line contains field names separated by commas. The following lines contain a value for each of the fields and are separated by commas. Note that all text file input is strings. Each line must be split on the field separator (comma) and then numeric fields must be converted to an integer or floating-point values for processing.

Pseudocode[edit | edit source]

Static Array Processing[edit | edit source]

Open file
Read header
While Not End-Of-File
    Read line
    Increment record count
Close file

Declare array with length based on record count
Read Header
While Not End-Of-File
    Read line
    Split line into field(s)
    Convert numeric values to numeric data types
    Add field(s) to array or parallel arrays
Close file

Dynamic Array Processing[edit | edit source]

Declare empty array
Open file
Read Header
While Not End-Of-File
    Read line
    Split line into field(s)
    Convert numeric values to numeric data types
    Add field(s) to array or parallel arrays
Close file

Key Terms[edit | edit source]

dynamic memory
Stack created memory associated with local scope.
parsing
Splitting
static memory
Data area memory associated with global scope.

References[edit | edit source]


String Examples C++

Strings[edit | edit source]

 #include <algorithm>
 #include <iostream>
 #include <string>
 
 using namespace std;
 
 string toLower(string);
 string toUpper(string);
 
 int main() {
     string str = "Hello";
 
     cout << "string: " << str << endl;
     cout << "tolower: " << toLower(str) << endl;
     cout << "toupper: " << toUpper(str) << endl;
     cout << "string.find('e'): " << str.find('e') << endl;
     cout << "string.length(): " << str.length() << endl;
     cout << "string.replace(0, 1, \"j\"): " << str.replace(0, 1, "j") << endl;
     cout << "string.substr(2, 2): " << str.substr(2, 2) << endl;
 
     string name = "Bob";
     double value = 123.456;
     cout << name << " earned $" << fixed << setprecision (2) << value << endl;
 
 }
 
 string toLower(string str) {
     transform(str.begin(), str.end(), str.begin(), ::tolower);
 
     return str;
 }
 
 string toUpper(string str) {
     transform(str.begin(), str.end(), str.begin(), ::toupper);
 
     return str;
 }

Output[edit | edit source]

string: Hello
tolower: hello
toupper: HELLO
string.find('e'): 1
string.length(): 5
string.replace(0, 1, "j"): jello
string.substr(2, 2): ll
Bob earned $123.46

Files[edit | edit source]

 // This program creates a file, adds data to the file, displays the file,
 // appends more data to the file, displays the file, and then deletes the file.
 // It will not run if the file already exists.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://en.wikibooks.org/wiki/C%2B%2B_Programming
 
 #include <fstream>
 #include <iomanip>
 #include <iostream>
 #include <string>
 
 using namespace std;
 
 double calculateFahrenheit(double celsius);
 void createFile(string);
 void readFile(string);
 void appendFile(string);
 void deleteFile(string);
 int fileExists(string);
 
 int main() {
     string FILENAME = "~file.txt";
 
     if(fileExists(FILENAME)) {
         cout << "File already exists." << endl;
     } else {
         createFile(FILENAME);
         readFile(FILENAME);
         appendFile(FILENAME);
         readFile(FILENAME);
         deleteFile(FILENAME);
     }
 }
 
 double calculateFahrenheit(double celsius) {
     double fahrenheit;
 
     fahrenheit = celsius * 9 / 5 + 32;
     return fahrenheit;
 }
 
 void createFile(string filename) {
     fstream file;
     float celsius;
     float fahrenheit;
     
     file.open(filename, fstream::out);
     if (file.is_open()) {
         file << "Celsius,Fahrenheit\n";
         for(celsius = 0; celsius <= 50; celsius++) {
             fahrenheit = calculateFahrenheit(celsius);
             file << fixed << setprecision (1) << celsius << "," << fahrenheit << endl;
         }
         file.close();
     } else {
         cout << "Error creating " << filename << endl;
     }
 }
 
 void readFile(string filename)
 {
     fstream file;
     string line;
 
     file.open(filename, fstream::in);
     if (file.is_open()) {
         while (getline(file, line))
         {
             cout << line << endl;
         }
         file.close();
         cout << endl;
     } else {
         cout << "Error reading " << filename << endl;
     }
 }
 
 void appendFile(string filename)
 {
     fstream file;
     float celsius;
     float fahrenheit;
     
     file.open(filename, fstream::out | fstream::app);
     if (file.is_open()) {
         for(celsius = 51; celsius <= 100; celsius++) {
             fahrenheit = calculateFahrenheit(celsius);
             file << fixed << setprecision (1) << celsius << "," << fahrenheit << endl;
         }
         file.close();
     } else {
         cout << "Error appending to " << filename << endl;
     }
 }
 
 void deleteFile(string filename)
 {
     remove(filename.c_str());
 }
 
 int fileExists(string filename)
 {
     FILE *file;
     
     file = fopen (filename.c_str(), "r");
     if (file != NULL)
     {
         fclose (file);
     }
     return (file != NULL);
 }

Output[edit | edit source]

Celsius,Fahrenheit
0.0,32.0
1.0,33.8
2.0,35.6
...
98.0,208.4
99.0,210.2
100.0,212.0

References[edit | edit source]


String Examples CSharp

Strings[edit | edit source]

 // This program demonstrates string functions.
 
 using System;
 
 class Strings 
 {
     public static void Main (string[] args) 
     {
         String str = "Hello";
 
         Console.WriteLine("string: " + str);
         Console.WriteLine("string.ToLower(): " + str.ToLower());
         Console.WriteLine("string.ToUpper(): " + str.ToUpper());
         Console.WriteLine("string.IndexOf('e'): " + str.IndexOf('e'));
         Console.WriteLine("string.Length: " + str.Length);
         Console.WriteLine("string.Replace('H', 'j'): " + str.Replace('H', 'j'));
         Console.WriteLine("string(Substring(2, 2)): " + str.Substring(2, 2));
         Console.WriteLine("string.Trim(): " + str.Trim());
 
         String name = "Bob";
         double value = 123.456;
         Console.WriteLine(String.Format("{0} earned {1:$0.00}", name, value));
     }
 }

Output[edit | edit source]

string: Hello
string.ToLower(): hello
string.ToUpper(): HELLO
string.IndexOf('e'): 1
string.Length: 5
string.Replace('H', 'j'): jello
string(Substring(2, 2)): ll
string.Trim(): Hello
Bob earned $123.46

Files[edit | edit source]

 // This program creates a file, adds data to the file, displays the file,
 // appends more data to the file, displays the file, and then deletes the file.
 // It will not run if the file already exists.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://en.wikibooks.org/wiki/C_Sharp_Programming
 
 using System;
 
 public class Files
 {
     public static void Main(String[] args)
     {
         string FILENAME = "~file.txt";
     
         if(System.IO.File.Exists(FILENAME))
         {
             System.Console.WriteLine("File already exists.\n");
         }
         else
         {
             CreateFile(FILENAME);
             ReadFile(FILENAME);
             AppendFile(FILENAME);
             ReadFile(FILENAME);
             DeleteFile(FILENAME);
         }
     }
     
     private static double CalculateFahrenheit(double celsius)
     {
         double fahrenheit;
 
         fahrenheit = celsius * 9 / 5 + 32;
         return fahrenheit;
     }
 
     private static void CreateFile(string filename)
     {
         System.IO.StreamWriter file;
         double celsius;
         double fahrenheit;
         
         try
         {
             file = System.IO.File.CreateText(filename);
             file.WriteLine("Celsius,Fahrenheit");
             for(celsius = 0; celsius <= 50; celsius++)
             {
                 fahrenheit = CalculateFahrenheit(celsius);
                 file.WriteLine(String.Format("{0:F1},{1:F1}", celsius, fahrenheit));
             }
             file.Close();
         }
         catch(Exception exception)
         {
             Console.WriteLine("Error creating " + filename);
             Console.WriteLine(exception.Message);
         }
     }
     
     private static void ReadFile(string filename)
     {
         System.IO.StreamReader file;
         string line;
 
         try
         {
             file = System.IO.File.OpenText(filename);
             while (true) 
             {
                 line = file.ReadLine();
                 if (line == null)
                 {
                     break;
                 }
                 Console.WriteLine(line);
             }
             file.Close();
             Console.WriteLine("");
         }
         catch(Exception exception)
         {
             Console.WriteLine("Error reading " + filename);
             Console.WriteLine(exception.Message);
         }
     }
     
     private static void AppendFile(string filename)
     {
         System.IO.StreamWriter file;
         double celsius;
         double fahrenheit;
         
         try
         {
             file = System.IO.File.AppendText(filename);
             for(celsius = 51; celsius <= 100; celsius++)
             {
                 fahrenheit = CalculateFahrenheit(celsius);
                 file.WriteLine(String.Format("{0:F1},{1:F1}", celsius, fahrenheit));
             }
             file.Close();
         }
         catch(Exception exception)
         {
             Console.WriteLine("Error appending to " + filename);
             Console.WriteLine(exception.Message);
         }
     }
     
     private static void DeleteFile(string filename)
     {
         try
         {
             System.IO.File.Delete(filename);
         }
         catch(Exception exception)
         {
             Console.WriteLine("Error deleting " + filename);
             Console.WriteLine(exception.Message);
         }
     }
 }

Output[edit | edit source]

Celsius,Fahrenheit
0.0,32.0
1.0,33.8
2.0,35.6
...
98.0,208.4
99.0,210.2
100.0,212.0

References[edit | edit source]


String Examples Java

Strings[edit | edit source]

 // This program demonstrates string functions.
 
 class Main {
     public static void main(String[] args) {
         String str = "Hello";
 
         System.out.println("string: " + str);
         System.out.println("string.toLowerCase(): " + str.toLowerCase());
         System.out.println("string.toUpperCase(): " + str.toUpperCase());
         System.out.println("string.indexOf('e'): " + str.indexOf('e'));
         System.out.println("string.length(): " + str.length());
         System.out.println("string.replace('H', 'j'): " + str.replace('H', 'j'));
         System.out.println("string(substring(2,4): " + str.substring(2, 4));
         System.out.println("string.trim(): " + str.trim());
 
         String name = "Bob";
         double value = 123.456;
         System.out.println(String.format("%s earned $%.2f", name, value));
     }
 }

Output[edit | edit source]

string: Hello
string..toLowerCase(): hello
string.toUpperCase(): HELLO
string.indexOf('e'): 1
string.length(): 5
string.replace('H', 'j'): jello
string(substring(2,4): ll
string.trim(): Hello
Bob earned $123.46

Files[edit | edit source]

 // This program creates a file, adds data to the file, displays the file,
 // appends more data to the file, displays the file, and then deletes the file.
 // It will not run if the file already exists.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://en.wikibooks.org/wiki/Java_Programming
 
 import java.util.*;
 
 class Main {
     public static void main(String[] args) {
         String FILENAME = "~file.txt";
     
         if(fileExists(FILENAME)) {
             System.out.println("File already exists.\n");
         } else {
             createFile(FILENAME);
             readFile(FILENAME);
             appendFile(FILENAME);
             readFile(FILENAME);
             deleteFile(FILENAME);
         }
     }
     
     private static double calculateFahrenheit(double celsius) {
         double fahrenheit;
 
         fahrenheit = celsius * 9 / 5 + 32;
         return fahrenheit;
     }
 
     private static void createFile(String filename) {
         try {
             java.io.File file = new java.io.File(filename);
             java.io.BufferedWriter writer = 
                 new java.io.BufferedWriter(new java.io.FileWriter(file));
             double celsius;
             double fahrenheit;
             
             writer.write("Celsius,Fahrenheit\n");
             for(celsius = 0; celsius <= 50; celsius++) {
                 fahrenheit = calculateFahrenheit(celsius);
                 writer.write(celsius + "," + fahrenheit + "\n");
             }
             writer.close();
         } catch(Exception exception) {
             System.out.println("Error creating " + filename);
             exception.printStackTrace();
         }
     }
     
     private static void readFile(String filename) {
         try {
             java.io.File file = new java.io.File(filename);
             java.io.BufferedReader reader = 
                 new java.io.BufferedReader(new java.io.FileReader(file));
             String line;
 
             while(true) {
                 line = reader.readLine();
                 if (line == null) {
                     break;
                 }
                 System.out.println(line);
             }
             reader.close();
             System.out.println("");
         } catch(Exception exception) {
             System.out.println("Error reading " + filename);
             exception.printStackTrace();
         }
     }
     
     private static void appendFile(String filename)
     {
         try {
             java.io.File file = new java.io.File(filename);
             java.io.BufferedWriter writer = 
                 new java.io.BufferedWriter(new java.io.FileWriter(file, true));
             double celsius;
             double fahrenheit;
             
             for(celsius = 51; celsius <= 100; celsius++) {
                 fahrenheit = calculateFahrenheit(celsius);
                 writer.write(celsius + "," + fahrenheit + "\n");
             }
             writer.close();
         } catch(Exception exception) {
             System.out.println("Error appending to " + filename);
             exception.printStackTrace();
         }
     }
     
     private static void deleteFile(String filename) {
         java.io.File file;
         
         try {
             file = new java.io.File(filename);
             file.delete();
         } catch(Exception exception) {
             System.out.println("Error deleting " + filename);
             exception.printStackTrace();
         }
         
     }
     
     private static boolean fileExists(String filename) {
         java.io.File file;
         
         file = new java.io.File(filename);
         return file.exists();
     }
 }

Output[edit | edit source]

Celsius,Fahrenheit
0.0,32.0
1.0,33.8
2.0,35.6
...
98.0,208.4
99.0,210.2
100.0,212.0

References[edit | edit source]


String Examples JavaScript

Strings[edit | edit source]

 // This program demonstrates string functions.
 
 main();
 
 function main()
 {
     var str = "Hello";
 
     output("string: " + str);
     output("string.toLowerCase(): " + str.toLowerCase());
     output("string.toUpperCase(): " + str.toUpperCase());
     output("string.indexOf('e'): " + str.indexOf('e'));
     output("string.length: " + str.length);
     output("string.replace('H', 'j'): " + str.replace('H', 'j'));
     output("string(substring(2,4): " + str.substring(2, 4));
     output("string.trim(): " + str.trim());
 
     var name = "Bob";
     var value = 123.456;
     output(`string.format(): ${name} earned $${value.toFixed(2)}`);
 } 
 
 function output(text) {
   if (typeof document === 'object') {
     document.write(text);
   } 
   else if (typeof console === 'object') {
     console.log(text);
   } 
   else {
     print(text);
   }
 }

Output[edit | edit source]

string: Hello
string..toLowerCase(): hello
string.toUpperCase(): HELLO
string.indexOf('e'): 1
string.length: 5
string.replace('H', 'j'): jello
string(substring(2,4): ll
string.trim(): Hello
string.format(): Bob earned $123.46

Files[edit | edit source]

Note: For security reasons, JavaScript in a browser requires the user to select the file to be processed. This example is based on node.js rather than browser-based JavaScript.

 // This program creates a file, adds data to the file, displays the file,
 // appends more data to the file, displays the file, and then deletes the file.
 // It will not run if the file already exists.
 
 function calculateFahrenheit(celsius) {
     fahrenheit = celsius * 9 / 5 + 32
     return fahrenheit
 }
 
 function createFile(filename) {
     var fs = require('fs')
 
     fs.writeFile(filename, "Celsius,Fahrenheit\n",  function(err) {
         if (err) return console.error(err);
     });
 
     for(var celsius = 0; celsius <= 50; celsius++) {
         var fahrenheit = calculateFahrenheit(celsius);
         fs.appendFile(filename, celsius.toFixed(1) + "," + 
             fahrenheit.toFixed(1) + "\n", function (err) {
             if (err) {
                 return console.error(err);
             }
         });
     }
 }
 
 function readFile(filename) {
     var file = require('readline').createInterface( {
       input: require('fs').createReadStream(filename)
     });
     
     file.on('line', function (line) {
         console.log(line);
     });
 }
 
 function appendFile(filename) {
     var fs = require('fs')
 
     for(var celsius = 51; celsius <= 100; celsius++) {
         var fahrenheit = calculateFahrenheit(celsius);
         fs.appendFile(filename, celsius.toFixed(1) + "," + 
             fahrenheit.toFixed(1) + "\n", function (err) {
             if (err) {
                 return console.error(err);
             }
         });
     }
 }
 
 function deleteFile(filename) {
     var fs = require("fs");
 
     fs.unlink(filename, function(err) {
         if (err) {
             return console.error(err);
         }
     });
 }
 
 function fileExists(filename) {
     var fs = require('fs');
     return fs.existsSync(filename);
 }
 
 function main() {
     var filename = "~file.txt";
 
     if(fileExists(filename)) {
         console.log("File already exists.")
     } else {
         createFile(filename);
         readFile(filename);
         appendFile(filename);
         readFile(filename);
         deleteFile(filename);
     }
 }
 
 main();

Output[edit | edit source]

Celsius,Fahrenheit
0.0,32.0
1.0,33.8
2.0,35.6
...
98.0,208.4
99.0,210.2
100.0,212.0

References[edit | edit source]


String Examples Python

Strings[edit | edit source]

 # This program demonstrates string functions.
 
 
 def main():
     string = "Hello"
 
     print("string: " + string)
     print("string.lower(): " + string.lower())
     print("string.upper(): " + string.upper())
     print("string.find('e'): " + str(string.find('e')))
     print("len(string): " + str(len(string)))
     print("string.replace('H', 'j'): " + string.replace('H', 'j')) 
     print("string[::-1]: " + string[::-1])
     print("string[2:4]: " + string[2:4])
     print("string.strip('H'): " + string.strip('H'))
 
     name = "Bob"
     value = 123.456
     print("string.format(): {0} earned ${1:.2f}".format(name, value))
 
 
 main()

Output[edit | edit source]

string: Hello
string.lower(): hello
string.upper(): HELLO
string.find('e'): 1
len(string): 5
string.replace('H', 'j'): jello
string[::-1]: olleH
string[2:4]: ll
string.strip('H'): ello
string.format(): Bob earned $123.46

Files[edit | edit source]

 # This program creates a file, adds data to the file, displays the file,
 # appends more data to the file, displays the file, and then deletes the file.
 # It will not run if the file already exists.
 #
 # References:
 #     https://www.mathsisfun.com/temperature-conversion.html
 #     https://en.wikibooks.org/wiki/Python_Programming
 
 
 import os
 import sys
 
 
 def calculate_fahrenheit(celsius):
     fahrenheit = celsius * 9 / 5 + 32    
     return fahrenheit
 
 
 def create_file(filename):
     try:
         file = open(filename, "w")
         file.write("Celsius,Fahrenheit\n")
         for celsius in range(0, 51):
             fahrenheit = calculate_fahrenheit(celsius)
             file.write("{:.1f},{:.1f}\n".format(celsius, fahrenheit))
         file.close()
     except:
         print("Error creating", filename)
         print(sys.exc_info()[1])
 
 
 def read_file(filename):
     try:
         file = open(filename, "r")
         for line in file:
             line = line.strip()
             print(line)
         file.close()
         print()
     except:
         print("Error reading", filename)
         print(sys.exc_info()[1])
 
 
 def append_file(filename):
     try:
         file = open(filename, "a")
         for celsius in range(51, 101):
             fahrenheit = calculate_fahrenheit(celsius)
             file.write("{:.1f},{:.1f}\n".format(celsius, fahrenheit))
         file.close()
     except:
         print("Error appending to", filename)
         print(sys.exc_info()[1])
 
 
 def delete_file(filename):
     try:
         os.remove(filename)
     except:
         print("Error deleting", filename)
         print(sys.exc_info()[1])
 
 
 def main():
     filename = "~file.txt"
 
     if os.path.isfile(filename):
         print("File already exists.")
     else:
         create_file(filename)
         read_file(filename)
         append_file(filename)
         read_file(filename)
         delete_file(filename)
         
 
 main()

Output[edit | edit source]

Celsius,Fahrenheit
0.0,32.0
1.0,33.8
2.0,35.6
3.0,37.4
...
98.0,208.4
99.0,210.2
100.0,212.0

References[edit | edit source]


String Examples Swift

Strings[edit | edit source]

 // This program demonstrates string functions.
 
 import Foundation
 
 func main() {
     let string:String = "Hello"
 
     print("string: " + string)
     print("string.lowercased(): " + string.lowercased())
     print("string.uppercased(): " + string.uppercased())
     print("find(string, \"e\"): " + String(find(string:string, character:"e")))
     print("string.count: " + String(string.count))
     print("string.replacingOccurrences(of:\"H\", with:\"j\"): " + string.replacingOccurrences(of:"H", with:"j"))
     print("string.reversed(): " + String(string.reversed()))
     print("substring(2, 2): " + substring(string:string, start:2, length:2))
     print("string.trimmingCharacters(\"H\"): " + string.trimmingCharacters(in:CharacterSet.init(charactersIn: "H")))
 
     let name:String = "Bob"
     let value:Double = 123.456
     print("\(name) earned $" + String(format:"%.2f", value))
 }
 
 func find(string:String, character:Character) -> Int {
     var result: Int
 
     if let index = string.firstIndex(of:character) {
         result = string.distance(from: string.startIndex, to: index)
     } else {
         result = -1
     }
     return result
 }
 
 func substring(string:String, start:Int, length:Int) -> String {
     let startIndex = string.index(string.startIndex, offsetBy: start)
     let endIndex = string.index(string.startIndex, offsetBy: start + length - 1)
     return String(string[startIndex...endIndex])
 }
 
 main()

Output[edit | edit source]

string: Hello
string.lowercased(): hello
string.uppercased(): HELLO
find(string, "e"): 1
string.count: 5
string.replacingOccurrences(of:"H", with:"j"): jello
string.reversed(): olleH
substring(2, 2): ll
string.trimmingCharacters("H"): ello
Bob earned $123.46

Files[edit | edit source]

 // This program creates a file, adds data to the file, displays the file,
 // appends more data to the file, displays the file, and then deletes the file.
 // It will not run if the file already exists.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
 
 import Foundation
 
 func fileExists(filename:String) -> Bool {
     let fileManager = FileManager.default
     return fileManager.fileExists(atPath:filename)
 }
 
 func calculateFahrenheit(celsius:Double) -> Double {
     var fahrenheit: Double
     fahrenheit = celsius * 9 / 5 + 32    
     return fahrenheit
 }
 
 func createFile(filename:String) {
     var text: String
     var fahrenheit: Double
 
     text = "Celsius,Fahrenheit\n"
     for celsius in stride(from: 0.0, through: 50.0, by: 1.0) {
         fahrenheit = calculateFahrenheit(celsius:celsius)
         text += String(celsius) + "," + String(fahrenheit) + "\n"
     }
 
     do {
         try text.write(toFile: filename, atomically: true, encoding: .utf8)
     } catch {
         print("Error creating ", filename)
         print(error.localizedDescription)
     }
 }
 
 func readFile(filename:String) {
     var text = ""
 
     do {
         text = try String(contentsOfFile: filename, encoding: .utf8)
 
         let lines = text.components(separatedBy:"\n")
         for line in lines {
             print(line)
         }
     } catch {
         print("Error reading " + filename)
         print(error.localizedDescription)
     }
 }
 
 func appendFile(filename:String) {
     var text: String
     var fahrenheit: Double
 
     do {
         text = try String(contentsOfFile: filename, encoding: .utf8)
 
         for celsius in stride(from: 51.0, through: 100.0, by: 1.0) {
             fahrenheit = calculateFahrenheit(celsius:celsius)
             text += String(celsius) + "," + String(fahrenheit) + "\n"
         }
 
         try text.write(toFile: filename, atomically: true, encoding: .utf8)
     } catch {
         print("Error appending to ", filename)
         print(error.localizedDescription)
     }
 }
 
 func deleteFile(filename:String) {
     do {
         let fileManager = FileManager.default
         try fileManager.removeItem(atPath:filename)
     } catch {
         print("Error deleting", filename)
         print(error.localizedDescription)
     }
 }
 
 func main() {
     let filename:String = "~file.txt"
 
     if (fileExists(filename:filename)) {
         print("File already exists.")
     }
     else {
         createFile(filename:filename)
         readFile(filename:filename)
         appendFile(filename:filename)
         readFile(filename:filename)
         deleteFile(filename:filename)
     }
 }
         
 main()

Output[edit | edit source]

Celsius,Fahrenheit
0.0,32.0
1.0,33.8
2.0,35.6
3.0,37.4
...
98.0,208.4
99.0,210.2
100.0,212.0

References[edit | edit source]


Practice: Strings and Files

Chapter Summary[edit | edit source]

  • Strings - An array of single digits or letters that is typically used to display to the user or is the user's input.
  • Arrays - Sequenced collections of elements of the same data type with a single identifier name.
  • String Functions - String functions are used in computer programming languages to manipulate a string or query information about a string.
  • String Formatting - String formatting uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.
  • File Input and Output -A computer file is a computer resource for recording data discretely in a computer storage device. By using computer programs, a person can open, read, change, and close a computer file. Computer files may be reopened, modified, and copied an arbitrary number of times.
  • Loading an Array from a Text File - Loading an array from a text file requires several steps, including: opening the file, reading the records, parsing (splitting) the records into fields, adding the fields to an array, and closing the file.
  • Error Handling - Anticipating conditions that may cause errors when a program runs.
  • Dynamic/Static Memory - Memory associated with local and global scope respectively.

Review Questions[edit | edit source]

True / False[edit | edit source]

  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. A filespec refers to a very small (like a spec dust) file.
  6. A device token is a special non zero value the operating system gives your program and is associated with the file that you requested to be opened.
  7. String length and storage are handled by the compiler or interpreter, not the user or programmer.
  8. A string can be both a literal constant and a variable.
  9. An array with string values can be edited in all the same ways as a single string.
  10. A program can only read a file line by line and process one record at a time.

Answers:

  1. false
  2. true
  3. false - Typedef is used to assign alternative names to any existing datatypes, which is mostly used with user-defined datatypes.
  4. false
  5. false
  6. true
  7. true
  8. true - A literal constant is a value, which can be a string.
  9. true
  10. false

Short Answer[edit | edit source]

  1. Describe the normal operations allowed with the string data type.
  2. Describe why unary positive is worthless.
  3. Describe how unary negative works.
  4. Describe (in your chosen language) how you would:
    • Change text to all uppercase
    • Get rid of the letter "b" from the given string.
    • string = "Hey buddy!"
  5. Describe the different ways you can read the contents of a file.
  6. Describe how string manipulation differs from variable manipulation

Activities[edit | edit source]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

String Activities[edit | edit source]

  1. Create a program that asks the user for a line of text containing a first name and last name, such as Firstname Lastname. Use string functions/methods to parse the line and print out the name in the form last name, first initial, such as Lastname, F. Include a trailing period after the first initial. Handle invalid input errors, such as extra spaces or missing name parts.
  2. Create a program that asks the user for a line of text. Use string functions/methods to delete leading, trailing, and duplicate spaces, and then print the line of text backwards. For example:
       the   cat   in   the   hat   
    tah eht ni tac eht
  3. Create a program that asks the user for a line of comma-separated-values. It could be a sequence of test scores, names, or any other values. Use string functions/methods to parse the line and print out each item on a separate line. Remove commas and any leading or trailing spaces from each item when printed.
  4. Create a program that asks the user for a line of text. Then ask the user for the number of characters to print in each line, the number of lines to be printed, and a scroll direction, right or left. Using the given line of text, duplicate the text as needed to fill the given number of characters per line. Then print the requested number of lines, shifting the entire line’s content by one character, left or right, each time the line is printed. The first or last character will be shifted / appended to the other end of the string. For example:
    Repeat this. Repeat this.
    epeat this. Repeat this. R
    peat this. Repeat this. Re

File Activities[edit | edit source]

Note: Each of the following activities uses code only to read the file. It is not necessary to use code to create the file.

  1. Using a text editor or IDE, copy the following list of names and grade scores and save it as a text file named scores.txt:
    Name,Score
    Joe Besser,70
    Curly Joe DeRita,0
    Larry Fine,80
    Curly Howard,65
    Moe Howard,100
    Shemp Howard,85
    Create a program that displays high, low, and average scores based on input from scores.txt. Verify that the file exists and then use string functions/methods to parse the file content and add each score to an array. Display the array contents and then calculate and display the high, low, and average score. Format the average to two decimal places. Note that the program must work for any given number of scores in the file. Do not assume there will always be six scores.
  2. Create a program that displays high, low, and average scores based on input from scores.txt. Verify that the file exists and then use string functions/methods to parse the file content and add each score to an array. Display the array contents and then calculate and display the high, low, and average score. Format the average to two decimal places. Include error handling in case the file is formatted incorrectly. Note that the program must work for any given number of scores in the file. Do not assume there will always be six scores.
  3. Create a program that asks the user for the name of a text/HTML file that contains HTML tags, such as:
    <p><strong>This is a bold paragraph.</strong></p>
    Verify that the file exists and then use string methods to search for and remove all HTML tags from the text, saving each removed tag in an array. Display the untagged text and then display the array of removed tags. For example:
    This is a bold paragraph.
    <p>
    <strong>
    </strong>
    </p>
  4. Using a text editor or IDE, create a text file of names and addresses to use for testing based on the following format:
    Firstname Lastname
    123 Any Street
    City, State/Province/Region PostalCode
    Include a blank line between addresses, and include at least three addresses in the file. Create a program that verifies that the file exists, and then processes the file and displays each address as a single line of comma-separated values in the form:
    Lastname, Firstname, Address, City, State/Province/Region, PostalCode

References[edit | edit source]


Object-Oriented Programming

Overview[edit | edit source]

This chapter introduces object-oriented programming, with a focus on understanding object-oriented concepts and terminology. It includes short examples of objects and classes in different programming languages.

Chapter Outline[edit | edit source]

Learning Objectives[edit | edit source]

  1. Understand key terms and definitions.
  2. Gain exposure to object-oriented programming.
  3. Given example source code, create a program that uses object-oriented programming concepts to solve a given problem.


Objects and Classes

Overview[edit | edit source]

Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. A feature of objects is that an object’s procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of “this” or “self”). There is significant diversity of OOP languages, but the most popular ones are class-based, meaning that objects are instances of classes, which typically also determine their type.[1]

Discussion[edit | edit source]

Thus far, we have focused on procedural programming. Based on structured programming, procedures (routines, subroutines, or functions) contain a series of computational steps to be carried out. Any given procedure might be called at any point during a program’s execution, including by other procedures or itself. The focus of procedural programming is to break down a programming task into a collection of variables, data structures, and subroutines.[2] Small programs and scripts tend to be easier to develop using a simple procedural approach.

Object-oriented programming instead breaks down a programming task into objects that expose behavior (methods) and data (members or attributes) using interfaces. The most important distinction is that while procedural programming uses procedures to operate on separate data structures, object-oriented programming bundles the two together, so an “object”, which is an instance of a class, operates on its “own” data structure.[3] Larger programs benefit from better code and data isolation and reuse provided by an object-oriented approach.

Objects and classes are often designed to represent real-world objects. Consider a door as an example of a real-world object. Most doors have limited functionality. They may be opened and closed, and locked and unlocked. In procedural programming, we might design functions to open, close, lock, and unlock a door, such as:

Procedural Programming - Functions
OpenDoor(door)
CloseDoor(door)
LockDoor(door)
UnlockDoor(door)

Object-oriented programming combines code and data, so that, rather than having separate functions act on doors, we design doors that have methods that can act on themselves. Methods represent something the object can do, and are typically defined using verbs. Object-oriented door pseudocode might look like:

Object-Oriented Programming - Methods
door.Open()
door.Close()
door.Lock()
door.Unlock()

Objects may also have attributes, something the object is or has, and are typically defined using nouns or adjectives. Door attributes might include:

Object-Oriented Programming - Attributes
door.Height
door.Width
door.Color
door.Closed
door.Locked

When we write code to define a generic door, we would create a door class. The door class would contain all of the methods a door can perform and all of the attributes a door might have. We would then create instances of the class (objects) to represent specific doors, such as a front door, back door, or room door on a house, or a left door and right door on a car.

Key Terms[edit | edit source]

attribute
A specification that defines a property of an object.[4]
class
An extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).[5]
instance
:A concrete occurrence of an object.[6]
method
A specification that defines a procedure or behavior of an object.[7]
object
A particular instance of a class where the object can be a combination of variables, functions, and data structures.[8]
this, self, or Me
Keywords used in some computer programming languages to refer to the object, class, or other entity that the currently running code is part of.[9]

References[edit | edit source]


Encapsulation

Overview[edit | edit source]

Encapsulation is one of the fundamentals of OOP (object-oriented programming). It refers to the bundling of data with the methods that operate on that data. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties’ direct access to them. Publicly accessible methods are generally provided in the class (so-called getters and setters) to access the values, and other client classes call these methods to retrieve and modify the values within the object.[1]

Discussion[edit | edit source]

The most important principle of object orientation is encapsulation: the idea that data inside the object should only be accessed through a public interface – that is, the object’s methods.

If we want to use the data stored in an object to perform an action or calculate a derived value, we define a method associated with the object which does this. Then whenever we want to perform this action we call the method on the object. We consider it bad practice to retrieve the information from inside the object and write separate code to perform the action outside of the object.

Encapsulation is a good idea for several reasons:

  • the functionality is defined in one place and not in multiple places.
  • it is defined in a logical place – the place where the data is kept.
  • data inside our object is not modified unexpectedly by external code in a completely different part of our program.
  • when we use a method, we only need to know what result the method will produce – we don’t need to know details about the object’s internals in order to use it. We could switch to using another object which is completely different on the inside, and not have to change any code because both objects have the same interface.

We can say that the object “knows how” to do things with its own data, and it’s a bad idea for us to access its internals and do things with the data ourselves. If an object doesn’t have an interface method which does what we want to do, we should add a new method or update an existing one.

Some languages have features which allow us to enforce encapsulation strictly. In Java or C++, we can define access permissions on object attributes, and make it illegal for them to be accessed from outside the object’s methods. In Java it is also considered good practice to write setters and getters for all attributes, even if the getter simply retrieves the attribute and the setter just assigns it the value of the parameter which you pass in.

In Python, encapsulation is not enforced by the language, but there is a convention that we can use to indicate that a property is intended to be private and is not part of the object’s public interface: we begin its name with an underscore. Python also supports the use of a property decorator to replace a simple attribute with a method without changing the object’s interface.

Key Terms[edit | edit source]

abstraction
A technique for arranging complexity of computer systems so that functionality may be separated from specific implementation details.[2][3]
accessor
A method used to return the value of a private member variable, also known as a getter method.[4]
encapsulation
A language mechanism for restricting direct access to some of an object’s components.[5]
information hiding
The principle of segregation of the design decisions in a computer program from other parts of the program. See encapsulation.[6]
mutator
A method used to control changes to a private member variable, also known as a setter method.[7]
private
An access modifier that restricts visibility of a property or method to the class in which it is defined.[8]
public
An access modifier that opens visibility of a property or method to all other classes.[9]

References[edit | edit source]


Inheritance and Polymorphism

Overview[edit | edit source]

In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object (prototypical inheritance) or class (class-based inheritance), retaining similar implementation. In most class-based object-oriented languages, an object created through inheritance (a “child object”) acquires all the properties and behaviors of the parent object (except: constructors, destructor, overloaded operators and friend functions of the base class). Inheritance allows programmers to create classes that are built upon existing classes, to specify a new implementation while maintaining the same behaviors (realizing an interface), to reuse code and to independently extend original software via public classes and interfaces.[1]

Discussion[edit | edit source]

Inheritance is a way of arranging objects in a hierarchy from the most general to the most specific. An object which inherits from another object is considered to be a subtype of that object. An example might include Instructor and Student, each of which inherit from Person. When we can describe the relationship between two objects using the phrase is-a, that relationship is inheritance.

We also often say that a class is a subclass or child class of a class from which it inherits, or that the other class is its superclass or parent class. We can refer to the most generic class at the base of a hierarchy as a base class.

Inheritance can help us to represent objects which have some differences and some similarities in the way they work. We can put all the functionality that the objects have in common in a base class, and then define one or more subclasses with their own custom functionality.

Inheritance is also a way of reusing existing code easily. If we already have a class which does almost what we want, we can create a subclass in which we partially override some of its behavior, or perhaps add some new functionality.

In some statically typed languages inheritance is very popular because it allows the programmer to work around some of the restrictions of static typing. If an instructor and a student are both a kind of person, we can write a function which accepts a parameter of type Person and have it work on both instructor and student objects because they both inherit from Person. This is known as polymorphism.

Key Terms[edit | edit source]

inheritance
An object or class being based on another object or class, using the same implementation or specifying a new implementation to maintain the same behavior.[2]
polymorphism
The provision of a single interface to entities of different types.[3]

References[edit | edit source]


Object Examples C++

Objects[edit | edit source]

 // This class converts temperature between Celsius and Fahrenheit.
 // It may be used by assigning a value to either Celsius or Fahrenheit 
 // and then retrieving the other value, or by calling the ToCelsius or
 // ToFahrenheit methods directly.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://en.wikibooks.org/wiki/C%2B%2B_Programming
 
 #include <iostream>
 
 using namespace std;
 
 class Temperature {
     public:
         double getCelsius(void);
         void setCelsius(double value);
         double getFahrenheit(void);
         void setFahrenheit(double value);
         double toCelsius(double fahrenheit);
         double toFahrenheit(double celsius);
     
     private:
         double celsius;
         double fahrenheit;
 };
 
 double Temperature::getCelsius(void) {
     return celsius;
 }
 
 void Temperature::setCelsius(double value) {
     celsius = value;
     fahrenheit = toFahrenheit(celsius);
 }
 
 double Temperature::getFahrenheit(void) {
     return fahrenheit;
 }
 
 void Temperature::setFahrenheit(double value) {
     fahrenheit = value;
     celsius = toCelsius(fahrenheit);
 }
     
 double Temperature::toCelsius(double fahrenheit) {
     return (fahrenheit - 32) * 5 / 9;
 }
 
 double Temperature::toFahrenheit(double celsius) {
     return celsius * 9 / 5 + 32;
 }
 
 // This program creates instances of the Temperature class to convert Celsius 
 // and Fahrenheit temperatures.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://en.wikibooks.org/wiki/C%2B%2B_Programming
 
 int main() {
     Temperature temp1;
     temp1.setCelsius(100.0);
     cout << "temp1.celsius = " << temp1.getCelsius() << endl;
     cout << "temp1.fahrenheit = " << temp1.getFahrenheit() << endl;
     cout << endl;
     
     Temperature temp2;
     temp2.setFahrenheit(100.0);
     cout << "temp2.fahrenheit = " << temp2.getFahrenheit() << endl;
     cout << "temp2.celsius = " << temp2.getCelsius() << endl;
 }

Output[edit | edit source]

temp1.celsius = 100
temp1.fahrenheit = 212

temp2.fahrenheit = 100
temp2.celsius = 37.7778

References[edit | edit source]


Object Examples CSharp

Objects[edit | edit source]

 // This program creates instances of the Temperature class to convert Celsius 
 // and Fahrenheit temperatures.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://en.wikibooks.org/wiki/C_Sharp_Programming
 
 using System;
 
 public class Objects  
 {
     public static void Main(String[] args)
     {
         Temperature temp1 = new Temperature(celsius: 0);
         Console.WriteLine("temp1.Celsius = " + temp1.Celsius.ToString());
         Console.WriteLine("temp1.Fahrenheit = " + temp1.Fahrenheit.ToString());
         Console.WriteLine("");
     
         temp1.Celsius = 100;
         Console.WriteLine("temp1.Celsius = " + temp1.Celsius.ToString());
         Console.WriteLine("temp1.Fahrenheit = " + temp1.Fahrenheit.ToString());
         Console.WriteLine("");
         
         Temperature temp2 = new Temperature(fahrenheit: 0);
         Console.WriteLine("temp2.Fahrenheit = " + temp2.Fahrenheit.ToString());
         Console.WriteLine("temp2.Celsius = " + temp2.Celsius.ToString());
         Console.WriteLine("");
     
         temp2.Fahrenheit = 100;
         Console.WriteLine("temp2.Fahrenheit = " + temp2.Fahrenheit.ToString());
         Console.WriteLine("temp2.Celsius = " + temp2.Celsius.ToString());
     }
 }
 
 // This class converts temperature between Celsius and Fahrenheit.
 // It may be used by assigning a value to either Celsius or Fahrenheit 
 // and then retrieving the other value, or by calling the ToCelsius or
 // ToFahrenheit methods directly.
 
 public class Temperature
 {
     double _celsius;
     double _fahrenheit;
 
     public double Celsius
     {
         get
         {
             return _celsius;
         }
         
         set
         {
             _celsius = value;
             _fahrenheit = ToFahrenheit(value);
         }
     }
     
     public double Fahrenheit
     {
         get
         {
             return _fahrenheit;
         }
         
         set
         {
             _fahrenheit = value;
             _celsius = ToCelsius(value);
         }
     }
     
     public Temperature(double? celsius = null, double? fahrenheit = null)
     {
         if (celsius.HasValue)
         {
             this.Celsius = Convert.ToDouble(celsius);
         }
         
         if (fahrenheit.HasValue)
         {
             this.Fahrenheit = Convert.ToDouble(fahrenheit);
         }
     }
 
     public double ToCelsius(double fahrenheit)
     {
         return (fahrenheit - 32) * 5 / 9;
     }
     
     public double ToFahrenheit(double celsius)
     {
         return celsius * 9 / 5 + 32;
     }
 }

Output[edit | edit source]

temp1.Celsius = 0
temp1.Fahrenheit = 32

temp1.Celsius = 100
temp1.Fahrenheit = 212

temp2.Fahrenheit = 0
temp2.Celsius = -17.7777777777778

temp2.Fahrenheit = 100
temp2.Celsius = 37.7777777777778

References[edit | edit source]


Object Examples Java

Objects[edit | edit source]

 // This program creates instances of the Temperature class to convert Celsius 
 // and Fahrenheit temperatures.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://en.wikibooks.org/wiki/Java_Programming
 
 import java.util.*;
 
 class Main {
     public static void main(String[] args) {
         Temperature temp1 = new Temperature();
         temp1.setCelsius(100.0);
         System.out.println("temp1.celsius = " + temp1.getCelsius().toString());
         System.out.println("temp1.fahrenheit = " + temp1.getFahrenheit().toString());
         System.out.println("");
         
         Temperature temp2 = new Temperature();
         temp2.setFahrenheit(100.0);
         System.out.println("temp2.fahrenheit = " + temp2.getFahrenheit().toString());
         System.out.println("temp2.celsius = " + temp2.getCelsius().toString());
     }
 }
 
 // This class converts temperature between Celsius and Fahrenheit.
 // It may be used by assigning a value to either Celsius or Fahrenheit 
 // and then retrieving the other value, or by calling the ToCelsius or
 // ToFahrenheit methods directly.
 
 class Temperature {
     Double celsius;
     Double fahrenheit;
 
     public Double getCelsius() {
         return celsius;
     }
     
     public void setCelsius(Double value) {
         celsius = value;
         fahrenheit = toFahrenheit(celsius);
     }
 
     public Double getFahrenheit() {
         return fahrenheit;
     }
     
     public void setFahrenheit(Double value) {
         fahrenheit = value;
         celsius = toCelsius(fahrenheit);
     }
 
     public Double toCelsius(Double fahrenheit) {
         return (fahrenheit - 32) * 5 / 9;
     }
     
     public Double toFahrenheit(Double celsius) {
         return celsius * 9 / 5 + 32;
     }
 }

Output[edit | edit source]

temp1.celsius = 100.0
temp1.fahrenheit = 212.0

temp2.fahrenheit = 100.0
temp2.celsius = 37.77777777777778

References[edit | edit source]


Object Examples JavaScript

Objects[edit | edit source]

 // This class converts temperature between Celsius and Fahrenheit.
 // It may be used by assigning a value to either Celsius or Fahrenheit 
 // and then retrieving the other value, or by calling the ToCelsius or
 // ToFahrenheit methods directly.
 
 class Temperature {
     constructor() {
         this._celsius = 0;
         this._fahrenheit = 32;
     }
 
     get celsius() {
         return this._celsius;
     }
 
     set celsius(value) {
         this._celsius = value;
         this._fahrenheit = this.toFahrenheit(value);
     }
 
     get fahrenheit() {
         return this._fahrenheit;
     }
 
     set fahrenheit(value) {
         this._fahrenheit = value;
         this._celsius = this.toCelsius(value);
     }
 
     toCelsius(fahrenheit) {
         return (fahrenheit - 32) * 5 / 9
     }
 
     toFahrenheit(celsius) {
         return celsius * 9 / 5 + 32
     }
 }
 
 // This program creates instances of the Temperature class to convert Celsius 
 // and Fahrenheit temperatures.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://en.wikibooks.org/wiki/JavaScript
 
 main()
 
 function main() {
     var temp1 =  new Temperature();
     temp1.celsius = 0
     output("temp1.celsius = " + temp1.celsius);
     output("temp1.fahrenheit = " + temp1.fahrenheit);
     output("");
 
     temp1.celsius = 100;
     output("temp1.celsius = " + temp1.celsius);
     output("temp1.fahrenheit = " + temp1.fahrenheit);
     output("");
     
     var temp2 = new Temperature();
     temp2.fahrenheit = 0
     output("temp2.fahrenheit = " + temp2.fahrenheit);
     output("temp2.celsius = " + temp2.celsius);
     output("");
 
     temp2.fahrenheit = 100;
     output("temp2.fahrenheit = " + temp2.fahrenheit);
     output("temp2.celsius = " + temp2.celsius);
 }
 
 function output(text) {
   if (typeof document === 'object') {
     document.write(text);
   } 
   else if (typeof console === 'object') {
     console.log(text);
   } 
   else {
     print(text);
   }
 }

Output[edit | edit source]

temp1.celsius = 0
temp1.fahrenheit = 32

temp1.celsius = 100
temp1.fahrenheit = 212

temp2.fahrenheit = 0
temp2.celsius = -17.77777777777778

temp2.fahrenheit = 100
temp2.celsius = 37.77777777777778

References[edit | edit source]


Object Examples Python

Objects[edit | edit source]

 # This class converts temperature between Celsius and Fahrenheit.
 # It may be used by assigning a value to either Celsius or Fahrenheit 
 # and then retrieving the other value, or by calling the to_celsius or
 # to_fahrenheit methods directly.
 #
 # References:
 #     https://www.mathsisfun.com/temperature-conversion.html
 #     https://en.wikibooks.org/wiki/Python_Programming
 
 class Temperature:
     _celsius = None
     _fahrenheit = None
     
     @property
     def celsius(self):
         return self._celsius 
 
     @celsius.setter
     def celsius(self, value):
         self._celsius = float(value)
         self._fahrenheit = self.to_fahrenheit(self._celsius)
             
     @property
     def fahrenheit(self):
         return self._fahrenheit 
     
     @fahrenheit.setter
     def fahrenheit(self, value):
         self._fahrenheit = float(value)
         self._celsius = self.to_celsius(self._fahrenheit)
 
     def __init__(self, celsius=None, fahrenheit=None):
         if celsius != None:
             self._celsius = celsius
             self._fahrenheit = self.to_fahrenheit(celsius)
         if fahrenheit != None:
             self._fahrenheit = fahrenheit
             self._celsius = self.to_celsius(fahrenheit)
 
     def to_celsius(self, fahrenheit):
         return (fahrenheit - 32) * 5 / 9
         
     def to_fahrenheit(self, celsius):
         return celsius * 9 / 5 + 32
 
 
 # This program creates instances of the Temperature class to convert Cesius 
 # and Fahrenheit temperatures.
 
 def main():
     temp1 = Temperature(celsius=0)
     print("temp1.celsius =", temp1.celsius)
     print("temp1.fahrenheit =", temp1.fahrenheit)
     print("")
     
     temp1.celsius = 100
     print("temp1.celsius =", temp1.celsius)
     print("temp1.fahrenheit =", temp1.fahrenheit)
     print("")
     
     temp2 = Temperature(fahrenheit=0)
     print("temp2.fahrenheit =", temp2.fahrenheit)
     print("temp2.celsius =", temp2.celsius)
     print("")
 
     temp2.fahrenheit = 100
     print("temp2.fahrenheit =", temp2.fahrenheit)
     print("temp2.celsius =", temp2.celsius)
 
 main()

Output[edit | edit source]

temp1.celsius = 0
temp1.fahrenheit = 32.0

temp1.celsius = 100.0
temp1.fahrenheit = 212.0

temp2.fahrenheit = 0
temp2.celsius = -17.77777777777778

temp2.fahrenheit = 100.0
temp2.celsius = 37.77777777777778

References[edit | edit source]


Object Examples Swift

Objects[edit | edit source]

 // This class converts temperature between Celsius and Fahrenheit.
 // It may be used by assigning a value to either Celsius or Fahrenheit 
 // and then retrieving the other value, or by calling the ToCelsius or
 // ToFahrenheit methods directly.
 
 class Temperature {
     var _celsius:Double = 0
     var _fahrenheit:Double = 32
 
     init(celsius:Double?=nil, fahrenheit:Double?=nil) {
         if celsius != nil {
             self.celsius = celsius!
         }
         
         if fahrenheit != nil {
             self.fahrenheit = fahrenheit!
         }
     }
 
     var celsius: Double {
         get {
             return self._celsius
         }
         set {
             self._celsius = newValue
             self._fahrenheit = toFahrenheit(celsius:self._celsius)
         }
     }
 
     var fahrenheit: Double {
         get {
             return self._fahrenheit
         }
         set {
             self._fahrenheit = newValue
             self._celsius = toCelsius(fahrenheit:self._fahrenheit)
         }
     }
     
     func getCelsius() -> Double {
         return self.celsius
     }
     
     func setCelsius(celsius:Double) {
         self.celsius = celsius
         self.fahrenheit = toFahrenheit(celsius:celsius)
     }
 
     func getFahrenheit() -> Double {
         return self.fahrenheit
     }
     
     func setFahrenheit(fahrenheit:Double) {
         self.fahrenheit = fahrenheit
         self.celsius = toCelsius(fahrenheit:fahrenheit)
     }
 
     func toCelsius(fahrenheit:Double) -> Double {
         return (fahrenheit - 32) * 5 / 9
     }
     
     func toFahrenheit(celsius:Double) -> Double {
         return celsius * 9 / 5 + 32
     }
 }
 
 // This program creates instances of the Temperature class to convert Celsius 
 // and Fahrenheit temperatures.
 //
 // References:
 //     https://www.mathsisfun.com/temperature-conversion.html
 //     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html
 
 func main() {
     let temp1 =  Temperature(celsius:0);
     print("temp1.celsius = " + String(temp1.celsius));
     print("temp1.fahrenheit = " + String(temp1.fahrenheit));
     print("");
 
     temp1.celsius = 100;
     print("temp1.celsius = " + String(temp1.celsius));
     print("temp1.fahrenheit = " + String(temp1.fahrenheit));
     print("");
     
     let temp2 = Temperature(fahrenheit:0);
     print("temp2.fahrenheit = " + String(temp2.fahrenheit));
     print("temp2.celsius = " + String(temp2.celsius));
     print("");
 
     temp2.fahrenheit = 100;
     print("temp2.fahrenheit = " + String(temp2.fahrenheit));
     print("temp2.celsius = " + String(temp2.celsius));
 }
 
 main()

Output[edit | edit source]

temp1.celsius = 0.0
temp1.fahrenheit = 32.0

temp1.celsius = 100.0
temp1.fahrenheit = 212.0

temp2.fahrenheit = 0.0
temp2.celsius = -17.7777777777778

temp2.fahrenheit = 100.0
temp2.celsius = 37.7777777777778

References[edit | edit source]


Practice: Object-Oriented Programming

Chapter Summary[edit | edit source]

  • Objects and Classes
  • Encapsulation
  • Inheritance and Polymorphism

Review Questions[edit | edit source]

Answer the following statements as either true or false:

  1. Procedural programming and object-oriented programming cannot be done with the same compiler/IDE.
  2. Object-oriented programming encapsulates data and functions.

Answers:

  1. false
  2. true

Short Answer[edit | edit source]

  1. Describe the fundamental differences between procedural (modular structured) programming and object-oriented programming.

Activities[edit | edit source]

Complete the following activities using your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

  1. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user what shape they would like to calculate the area for. Use if/else conditional statements to determine their selection and then gather the appropriate input and calculate and display the area of the shape. Perform all area calculations using a ShapeArea class that has separate methods to calculate and return the area for different shapes. Include data validation in the class and error handling in the main program.
  2. Create a program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use if/else conditional statements to display their approximate age in the selected timeframe. Perform all calculations using an AgeConverter class that accepts the age in years during initialization and has separate properties and methods to calculate and return the age in months, days, hours, and seconds. Include data validation in the class and error handling in the main program.
  3. Review Wikipedia: Zeller’s congruence. Create a program that asks the user for their birthday (year, month, and day) and then calculate and display the day of the week on which they were born. Use if/else conditional statements to convert the numeric day of the week to the correct string representation (Monday, Tuesday, Wednesday, etc.). Perform all calculations using a DayOfWeek class that accepts the year, month, and day during initialization and has separate properties and methods to calculate and return the day of week as a number, as an abbreviated string (Mon, Tue, etc.), and as a full string (Monday, Tuesday, etc.). Include data validation in the class and error handling in the main program.

References[edit | edit source]


Sizeof Operator

An explanation of the sizeof operator with examples as used within the C++ programming language.

Overview[edit | edit source]

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.

There is an operator named "sizeof (… )" that is a unary operator, that is it has only one operand. The operand is to the right of the operator and is placed within the parentheses if it is a data type. The operand may be any data type (including those created by typedef). If the operand is an identifier name it does not need to go inside a set of parentheses. It works for both variable and memory constant identifier names. This operator is unique in that it performs its calculation at compile time for global scoped items and at run time for local scoped items. Examples:

cout << "The size of an integer is: " << sizeof (int);

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:

cout << "The size of an integer is: " << 4;

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 1: sizeof with a Variable[edit | edit source]

double money;     // variable set up with initialization
    then later on in the program
cout << "The size of money is: " << sizeof money;

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:

cout << "The size of money is: " << 8;

Definitions[edit | edit source]

sizeof
An operator that tells you how many bytes a data type occupies in storage.