Jump to content

Programming Fundamentals/Collection

From Wikiversity

Programming Fundamentals

[edit | edit source]

Computer programming (often shortened to programming) is a process that leads from an original formulation of a computing problem to executable computer programs. Programming involves activities such as analysis, developing understanding, generating algorithms, verification of requirements of algorithms including their correctness and resources consumption, and implementation (commonly referred to as coding) of algorithms in a target programming language.[1]

This course comprises nine lessons on the fundamentals of computer programming. Each lesson includes a combination of Wikibooks, Wikipedia, and Internet-based readings, YouTube videos, and hands-on, interactive learning activities. Examples are provided using flowcharts, pseudocode, and a wide variety of computer programming languages.

This entire Wikiversity course can be downloaded in book form by selecting Download Learning Guide in the sidebar.

Preparation

[edit | edit source]

This is a second-semester, college-level course. Learners should already be familiar with introductory computer concepts and have advanced or proficient-level computer skills. Learners need to have access to the internet readily available to them.

Lessons

[edit | edit source]
  1. Introduction
  2. Variables
  3. Functions
  4. Conditions
  5. Loops
  6. Arrays
  7. Strings
  8. Files
  9. Objects

See Also

[edit | edit source]

Bibliography

[edit | edit source]
  • Braunschweig, D. and Busbee, K. L. (2018). Programming Fundamentals - A Modular Structured Approach, 2nd Edition. Pressbooks.
  • Farrell, J. (2015). Programming Logic and Design, Introductory, 8th Edition. Cengage. ISBN 9781285845777
  • Gaddis, T. (2016). Starting Out with Programming Logic and Design, 4th Edition. Pearson. ISBN 9780133998160

References

[edit | edit source]

Lesson 1 - Introduction

[edit | edit source]
Flowchart displaying "Hello, world!"
Flowchart displaying "Hello, world!"

This lesson introduces computer programming, flowcharts, pseudocode, and integrated development environments (IDEs). These will help you to learn a chosen programming language as well as help you learn to write your own programs. Each of the programs are essential to helping you take the steps needed to go further in your field.


Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:

  • Understand fundamental computer programming concepts.
  • Use a flowchart to describe a simple process.
  • Use pseudocode to describe a simple process.
  • Use an online IDE to edit and test simple programs.
  • Understand available compilers/interpreters and IDEs for a selected programming language.

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: Computer programming
  3. Wikipedia: Software development process
  4. Wikipedia: Flowchart
  5. Wikipedia: Pseudocode
  6. Wikipedia: Programming language
  7. Wikipedia: Visual programming language
  8. Wikipedia: Integrated development environment
  9. Wikipedia: "Hello, World!" program
  10. Wikipedia: Comment (computer programming)

Multimedia

[edit | edit source]
  1. YouTube: How to Think Like a Programmer
  2. YouTube: Should I Give Up Computer Science If I Find It Hard?
  3. YouTube: Introduction to Programming
  4. YouTube: Elements of High-Quality Programs (Through the development life cycle)
  5. YouTube: Programming Basics "Pseudocode"
  6. YouTube: Sandwich making algorithm
  7. YouTube: What is an IDE?
  8. YouTube: What Programming Language Should I Learn First
  9. YouTube: What is Version Control?

Practice

[edit | edit source]

Examples

[edit | edit source]

Activities

[edit | edit source]

Flowcharts

[edit | edit source]
  1. Review Flowchart. Use one of the free online or downloadable flowchart tools to create a flowchart that describes how to make your favorite sandwich or other non-prepackaged food. If unsure how to proceed, search the Internet for flowchart peanut butter and jelly sandwich to use as an example. Note: Because peanut butter and jelly sandwich examples are already available, you must select something else for your flowchart.

Pseudocode

[edit | edit source]
  1. Review Pseudocode. Create a text document that uses pseudocode to describe how to make your favorite sandwich or other non-prepackaged food. If unsure how to proceed, search the Internet for pseudocode peanut butter and jelly sandwich to use as an example. Note: Because peanut butter and jelly sandwich examples are already available, you must select something else for your pseudocode.

Programming Languages

[edit | edit source]
  1. Research different programming languages and select a programming language to use for this course. If unsure, Python3 is currently a popular choice for a first programming language. Use the Examples link above for your selected programming language and use one of the free online IDE links provided 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.

Interactive Learning/Programming Games

[edit | edit source]
  1. Code.org
  2. CodeCombat.com
  3. Codingame.com
  4. Checkio.org
  5. Codewars.com
  6. Microsoft MakeCode

Coding Apps

[edit | edit source]

Try one or more of the following mobile coding applications:

  • Grasshopper - Google's Grasshopper app is a fantastic way for beginners to start coding. There's no shortage of coding tutorials or programs that aim to teach coding to beginners.
  • Encode - Provides small lessons that teach coding concepts and provide examples of real code (uses JavaScript)
  • Mimo: Learn to code - Learn basics of coding and do lessons based on your areas of interest (various languages)
  • ProgrammingHub - Add courses based on your interests and skill levels. Can be used by beginners or pros looking to refine skills (various languages)
  • Py - Offers beginner, intermediate, and advanced courses in the areas of iOS development, website development, and data science (various languages)
  • SoloLearn - Teaches beginner lessons in a large number of languages that have many different applications (various languages)

All apps offer free versions, some offer premium versions.

Developer Networks

[edit | edit source]

Many hardware and software vendors maintain a developer network as a part of their public website. Developer networks are maintained to allow communities of people learn, use, and even exchange and review programs with other members of the online community. Spend some time at a the development network websites below and see what kinds of resources common vendors offer to enable and encourage developers to grow within their communities. Or, if you have a favorite game, program or vendor, spend some time searching to see if they too host an online development community.

Lesson Summary

[edit | edit source]

Overall, this first lesson goes over the different fundamentals crucial to starting the development process.

  • Computer Programming is the process of writing the source code for computer applications. The source code is written in one of many programming languages which will tell the application to carry out a task depending on what code has been written.[1], [2]
    • A programming language is a formal language that specifies a set of instructions that can be used to produce various kinds of output. Programming languages can be used to create programs that implement specific algorithms, and is usually split into the two components of syntax (form) and semantics (meaning).[3][4]
  • A "Hello, world!" program is a computer program that outputs or displays "Hello, world!" to a user. It is often used as an intro to the basic syntax of a programming language for a working program, and is often the very first program people write when they are new to a language.[5]
  • The input–process–output (IPO) model, or input-process-output pattern, is a widely used approach in systems analysis and software engineering for describing the structure of an information processing program or other process. Many introductory programming and systems analysis texts introduce this as the most basic structure for describing a process.[6]
    • A program or process using the input-process-output model receives inputs from a user or other source and returns the results of the computations. The system separates itself from the environment, thus defining both inputs and outputs, as one united mechanism.[7]
  • A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the steps as different boxes joined by arrows. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields.[8]
  • Visual programming languages (VPL) are any programming language that lets users create programs by manipulating program elements graphically rather than by specifying them textually.
    • A VPL allows programming with visual expressions, spatial arrangements of text and graphic symbols, used either as elements of syntax or secondary notation.[9]
  • Programming involves problem analysis, solution design, source code development, testing, and maintenance.[10][11]
    • Common methodologies include Agile, waterfall, prototyping, iterative and incremental development, spiral development, rapid application development, extreme programming and various types of agile methodology.[12]
  • Program quality requirements include reliability, robustness, usability, portability, maintainability, and efficiency/performance.[13]
  • 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.
    • Integrated development environments are designed to maximize programmer productivity by providing tightly-knit components with similar user interfaces.[14]
    • Some IDEs, such as NetBeans and Eclipse, contain a compiler, interpreter, or both. Others, such as SharpDevelop and Lazarus, do not.[15]
  • Comments are programmer-readable explanations or annotations 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.[16]

Key Terms

[edit | edit source]
agile software development
Agile software development comprises various approaches to software development under which requirements and solutions evolve through the collaborative effort of self-organizing and cross-functional teams and their customer(s)/end user(s). It advocates adaptive planning, evolutionary development, early delivery, and continual improvement, and it encourages rapid and flexible response to change.[17]
algorithm
A self-contained step-by-step set of operations to be performed.[18]
compiler
A computer program that transforms source code written in a programming language (the source language) into another computer language (the target language), with the latter often having a binary form known as object code.[19]
continuous integration
Practice of merging all developer working copies to a shared mainline several times a day.[20]
flowchart
A type of diagram that represents an algorithm, workflow or process, showing the steps as boxes of various kinds, and their order by connecting them with arrows.[21]
incremental development
Breaks down a development project into smaller segments that are completed before moving on to the next segment. This method reduces risk and facilitates more ease-of-change in the development process.[22]
input
Signals or data received by a computer system.[23]
integrated development environment (IDE)
A software application that provides comprehensive facilities to computer programmers for software development.[24]
interpreter
A computer program that directly executes, i.e. performs, instructions written in a programming or scripting language, without previously compiling them into a machine language program.[25]
IPO
An acronym for the Inputs - Processing - Outputs model which describes the structure of a program as what data would be inputted into an information system, how that information is processed, what the processed information would output from the information system.[26]
machine code
A set of instructions executed directly by a computer's central processing unit (CPU).[27]
object code
A sequence of statements or instructions produced by a compiler, usually in a machine code language or an intermediate language.[28]
object-oriented programming
A programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.[29]
output
Signals or data sent from a computer system.[30]
procedural programming
A programming paradigm, derived from structured programming, based upon the concept of the procedure call, where any given procedure might be called at any point during a program's execution, including by other procedures or itself.[31]
process
An instance of a computer program that is being executed, which contains the program code and its current activity.[32]
programming language
A formal computer language designed to communicate instructions to a machine, particularly a computer.[33]
prototyping
Developing incomplete versions of the software program being developed. Allows developers to test individual features of a larger program.[34]
pseudocode
An informal high-level description of the operating principle of a computer program or other algorithm.[35]
rapid application development
Favors rapid construction of prototypes over a large up-front planning phase. The lack of planning allows for software to be completed much faster.[36]
scripting language
A programming language that supports programs written for a special run-time environment that automate the execution of tasks that could alternatively be executed one-by-one by a human operator.[37]
source code
Any collection of computer instructions, possibly with comments, written using a human-readable programming language, usually as ordinary text.[38]
syntax
The set of rules that defines the combinations of symbols that are considered to be a correctly structured document or fragment in that language.[39]
waterfall development
Sequential development approach in which development goes through several phases: requirement analysis, design, implementation, verification, and maintenance.[40]

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
  1. Wikipedia: Computer programming
  2. Wikipedia: List of programming languages
  3. Wikipedia: Programming Language
  4. Wikipedia: Programming language
  5. Wikipedia: "Hello, World!"
  6. Wikipedia: IPO model
  7. Wikipedia: IPO model
  8. Wikipedia: Flowchart
  9. Wikipedia: Visual programming language
  10. Wikipedia: Computer programming
  11. Wikipedia: Software development process
  12. Wikipedia: Software development process,
  13. Wikipedia: Computer programming
  14. Wikipedia: Integrated development environment
  15. Wikipedia: Integrated development environment
  16. Wikipedia: Comment (computer programming)
  17. Wikipedia: Agile software development
  18. Wikipedia: Algorithm
  19. Wikipedia: Compiler
  20. "Software development process". Wikipedia. 2019-01-09. https://en.wikipedia.org/w/index.php?title=Software_development_process&oldid=877599120. 
  21. Wikipedia: Flowchart
  22. "Software development process". Wikipedia. 2019-01-09. https://en.wikipedia.org/w/index.php?title=Software_development_process&oldid=877599120. 
  23. Wikipedia: Input/output
  24. Wikipedia: Integrated development environment
  25. Wikipedia: Interpreter (computing)
  26. "IPO model". Wikipedia. 2019-08-06. https://en.wikipedia.org/w/index.php?title=IPO_model&oldid=909589659. 
  27. Wikipedia: Machine code
  28. Wikipedia: Object code
  29. Wikipedia: Object-oriented programming
  30. Wikipedia: Input/output
  31. Wikipedia: Procedural programming
  32. Wikipedia: Process (computing)
  33. Wikipedia: Programming language
  34. "Software development process". Wikipedia. 2019-01-09. https://en.wikipedia.org/w/index.php?title=Software_development_process&oldid=877599120. 
  35. Wikipedia: Pseudocode
  36. "Software development process". Wikipedia. 2019-01-09. https://en.wikipedia.org/w/index.php?title=Software_development_process&oldid=877599120. 
  37. Wikipedia: Scripting language
  38. Wikipedia: Source code
  39. Wikipedia: Syntax (programming languages)
  40. "Software development process". Wikipedia. 2019-01-09. https://en.wikipedia.org/w/index.php?title=Software_development_process&oldid=877599120. 

Lesson 2 - Variables

[edit | edit source]
Flowchart displaying variables
Flowchart displaying variables

This lesson introduces variables, constants, data types, expressions, statements, and order of operations.


Objectives and Skills

[edit | edit source]
  • Understand variables and constants.
  • Use integer, floating-point, and string data types appropriately.
  • Use expressions and statements to assign values to variables.
  • Understand the order of operations for arithmetic and logical operators.

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: Variable (computer science)
  3. Wikipedia: Constant (computer programming)
  4. Wikipedia: Data type
  5. Wikipedia: Expression (computer science)
  6. Wikipedia: Statement (computer science)
  7. Wikipedia: Assignment (computer science)
  8. Wikipedia: Order of operations
  9. Wikipedia: Input/output
  10. Wikipedia: Self-documenting code

Multimedia

[edit | edit source]
  1. YouTube: Programming For Beginners - Variables
  2. YouTube: Programming For Beginners - Data Types
  3. YouTube: Introduction to Programs Data Types and Variables
  4. YouTube: Introduction to Programming - Basics
  5. YouTube: Declaring and using variables and constants
  6. YouTube: Performing arithmetic operations
  7. YouTube: Introduction to order of operations
  8. YouTube: Algorithm using Flowchart and Pseudo code Level 1 Flowchart
  9. YouTube: Basic program using outputs- example 1
  10. YouTube: Basic program - random number example 2
  11. YouTube: Basic program - using inputs - example 3

Practice

[edit | edit source]

Examples

[edit | edit source]

Activities

[edit | edit source]

Complete the following activities using a flowchart tool, pseudocode, or your selected programming language.

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

Lesson Summary

[edit | edit source]
  • Variables are parts of an equation that can change, thus they typically depend on user input. They should be named to refer to what the input/data represents.[4]
  • There are five variable data types. Integer, Floating point, string, Boolean, and nothing data types.[5]
  • Integer data types are values that have a mathematical value, or numbers. the range of these numbers can from -2,147,483,647 to 2,147,483,647.[6]
  • A Floating points are data types that allow a fractional numerical value. The difference between integer data types and float types is that floats are used when a more precise number value is needed.[7]
  • A String data type is a data type that consists of characters that are set to one order.[8]
  • A Boolean data type is a data type that simply has two values; true or false. It's usually used to set loops and conditions.[9]
  • A Nothing data type is a data type that is used to set a null or zero value.[10]
  • Constants are part of an equation that can never change.[11]
  • Programs are built on statements and expressions.[12]
  • Expressions must be declared in order to be used, and they must have a unique identifier name, as well as a data type.[13]
  • Statements contain executable code that modifies the actions of the program.[14]
  • Operator precedence sets the rules that govern the 'order of operations' or the order of parsing operators for a particular language as the order may vary from one programming language to another.[15]
  • Most programming languages follow the order of operations (PEMDAS) just like in regular math.[16]
  • Identifier names follow a set of rules imposed by the language's technical limitations, good programming practices, and common industry standards for language.[17]
  • Good programming techniques involve using meaningful and case consistent identifiers. Meaningful identifier helps others to understand your code better. Case consistent practice will help you to avoid errors.[18]
  • The data type used for a variable's declaration sets the parameters for the kind of data that the variable can contain.[19]

Key Terms

[edit | edit source]
assignment
Assigns a variable name to a value of data (or resets the value of data), that will then be stored by the computer.[20]
Boolean
A data type having two values, typically denoted true and false.[21]
constant
A value that cannot be altered by the program during normal execution.[22]
data type
A classification of data which tells the compiler or interpreter how the programmer intends to use the data.[23]
declaration
A language construct that specifies the properties of a given identifier.[24]
double
The most often used floating-point family data type used.[25]
expression
A combination of one or more explicit values, constants, variables, operators, and functions that a programming language interprets and computes to produce another value.[26]
floating point
The formulaic representation that approximates a real number to a fixed amount of significant digits.[27]
integer
A number that can be written without a fractional component.[28]
modulus
The remainder part after the division of one number by another.[29]
NaN
Reserved word used to indicate a non-numeric value in a numeric variable.[30]
null
Reserved word used to represent a missing value or invalid value.[31]
operator
A programming language construct that performs a calculation from zero or more input values to an output value.[32]
precedence
Determines the order in which the operators are allowed to manipulate the operands.[33]
order of operations
A collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression.[34]
real number
a value that represents a quantity along a line, including integers, fractions, and irrational numbers.[35]
self-documenting code
Source code and user interfaces that follow naming conventions and structured programming conventions that enable the use of a system without prior specific knowledge.[36]
statement
The smallest standalone element of an imperative programming language that expresses some action to be carried out.[37]
string
A data type used to represent text rather than numbers.[38]
truncation
The fractional part of a floating-point data type that is dropped when converted to an integer.[39]
variable
A storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value. In which case, the value can change during the program's execution.[40]

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
  1. PythonLearn: Variables, expressions, and statements
  2. Wikibooks: Programming Fundamentals/Practice: Data and Operators
  3. Wikibooks: Programming Fundamentals/Practice: Data and Operators
  4. https://press.rebus.community/programmingfundamentals/chapter/constants-and-variables/
  5. https://press.rebus.community/programmingfundamentals/chapter/data-types/
  6. https://press.rebus.community/programmingfundamentals/chapter/integer-data-type/
  7. https://press.rebus.community/programmingfundamentals/chapter/floating-point-data-type/
  8. https://press.rebus.community/programmingfundamentals/chapter/string-data-type/
  9. https://press.rebus.community/programmingfundamentals/chapter/boolean-data-type/
  10. https://press.rebus.community/programmingfundamentals/chapter/nothing-data-type/
  11. https://press.rebus.community/programmingfundamentals/chapter/constants-and-variables/
  12. https://www.webopedia.com/TERM/S/statement.html
  13. https://press.rebus.community/programmingfundamentals/chapter/order-of-operations/
  14. https://en.wikipedia.org/wiki/Statement_(computer_science)
  15. https://press.rebus.community/programmingfundamentals/chapter/order-of-operations/
  16. https://press.rebus.community/programmingfundamentals/chapter/order-of-operations/
  17. https://press.rebus.community/programmingfundamentals/chapter/identifier-names/
  18. https://press.rebus.community/programmingfundamentals/chapter/identifier-names/
  19. https://press.rebus.community/programmingfundamentals/chapter/identifier-names/
  20. Wikipedia: Assignment (computer science)
  21. Wikipedia: Boolean data type
  22. Wikipedia: Constant (computer programming)
  23. Wikipedia: Data type
  24. Wikipedia: Declaration (computer programming)
  25. https://press.rebus.community/programmingfundamentals/chapter/floating-point-data-type/
  26. Wikipedia: Expression (computer science)
  27. Wikipedia: Floating point
  28. Wikipedia: Integer
  29. Wikipedia: Modulo operation
  30. https://press.rebus.community/programmingfundamentals/chapter/nothing-data-type/
  31. https://press.rebus.community/programmingfundamentals/chapter/nothing-data-type/
  32. Wikipedia: Operation (mathematics)
  33. https://press.rebus.community/programmingfundamentals/chapter/order-of-operations/
  34. Wikipedia: Order of operations
  35. Wikipedia: Real number
  36. "Self-documenting code". Wikipedia. 2019-06-03. https://en.wikipedia.org/w/index.php?title=Self-documenting_code&oldid=900074753. 
  37. Wikipedia: Statement (computer science)
  38. TechTerms: String
  39. https://press.rebus.community/programmingfundamentals/chapter/data-type-conversions/
  40. Wikipedia: Variable (computer science)

Lesson 3 - Functions

[edit | edit source]
Flowchart calling subroutines
Flowchart calling subroutines

This lesson introduces functions. A function is a block of organized code that is used to perform a single task. They provide better modularity for your application and reuse-ability. Depending on the programming language, a function may be called a subroutine, a procedure, a routine, a method, or a subprogram. The generic term, callable unit, is sometimes used. Using functions can allow you to be able to keep your code clean and organized, making it easy to read, and allows the debugging process to be easier.[1]


Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:

  • Understand the benefits of modular programming
  • Understand functions, passed parameters, and return values
  • Understand variable scope
  • Use functions to implement program functionality
  • Use local variables, passed parameters, and return values
  • Apply standard coding style to source code

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: Modular programming
  3. Wikipedia: Function (computer science)
  4. Wikipedia: Parameter (computer programming)
  5. Wikipedia: Scope (computer science)
  6. Wikipedia: Naming convention (programming)

Multimedia

[edit | edit source]
  1. YouTube: The advantages of modularization
  2. YouTube: Programming For Beginners - Functions
  3. YouTube: Introduction to Programming - Functions
  4. YouTube: Programming Basics: Statements & Functions: Crash Course Computer Science #12
  5. YouTube: Programming Basics #22 Parameters and Arguments
  6. What is a Function in Programming?
  7. Youtube: All About Functions in Programming

Practice

[edit | edit source]

Examples

[edit | edit source]

Activities

[edit | edit source]

Complete the following activities using a flowchart tool, pseudocode, or your selected programming language. Use separate functions for input, processing, and output. Avoid global variables by passing parameters and returning results.

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

Lesson Summary

[edit | edit source]
  • Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.[5]
  • The hierarchy chart shows the relationship between various models. They are created by the programmer to help document a program.[6]
  • Functions allow you to break down programs into smaller, simpler, programs or "blocks" making it easier for the user to test and work on. Functions also allow the user to keep their programs organized and easy to read.[source?] A function acts as a miniature program, with its own input, processing, and output.[7]
  • The scope is the area of the program where an item that has an identifier name is recognized. It is an important concept for modularization. A Scope can be two types of a Global scope and a Local scope. Global scope occurs when a variable is "defined outside of the function". The local scope, from the other hand, is defined "inside of the function" and exist only until the function completes its task.[8]
  • A good rule of thumb for identifiers in procedural programs is to use verb-noun combinations for function identifiers and use a 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.[9]
  • Programming style is a set of rules or guidelines of writing the code for a computer program. Almost all languages have their own set of guidelines that allow programmers to code efficiently. Following a programming style of a particular language will help programmers to read and understand source code confirming to the style set and help to avoid introducing errors. Code that is written well should have appropriate spacing and proper indentations and be free from grammar and spelling errors.[10][11]

Key Terms

[edit | edit source]
argument
In programming, a value that is passed between programs, subroutines or functions; which are provided as an input to a function. Arguments are independent items, or variables, that contain data or codes. When an argument is used to customize a program for a user, it is typically called a "parameter."[12]
call-by-reference
Arguments are passed to the subroutine by direct reference, typically using the argument's address. Which can be modified by called functions.[13]
call-by-value
Arguments are evaluated and a copy of the value is passed to the subroutine. Which cannot be modified by called functions.[14]
function
A section of a program designed to perform a specific procedure or task.[15]
function header
The header includes the name of the function and tells us (and the compiler) what type of data it expects to receive (the parameters) and the type of data it will return (return value type) to the calling function or program.[16]
identifier name
The name given by the programmer to identify a function or other program items such as variables.[17]
modularization
The ability to group code into a unit, most often being functions, that can be used as independent and self-contained sub-programs within the main program.[18]
parameter
In computer programming, a parameter is a value that is passed into a function.[19]
return statement
Stops the function and returns a variable to the call location.[20]
return value
Return value is a variable or other information coming back from the subroutine.[21]
scope
Variables can only effect areas in which they are defined, their reach by default is local to the function in which they are defined.[22]
subroutine
In computer programming, a subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.[23]
void
A data type that represents a return of no value.[24]

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]

Lesson 4 - Conditions

[edit | edit source]
Flowchart Conditions
Flowchart Conditions

This lesson introduces conditions, including if-then-else, case/switch, and structured exception handling. Conditions are statements that are created by the programmer which evaluates actions in the program and evaluates if it's true or false. If-then-else statement allows conditional execution based on the evaluation of an expression.[1] Case/Switch statement type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.[2] This can be used to create pathways in a program which can allow efficiency and a better system of evaluation.


Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:

  • Understand structured programming concepts
  • Understand sequence, selection/condition, and iteration/loop control structures
  • Understand if-then-else and case/switch statements
  • Understand structured exception handling concepts
  • Use conditional code to implement program functionality

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: Structured programming
  3. Wikipedia: Conditional (computer programming)
  4. Wikipedia: Exception handling

Multimedia

[edit | edit source]
  1. YouTube: The three basic structures—sequence, selection, and loop
  2. YouTube: Programming For Beginners - Relational Operators
  3. YouTube: Introduction to Programming - Control Flow
  4. Youtube: Programming Basics: Statements & Functions
  5. Youtube: Introduction to Conditional Statements

Practice

[edit | edit source]

Examples

[edit | edit source]

Activities

[edit | edit source]

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

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

Lesson Summary

[edit | edit source]
  • Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified Boolean condition evaluates to true or false.[5] The basic attribute of a selection control structure is to select between two or more alternative paths. A question using Boolean logic controls which path is selected.[6]
  • The pseudocode structure of a conditional statement is:[7]
IF (Boolean condition) THEN
    (consequent)
ELSE
    (alternative)
END IF
  • If the condition is true, the statements following the THEN are executed. Otherwise, the execution continues in the following branch – either in the ELSE block (which is usually optional), or if there is no ELSE branch, then after the END IF.[8]
  • By using ELSE IF/ELSEIF, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.[9]
  • Exception handling is the process of responding to the occurrence, during computation, of anomalous or exceptional events requiring special processing, often changing the normal flow of program execution.[10]
  • In programming language mechanisms for exception handling, the term exception is typically used in a specific sense to denote a data structure storing information about an exceptional condition.[11]
  • One mechanism to transfer control, or raise an exception, is known as a throw.[12]
  • The scope for exception handlers starts with a "try" clause.[13]
  • An exception is said to be thrown and execution is transferred to a "catch" or "except" statement.[14][15]
  • Operator symbols and/or names can vary with different programming languages. Most programming languages use relational operators similar to the following:[16]
Operator	Meaning
<	        less than
>	        greater than
<=	        less than or equal to
>=	        greater than or equal to
==	        equality (equal to)
!= or <>	inequality (not equal to)

Please, be careful as in many programming languages the ≠ is not used and the = symbol means assignment.[17]

  • Two-way selection structures may be nested inside other two-way selection structures, resulting in multi-way selection. The concept of nesting allows the mixing of the different categories of control structures.[18]
  • One of the most important concepts of programming is the ability to control a program so that different lines of code are executed or that some lines of code are executed many times. The mechanisms that allow us to control the flow of execution are called control structures.[19]
  • It is possible to establish more than one condition in one IF by using logical operators (AND, OR and NOT), these operations are used to make more open or strict decisions, depending on the programmer's needs.[source?]

Key Terms

[edit | edit source]
Boolean expression
A logical statement that is either "True" or "False". It is used to compare 2 variables as long as they are the same data type.[20]
branching
An instruction in a computer program that can cause a computer to begin executing a different instruction sequence. This causes the program to deviate from its default behavior of executing instructions in order. This behavior is undesirable, and is therefore rarely used in modular structured programming.[21]
code block
In computer programming, a block or code block is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements. Depending on the programming language, a code block can be signified by curly brackets "{}" or indentation.[22]
control structures
The mechanisms used to control the code's flow of execution.[23]
if then else
A two-way selection control structure. Questions with a Boolean true or false answer controls what the structure does. Simply put, the "if" part of the structure will do something if the question's answer is true, while the "else" part of the statement will do something if the question's answer is false.[24]
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.[25]
logical operator
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. Common logical operators include AND, OR, and NOT. Python just uses the words and, or, and not. In many other languages && is used for AND, || is used for OR, and ! is used for not.[source?]
relational operator
An operator that defines or tests a relationship between 2 variables. They consist of: less than, less than or equal to, equal to, not equal to, more than, more than or equal to.[26]
selection
A control structure where the program chooses between two or more options.[27]
sequence
A control structure where the program executes the items in the order listed.[28]
spaghetti code
A pejorative phrase for unstructured and difficult-to-maintain source code. Spaghetti code can be caused by several factors, such as volatile project requirements, lack of programming style rules, and insufficient ability or experience.[29]
structured programming
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) and repetition (while and for), block structures, and subroutines. Thus, preventing Spaghetti code as a result.[30]
truth table
A table used to test Boolean logic. The table compares different combinations of a function's input values. It is also a common way to show logical relationships.[31]
truthy
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, 0n, "", null, undefined, and NaN).[32]

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
  1. Actian: If Then Else Statements
  2. Wikipedia: Switch statement
  3. PythonLearn: Conditional Execution
  4. Wikibooks: Programming Fundamentals/Practice: Conditions
  5. Wikipedia: Conditional (computer programming)
  6. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweig)
  7. Wikipedia: Conditional (computer programming)
  8. Wikipedia: Conditional (computer programming)
  9. Wikipedia: Conditional (computer programming)
  10. Wikipedia: Exception handling
  11. Wikipedia: Exception handling
  12. Wikipedia: Exception handling
  13. Wikipedia: Exception handling
  14. Wikipedia: Exception handling
  15. Python.org Handling Exceptions
  16. https://press.rebus.community/programmingfundamentals/chapter/relational-operators/
  17. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweig)
  18. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweig)
  19. https://press.rebus.community/programmingfundamentals/chapter/structured-programming/
  20. Wikipedia: Boolean expression
  21. Wikipedia: Branch (computer science)
  22. Wikipedia: Block (programming)
  23. https://press.rebus.community/programmingfundamentals/chapter/structured-programming/
  24. https://press.rebus.community/programmingfundamentals/chapter/if-then-else/
  25. https://press.rebus.community/programmingfundamentals/chapter/nested-if-then-else/
  26. Wikipedia: Relational operator
  27. https://press.rebus.community/programmingfundamentals/chapter/structured-programming/
  28. https://press.rebus.community/programmingfundamentals/chapter/structured-programming/
  29. Wikipedia: Spaghetti code
  30. Wikipedia: Structured programming
  31. Wikipedia: Truth table
  32. https://developer.mozilla.org/en-US/docs/Glossary/Truthy

Lesson 5 - Loops

[edit | edit source]
Flowchart Conditions
Flowchart Conditions

This lesson introduces loops, including while, for, and do loops. A loop is a sequence of instructions designed to be repeated until a certain condition is met or achieved. Loops only need to be written once, but may repeat multiple times over. Loops are typically used to do certain tasks multiple times based on the program's task, avoiding having to create extra, unnecessary steps in a program. Here's a brief explanation of each loop.:

  • While loops are used when the program is designed to count the iterations by itself, which can set up the loop in the program based on the user's input.
  • Do loops are designed to continue a section of code until a condition is met, testing to see if the condition is met between iterations. This is similar to while loops because they also make it easier to set up the condition's loop based on the user's input.
  • For loops are designed to have a controlled amount of loops, where the number of times a loop must repeat is already decided, unlike the other two where a condition must be met to exit and continue to the rest of the program.


Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:

  • Understand while and do while loops
  • Understand for and foreach loops
  • Use loops to implement program functionality
  • Understand when to use each type of loop

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: Control flow

Multimedia

[edit | edit source]
  1. YouTube: Programming For Beginners - 'while' loops
  2. YouTube: Programming For Beginners - 'for' loops
  3. Youtube: Intro to Programming: Loops
  4. Youtube: Intro to Programming - Loops
  5. YouTube: Introduction to Programming - Iteration
  6. Youtube: Loops - Coding Basics
  7. YouTube: For Loop - Processing Tutorial
  8. YouTube: While Loop - Processing Tutorial
  9. YouTube: 6.6: Nested Loops - Processing Tutorial
  10. YouTube: Basic for For Loops and Nesting Loops
  11. YouTube: Nested Loops - Processing Tutorial
  12. YouTube : Loops - Four styles - While, For, Do While, Repeat Until
  13. Youtube: Control Structures - while loop - do-while loop - for loop - Goto - break - continue statements

Practice

[edit | edit source]

Examples

[edit | edit source]

Activities

[edit | edit source]

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

While Loops

[edit | edit source]

Complete the following using a while loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
        1 * 1 = 1
        1 * 2 = 2
        1 * 3 = 3
    A list of five expressions for the value 3 would be:
        3 * 1 = 3
        3 * 2 = 6
        3 * 3 = 9
        3 * 4 = 12
        3 * 5 = 15
  2. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores.
  3. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.
  4. Review MathsIsFun: Fibonacci Sequence. Write a program that displays the Fibonacci sequence based on a given number of iterations entered by the user.

Do While / Repeat Until Loops

[edit | edit source]

Complete the following using a do while / repeat until loop structure.

  1. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Use a loop to request each score and add it to a total. Continue accepting scores until the user enters either a negative value or no value (your choice). Finally, calculate and display the average for the entered scores.
  2. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Continue efficiently guessing higher or lower until they indicate equal, then print the number of guesses required to guess their number and end the program.
  3. Add a do while / repeat until loop to any activity from a previous chapter. Continue running the program while the user wants to continue or until the user wants to stop.
  4. Add an input validation loop to any activity from a previous chapter. Verify that the input is valid before returning the value. Ask the user to input the value again while the input is invalid.

For Loops

[edit | edit source]

Complete the following using a for loop structure.

  1. Create a program that uses a loop to generate a list of multiplication expressions for a given value. Ask the user to enter the value and the number of expressions to be displayed. For example, a list of three expressions for the value 1 would be:
        1 * 1 = 1
        1 * 2 = 2
        1 * 3 = 3
    A list of five expressions for the value 3 would be:
        3 * 1 = 3
        3 * 2 = 6
        3 * 3 = 9
        3 * 4 = 12
        3 * 5 = 15
  2. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores.
  3. Review MathsIsFun: Pi. Write a program that uses the Nilakantha series to calculate Pi based on a given number of iterations entered by the user.
  4. Review MathsIsFun: Fibonacci Sequence. Write a program that displays the Fibonacci sequence based on a given number of iterations entered by the user.

Nested Loops

[edit | edit source]

Complete the following using a nested loop structure.

  1. Review MathsIsFun: 10x Printable Multiplication Table. Create a program that uses nested loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Include row and column labels. For example, the output from 1 to 3 might look like:
            1   2   3
        1   1   2   3
        2   2   4   6
        3   3   6   9
    The output from 3 to 5 might look like:
            3   4   5
        3   9  12  15
        4  12  16  20
        5  15  20  25
    Use separate subroutines/functions/methods for input, processing, and output. Avoid global variables by passing parameters and returning results.
  2. Add a do while / repeat until loop to any activity from this chapter. Continue running the program while the user wants to continue or until the user wants to stop.

Lesson Summary

[edit | edit source]
  • Control flow refers to the order in which the individual statements, instructions, or function calls of an imperative or a declarative program are executed or evaluated.[1]
  • Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.[2]
  • A loop is a sequence of statements which is specified once but which may be carried out several times in succession.[3]
  • Do while is a test after control structure. A do while loop will run at least once, and will test the given condition after each execution.[source?]
  • There are two commonly used test before loops in the iteration (or repetition) category of control structures. They are: while and for.[4]
  • While loops are used when the code inside the loop will determine how many iterations are required.[5]
  • For loops are used when it is known before the loop starts how many iterations are required.[6]
  • Within the while control structure there are four attributes to a properly working loop. They are:[7]
    • Initializing the flag
    • Test expression
    • Action or actions
    • Update of the flag
  • Within the do while control structure there are three attributes to a properly working loop. They are:[8]
    • Action or actions
    • Update of the flag
    • Test expression
  • Within the for control structure, there are four attributes to a properly working loop. They are:[9]
    • Initializing the flag - done once
    • Test expression
    • Action or actions
    • Update of the flag
  • Goto is usually not considered to be good programming structure. However, a few programming languages will allow you the ability to create a label with an identifier name followed by a colon.[source?]
  • 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. Otherwise, the program can get into an infinite loop.[10]

Key Terms

[edit | edit source]
break
A branching function that terminates the existing structure.[11]
condition
The statement a loop checks in order to decide if it should loop again or stop looping.[12] It's a set of rules performed if a certain condition is met. It is sometimes referred to as an If-Then statement, because IF a condition is met, THEN an action is performed.[13]
continue
A branching function that causes a loop to stop its current iteration and begin the next one.[14] It works like a break statement but instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.[15]
counting controlled
A loop where a variable (such as a counter) predetermines how many times a loop will run.[16]
do while loop
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.[17]
exit
A predefined function used to prematurely stop a program and return to the operating system.[18] It is used to finish or exit the execution of an enclosing loop statement. If the statement includes a condition, then the exit from the loop is conditional.[19]
flag
commonly used to control or to indicate the intermediate state or outcome of a particular operation[20] It is the value that acts as a signal for a function or process. The value is used to determine the next step of a program.[21]
for loop
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.[22]
foreach loop
For each (or foreach, sometimes called an iterative for-loop) is a control flow statement for traversing items in a collection.[23]
goto
An unstructured branching statement that makes the logic in a program jump around to a different location[24]
infinite loop (or endless loop)
A sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition or having one that can never be met.[25]
iteration control structure
A statement or block is executed until the program reaches a certain state, or operations have been applied to every element of a collection.[26]
nested loop
Places one loop inside of another loop. The inner loop will repeat depending on the number of iterations of the outer loop.[27]
return
A branching statement that causes a function to jump back to the function that called it. Allowing it to be also used as a way to break out of a loop.[28] A return statement returns occasional results from a function or simply finishes a function. There is an implicit return at the end of any function, so you do not need to use one if your function ends naturally, without returning any value.[29]
while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.[30]

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
  1. Wikipedia: Control flow
  2. Wikipedia: Control flow
  3. Wikipedia: Control flow
  4. https://press.rebus.community/programmingfundamentals/chapter/while-loop/
  5. https://press.rebus.community/programmingfundamentals/chapter/while-loop/
  6. https://press.rebus.community/programmingfundamentals/chapter/for-loop/
  7. https://press.rebus.community/programmingfundamentals/chapter/while-loop/
  8. https://press.rebus.community/programmingfundamentals/chapter/do-while-loop/
  9. https://press.rebus.community/programmingfundamentals/chapter/for-loop/
  10. Programing Fundamentals (Kenneth Leroy Busbee and Dave Braunschweigh)
  11. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  12. Wikipedia: Conditional (computer programming)
  13. https://www.computerhope.com/jargon/c/contstat.htm
  14. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  15. https://www.tutorialspoint.com/cprogramming/c_continue_statement.htm
  16. http://www.cs.iit.edu/~cs561/cs115/looping/count.html
  17. https://press.rebus.community/programmingfundamentals/chapter/do-while-loop/
  18. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  19. http://vhdl.renerta.com/mobile/source/vhd00028.htm
  20. https://press.rebus.community/programmingfundamentals/chapter/flag-concept/
  21. https://techterms.com/definition/flag
  22. https://press.rebus.community/programmingfundamentals/chapter/for-loop/
  23. https://en.wikipedia.org/wiki/Foreach_loop
  24. https://press.rebus.community/programmingfundamentals/chapter/branching-statements/
  25. Wikipedia: Infinite loop
  26. https://press.rebus.community/programmingfundamentals/chapter/iteration-control-structures/
  27. https://press.rebus.community/programmingfundamentals/chapter/nested-for-loops/
  28. https://press.rebus.community/programmingfundamentals/chapter/return-statement/
  29. https://www.lua.org/pil/4.4.html
  30. https://press.rebus.community/programmingfundamentals/chapter/while-loop/

Lesson 6 - Arrays

[edit | edit source]
Arrays
Arrays

An array is a data type that represents a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time during program execution. Such a collection is usually called an array variable, array value, or simply array.[1] Some programming languages may refer to arrays as lists. This lesson introduces defined-value arrays, fixed-length arrays, and dynamic arrays.


Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:

  • Understand single and multi-dimensional arrays
  • Understand dynamic arrays
  • Use arrays to implement program functionality

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: Array data type
  3. Wikipedia: Dynamic array

Multimedia

[edit | edit source]
  1. YouTube: Programming For Beginners - Arrays
  2. YouTube: Programming For Beginners - Dictionaries and Hashes
  3. YouTube: Static Arrays vs. Dynamic Arrays
  4. YouTube: An Overview of Arrays and Memory (Data Structures and Algorithms #2)
  5. YouTube: What is an Array? - Processing Tutorial

Practice

[edit | edit source]

Examples

[edit | edit source]

Activities

[edit | edit source]

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

Defined-Value Arrays

[edit | edit source]
  1. Review MathsIsFun: Leap Years. Create a program that displays the number of days in a given month. Start by asking the user to enter a year and month number. Use a defined array to look up the corresponding month name (January, February, etc.). Use another defined array to look up the corresponding number of days in the month (January = 31, February = 28 or 29 depending on year, etc.). Display results similar to the following:[2]
        February 2020 has 29 days
  2. Review Wikipedia: Zeller's congruence. Create a program that asks the user for their birthday (year, month, and day) and then calculate and display the day of the week on which they were born. Use a defined array to look up the numeric day of the week and display the corresponding string representation (Monday, Tuesday, Wednesday, etc.).

Fixed-Length Arrays

[edit | edit source]
  1. Review MathsIsFun: Definition of Average. Create a program that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a static (fixed-size) array. After the scores are entered, calculate and display the high, low, and average for the entered scores.
  2. If your programming language supports it, use a built-in sort function to sort the grade scores from the activity above and display the array in order from highest score to lowest score.
  3. Review Wikipedia: Monty Hall problem. Create a program that uses an array to simulate the three doors. Use 0 (zero) to indicate goats and 1 (one) to indicate the car. Clear each "door" and then use a random number function to put the number 1 in one of the array elements. Then use the random number function to randomly select one of the three elements. Run the simulation in a loop 100 times to confirm a 1/3 chance of winning. Then run the simulation again, this time switching the selection after a 0 (goat) is removed from the remaining choices. Run the simulation in a loop 100 times to confirm a 2/3 chance of winning by switching.

Dynamic Arrays / Lists

[edit | edit source]
  1. If your programming language supports it, update the grade score program above to replace the static array with a dynamic array, and extend the array as each item is added to the array. Continue accepting scores until the user enters a negative value.
  2. If your programming language supports it, use a built-in sort function to sort the grade scores from the activity above and display the array in order from highest score to lowest score.
  3. Review Khan Academy: A guessing game. Write a program that allows the user to think of a number between 0 and 100, inclusive. Then have the program try to guess their number. Start at the midpoint (50) and ask the user if their number is (h)igher, (l)ower, or (e)qual to the guess. If they indicate lower, guess the new midpoint (25). If they indicate higher, guess the new midpoint (75). Record each guess in an array and continue efficiently guessing higher or lower until they indicate equal. Finally, display the array/list of guesses made while attempting to guess their number and end the program.

Lesson Summary

[edit | edit source]
  • Depending on the language, array types may overlap (or be identified with) other data types that describe aggregates of values, such as lists and strings. Array types are often implemented by array data structures, but sometimes by other means, such as hash tables, linked lists, or search trees.[3] In Python, the built-in array data structure is a list.[4]
  • Each element in an array will be assigned an index position. Most programming languages will begin at index position 0. This allows the program to recall data stored in a specific position. for instance, an array named "months" would have the data value "March" stored at index position 2. A program can reference this value by referring to "months[2]".[5]
  • Arrays can have multiple axes (more than one axis). Each axis is a dimension. Thus a single-dimension array is also known as a list. A two-dimension array is commonly known as a table.[6]
  • Arrays are an important complex data type used in almost all programming. We continue to concentrate on simple one dimension arrays also called a list. Most programmers develop a series of user-defined specific task functions that can be used with an array for normal processing. These functions are usually passed the array along with the number of elements within the array. Some functions also pass another piece of data needed for that particular functions task.[7]
  • Finding a specific member of an array means searching the array until the member is found. It’s possible that the member does not exist and the programmer must handle that possibility within the logic of his or her algorithm.[8]
  • It is important to follow the "Don't Repeat Yourself" (DRY) principle. Rather than having to keep repeating yourself, you can use loops to visit each element of an array and the loop control variable as an array index. This allows for more efficient code and smaller programs.[9]

Key Terms

[edit | edit source]
array
Data structure consisting of a collection of elements (variables or values), each identified by at least one index or key.[10] It can also be defined as an ordered collection of items indexed by contiguous inters.[11]
array member
An item or value in an array.[12]
dimension
An axis of an array. Defines the amount of associated pieces of data that can be stored.[13]
don’t repeat yourself
A principle of software development aimed at reducing repetition of software patterns, replacing it with abstractions, or repetition of the same data, using data normalization to avoid redundancy.[14]
dynamic array
A random access, variable-size list data structure that allows elements to be added or removed. The size can be changed when new items are added.[15]
flexible coding
Using the size of an array to determine the number of loop iterations required.[16]
index notation
Used to specify the elements of an array. Most current programming languages use square brackets [] as the array index operator.[17] There are different methods for referring to the elements of a list, a vector, or a matrix, depending on whether one is writing a formal mathematical paper for publication, or when one is writing a computer program. [18]
linear search
Sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.[19]
list
Lists are a form of compiled data, in which there are two types, linear lists which are similar to static arrays, and linked lists, which are similar to dynamic arrays. They can compile multiple different data types.[20]
offset
The method of referencing array members by starting at zero.[21]
parallel array
A form of implicit data structure that uses multiple arrays to represent a singular array of records.[22] Also known as structure an array (SoA), multiple arrays of the same size such that i-th element of each array is closely related and all i-th elements together represent an object or entity.[23]
sort
Arranging data according to their values.[24]
static array
An array with its length not changing. Items can be replaced or changed but no more can be added or subtracted.[25]
table
A two dimensional array.[26] A data structure used to organize information, just as it is on paper. There are many different types of computer-related tables, which work in a number of different ways. The following are examples of the more common types.[27]

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
  1. Wikipedia: Array data type
  2. Farrell, J. (2015). Programming Logic and Design, Introductory, 8th Edition. Cengage. ISBN 9781285845777
  3. "Array data type". Wikipedia. 2019-01-30. https://en.wikipedia.org/w/index.php?title=Array_data_type&oldid=881001423. 
  4. https://press.rebus.community/programmingfundamentals/chapter/arrays-and-lists/#footnote-262-2
  5. "Arrays and Lists – Index Notation". press.rebus.community. Retrieved 2019-10-25.
  6. "Arrays and Lists – Programming Fundamentals". press.rebus.community. Retrieved 2019-04-03.
  7. "Math Statistics with Arrays – Programming Fundamentals". press.rebus.community. Retrieved 2019-04-03.
  8. "Searching Arrays – Programming Fundamentals". press.rebus.community. Retrieved 2019-04-03.
  9. https://press.rebus.community/programmingfundamentals/chapter/displaying-array-members/
  10. https://press.rebus.community/programmingfundamentals/chapter/arrays-and-lists/
  11. https://www.toolsqa.com/data-structures/array-in-programming/
  12. https://press.rebus.community/programmingfundamentals/chapter/index-notation/
  13. https://press.rebus.community/programmingfundamentals/chapter/arrays-and-lists/
  14. https://press.rebus.community/programmingfundamentals/chapter/displaying-array-members/
  15. https://press.rebus.community/programmingfundamentals/chapter/dynamic-arrays/
  16. https://press.rebus.community/programmingfundamentals/chapter/displaying-array-members/
  17. https://press.rebus.community/programmingfundamentals/chapter/index-notation/
  18. https://en.wikipedia.org/wiki/Index_notation
  19. https://press.rebus.community/programmingfundamentals/chapter/searching-arrays/
  20. "Programming Concepts: Lists - Wikibooks, open books for an open world". en.m.wikibooks.org. Retrieved 2019-11-01.
  21. https://press.rebus.community/programmingfundamentals/chapter/index-notation/
  22. https://press.rebus.community/programmingfundamentals/chapter/parallel-arrays/
  23. https://www.geeksforgeeks.org/parallel-array/
  24. https://press.rebus.community/programmingfundamentals/chapter/sorting-arrays/
  25. Wikipedia: Array data structure
  26. https://press.rebus.community/programmingfundamentals/chapter/arrays-and-lists/
  27. https://whatis.techtarget.com/definition/table

Lesson 7 - Strings

[edit | edit source]
Strings
Strings

This lesson introduces strings and string processing. A string is a data type used to represent integers instead of numbers in programming. This data type can contain spaces and numbers as well. You can edit string data types by something called string processing. This is when you edit the data in the string by adding, moving, or replacing characters using specific string functions.


Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:

  • Manipulate string data

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: String (computer science)

Multimedia

[edit | edit source]
  1. YouTube: Programming Basics #28 String Concatenation
  2. YouTube: What Are Strings In Programming?
  3. YouTube: Computer programming tutorial: How to use strings
  4. Youtube: Strings - Intro to Computer Science
  5. YouTube: Programming/Scripting Concepts Explained (Variables, Arrays, Strings, & Length)

Examples

[edit | edit source]

Activities

[edit | edit source]

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

  1. Create a program that asks the user for a single line of text containing a first name and last name, such as Firstname Lastname. Use string functions/methods to parse the line and print out the name in the form last name, first initial, such as Lastname, F. Include a trailing period after the first initial. Handle invalid input errors, such as extra spaces or missing name parts.
  2. Create a program that asks the user for a line of text. Use string functions/methods to delete leading, trailing, and duplicate spaces, and then print the line of text backwards. For example:
          the   cat   in   the   hat  
        tah eht ni tac eht
    Use separate subroutines/functions/methods to implement input, each type of processing, and output. Avoid global variables by passing parameters and returning results.
  3. Create a program that asks the user for a line of comma-separated-values. It could be a sequence of test scores, names, or any other values. Use string functions/methods to parse the line and print out each item on a separate line. Remove commas and any leading or trailing spaces from each item when printed.
  4. Create a program that asks the user for a line of text. Then ask the user for the number of characters to print in each line, the number of lines to be printed, and a scroll direction, right or left. Using the given line of text, duplicate the text as needed to fill the given number of characters per line. Then print the requested number of lines, shifting the entire line's content by one character, left or right, each time the line is printed. The first or last character will be shifted / appended to the other end of the string. For example, if shifting the line to the left:
        Repeat this. Repeat this. 
        epeat this. Repeat this. R
        peat this. Repeat this. Re
    Or if shifting the line to the right:
        Repeat this. Repeat this. 
         Repeat this. Repeat this.
        . Repeat this. Repeat this

Lesson Summary

[edit | edit source]
  • Most current programming languages include built-in or library functions to process strings. Common examples include case conversion, comparison, concatenation, find, join, length, reverse, split, substring, and trim.[1]
  • Most current programming languages implement strings as a data type or class where strings are stored as a length controlled array. String length and storage are handled by the compiler or interpreter, reducing program errors.[2]

String Functions

[edit | edit source]
Function C++ C# Java
case tolower(), toupper(), etc. ToLower(), ToUpper(), etc. toLowerCase(), toUpperCase(), etc.
comparison <, >, ==, etc. <, >, ==, etc. <, >, ==, etc.
concatenation +, += +, += +, +=
find find() IndexOf() indexOf()
join N/A Join() join()
length length() Length length()
replace replace() Replace() replace()
reverse reverse() Reverse() N/A
split strtok() Split() split()
substring substr() Substring() substring()
trim N/A Trim() trim()

[3]

Function JavaScript Python Swift
case toLowerCase(), toUpperCase(), etc. lower(), upper(), etc. lowercased(), uppercased()
comparison <, >, ==, etc. <, >, ==, etc. <, >, ==, etc.
concatenation +, += +, += +, +=
find indexOf() find() firstIndex()
join join() join() joined()
length length len() count
replace replace() replace() replacingOccurrences()
reverse N/A string[::-1] reversed()
split split() split() split()
substring substring() string[start:end] string[start...end]
trim trim() strip()

[4]

Terms

[edit | edit source]
buffer overflow
An anomaly where a program overruns a memory storage location and overwrites adjacent memory locations.[5]
code injection
The exploitation of a computer bug that is caused by processing invalid data.[6]
concatenation
The process in which you add two strings together in order to create a longer string[7]
dynamic memory
Stack created memory associated with local scope. You now control the exact size and the lifetime of these memory locations.[8]
join
Takes elements of an array/list, joins them together, and makes them into a string. Can also use a separator between each element.[9]
split
Splits a string into a list.[10]
static memory
Memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.[11]
string
In most programming languages a string is a sequence of characters, either as a literal constant or as some kind of variable.[12]
string formatting
uses a process of string interpolation (variable substitution) to evaluate a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.[13]
string interpolation
Evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.[14]
title
A string method which is used to convert the first character in each word to uppercase and the remaining characters to lowercase and returns new string.

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]

Lesson 8 - Files

[edit | edit source]

This lesson introduces files and file processing. A File is an object on a computer that stores data, information, settings, or commands used with a computer program.[1]. File processing consists of creating, storing, or retrieving the contents of a file from a recognizable medium.[2].


Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:

  • Understand file input and output
  • Validate file open, edit, and close operations
  • Use error handling with file operations tasks

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: File system
  3. Wikipedia: Directory (computing)
  4. Wikipedia: Directory structure
  5. Wikipedia: Text file
  6. Wikipedia: Binary file

Multimedia

[edit | edit source]
  1. YouTube: File Handling and Applications
  2. YouTube: Introduction To File Processing System

Examples

[edit | edit source]

Activities

[edit | edit source]

Complete the following activities using pseudocode, a flowcharting tool, or your selected programming language. Use separate functions for input, each type of processing, and output. Avoid global variables by passing parameters and returning results. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used. Note: Each of the following activities uses code only to read the file. It is not necessary to use code to create the file.

  1. Using a text editor or IDE, copy the following list of names and grade scores and save it as a text file named scores.txt:
        Name,Score
        Joe Besser,70
        Curly Joe DeRita,0
        Larry Fine,80
        Curly Howard,65
        Moe Howard,100
        Shemp Howard,85
    Create a program that displays high, low, and average scores based on input from scores.txt. Verify that the file exists and then use string functions/methods to parse the file content and add each score to an array. Display the array contents and then calculate and display the high, low, and average score. Format the average to two decimal places. Note that the program must work for any given number of scores in the file. Do not assume there will always be six scores.
  2. Create a program that displays high, low, and average scores based on input from scores.txt. Verify that the file exists and then use string functions/methods to parse the file content and add each score to an array. Display the array contents and then calculate and display the high, low, and average score. Format the average to two decimal places. Include error handling in case the file is formatted incorrectly. Note that the program must work for any given number of scores in the file. Do not assume there will always be six scores.
  3. Create a program that asks the user for the name of a text/HTML file that contains HTML tags, such as:
        <h1>Strings and Files</h1>
        <p><strong>This is a bold paragraph.</strong></p>
    Verify that the file exists and then use string methods to search for and remove all HTML tags from the text, saving each removed tag in an array. Display the untagged text and then display the array of removed tags. For example:
        Strings and Files
        This is a bold paragraph.

        <h1>
        </h1>
        <p>
        <strong>
        </strong>
        </p>
  4. Using a text editor or IDE, create a text file of names and addresses to use for testing based on the following format:
        Firstname Lastname
        123 Any Street
        City, State/Province/Region PostalCode
    Include a blank line between addresses, and include at least three addresses in the file. Create a program that verifies that the file exists, and then processes the file and displays each address as a single line of comma-separated values in the form:
        Lastname, Firstname, Address, City, State/Province/Region, PostalCode

Lesson Summary

[edit | edit source]
  • In computer programming, standard streams are pre-connected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin – keyboard), standard output (stdout – originally a printer) and standard error (stderr – monitor). Streams may be redirected to other devices and/or files. In current environments, stdout is usually redirected to the monitor.[3]
  • It is considered good programming practice to determine if the file was opened properly. The reason the operating system usually can’t open a file is because the filespec is wrong (misspelled or not typed case consistent in some operating systems) or the file is not stored in the location specified. Accessing files stored on a network or the Internet may fail due to a network error.[4]
  • Loading an array from a text file requires several steps, including: opening the file, reading the records, parsing (splitting) the records into fields, adding the fields to an array, and closing the file. The file may be read all at once and then parsed, or processed line by line. The array must either be at least as large as the number of records in the file, or must be generated dynamically.[5]

Key Terms

[edit | edit source]
append
Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.[6]
close
Your program requesting the operating system to release a file that was previously opened.[7]
create
Opens a file for exclusive creation. If the file already exists, the operation fails.[8]
device token
A key value provided by the operating system to associate a device to your program.[9]
filename
The name and its extension.[10]
filespec
The location of a file along with its filename.[11]
open
Your program requesting the operating system to let it have access to an existing file or to open a new file.[12]
read
Moving data from a device that has been opened into a memory location defined in your program.[13]
stream
A sequence of data elements made available over time.[14]
stdin
Standard input stream, typically the keyboard. [15]
stderr
Standard output error stream, typically the monitor.[16]
stdout
Standard output stream, originally a printer, but now typically the monitor.[17]
text file
A file consisting of characters from the ASCII character code set.[18]
using / with
A wrapper around a processing block that will automatically close opened resources.[19]
write
Moving data from a memory location defined in your program to a device that has been opened.[20]

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
  1. "File". Computer Hope. 2018-08-03. https://www.computerhope.com/jargon/f/file.htm. 
  2. "Introduction to File Processing". Yevol. 2007. http://www.yevol.com/en/vccli/Lesson10.htm. 
  3. "Standard streams". Wikipedia. 2019-03-05. https://en.wikipedia.org/w/index.php?title=Standard_streams&oldid=886304371. 
  4. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  5. Braunschweig, Dave; Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/loading-an-array-from-a-text-file/. 
  6. https://www.w3schools.com/python/python_file_handling.asp
  7. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  8. https://www.w3schools.com/python/python_file_handling.asp
  9. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  10. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  11. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  12. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  13. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  14. "Stream (computing)". Wikipedia. 2019-10-01. https://en.wikipedia.org/w/index.php?title=Stream_(computing)&oldid=918985904. 
  15. "Standard streams". Wikipedia. 2019-10-11. https://en.wikipedia.org/w/index.php?title=Standard_streams&oldid=920720336. 
  16. "Standard streams". Wikipedia. 2019-10-11. https://en.wikipedia.org/w/index.php?title=Standard_streams&oldid=920720336. 
  17. "Standard streams". Wikipedia. 2019-10-11. https://en.wikipedia.org/w/index.php?title=Standard_streams&oldid=920720336. 
  18. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  19. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 
  20. Busbee, Kenneth Leroy. Programming Fundamentals (in en). https://press.rebus.community/programmingfundamentals/chapter/file-input-and-output/. 

Lesson 9 - Objects

[edit | edit source]

This lesson introduces objects and object-oriented programming.


Objectives and Skills

[edit | edit source]

Objectives and skills for this lesson include:

Readings

[edit | edit source]
  1. Pressbooks: Programming Fundamentals
  2. Wikipedia: Object-oriented programming

Multimedia

[edit | edit source]
  1. YouTube: Object-oriented Programming in 7 minutes
  2. YouTube: Programming For Beginners - Object Orientation
  3. YouTube: Principles of OOP

Examples

[edit | edit source]

Activities

[edit | edit source]
  1. Review MathsIsFun: Area of Plane Shapes. Create a program that asks the user what shape they would like to calculate the area for. Use if/else conditional statements to determine their selection and then gather the appropriate input and calculate and display the area of the shape. Perform all area calculations using a ShapeArea class that has separate methods to calculate and return the area for different shapes. Include data validation in the class and error handling in the main program.
  2. Create a program that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use if/else conditional statements to display their approximate age in the selected timeframe. Perform all calculations using an AgeConverter class that accepts the age in years during initialization and has separate properties and methods to calculate and return the age in months, days, hours, and seconds. Include data validation in the class and error handling in the main program.
  3. Review Wikipedia: Zeller's congruence. Create a program that asks the user for their birthday (year, month, and day) and then calculate and display the day of the week on which they were born. Use if/else conditional statements to convert the numeric day of the week to the correct string representation (Monday, Tuesday, Wednesday, etc.). Perform all calculations using a DayOfWeek class that accepts the year, month, and day during initialization and has separate properties and methods to calculate and return the day of week as a number, as an abbreviated string (Mon, Tue, etc.), and as a full string (Monday, Tuesday, etc.). Include data validation in the class and error handling in the main program.

Lesson Summary

[edit | edit source]
  • Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.[1]
  • A feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated.[2]
  • Most object-oriented programming languages are class-based, meaning that objects are instances of classes, which typically also determine their type.[3]
  • Classes define the data format and available procedures for a given type of object.[4]
  • Classes may contain data members and member functions (known as class methods) themselves.[5]
  • Objects are instances of classes.[6]
  • Each object is said to be an instance of a particular class.[7]
  • Procedures in object-oriented programming are known as methods; variables are also known as fields, members, attributes, or properties.[8]
  • Class variables belong to the class as a whole; there is only one copy of each one..[9]
  • Instance variables or attributes belong to individual objects; every object has its own copy of each one.[10]
  • Member variables refer to both the class and instance variables that are defined by a particular class.[11]
  • Class methods belong to the class as a whole and have access only to class variables and inputs from the procedure call.[12]
  • Instance methods belong to individual objects, and have access to instance variables for the specific object they are called on, inputs, and class variables.[13]
  • Objects provide a layer of abstraction which can be used to separate internal from external code.[14]
  • Objects are created by calling a special type of method in the class known as a constructor.[15]
  • Encapsulation is an object-oriented programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation supports data or information hiding.[16]
  • Some languages let classes enforce access restrictions explicitly, for example denoting internal data with the private keyword and designating methods intended for use by code outside the class with the public keyword.[17]

Key Terms

[edit | edit source]
abstraction
A technique for arranging complexity of computer systems so that functionality may be separated from specific implementation details.[18][19]
accessor
A method used to return the value of a private member variable, also known as a getter method.[20]
attribute
A specification that defines a property of an object.[21]
class
An extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).[22]
encapsulation
A language mechanism for restricting direct access to some of an object's components.[23]
field
Also known as data member or member variable, is data encapsulated within a class or object.[24]
information hiding
The principle of segregation of the design decisions in a computer program from other parts of the program. See encapsulation.[25]
inheritance
An object or class being based on another object or class, using the same implementation or specifying a new implementation to maintain the same behavior.[26]
instance
A concrete occurrence of an object.[27]
method
A specification that defines a procedure or behavior of an object.[28]
mutator
A method used to control changes to a private member variable, also known as a setter method.[29]
object
A particular instance of a class where the object can be a combination of variables, functions, and data structures.[30]
polymorphism
The provision of a single interface to entities of different types.[31]
private
An access modifier that restricts visibility of a property or method to the class in which it is defined.[32]
property
A class member, intermediate in functionality between a field (or data member) and a method, which supports reading and writing like a field using 'getter' and 'setter' method calls.[33]
public
An access modifier that opens visibility of a property or method to all other classes.[34]
state
Recorded information supporting preceding events or user interactions.[35]
static
Properties or methods of a class that apply to all instances of the class rather than to any specific instance.[36]
this, self, or Me
Keywords used in some computer programming languages to refer to the object, class, or other entity that the currently running code is part of.[37]

Assessments

[edit | edit source]

See Also

[edit | edit source]

References

[edit | edit source]
  1. Wikipedia: Object-oriented programming
  2. Wikipedia: Object-oriented programming
  3. Wikipedia: Object-oriented programming
  4. Wikipedia: Object-oriented programming
  5. Wikipedia: Object-oriented programming
  6. Wikipedia: Object-oriented programming
  7. Wikipedia: Object-oriented programming
  8. Wikipedia: Object-oriented programming
  9. Wikipedia: Object-oriented programming
  10. Wikipedia: Object-oriented programming
  11. Wikipedia: Object-oriented programming
  12. Wikipedia: Object-oriented programming
  13. Wikipedia: Object-oriented programming
  14. Wikipedia: Object-oriented programming
  15. Wikipedia: Object-oriented programming
  16. Wikipedia: Object-oriented programming
  17. Wikipedia: Object-oriented programming
  18. Wikipedia: Object-oriented programming
  19. Wikipedia: Abstraction (software engineering)
  20. Wikipedia: Mutator method
  21. Wikipedia: Attribute (computing)
  22. Wikipedia: Class (computer programming)
  23. Wikipedia: Encapsulation (computer programming)
  24. Wikipedia: Field (computer science)
  25. Wikipedia: Information hiding
  26. Wikipedia: Inheritance (object-oriented programming)
  27. Wikipedia: Instance (computer science)
  28. Wikipedia: Method (computer programming)
  29. Wikipedia: Mutator method
  30. Wikipedia: Object (computer science)
  31. Wikipedia: Polymorphism (computer science)
  32. Wikipedia: Access modifiers
  33. Wikipedia: Property (programming)
  34. Wikipedia: Access modifiers
  35. Wikipedia: State (computer science)
  36. Wikipedia: Method (computer programming)
  37. Wikipedia: this (computer programming)