Programming Fundamentals/Printable version


Programming Fundamentals

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

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

Preface

A Note to Readers

edit

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

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

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

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

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

Dave Braunschweig

About this Book

edit

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

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

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

Learning Modules

edit

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

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

Conceptual Approach

edit

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

Re-use and Customization

edit

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

PDF Conversion Problems

edit

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

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

References

edit


Author Acknowledgements

1st Edition Acknowledgements

edit

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

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

Kenneth Leroy Busbee

2nd Edition Acknowledgements

edit

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

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

Dave Braunschweig

References

edit


Introduction to Programming

Overview

edit

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

Chapter Outline

edit

Learning Objectives

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


Systems Development Life Cycle

Overview

edit
 
Systems Development Life Cycle

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

Discussion

edit

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

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

Computer professionals that are in charge of creating applications often have the job title of System Analyst. The major steps in creating an application include the following: planning, analysis, design, implementation, and maintenance. In the first step, the Planning phase, the System Analyst will identify if there is a demand for replacing or creating a new application. This is where a feasibility test is conducted to determine the success of the new application. During the Analysis phase, the desired operations of the application must be stated. This helps verify that the needs of the end-user are satisfied.[2] During the Design phase, the System Analyst will document the inputs, processing, and outputs of each program within the application. During the Implementation phase, programmers would be assigned to write the specific programs using a programming language decided by the System Analyst. Once the system of programs is tested, the new application is installed for people to use. As time goes by, things change and a specific part or program might need repair. During the Maintenance phase, it goes through a mini planning, analysis, design, and implementation cycle. The programs that need modification are identified and programmers change or repair those programs. After several years of use, the system usually becomes obsolete. At this point, a major revision of the application is done. Thus the cycle repeats itself.

Key Terms

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

References

edit


Program Design

Overview

edit

Program design consists of the steps a programmer should take before they start coding a program. These steps when properly documented will make the completed program easier for other programmers to maintain in the future. There are three broad areas of activity:

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

Understanding the Program

edit

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

  • Inputs
  • Processing
  • Outputs

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

Algorithm

edit

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

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

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

Using Design Tools to Create a Model

edit

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

The first modeling tool you usually learn is pseudocode. You will document the logic or algorithm of each function in your program. At first, you will have only one function, and thus your pseudocode will follow closely the IPO approach above.

There are several methods or tools for planning the logic of a program. They include: flowcharting, hierarchy or structure charts, pseudocode, HIPO, Nassi-Schneiderman charts, Warnier-Orr diagrams, etc. Programmers are expected to understand and create flowcharts and pseudocode. These methods of developing a program's model are usually taught in computer courses. Several standards exist for flowcharting and pseudocode and most are very similar. However, most companies have their own documentation standards and styles. Programmers are expected to quickly adapt to any flowcharting or pseudocode standards for the company at which they work. The other methods that are less universal require some training which is generally provided by the employer.

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

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

Develop Test Data

edit

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

Key Terms

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

References

edit


Program Quality

Overview

edit

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

Discussion

edit

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

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

Key Terms

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

References

edit


Pseudocode

Overview

edit

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

Discussion

edit

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

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

Outline using Pseudocode

Input
    display a message asking the user to enter the first age
    get the first age from the keyboard
    display a message asking the user to enter the second age
    get the second age from the keyboard

Processing
    calculate the answer by adding the two ages together and dividing by two

Output
    display the answer on the screen
    pause so the user can see the answer

After developing the program design, we use the pseudocode to write code in a language (like C++, Java, Python, etc.) where you must follow the rules of the language (syntax) to code the logic or algorithm presented in the pseudocode. Pseudocode usually does not include other items produced during programming design, such as identifier lists for variables or test data.

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

Key Terms

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

References

edit


Flowcharts

Overview

edit
 
Flowchart displaying "Hello world!"

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

Discussion

edit

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

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

Simple Flowcharting Symbols

edit

Terminal

edit

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

 

Flow Lines

edit

Note: The default flow is left to right and top to bottom (the same way you read English). To save time arrowheads are often only drawn when the flow lines go contrary the normal.

 

Input/Output

edit

The parallelograms designate input or output operations.

 

Process

edit

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

 

Decision

edit

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

 

Advanced Flowcharting Symbols

edit

Module Call

edit

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.

 

Connectors

edit

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 Examples

edit


Simple Examples

edit

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

Functions

edit

pseudocode: Function with no parameter passing

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

pseudocode: Function main calling the clear monitor function

Function main
    Pass In: nothing
    Doing some lines of code
    Call: clear monitor
    Doing some lines of code
    Pass Out: value zero to the operating system
End function

Sequence Control Structures

edit

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

pseudocode: Sequence control structure

Filename: Solution_Lab_04_Pseudocode.txt
Purpose:  Convert Temperature from Fahrenheit to Celsius
Author:   Ken Busbee; © 2008 Kenneth Leroy Busbee
Date:     Dec 24, 2008

Pseudocode = IPO Outline

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

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

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

Advanced Examples

edit

Selection Control Structures

edit

pseudocode: If then Else

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

pseudocode: Case

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

Iteration (Repetition) Control Structures

edit

pseudocode: While

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

pseudocode: For

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

The for loop does not have a standard flowcharting method and you will find it done in different ways. The for loop as a counting loop can be flowcharted similar to the while loop as a counting loop.

pseudocode: Do While

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

pseudocode: Repeat Until

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

Key Terms

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

References

edit


Software Testing

Overview

edit

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

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

Discussion

edit

Test data consists of the user providing some input values and predicting the outputs. This can be quite easy for a simple program and the test data can be used twice.

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

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

Pseudocode using an IPO Outline for Calculating Gross Pay

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

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

Creating Test Data and Model Checking

edit

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

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

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

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

Testing the Coded Program – Code Checking

edit

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

By developing test data we are predicting what the results should be, thus we can verify that our program is working properly. When we run the program we would enter the input values used in our test data. Hopefully, the program will output the predicted values. If not then our problem could be any of the following:

  1. The plan (IPO outline or another item) could be wrong
  2. The conversion of the plan to code might be wrong
  3. The test data results were calculated wrong

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

Key Terms

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

References

edit


Integrated Development Environment

Overview

edit

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

Discussion

edit

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

 
Integrated Development Environment or IDE

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

Upon starting the IDE software the programmer usually indicates the file he or she wants to open for editing as source code. As they make changes they might either do a “save as” or “save”. When they have finished entering the source code, they usually direct the IDE to “compile & run” the program. The IDE does the following steps:

  1. If there are any unsaved changes to the source code file it has the test editor save the changes.
  2. The compiler opens the source code file and performs the first step which is executing the pre-processor compiler directives and other steps needed to get the file ready for the second step. The #include will insert-header files into the code at this point. If it encounters an error, it stops the process and returns the user to the source code file within the text editor with an error message. If no problems are encountered, it saves the source code to a temporary file called a translation unit.
  3. The compiler opens the translation unit file and performs the second step which is converting the programming language code to machine instructions for the CPU, a data area, and a list of items to be resolved by the linker. Any problems encountered (usually a syntax or violation of the programming language rules) stops the process and returns the user to the source code file within the text editor with an error message. If no problems are encountered it saves the machine instructions, data area, and linker resolution list as an object file.
  4. The linker opens the program object file and links it with the library object files as needed. Unless all linker items are resolved, the process stops and returns the user to the source code file within the text editor with an error message. If no problems are encountered it saves the linked objects as an executable file.
  5. The IDE directs the operating system’s program called the loader to load the executable file into the computer’s memory and have the Central Processing Unit (CPU) start processing the instructions. As the user interacts with the program, entering test data, he or she might discover that the outputs are not correct. These types of errors are called logic errors and would require the user to return to the source code to change the algorithm.

Resolving Errors

edit

Despite our best efforts at becoming perfect programmers, we will create errors. Solving these errors is known as debugging your program. The three types of errors in the order that they occur are:

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

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

During the conversion (2nd step) the compiler might give a warning message which in some cases may not be a problem to worry about. For example Data type demotion may be exactly what you want your program to do, but most compilers give a warning message. Warnings don’t stop the compiling process but as their name implies, they should be reviewed.

Key Terms

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

References

edit


Version Control

Overview

edit

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

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

Discussion

edit

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

Version control allows you to:[3]

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

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

Popular version control systems include:[5]

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

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

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

Free public git repositories are available from:

  • Bitbucket
  • GitHub

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

  • git init

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

  • git clone <url>

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

  • git pull

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

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

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

  • git push --force

Key Terms

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

References

edit


Input and Output

Overview

edit

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

Discussion

edit
 
CPU – Memory – Input/Output Devices

Every task done on the computer happens inside the central processing unit (CPU) and the associated memory. Once our program is loaded into memory and the operating system directs the CPU to start executing our programming statements the computer looks like this:

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

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

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

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

Key Terms

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

References

edit


Hello World

Overview

edit

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

Discussion

edit

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

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

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

Pseudocode

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

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

Output

edit
Hello world!

Each code element represents:[5]

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

Flowchart

edit

Examples

edit

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

Key Terms

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

References

edit


Introduction Examples C++

Overview

edit

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

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

Example

edit

Hello World

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

Output

edit
Hello world!

Discussion

edit

Each code element represents:[3]

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

C++ IDEs

edit

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

Cloud-Based IDEs

edit

Local IDEs

edit

References

edit


Introduction Examples CSharp

Overview

edit

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

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

Example

edit

Input: Hello World

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

Output

edit
Hello world!

Discussion

edit

Each code element represents:Programming Fundamentals/Hello World

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

C# IDEs

edit

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

Cloud-Based IDEs

edit

Local IDEs

edit

References

edit


Introduction Examples Java

Overview

edit

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

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

Example

edit

Hello World

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

Output

edit
Hello world!

Discussion

edit

Each code element represents:Programming Fundamentals/Hello World

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

Java IDEs

edit

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

Cloud-Based IDEs

edit

Local IDEs

edit

References

edit


Introduction Examples JavaScript

Overview

edit

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

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

Example

edit

Hello World – Console Log

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

Output

edit
Hello world!

Discussion

edit

Each code element represents:

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

Hello World – Window Alert

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

Output

edit
Hello world!

Discussion

edit

Each code element represents:

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

Hello World – Document Write

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

Output

edit
Hello world!

Discussion

edit

Each code element represents:

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

JavaScript IDEs

edit

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

Cloud-Based IDEs

edit

Local IDEs

edit

References

edit


Introduction Examples Python

Overview

edit

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

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

Example

edit

Input: Hello World

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

Output

edit
Hello world!

Discussion

edit

Each code element represents:Programming Fundamentals/Hello World

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

Python IDEs

edit

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

Cloud-Based IDEs

edit

Local IDEs

edit

References

edit


Introduction Examples Swift

Overview

edit

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

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

Example

edit

Hello World

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

Output

edit
Hello world!

Discussion

edit

Each code element represents:Programming Fundamentals/Hello World

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

Swift IDEs

edit

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

Cloud-Based IDEs

edit

Local IDEs

edit

References

edit


Practice: Introduction to Programming

Chapter Summary

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

Review Questions

edit

True / False:

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

Answers:

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

Short Answer:

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

Activities

edit

Pseudocode and Flowcharts

edit

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

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

Programming Languages and Integrated Development Environments

edit

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

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

References

edit


Data and Operators

Overview

edit

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

Chapter Outline

edit

Learning Objectives

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


Constants and Variables

Overview

edit

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

Discussion

edit

Understanding Constants

edit

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

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

Constants are used in two ways. They are:

  1. literal constant
  2. defined constant

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

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

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

Language Example
C++ #define PI 3.14159or

const double PI = 3.14159;

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

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

Defining Constants and Variables

edit

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

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

Key Terms

edit
Constant
A data item whose value cannot change during the program’s execution.
Variable
A data item whose value can change during the program’s execution.

References

edit


Identifier Names

Overview

edit

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

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

Discussion

edit

Language Technical Limitations

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

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

Good Programming Techniques

edit
  • Meaningful
  • Be case consistent

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

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

Industry Rules

edit

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

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

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

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

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

Key Terms

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

References

edit


Data Types

Overview

edit

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

Discussion

edit

Our interactions (inputs and outputs) with a program are treated in many languages as a stream of bytes. These bytes represent data that can be interpreted as representing values that we understand. Additionally, within a program, we process this data in various ways such as adding them up or sorting them. This data comes in different forms. Examples include:

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

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

Common data types include:

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

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

Pseudocode

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

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

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

Output

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

Flowchart

edit

 

Key Terms

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

References

edit


Integer Data Type

Overview

edit

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

Discussion

edit

The integer data type represents whole numbers (no fractional parts). The integer values jump from one value to another. There is nothing between 6 and 7. It could be asked why not make all your numbers floating point which allow for fractional parts. The reason is threefold. First, some things in the real world are not fractional. A dog, even with only 3 legs, is still one (1) dog not ¾ of a dog. Second, the integer data type is often used to control program flow by counting, thus the need for a data type that jumps from one value to another. Third, integer processing is significantly faster within the CPU than is floating point processing.

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

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

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

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

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

Key Terms

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

References

edit


Floating-Point Data Type

Overview

edit

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

Discussion

edit

The floating-point data type is a family of data types that act alike and differ only in the size of their domains (the allowable values). The floating-point family of data types represents number values with fractional parts. They are technically stored as two integer values: a mantissa and an exponent. The floating-point family has the same attributes and acts or behaves similarly in all programming languages. They can always store negative or positive values thus they always are signed; unlike the integer data type that could be unsigned. The domain for floating-point data types varies because they could represent very large numbers or very small numbers. Rather than talk about the actual values, we mention the precision. The more bytes of storage the larger the mantissa and exponent, thus more precision.

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

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

Key Terms

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

References

edit


String Data Type

Overview

edit

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

Discussion

edit

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

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

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

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

Most computing devices use the ASCII (stands for American Standard Code for Information Interchange and is pronounced “ask-key”) Character Set which has established values for 0 to 127. For the values of 128 to 255 they usually use the Extended ASCII Character Set. When we hit the capital A on the keyboard, the keyboard sends a byte with the bit pattern equal to an integer 65. When the byte is sent from the memory to the monitor, the monitor converts the integer value of 65 to into the symbol of the capital A to display on the monitor.

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

Key Terms

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

References

edit


Boolean Data Type

Overview

edit

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

Discussion

edit

The Boolean data type is also known as the logical data type and represents the concepts of true and false. The name “Boolean” comes from the mathematician George Boole; who in 1854 published: An Investigation of the Laws of Thought. Boolean algebra is the area of mathematics that deals with the logical representation of true and false using the numbers 0 and 1. The importance of the Boolean data type within programming is that it is used to control programming structures (if then else, while loops, etc.) that allow us to implement “choice” into our algorithms.

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

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

Key Terms

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

References

edit


Nothing Data Type

Overview

edit

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

Discussion

edit

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

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

Key Terms

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

References

edit