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., 44, AA, %\%, mm).

    • Field (Data Item): A group of characters (e.g., a person's name like "John" or a number like 120120).

    • 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 bookPages or underscores), must start with a letter, and contain no special characters (e.g., &,#,@\&, \#, @).

    • Numeric Types:

      • Integers: Whole numbers (positive, negative, or zero; e.g., 15,−233415, -2334).

      • Real Numbers: Numbers with decimal parts (e.g., 12.47,17.0012.47, 17.00).

    • Non-numeric Types:

      • Character: Single character in quotes (e.g., "A\text{A}").

      • String: Two or more characters in quotes (e.g., "32 Long Street\text{32 Long Street}").

      • Boolean: A logical value, either True (non-zero\text{non-zero}) or False (00).

  • Constants: Fixed values that never change during program execution (e.g., π=3.14159π = 3.14159 or hours in a day = 2424).

  • Arithmetic Operators and Precedence:

    1. Exponentiation: ^ (e.g., 24=162 ^ 4 = 16)

    2. Negation: −- (e.g., −6-6)

    3. Multiplication and Division: ∗* and // (e.g., 5×7=355 \times 7 = 35)

    4. Integer Division: \\ (e.g., 375=737 \\ 5 = 7—decimal part is discarded)

    5. Modulus Arithmetic: modmod (e.g., 37 mod 5=237 \, mod \, 5 = 2—returns the remainder)

    6. Addition and Subtraction: ++ and −- (e.g., 4+7=114 + 7 = 11)

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

    1. Analyse the problem: Understand available data (input) and expected results (output).

    2. Identify alternative ways: Look at the problem from different angles.

    3. Select the most effective way: Choose the logic that requires the fewest steps.

    4. List all steps: Present steps unambiguously (using pseudocode, which is structured English rather than code syntax).

    5. Evaluate for accuracy: Perform "desk checking" by manually working through the algorithm with test values.

  • Six Basic Computer Operations:

    1. Receive Data: Read (from file) or Enter (keyboard).

    2. Produce Info: Write (to file) or Display (screen).

    3. Perform Arithmetic: Use math symbols or keywords (Add, Calculate, Compute).

    4. Assign Value: Initialise (total=0total = 0) or Save (x=5+yx = 5 + y).

    5. Compare: if condition then ... else ... endif.

    6. Repeat: while or for loops.

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 (∼\sim).

  • Trace Tables: A method of logic testing. Each row tracks the value of variables after an instruction is executed.

  • Example Comparison:

    • Equation: perim=2×(length+width)perim = 2 \times (length + width)

    • Logic Sequence: display "Enter length" →→ enter length →→ display "Enter width" →→ enter width →→ calculate →→ display result.

Selection Control Structures: Part 1

  • Relational Expressions: Yield Boolean results (True\text{True} or False\text{False}). 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 else block executes.

    • Compound If: Uses AND or OR to 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 variable …… case value1 …… case else …… endselect.

    • Example: case 1 to 10 for ranges or case "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., sum=sum+numbersum = sum + number).

    • Counter: An accumulator that adds a constant (usually 11).

  • 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 −1-1 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 00. Last element is (n−1)(n - 1).

    • 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 stNums and an array of stNames).

  • 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 return statement; instead, it can modify multiple variables via ref parameters.

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 (eof\text{eof}) 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).