Programming Fundamentals/Printable version


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 ReadersEdit

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 BookEdit

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 ModulesEdit

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 ApproachEdit

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 CustomizationEdit

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 ProblemsEdit

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

ReferencesEdit



Author Acknowledgements

1st Edition AcknowledgementsEdit

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 AcknowledgementsEdit

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

ReferencesEdit



Introduction to Programming

OverviewEdit

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 OutlineEdit

Learning ObjectivesEdit

  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

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



Program Design

OverviewEdit

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 ProgramEdit

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.

AlgorithmEdit

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 ModelEdit

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 DataEdit

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 TermsEdit

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.

ReferencesEdit



Program Quality

OverviewEdit

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

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Pseudocode

OverviewEdit

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

DiscussionEdit

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 layman's 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) in order to code the logic or algorithm presented in the pseudocode. Pseudocode usually does not include other items produced during programming design such as identifier lists for variables or test data.

There are other methods for planning and documenting the logic for a program. One method is HIPO. It stands for Hierarchy plus Input Process Output and was developed by IBM in the 1960s. It involved using a hierarchy (or structure) chart to show the relationship of the sub-routines (or functions) in a program. Each sub-routine had an IPO piece. Since the above problem/task was simple, we did not need to use multiple sub-routines, thus we did not produce a hierarchy chart. We did incorporate the IPO part of the concept for the pseudocode outline.

Key TermsEdit

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

ReferencesEdit



Flowcharts

OverviewEdit

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]

DiscussionEdit

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 SymbolsEdit

TerminalEdit

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

Terminal

Flow LinesEdit

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/OutputEdit

The parallelograms designate input or output operations.

Input/Output

ProcessEdit

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

Process

DecisionEdit

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

Decision

Advanced Flowcharting SymbolsEdit

Module CallEdit

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

ConnectorsEdit

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 ExamplesEdit


Simple ExamplesEdit

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

FunctionsEdit

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 StructuresEdit

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 ExamplesEdit

Selection Control StructuresEdit

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 StructuresEdit

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 TermsEdit

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.

ReferencesEdit



Software Testing

OverviewEdit

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

DiscussionEdit

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 CheckingEdit

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 CheckingEdit

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 TermsEdit

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

ReferencesEdit



Integrated Development Environment

OverviewEdit

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]

DiscussionEdit

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 ErrorsEdit

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 TermsEdit

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.

ReferencesEdit



Version Control

OverviewEdit

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

DiscussionEdit

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.

GitEdit

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 TermsEdit

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

ReferencesEdit



Input and Output

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Hello World

OverviewEdit

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]

DiscussionEdit

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]

PseudocodeEdit

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

OutputEdit

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

FlowchartEdit

ExamplesEdit

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 TermsEdit

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

ReferencesEdit



Introduction Examples C++

OverviewEdit

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.

ExampleEdit

Hello WorldEdit

// This program displays "Hello world!"
//
// References:
// http://www.cplusplus.com/doc/tutorial/program_structure/

#include <iostream>

int main()
{
    std::cout << "Hello world!";
}

OutputEdit

Hello world!

DiscussionEdit

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++ IDEsEdit

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 IDEsEdit

Local IDEsEdit

ReferencesEdit



Introduction Examples CSharp

OverviewEdit

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.

ExampleEdit

Input: Hello WorldEdit

// 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!");
    }
}

OutputEdit

Hello world!

DiscussionEdit

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# IDEsEdit

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 IDEsEdit

Local IDEsEdit

ReferencesEdit



Introduction Examples Java

OverviewEdit

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.

ExampleEdit

Hello WorldEdit

// 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!");
    }
}

OutputEdit

Hello world!

DiscussionEdit

Each code element represents:Programming Fundamentals/Hello World

  • // begins a comment
  • class hello 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 IDEsEdit

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 IDEsEdit

Local IDEsEdit

ReferencesEdit



Introduction Examples JavaScript

OverviewEdit

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.

ExampleEdit

Hello World – Console LogEdit

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

console.log("Hello world!")

OutputEdit

Hello world!

DiscussionEdit

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 AlertEdit

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

alert("Hello world!")

OutputEdit

Hello world!

DiscussionEdit

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 WriteEdit

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

OutputEdit

Hello world!

DiscussionEdit

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 IDEsEdit

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 IDEsEdit

Local IDEsEdit

ReferencesEdit



Introduction Examples Python

OverviewEdit

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.

ExampleEdit

Input: Hello WorldEdit

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

print("Hello world!")

OutputEdit

Hello world!

DiscussionEdit

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 IDEsEdit

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 IDEsEdit

Local IDEsEdit

ReferencesEdit



Introduction Examples Swift

OverviewEdit

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.

ExampleEdit

Hello WorldEdit

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

print("Hello world!")

OutputEdit

Hello world!

DiscussionEdit

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 IDEsEdit

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 IDEsEdit

Local IDEsEdit

ReferencesEdit



Practice: Introduction to Programming

Chapter SummaryEdit

  • 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 QuestionsEdit

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.

ActivitiesEdit

Pseudocode and FlowchartsEdit

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 EnvironmentsEdit

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.

ReferencesEdit



Data and Operators

OverviewEdit

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

Chapter OutlineEdit

Learning ObjectivesEdit

  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

OverviewEdit

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.

DiscussionEdit

Understanding ConstantsEdit

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 VariablesEdit

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 TermsEdit

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.

ReferencesEdit



Identifier Names

OverviewEdit

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

DiscussionEdit

Language Technical LimitationsEdit

  • 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 TechniquesEdit

  • 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 RulesEdit

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 TermsEdit

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.

ReferencesEdit



Data Types

OverviewEdit

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.

DiscussionEdit

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.

PseudocodeEdit

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

OutputEdit

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

FlowchartEdit

Data types flowchart

Key TermsEdit

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.

ReferencesEdit



Integer Data Type

OverviewEdit

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]

DiscussionEdit

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 to32,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 TermsEdit

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

ReferencesEdit



Floating-Point Data Type

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



String Data Type

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Boolean Data Type

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



Nothing Data Type

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Order of Operations

OverviewEdit

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]

DiscussionEdit

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 EvaluationEdit

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 ChartEdit

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 TermsEdit

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.

ReferencesEdit



Assignment

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

MultimediaEdit

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

ReferencesEdit



Arithmetic Operators

OverviewEdit

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

DiscussionEdit

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 OperatorsEdit

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;

PseudocodeEdit

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

OutputEdit

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

FlowchartEdit

Arithmetic operations flowchart

ReferencesEdit



Integer Division and Modulus

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



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

DiscussionEdit

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 NegativeEdit

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 – WorthlessEdit

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 ConfusionEdit

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.

ExercisesEdit

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 TermsEdit

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

ReferencesEdit



Lvalue and Rvalue

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Data Type Conversions

OverviewEdit

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

DiscussionEdit

Implicit Type ConversionEdit

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.

PromotionEdit

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.

DemotionEdit

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 ConversionEdit

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 TermsEdit

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.

ReferencesEdit



Input-Process-Output Model

OverviewEdit

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]

DiscussionEdit

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)

PseudocodeEdit

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

OutputEdit

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

FlowchartEdit

Fahrenheit to Celsius flowchart

ReferencesEdit



Variable Examples C++

OverviewEdit

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

Data TypesEdit

// 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;
}

OutputEdit

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

DiscussionEdit

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

ArithmeticEdit

// 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;
}

OutputEdit

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

DiscussionEdit

Each new code element represents:

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

TemperatureEdit

// 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;
}

OutputEdit

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

DiscussionEdit

Each new code element represents:

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

ReferencesEdit



Variable Examples CSharp

OverviewEdit

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

Data TypesEdit

// 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);
    }
}

OutputEdit

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

DiscussionEdit

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

ArithmeticEdit

// 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));
    }
}

OutputEdit

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

DiscussionEdit

Each new code element represents:

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

TemperatureEdit

// 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");
    }
}

OutputEdit

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

DiscussionEdit

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

ReferencesEdit



Variable Examples Java

OverviewEdit

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

Data TypesEdit

// 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);
    }
}

OutputEdit

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

DiscussionEdit

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

ArithmeticEdit

// 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));
    }
}

OutputEdit

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

DiscussionEdit

Each new code element represents:

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

TemperatureEdit

// 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");
    }
}

OutputEdit

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

DiscussionEdit

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

ReferencesEdit



Variable Examples JavaScript

OverviewEdit

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

Data TypesEdit

// 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);
  }
}

OutputEdit

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

DiscussionEdit

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.

ArithmeticEdit

// 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);
  }
}

OutputEdit

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

DiscussionEdit

Each new code element represents:

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

TemperatureEdit

// 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);
  }
}

OutputEdit

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

DiscussionEdit

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.

ReferencesEdit



Variable Examples Python

OverviewEdit

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

Data TypesEdit

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

OutputEdit

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

DiscussionEdit

Each code element represents:

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

ArithmeticEdit

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

OutputEdit

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

DiscussionEdit

Each new code element represents:

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

TemperatureEdit

# 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")

OutputEdit

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

DiscussionEdit

Each new code element represents:

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

ReferencesEdit



Variable Examples Swift

OverviewEdit

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

Data TypesEdit

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

OutputEdit

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

DiscussionEdit

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

ArithmeticEdit

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

OutputEdit

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

DiscussionEdit

Each new code element represents:

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

TemperatureEdit

// 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")

OutputEdit

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

DiscussionEdit

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

ReferencesEdit



Practice: Data and Operators

Chapter SummaryEdit

  • 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 QuestionsEdit

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?

ActivitiesEdit

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.

ReferencesEdit

See AlsoEdit

  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

OverviewEdit

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

Chapter OutlineEdit

Learning ObjectivesEdit

  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

OverviewEdit

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 ModularizationEdit

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 FunctionEdit

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 FunctionEdit

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 LayoutEdit

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 TermsEdit

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.

ReferencesEdit



Hierarchy or Structure Chart

OverviewEdit

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 TermsEdit

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

ReferencesEdit



Function Examples

OverviewEdit

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.

DiscussionEdit

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

PseudocodeEdit

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

OutputEdit

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

FlowchartEdit

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

ReferencesEdit



Parameters and Arguments

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



Call by Value vs Call by Reference

OverviewEdit

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]

Call by value and call by reference.png

DiscussionEdit

Call by ValueEdit

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

OutputEdit

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 ReferenceEdit

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 TermsEdit

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.

ReferencesEdit



Return Statement

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



Void Data Type

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



Scope

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Programming Style

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

OverviewEdit

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.

DiscussionEdit

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.

DocumentationEdit

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 AlignmentEdit

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.

CommentsEdit

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.

IndentationEdit

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 TypedEdit

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 TermsEdit

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.

ReferencesEdit



Standard Libraries

OverviewEdit

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.

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Function Examples C++

TemperatureEdit

// 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;
}

OutputEdit

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

ReferencesEdit



Function Examples CSharp

TemperatureEdit

// 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");
    }
}

OutputEdit

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

ReferencesEdit



Function Examples Java

TemperatureEdit

// 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");
    }
}

OutputEdit

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

ReferencesEdit



Function Examples JavaScript

TemperatureEdit

// 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);
  }
}

OutputEdit

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

ReferencesEdit



Function Examples Python

TemperatureEdit

# 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()

OutputEdit

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

ReferencesEdit



Function Examples Swift

TemperatureEdit

// 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()

OutputEdit

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

ReferencesEdit



Practice: Functions

Chapter SummaryEdit

  • 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 QuestionsEdit

True / FalseEdit

  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 AnswerEdit

  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.

ActivitiesEdit

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.

ReferencesEdit



Conditions

OverviewEdit

This chapter introduces conditions and selection control structures.

Chapter OutlineEdit

Learning ObjectivesEdit

  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

OverviewEdit

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]

DiscussionEdit

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, it’s 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 + “
”; 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 TermsEdit

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.

ReferencesEdit



Selection Control Structures

OverviewEdit

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]

DiscussionEdit

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 StructureEdit

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 StructureEdit

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 TermsEdit

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

ReferencesEdit



If Then Else

OverviewEdit

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

DiscussionEdit

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 SelectionEdit

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 TermsEdit

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

ReferencesEdit



Code Blocks

OverviewEdit

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]

DiscussionEdit

The Need for a Compound StatementEdit

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 BlockEdit

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 TermsEdit

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

ReferencesEdit



Relational Operators

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



Assignment vs Equality

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



Logical Operators

OverviewEdit

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.

DiscussionEdit

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 TablesEdit

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

ExamplesEdit

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 TermsEdit

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.

ReferencesEdit



Nested If Then Else

OverviewEdit

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

DiscussionEdit

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 SelectionEdit

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 TermsEdit

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.

ReferencesEdit



Case Control Structure

OverviewEdit

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]

DiscussionEdit

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 SelectionEdit

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 StructureEdit

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 MethodsEdit

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 TermsEdit

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

ReferencesEdit



Condition Examples

TemperatureEdit

PseudocodeEdit

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

OutputEdit

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.

FlowchartEdit

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

ReferencesEdit



Condition Examples C++

TemperatureEdit

// 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;
}

OutputEdit

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.

ReferencesEdit



Condition Examples CSharp

TemperatureEdit

// 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);
    }
}

OutputEdit

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.

ReferencesEdit



Condition Examples Java

TemperatureEdit

// 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);
    }
}

OutputEdit

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.

ReferencesEdit



Condition Examples JavaScript

TemperatureEdit

// 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);
  }
}

OutputEdit

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.

ReferencesEdit



Condition Examples Python

TemperatureEdit

# 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()

OutputEdit

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.

ReferencesEdit



Condition Examples Swift

TemperatureEdit

// 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()

OutputEdit

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.

ReferencesEdit



Practice: Conditions

Chapter SummaryEdit

  • 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 QuestionsEdit

True / FalseEdit

  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 AnswerEdit

  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.

ActivitiesEdit

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.

ReferencesEdit



Loops

OverviewEdit

This chapter introduces loops and iteration control structures.

Chapter OutlineEdit

Learning ObjectivesEdit

  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

OverviewEdit

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]

DiscussionEdit

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 StructuresEdit

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

ReferencesEdit



While Loop

OverviewEdit

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]

DiscussionEdit

Introduction to "Test Before" LoopsEdit

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

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" LoopEdit

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 LoopsEdit

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 LoopsEdit

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 LoopsEdit

Consider:

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

Missing the flag update usually causes an infinite loop.

Variations on CountingEdit

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 TermsEdit

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.

ReferencesEdit



Do While Loop

OverviewEdit

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]

DiscussionEdit

Introduction to Test After LoopsEdit

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 whileEdit

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 untilEdit

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 ExampleEdit

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 LoopsEdit

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 TermsEdit

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.

ReferencesEdit



Flag Concept

OverviewEdit

Checkered flags

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

DiscussionEdit

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

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 MeaningEdit

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 ByteEdit

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 TermsEdit

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

ReferencesEdit



For Loop

OverviewEdit

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]

DiscussionEdit

Introduction to Test Before LoopsEdit

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 – forEdit

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 ExampleEdit

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 LoopsEdit

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 TermsEdit

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.

ReferencesEdit



Branching Statements

OverviewEdit

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.

DiscussionEdit

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.

ExamplesEdit

breakEdit

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

continueEdit

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

returnEdit

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>

gotoEdit

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;

exitEdit

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 TermsEdit

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.

ReferencesEdit



Increment and Decrement Operators

OverviewEdit

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]

DiscussionEdit

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 ExamplesEdit

Basic ConceptEdit

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 IncrementEdit

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 IncrementEdit

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 TypesEdit

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

ExercisesEdit

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 TermsEdit

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.

ReferencesEdit



Integer Overflow

OverviewEdit

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]

DiscussionEdit

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 LoopsEdit

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 TermsEdit

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

ReferencesEdit



Nested Loops

OverviewEdit

Nested for loops places one for loop inside another for loop. The inner loop is repeated for each iteration of the outer loop.

DiscussionEdit

Nested Control StructuresEdit

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 loopsEdit

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 LoopsEdit

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 TermsEdit

complex logic
Often solved with nested control structures.

ReferencesEdit



Loop Examples

CountingEdit

PseudocodeEdit

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

OutputEdit

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

FlowchartEdit

Loops main flowchart Loops Get Value flowchart Loops While Loop flowchart Loops Do Loop flowchart Loops For Loop flowchart

ReferencesEdit



Loop Examples C++

CountingEdit

// 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;
    }
}

OutputEdit

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

ReferencesEdit



Loop Examples CSharp

CountingEdit

// 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 <= stop)
        {
            Console.WriteLine(count);
            count = count + increment;
        }
    }
    
    public static void DoLoop(int start, int stop, int increment)
    {
        Console.WriteLine("Do loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        int count = start;
        do
        {
            Console.WriteLine(count);
            count = count + increment;
        }
        while (count <= stop);
    }
    
    public static void ForLoop(int start, int stop, int increment)
    {
        Console.WriteLine("For loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        for (int count = start; count <= stop; count += increment)
        {
            Console.WriteLine(count);
        }
    }
}

OutputEdit

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

ReferencesEdit



Loop Examples Java

CountingEdit

// 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 <= stop) {
            System.out.println(count);
            count = count + increment;
        }
    }
    
    public static void doLoop(int start, int stop, int increment) {
        System.out.println("Do loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        int count = start;
        do {
            System.out.println(count);
            count = count + increment;
        } while (count <= stop);
    }
    
    public static void forLoop(int start, int stop, int increment) {
        System.out.println("For loop counting from " + start + " to " + 
            stop + " by " + increment + ":");
        
        for (int count = start; count <= stop; count += increment) {
            System.out.println(count);
        }
    }
}

OutputEdit

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

ReferencesEdit



Loop Examples JavaScript

CountingEdit

// 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 <= stop) {
        output(count);
        count = count + increment;
    }
}

function doLoop(start, stop, increment) {
    output("Do loop counting from " + start + " to " + stop + 
        " by " + increment + ":");
    
    var count = start;
    do {
        output(count);
        count = count + increment;
    } while (count <= stop);
}

function forLoop(start, stop, increment) {
    output("For loop counting from " + start + " to " + stop + 
        " by " + increment + ":");
    
    for (var count = start; count <= stop; count += increment) {
        output(count);
    }
}

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);
  }
}

OutputEdit

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

ReferencesEdit



Loop Examples Python

CountingEdit

# 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()

OutputEdit

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

ReferencesEdit



Loop Examples Swift

CountingEdit

// 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()

OutputEdit

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

ReferencesEdit



Practice: Loops

Chapter SummaryEdit

  • 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 QuestionsEdit

True / FalseEdit

  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 TablesEdit

  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 = _____

ActivitiesEdit

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 LoopsEdit

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 LoopsEdit

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 LoopsEdit

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 LoopsEdit

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.

ReferencesEdit



Arrays

OverviewEdit

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 OutlineEdit

Learning ObjectivesEdit

  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

OverviewEdit

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]

DiscussionEdit

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 ArrayEdit

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 TermsEdit

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.

ReferencesEdit



Index Notation

OverviewEdit

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.

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Displaying Array Members

OverviewEdit

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.

DiscussionEdit

Accessing Array MembersEdit

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 TermsEdit

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.

ReferencesEdit



Arrays and Functions

OverviewEdit

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.

DiscussionEdit

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.

PseudocodeEdit

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

OutputEdit

49
48
26
19
16

Key TermsEdit

array function
A user-defined specific task function designed to process an array.

ReferencesEdit



Math Statistics with Arrays

OverviewEdit

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]

DiscussionEdit

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.

PseudocodeEdit

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

OutputEdit

Total age is: 158

Key TermsEdit

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.

ReferencesEdit



Searching Arrays

OverviewEdit

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]

DiscussionEdit

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.

PseudocodeEdit

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

OutputEdit

Maximum age is: 49
Minimum age is: 16

Key TermsEdit

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.

ReferencesEdit

  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

OverviewEdit

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.

DiscussionEdit

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 TermsEdit

sorting
Arranging data according to their values.

ReferencesEdit



Parallel Arrays

OverviewEdit

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]

DiscussionEdit

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.

PseudocodeEdit

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

OutputEdit

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 TermsEdit

parallel array
An implicit data structure that uses multiple arrays to represent a singular array of records.

ReferencesEdit



Multidimensional Arrays

OverviewEdit

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]

DiscussionEdit

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.

PseudocodeEdit

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

OutputEdit

Tic-Tac-Toe
X | O | X
O | O | O
X | O | X

Key TermsEdit

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.

ReferencesEdit



Fixed and Dynamic Arrays

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



Array Examples C++

ArraysEdit

// 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;
    }    
}

OutputEdit

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

ReferencesEdit



Array Examples CSharp

ArraysEdit

// 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();
        }
    }
}

OutputEdit

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

ReferencesEdit



Array Examples Java

ArraysEdit

// 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();
        }
    }
}

OutputEdit

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

ReferencesEdit



Array Examples JavaScript

ArraysEdit

// 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);
  }
}

OutputEdit

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

ReferencesEdit



Array Examples Python

ArraysEdit

# 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()

OutputEdit

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

ReferencesEdit



Array Examples Swift

ArraysEdit

// 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()

OutputEdit

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]

ReferencesEdit



Practice: Arrays

Chapter SummaryEdit

  • 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 QuestionsEdit

True / FalseEdit

  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 AnswerEdit

  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.

ActivitiesEdit

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 ArraysEdit

  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 ArraysEdit

  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 / ListsEdit

  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.

ReferencesEdit

  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

OverviewEdit

This chapter introduces string and file processing.

Chapter OutlineEdit

Learning ObjectivesEdit

  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

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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

ReferencesEdit



String Functions

OverviewEdit

String functions are used in computer programming languages to manipulate a string or query information about a string.[1]

DiscussionEdit

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 TermsEdit

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]

ReferencesEdit



String Formatting

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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.

ReferencesEdit



File Input and Output

OverviewEdit

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]

DiscussionEdit

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 TermsEdit

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