Comprehensive Study Guide for Basic Programming Principles 2nd Edition
General Concepts and Arithmetic
Introduction to Programming: A computer is essentially a "dumb machine" that executes only what it is instructed to do. A programmer must first derive the logical steps to solve a problem and then use a compiler to translate those steps into a computer-programming language.
Data Hierarchy: Refers to the systematic organization of data from the smallest unit to the largest:
Character: A single number, letter, or special character (e.g., , , , ).
Field (Data Item): A group of characters (e.g., a person's name like "John" or a number like ).
Record: A group of related fields, such as a student's record containing student number, name, and course.
File: A collection of related records, such as an employee file for monthly salary processing.
Table: A structure of rows and columns where each row represents one entity (e.g., an employee) and each column a category of data.
Database: A collection of related files or tables.
Data Warehouse: The largest structure used for collection, processing, and reporting, potentially consisting of several databases.
Variables: Positions in memory where values can be stored. Initially, they may be empty. A variable is analogous to a box that contains exactly one value at any given time.
Naming Rules: Must be unique, descriptive, contain no spaces (use camel casing like
bookPagesor underscores), must start with a letter, and contain no special characters (e.g., ).Numeric Types:
Integers: Whole numbers (positive, negative, or zero; e.g., ).
Real Numbers: Numbers with decimal parts (e.g., ).
Non-numeric Types:
Character: Single character in quotes (e.g., "").
String: Two or more characters in quotes (e.g., "").
Boolean: A logical value, either True () or False ().
Constants: Fixed values that never change during program execution (e.g., or hours in a day = ).
Arithmetic Operators and Precedence:
Exponentiation:
^(e.g., )Negation:
(e.g., )Multiplication and Division:
and(e.g., )Integer Division:
(e.g., —decimal part is discarded)Modulus Arithmetic:
(e.g., —returns the remainder)Addition and Subtraction:
and(e.g., )
Operator Execution: Parentheses change the order of execution. Otherwise, operators with the same precedence are executed from left to right.
Understanding a Problem and Using a Computer to Solve It
Problem-Solving Process: Programmers must analyze a statement multiple times, deleting redundant information to reach the "crux." For example, to calculate area, the color of the room or its floor level is irrelevant; only length and width matter.
Data Processing Phases:
Input: Data received to solve a problem.
Processing: The steps taken to transform data.
Output: Meaningful information produced (processed data).
The Problem-Solving Approach:
Analyse the problem: Understand available data (input) and expected results (output).
Identify alternative ways: Look at the problem from different angles.
Select the most effective way: Choose the logic that requires the fewest steps.
List all steps: Present steps unambiguously (using pseudocode, which is structured English rather than code syntax).
Evaluate for accuracy: Perform "desk checking" by manually working through the algorithm with test values.
Six Basic Computer Operations:
Receive Data: Read (from file) or Enter (keyboard).
Produce Info: Write (to file) or Display (screen).
Perform Arithmetic: Use math symbols or keywords (Add, Calculate, Compute).
Assign Value: Initialise () or Save ().
Compare:
if condition then ... else ... endif.Repeat:
whileorforloops.
Write Algorithms in Sequential Steps
Sequential Control Structure: Steps are executed once in order. Errors here are usually logical (wrong position or missing step).
IPO Charting: A tool for planning where columns represent Input, Processing, and Output. Input and Output columns contain only variable names.
Algorithm Properties:
Every algorithm starts with a descriptive name starting with an uppercase letter.
The final statement is always
end.Comments are indicated with a tilde ().
Trace Tables: A method of logic testing. Each row tracks the value of variables after an instruction is executed.
Example Comparison:
Equation:
Logic Sequence:
display "Enter length"enter lengthdisplay "Enter width"enter widthcalculatedisplay result.
Selection Control Structures: Part 1
Relational Expressions: Yield Boolean results ( or ). Operators include
, , , ,, and(not equal to).Logical Operations:
NOT: Yields the opposite value.
AND: True only if both expressions are True.
OR: True if at least one expression is True.
Selection Types:
Simple If Statement: Checks a condition; if True, executes the body.
if mark >= 50 then display "Pass" endif.If-then-else: Provides two paths. If the condition is False, the
elseblock executes.Compound If: Uses
ANDorORto check multiple conditions. It is advisable to use parentheses to clarify order (e.g.,if (gender = "M" OR age > 20) AND member then).
Data Validation: The practice of "defensive coding" to identify user errors before processing (e.g.,
if hours is numeric AND tariff is numeric then ...).
Selection Control Structures: Part 2
Nested If Statements: An If statement contained within another. This is used for complex decisions (e.g., checking gender, then age, to determine competition points).
Select Case Structure: Used when a single variable is tested for many different values. It is cleaner than multiple nested Ifs.
Syntax:
select case variablecase value1case elseendselect.Example:
case 1 to 10for ranges orcase "Sally", "Tania"for lists.
Iteration: Fixed Count Loops
The For-next Loop: Used when the number of repetitions is known (Automatic Count Loop).
Syntax:
for variable = begin-value to end-value [step variable2]…next variable.Direction: A negative step (e.g.,
step -1) requires the begin-value to be greater than the end-value.
Accumulators and Counters:
Accumulator: Used to sum values (e.g.,
).Counter: An accumulator that adds a constant (usually ).
Nested For Loops: A loop within a loop. The inner loop completes all iterations for every single iteration of the outer loop.
Iteration: The Do Loop
Nature: Used when the exact number of repetitions is unknown.
Types:
Pre-test Loop (Do-while): Tests condition before entry. May run zero times.
Post-test Loop (Do-loop-until): Tests condition after first execution. Always runs at least once.
Terminating Loops:
Condition Variable: Must be modified within the loop body to avoid an "endless loop."
Sentinel: A flag value (not valid data, like for sales) used to signal the end of input.
Arrays
Properties: A numbered collection of related variables of the same data type.
Index (Subscript): Position of an element. Usually starts at . Last element is .
Reference:
arrayName(index).
One-Dimensional Arrays: Visualized as a single column. Useful for storing data for multiple interactions (e.g., finding the best test mark after all marks are entered).
Two-Dimensional Arrays: Consists of rows and columns, referenced as
arrayName(row, column).Parallel Arrays: Separate arrays linked by a common index (e.g., an array of
stNumsand an array ofstNames).Sorting Methods:
Bubble Sort: Comprising pairs that trade places until in order. The largest values "bubble" to the end.
Selection Sort: Finds the smallest value in the remaining list and swaps it with the current front position.
Function Procedures and Subprocedures
Modularisation: Breaking complex programs into smaller modules to improve flexibility and reduce development time.
Hierarchy Charts: Diagrams showing the global view of modules and their relationships.
Parameters: Data passed between modules.
Value Parameter (
val): Passes a copy. Changes inside the procedure do not affect the original variable.Reference Parameter (
ref): Passes the actual memory address. Changes inside the procedure do modify the original variable.
Function Procedure: Performs a task and returns exactly one value to the calling statement.
Subprocedure: Performs a task but does not return a value via a
returnstatement; instead, it can modify multiple variables viarefparameters.
Sequential Text Files
Concepts: Files are permanent data storage on disks/CDs.
Input File: Data read by the program.
Output File: Program writes new data to it (
outputCreate) or adds to it (outputAppend).File Operations:
Open: Connects physical file to a program name.
Read/Write: Processes one line at a time until the End-of-File () character.
Close: Essential to prevent data loss.
Editing: Sequential files cannot be updated mid-stream. The technique is: Read file into an array Update array Re-create file from array.
Object-Oriented Programming (OOP)
Paradigm shift: Focusing on data and its properties/responsibilities rather than just procedures.
Core Components:
Object: A container for data (properties) and methods (operations).
Class: A template or pattern for creating objects.
Instantiation: The action of creating an object from a class.
Principles:
Encapsulation/Information Hiding: Making internal workings invisible. Data is kept private; only the "interface" (public methods) is accessible.
Inheritance: Subclasses inherit properties from a super class ("Kind-of" relationship).
Aggregation: A "Part-of" relationship where one class is a component of another.
Association: A dependency relationship where one class uses another.
Appendices and Debugging
Error Types:
Syntax Errors: Violations of the grammar/rules of the programming language.
Logical Errors: Faulty reasoning (e.g., adding numbers before they are entered). The program runs but yields wrong results.
Data Errors: Incorrect input data (e.g., entering a letter when a number was expected).
Nassi-Shneiderman (NSD): Also called structograms; a way to visualize program structures without the flow lines used in flowcharts.
Flowchart Symbols: Oval (Terminal/Start/Stop), Parallelogram (Input/Output), Rectangle (Process), Diamond (Decision).