Programming Fundamentals/Printable version
This is the print version of Programming Fundamentals You won't see this message or any elements not part of the book's content when you print or preview this page. |
The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Programming_Fundamentals
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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Cover Art: Puzzle pieces – CC0 by MsReadIt, downloaded from https://openclipart.org/detail/231093/puzzle-pieces
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
- Why Learn Programming?
- Systems Development Life Cycle
- Program Design
- Program Quality
- Pseudocode
- Flowcharts
- Software Testing
- Integrated Development Environment
- Version Control
- Input and Output
- Hello World
- Code Examples
- Practice: Introduction to Programming
Learning ObjectivesEdit
- Understand key terms and definitions.
- Create pseudocode for a programming problem.
- Create a flowchart for a programming problem.
- Perform software testing for a programming problem.
- List the four categories and give examples of errors that may be encountered when using an Integrated Development Environment (IDE).
- Test an Integrated Development Environment using a Hello World program.
- Modify an existing program to meet given requirements.
Systems Development Life Cycle
OverviewEdit
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:
- Understand the problem
- Define an input
- Process the input data
- Expect output
- 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
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.
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.
Input/OutputEdit
The parallelograms designate input or output operations.
ProcessEdit
The rectangle depicts a process such as a mathematical computation, or a variable assignment.
DecisionEdit
The diamond is used to represent the true/false statement being tested in a decision symbol.
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.
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.
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.
- to check the model to see if it produces the correct results (model checking)
- 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:
- The plan (IPO outline or another item) could be wrong
- The conversion of the plan to code might be wrong
- 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.
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:
- If there are any unsaved changes to the source code file it has the test editor save the changes.
- 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.
- 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.
- 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.
- 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:
- Compiler - A program that turns programming language code into machine code.
- Linker - A program that takes files and combines them into a singular file. (Examples include .exe, .lib, etc.)
- 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
- ↑ Wikipedia: Version control
- ↑ Programming Historian: An Introduction to Version Control Using GitHub Desktop
- ↑ Programming Historian: An Introduction to Version Control Using GitHub Desktop
- ↑ Programming Historian: An Introduction to Version Control Using GitHub Desktop
- ↑ G2Crowd: Best Version Control Systems
- ↑ Wikipedia: Git
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
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 commentOutput
indicates the following value(s) will be displayed or printed"Hello world!"
is the literal string to be displayedEnd
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 streamsint main()
begins the main function, which returns an integer value{
begins a block of codestd::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
- CodeChef
- GDB Online
- Ideone
- paiza.IO
- PythonTutor
- repl.it
- TutorialsPoint
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 commentpublic class Hello
begins the Hello World program{
begins a block of codepublic static void Main()
begins the main functionSystem.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 commentclass Main
begins the Hello World program{
begins a block of codepublic static void main(String[] args)
begins the main functionSystem.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
- CodeChef
- GDB Online
- Ideone
- paiza.IO
- PythonTutor
- repl.it
- TutorialsPoint
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 commentconsole.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 commentalert()
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 commentdocument.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 commentprint()
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
- CodeChef
- GDB Online
- Ideone
- paiza.IO
- Python Fiddle
- PythonTutor
- repl.it
- TutorialsPoint
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 commentprint()
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:
- Coding the program in a language like C++ is the first task of planning. You plan as you code.
- Usability is the single most important fundamental property in the development process of a new program.
- Pseudocode has a strict set of rules and is the same everywhere in the computer programming industry.
- Test data is developed for testing the program once it is coded into a language like C++.
- Commit is to write or merge the changes made in the working copy back to the repository.
- Not writing down your vision of a program could lead to problems further down the coding process.
- IDE "compile and run" is a five (5) step process.
- Git is a version control system for tracking changes in computer files and coordinating work on those files among multiple people.
- Printing "Hello World" on screen is the same for Python as is in Pseudocode.
- The robustness of a program is its ability to work around bugs in the code and still function as intended.
- Psuedocode can help increase the maintainability of a program.
- The reliability of a program refers to how often the results of a program are correct.
Answers:
- 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.
- False
- False
- False
- True
- True
- True
- True
- False - Although they may seem similar no two programming languages are exactly the same.
- False
- True
- True
Short Answer:
- List the steps of the Systems Development Life Cycle and indicate which step you are likely to work in as a new computer professional.
- 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.
- List and describe seven (7) properties that are evaluated when determining the quality of a program's source code.
- List three (3) errors that you may encounter when testing a coded program using test data that outputs the wrong values.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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. - 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
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Wikiversity: Computer Programming
- Systems Development Life Cycle
- Program Design
- Program Quality
- Pseudocode
- Flowcharts
- Software Testing
- Integrated Development Environment
- Version Control
- Input and Output
- Hello World
Data and Operators
OverviewEdit
This chapter introduces constants and variables, data types, and operators.
Chapter OutlineEdit
- Constants and Variables
- Identifier Names
- Data Types
- Order of Operations
- Assignment
- Arithmetic Operators
- Integer Division and Modulus
- Unary Operations
- Lvalue and Rvalue
- Data Type Conversions
- Input-Process-Output Model
- Code Examples
- Practice: Data and Operators
Learning ObjectivesEdit
- Understand key terms and definitions.
- Understand basic data types and how operators manipulate data.
- 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:
- literal constant
- 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.14159 or
|
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:
- the language's technical limitations
- good programming practices
- 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
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
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Flowgorithm – Flowchart Programming Language
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 to 32,767 |
C++ | int
|
varies | depends on compiler |
C++ | long
|
32 bits / 4 bytes | -2,147,483,648 to 2, 147,483,647 |
C++ | long long
|
64 bits / 8 bytes | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
C# | short
|
16 bits / 2 bytes | -32,768 to32,767 |
C# | int
|
32 bits / 4 bytes | -2,147,483,648 to 2, 147,483,647 |
C# | long
|
64 bits / 8 bytes | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Java | short
|
16 bits / 2 bytes | -32,768 to32,767 |
Java | int
|
32 bits / 4 bytes | -2,147,483,648 to 2, 147,483,647 |
Java | long
|
64 bits / 8 bytes | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
JavaScript | N/A | ||
Python | int()
|
no limit | |
Swift | Int
|
varies | depends on platform |
Swift | Int32
|
32 bits / 4 bytes | -2,147,483,648 to 2, 147,483,647 |
Swift | Int64
|
64 bits / 8 bytes | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
For C++ and Swift the size of a default integer varies with the compiler being used and the computer. This effect is known as being machine dependent. These variations of the integer data type are an annoyance for a beginning programmer. For a beginning programmer, it is more important to understand the general attributes of the integer data type that apply to most programming languages.
JavaScript does not support an integer data type, but the Math.round()
function may be used to return the value of a number rounded to the nearest integer.[2]
Python 3 integers are not limited in size, however, sys.maxsize
may be used to determine the maximum practical size of a list or string index.[3]
Key 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?
- the symbols of + meaning addition and * meaning multiplication are our operators
- the values 2, 3, 4 and 5 are our operands
- precedence says that multiplication is higher than addition
- thus, we evaluate the 3 * 4 to get 12
- now we have: 2 + 12 + 5
- the associativity rules say that addition goes left to right, thus we evaluate the 2 +12 to get 14
- now we have: 14 + 5
- 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:
- Unary – only have one operand
- Binary – have two operands, one on each side of the operator
- 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
- 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
ReferencesEdit
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Flowgorithm – Flowchart Programming Language
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:
- 14 / 4
- 5 / 13
- 7 / 2.0
Evaluate the following modulus expressions:
- 14 % 4
- 5 % 13
- 7 % 2.0
Solutions
- 14 % 4 = 2
- 5 % 13 = 5
- 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:
- +10 – -2
- -18 + 24
- 4 – +3
- +8 + – +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:
- Implicit – the change is implied
- Explicit – the change is explicitly done with an operator or function
The value being changed may be:
- Promotion – going from a smaller domain to a larger domain
- 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
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 tostring
,cout
, andendl
without writingstd::string
,std::cout
, andstd::endl
.int main()
begins the main function, which returns an integer value{
begins a block of codeint i
defines an integer variable named i;
ends each line of C++ codedouble d
defines a double floating-point variable named dstring s
defines a string variable named sbool b
defines a Boolean variable named bi = , d = , s =, b =
assign literal values to the corresponding variablescout
is standard output<<
directs the next element to standard outputendl
ends the current linereturn 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 commentusing System
allows references toBoolean
andConsole
without writingSystem.Boolean
andSystem.Console
public class DataTypes
begins the Data Types program{
begins a block of codepublic static void Main()
begins the main functionint i
defines an integer variable named i;
ends each line of C# codedouble d
defines a double floating-point variable named dstring s
defines a string variable named sBoolean b
defines a Boolean variable named bi = , d = , s =, b =
assign literal values to the corresponding variablesConsole.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 inputConvert.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 commentpublic class DataTypes
begins the Data Types program{
begins a block of codepublic static void main(String[] args)
begins the main functionint i
defines an integer variable named i;
ends each line of Java codedouble d
defines a double floating-point variable named dstring s
defines a string variable named sboolean b
defines a Boolean variable named bi = , d = , s =, b =
assign literal values to the corresponding variablesSystem.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 inputinput.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 commentvar n, s, and b
define variables;
ends each line of JavaScript codei = , d = , s =, b =
assign literal values to the corresponding variablesoutput()
calls the output functionfunction 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 commenti = , d = , s =, b =
assign literal values to the corresponding variablesprint()
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 inputfloat()
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 commentvar i: Int
defines an integer variable named ivar d: Double
defines a double floating-point variable named dvar s: String
defines a string variable named svar b: Bool
defines a Boolean variable named bi = , d = , s =, b =
assign literal values to the corresponding variablesprint()
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 inputDouble()!
converts the input to a double floating-point valueString()
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:
- A data type defines a set of values and the set of operations that can be applied to those values.
- Reserved or keywords can be used as identifier names.
- The concept of precedence says that some operators (like multiplication and division) are to be executed before other operators (like addition and subtraction).
- An operator that needs two operands will promote one of the operands as needed to make both operands be of the same data type.
- Parentheses change the precedence of operators.
- Integer data types are stored with a mantissa and an exponent.
- Strings are identified by single quote marks in most programming languages.
- An operand is a value that receives the operator’s action.
- Arithmetic assignment is a shorter way to write some expressions.
- Integer division is rarely used in computer programming.
- The Nothing data type is the same as the value 0 (zero).
- A boolean data type has two or more possible values. One possibility can be a null data type.
- A constant can change its value.
- The Pascal case standard uses all lowercase letters with underscores separating words.
Answers:
- true
- false
- true
- true
- false – Parentheses change the order of evaluation in an expression.
- false
- false - Strings can be identified by double quotation marks as well.
- true
- true
- false
- false
- false - Boolean is a binary variable, only having two possible values, such as true/false.
- false
- false
Variables:
In each of the following, determine appropriate identifier names and data types:
- You are buying paint for a mural project in your neighborhood, so you must calculate how many gallons of paint you'll need.
- 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.
- There is a sale at your local supermarket, and you want to know how much you saved on your purchase.
- You are taking a poll to see which flavor of ice cream people like most at your school.
- 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:
- 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.
- 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?
- 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"?
- 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.
- 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.
- 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]
- 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.
- 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.
- 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.
- 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.
- 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, add0.9999
and then convert the resulting value to an integer. Calculate the total cost of the paint as:gallons * price per gallon
. - 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
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Wikiversity: Computer Programming
See AlsoEdit
- http://flowgorithm.org/documentation/operators.htm
- http://flowgorithm.org/documentation/declare.htm
- http://flowgorithm.org/documentation/output.htm
- http://flowgorithm.org/documentation/types.htm
- http://flowgorithm.org/documentation/input.htm
Functions
OverviewEdit
This chapter introduces modular programming, functions, parameters, return values, and scope.
Chapter OutlineEdit
- Modular Programming
- Hierarchy or Structure Chart
- Function Examples
- Parameters and Arguments
- Call by Value vs Call by Reference
- Return Statement
- Void Data Type
- Scope
- Programming Style
- Standard Libraries
- Code Examples
- Practice: Functions
Learning ObjectivesEdit
- Understand key terms and definitions.
- 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:
- 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.
- 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:
- define a function (its definition or the code it will execute)
- call a function
- 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:
- no communication in with no communication out
- no communication in with some communication out
- some communication in with some communication out
- 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:
- Documentation – Most programs have a comment area at the start of the program with a variety of comments pertinent to the program.
- Include or import statements used to access standard library functions.
- Language-specific code such as namespace references or function prototypes.
- 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
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
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]
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 ¶meter 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
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Wikiversity: Computer Programming
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
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:
- Documentation
- Vertical Alignment
- Comments
- Indentation
- Meaningful Identifier Names Consistently Typed
- 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:
- define a function
- declare a function (a prototype is a declaration to a compiler)
- call a function
When we create functions in our program, we usually see them in the following order in our source code listing:
- declare the function (prototype)
- call the function
- 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:
- declaring the function (prototype provided in the include file)
- calling the function (with parameter passing of values)
- 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
- In addition to the term function as the name of a subprogram, the computer industry also uses macro, procedure and module.
- Generally, functions fall into two categories: Program Control and Specific Task.
- Functions must always have a return value.
- Hierarchy Charts and Structure Charts are basically the same thing.
- Program Control functions are used to simply subdivide and control the program.
- The void data type is rarely used in C++.
- Making source code readable is only used by beginning programmers.
- User-defined specific task functions are usually placed into a user-defined library.
- Local and global data storage is associated with the concept of scope.
- Creating a header file for user-defined specific task functions is a difficult task.
- The stack is part of the computer’s memory used for storage of data.
- The standard library is a set of specific task functions that have been added to the programming language for universal use.
- Programmers should have confidence that standard library functions work properly.
- It would be easier to write programs without using specific task functions.
- In order to separate the functionality of one function from another, you need to give each function its own parameters.
- Call-by-value evaluates arguments and passes a copy of the value to the subroutine.
- All functions should be called from "Output" because "Output" needs to call information from the other functions to get the correct output.
- Functions can only return 1 output.
Answers:
- true
- true
- 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.
- true - Both names come from showing the organization / structure of a business, or the relationship between various modules.
- true
- false - The void can be used in a function's parameter list if it does not feed to return a value in C++.
- false - Making source code readable should be a priority for all programmers.
- true
- true
- false – It may seem difficult at first, but with a little practice it is really quite easy.
- true
- true
- true
- false - That may be the case in very simple code, but when the programs becomes complicated it becomes crucial to use functions.
- true
- true
- false - All functions should be called from main, because main is in charge of the other functions.
- true - only Python has the ability to return multiple variables from a single function.
Short AnswerEdit
- Create a hierarchy chart for the function example program found in this chapter.
- 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.
- Describe the differences between the local scope and the global scope.
- 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?
- In your own words describe the difference between calling by value and calling by reference.
- Explain the differences between the void data type and the Nothing data type.
- 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.
- 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]
- 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.
- 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.
- 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.
- 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.
- 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, add0.9999
and then convert the resulting value to an integer. Calculate the total cost of the paint as:gallons * price per gallon
. - 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
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Wikiversity: Computer Programming
Conditions
OverviewEdit
This chapter introduces conditions and selection control structures.
Chapter OutlineEdit
- Structured Programming
- Selection Control Structures
- If Then Else
- Code Blocks
- Relational Operators
- Assignment vs Equality
- Logical Operators
- Nested If Then Else
- Case Control Structure
- Condition Examples
- Code Examples
- Practice: Conditions
Learning ObjectivesEdit
- Understand key terms and definitions.
- 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:
- Selection (if/then/else)
- Repetition (while and for)
- Block Structures
- Subroutines
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 + “<br>”;
a++;
}
document.getElementById(“demo”).innerHTML = text;
</script>
Branching – An uncontrolled structure that allows the flow of execution to jump to a different part of the program. This category is rarely used in modular structured programming. For example, and if/else statement depending on the condition.
<script>
var x="";
var time=new Date().getHours();
if (time<20)
{x="Have Good day";
}
else
{x="Have Good evening";
}
document.write(x);
</script>
All high-level programming languages have control structures. All languages have the first three categories of control structures (sequence, selection, and iteration). Most have the if then else structure (which belongs to the selection category) and the while structure (which belongs to the iteration category). After these two basic structures, there are usually language variations.
The concept of structured programming started in the late 1960’s with an article by Edsger Dijkstra. He proposed a “go to less” method of planning programming logic that eliminated the need for the branching category of control structures. The topic was debated for about 20 years. But ultimately – “By the end of the 20th century nearly all computer scientists were convinced that it is useful to learn and apply the concepts of structured programming.”[2]
Key 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.
x | y | x and y |
false | false | false |
false | true | false |
true | false | false |
true | true | true |
x | y | x or y |
false | false | false |
false | true | true |
true | false | true |
true | true | true |
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
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
- There are only two categories of control structures.
- Branching control structures are rarely used in good structured programming.
- If then else is a multiway selection control structure.
- The while control structure is part of the branching category.
- Pseudocode is better than flowcharting.
- In a sequence control structure, the program executed path is chosen by options prompted by questions.
- An iteration control structure allows some lines of code to be executed many times.
- A relational operator is an operator used to create complex Boolean expressions.
- The best way to structure an if-then-else statement is to check if a statement is True.
- The value of the statement "True and False" is 'True'.
- To initialize or set the value of a variable, you should use the equality operator (==)
Answers:
- false - There are three.
- true
- false - It is part of the selection structure.
- false - It is part of the repetition category.
- false - While pseudocode may be very useful, it does not have the same clarity as flowcharting.
- false - Sequence structure programs execute items in the order listed.
- true
- false - They are used to test relationships between values.
- false - In general, it is better to test for False or not False rather than True or not True.
- false - The statement's value is 'False'.
- false - Use the assignment operator (=)
Evaluate the following Boolean expressions:
- 25 < 7
- 3 < 7
- 14 > 7
- 17 <= 7
- 25 >= 7
- 13 == 7
- 9 != 7
- 5 !> 7
- 25 > 39 || 15 > 36
- 19 > 26 || 13 < 17
- 14 < 7 && 6 <= 6
- 4 > 3 && 17 >= 7
- ! true
- ! (13 == 7)
- 9 != 7 && ! 1
- 6 < && 8
Answers:
- 0
- 1
- 1
- 0
- 1
- 0
- 1
- Error, the “not greater than” is not a valid operator.
- 0
- 1
- 0
- 1
- 0
- 1
- 0
- Error, there needs to be an operand between the operators < and &&.
Short AnswerEdit
- List the four categories of control structures and provide a brief description of each category.
- Create a table with the six relational operators and their meanings.
- Provide examples of when it is appropriate to use "if" vs. "if-else" vs. "if-else if-else".
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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. - 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.
- 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.
- 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
- cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
- Wikiversity: Computer Programming
Loops
OverviewEdit
This chapter introduces loops and iteration control structures.
Chapter OutlineEdit
- Iteration Control Structures
- While Loop
- Do While Loop
- Flag Concept
- For Loop
- Branching Statements
- Increment and Decrement Operators
- Integer Overflow
- Nested Loops
- Loop Examples
- Code Examples
- Practice: Loops
Learning ObjectivesEdit
- Understand key terms and definitions.
- Identify control structures based on test before iteration, test after iteration, and counting, and when to use each type.
- 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
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:
- True or false: x = x +1 and x+=1 and x++ all accomplish increment?
- Given: int y = 19; and int z; what values will y and z have after: z = y–;
- Given: double x = 7.77; and int y; what values will x and y have after: y = ++x;
- 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
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;
}
}