Elementary Programming Principles Complete Study Notes

Definition of Key Terms in Computer Programming

  • Computer Program:     * An organized set of instructions that, when executed, causes the computer to carry out a defined task or behave in a predetermined manner.     * A set of coded instructions given to the computer representing a logical solution to a problem.     * A set of instructions directing a computer on how to process a particular task.     * Written by hardware manufacturers, software houses, or programmers to solve user problems and direct operations on supplied data.
  • Programming:     * The process of designing a set of computer instructions used to perform a specific task or solve a specific problem.     * The process of writing, creating, or developing logical and systematic computer programs.     * Involves using special characters, signs, and symbols from a particular programming language.     * Requires specifying detailed logical steps and data processing methods.
  • Functions of a Computer Program:     1. Accepts data from outside the computer as Input.     2. Carries out a set of Processes on the data within the computer memory.     3. Stores the data for future use.     4. Presents processing results as Output.
  • Programming Language:     * A set of instructions used by a programmer to solve a problem using a computer.     * Must be translatable into machine-readable form when arranged in a specific order.
  • Source Code (Program):     * Program statements entered in the program editor window that have not yet been translated into machine-readable form.     * Understood by the programmer; usually written in assembly or high-level language.
  • Object Code:     * Program code in machine-readable (binary) form.     * Understood by the computer; produced by compilers or assemblers after translation.
  • Syntax:     * A well-defined set of rules concerning the order of characters, punctuation, and naming of variables.     * Grammatical rules governing how words, symbols, expressions, and statements are formed and combined.
  • Semantics:     * Rules governing the meaning of syntax.     * Dictates what takes place when a program is run or executed.     * The meaning attached to every command in a language.

Language Translators

  • Overview:     * Code in assembly or high-level languages must be translated into machine language before the computer can run it.     * Translators are special system software stored in the Read-Only Memory (ROM).     * They take assembly or high-level code as input and provide machine-readable code as output.
  • Three Main Types of Translators:     1. Assembler:         * Translates programs from Assembly language into Machine language.         * Functions:             * Checks if instructions are valid.             * Identifies errors (typing mistakes, wrong formats) before translation.             * Displays errors, plus complete source and object programs.             * Assigns memory locations to programmer-defined names (maintains a name table).             * Identifies the proper order of processing for fast execution.             * Generates machine code equivalent if no errors are found.             * Combines generated code with library subroutines.     2. Interpreter:         * Translates source programs word-by-word or line-by-line.         * CPU executes one line immediately after translation before the next is processed.         * Translated lines are not stored in memory; the program must be re-translated for every execution.     3. Compiler:         * Translates the entire source program into object code at once before execution.         * Compilation: The process of using a compiler to translate high-level source language to machine language.         * Activities during compilation:             * Line-by-line syntax error checking.             * Converting source code to object code.             * Testing the program.             * Running the compiled object code.         * Functions of a Compiler:             * Identifies proper processing order.             * Allocates memory space for defined storage locations.             * Reads each line and converts it to machine language.             * Checks for syntax errors (violations of grammatical rules).             * Generates a machine code listing.             * Combines code with library subroutines.

Differences Between Compilers and Interpreters

  • Interpreter Characteristics:     1. Translates and executes each statement one at a time (translation and execution occur together).     2. Translates the program every time it is needed; slower than compiling.     3. Object codes take less memory.     4. Syntax errors are reported and corrected before execution continues.
  • Compiler Characteristics:     1. Translates all source code at once as a unit (translation and execution are separate phases).     2. Object codes can be saved on storage media and run later; faster execution.     3. Requires more memory as object files are larger.     4. Syntax errors are reported after the entire source code has been translated into its object equivalent.

Linker and Loader Utility Programs

  • Program Linking: The process of joining an object code to all other files needed for execution to generate an executable file.
  • Linker:     * Software that accepts separately translated program modules or subroutines as input.     * Combines them into one logical module called a "Load module" for the computer hardware.
  • Loader:     * Utility program that transfers the linker's output (load module) into the computer memory for execution by the hardware.

Levels of Programming Languages

  • Categorization: Divided into Low-level and High-level languages.
  • Low-Level Languages:     * Basic languages understood directly by the computer or requiring minimal translation.     * Types: Machine language and Assembly languages.     * Features:         * Machine hardware-oriented.         * Non-portable (constrained to a specific computer family).         * Use mnemonic codes and symbolic addresses.     * Machine Language (1st Generation):         * Written in binary digits (00's and 11's).         * Requires no translation; codes differ by CPU manufacturer (e.g., Intel Pentium vs. Motorola).     * Assembly Languages (2nd Generation):         * Use predefined symbols called Mnemonic codes (e.g., ADDADD, SUBSUB, RDRD).         * Requires an Assembler for conversion; machine-dependent.         * Easier to use/modify and has fewer error chances than machine language.         * Example: EDSACEDSAC.     * Advantages of Low-Level Languages:         * Understood by CPU with little/no translation.         * Closer hardware control and high efficiency.         * Ideal for Operating Systems and Games requiring fast CPU time.         * Execute much faster and require less memory.         * High stability.     * Disadvantages of Low-Level Languages:         * Difficult to learn, read, understand, and debug.         * Tedious and time-consuming long programs.         * Machine-dependent and non-portable.         * Requires knowledge of internal computer circuitry; revision requires re-writing.
  • High-Level Programming Languages:     * Grammar is close to natural human language (English).     * Must be translated via Compiler or Interpreter.     * Purpose: Improve programmer productivity, ease training, make programs easy to follow, and speed up testing/debugging.     * Advantages:         * Portable between different computer makes.         * Shorter programs with faster translation.         * Easy to learn, use, debug, and maintain.         * User-friendly and problem-oriented.         * Self-documenting and flexible.     * Disadvantages:         * Not machine-oriented; inefficient use of CPU/Hardware.         * Cannot program hardware directly.         * Use more storage space and take more time to run (one statement converts to several machine instructions).         * Cannot be used on very small computers due to compiler memory demands.

Classification of High-Level Languages

  • 1. Structured (Procedural or 3rd Generation) Languages:     * Large programs are broken into smaller components (modules/sub-routines) performing specific tasks.     * Characteristics: Use of modules, control structures (sequence, selection, iteration), and data types (Integer, Real, Char, String).     * Advantages: Easier to read, code, run, test, and document; allows creation of routine libraries.     * Examples:         * BASIC: Beginners All-purpose Symbolic Instruction Code (Business/Education).         * PASCAL: Named after Blaise Pascal; used for teaching academic programming.         * COBOL: COmmon Business Oriented Language (Commercial data processing).         * FORTRAN: FORmula TRANslation (Math, science, engineering).         * Ada: Named after Ada Lovelace (Military, industrial, real-time).         * C: Used for system software and application packages.
  • 2. Fourth Generation Languages (4GLs):     * User-oriented languages designed to speed up application building.     * Features: Include design tools (Forms, Buttons), mouse-pointing (drag and drop), and application generators.     * Nonprocedural: Programmers state what is wanted, not how to do it.     * Query Languages: Used to access data in database systems.     * Examples: Visual Basic, Visual COBOL, Delphi Pascal.
  • 3. Fifth Generation Languages (5GLs):     * Used for Expert Systems and Artificial Intelligence (AI).     * Designed to emulate human intelligence; programmer focuses on the problem and conditions rather than algorithms.     * Examples: PROLOG (Programming in Logic), LISP (List Processing), Mercury, OCCAM.
  • 4. Object-Oriented Programming (OOP):     * Combines data and instructions into a self-sufficient "object."     * Encapsulation: The process of joining data and functions into one object.     * Used in GUI-based OS and applications.     * Uses assembled modules with properties (color, size) and events (on-click actions).     * Examples: Simula, JAVA, SmallTalk, C++, Visual C++, Object COBOL, Access Basic.
  • 5. Web Scripting Languages:     * Used for developing web pages.     * Characteristics: Use tags, lack declaration parts and control structures, interpreted not compiled, portable.     * Examples: HTML, XML, JavaScript, VBScript, PHP, Microsoft FrontPage, Dreamweaver.

Factors for Choosing a Programming Language

  1. Availability of relevant translators.
  2. Programmer familiarity with the language.
  3. Ease of learning and use.
  4. Purpose (Application area): education, business, science, etc.
  5. Execution time: Apps requiring quick responses need machine/assembly code.
  6. Development time: HLLs require less time.
  7. Popularity and market success.
  8. Documentation availability for usage and maintenance.
  9. Maintenance ease (easier with HLLs).
  10. Availability of skilled programmers.

Program Development Cycle

  1. Problem Recognition:     * Identifying environmental problems to solve with a program.     * Situations: achieving purpose, improving current programs, or management directives.     * Sample Problem: Calculating the area of a circle using A=extπr2A = ext{\pi} r^2.
  2. Problem Definition (Problem Analysis):     * Stating the program's functions, inputs, processes, outputs, and files needed.     * Circle Example: Input (Pi constant, Radius), Process (π×radius×radius\pi \times radius \times radius), Output (Area).
  3. Program Design:     * Development of the algorithm (problem-solving logic).     * Monolithic Programs: Large, non-structured single blocks of code; difficult to test, modify, or learn.     * Modular Programs: Broken into units; easier to read, understand, and change.
  4. Program Coding:     * Converting the algorithm into actual computer instructions.     * Rules: Meaningful identifiers, comments, neat layout, indentation, only one instruction per line, and modularization.
  5. Program Testing and Debugging:     * Testing: Detection of bugs.         * Unit Testing: Individual modules.         * Link Testing: Joined components/communication.         * System Testing: All components as one unit.     * Error Types:         * Syntax: Grammatical errors detected by translators.         * Logical: Bad design; program runs but gives wrong results.         * Run-time: Invalid input during execution (e.g., division by zero).         * Semantic: Deviations from objectives; not computer-detected.         * Lexicon: Misusing reserved words.     * Detection Methods: Dry running, translator system checking, debugging utilities, test data (Normal, Extreme, Invalid), system tests with actual data, and diagnostic trace routines.     * Debugging: The process of detecting, locating, and correcting errors.
  6. Program Implementation and Maintenance:     * Implementation: Installation and training. Parallel runs with old programs are common.     * Maintenance: Reviewing and adjusting routines to keep the system functioning.     * Documentation: Supportive materials for users (User Guide), operators (Technical Manuals), and programmers (Reference/Technical manuals).

Pascal Language Snippets and Explanations

Example 1: Area of a Circle

Program AreaCircle (input, output);
CONST Pi = 3.142;
VAR Radius, Area: REAL;
BEGIN
    Writeln (‘Enter the radius’);
    Readln (Radius);
    Area: = Pi * Radius * Radius;
    Writeln (‘The Area is’, Area);
END.
  • Program Header: Program AreaCircle (input, output); names the program and indicates I/O.
  • CONST: Declares a fixed value Pi=3.142Pi = 3.142.
  • VAR: Declares variables Radius and Area as REAL (fractional numbers).
  • BEGIN/END: Marks the start and end of the executable body.
  • Assignment (:=:=): Stores the result of calculations in a variable.

Example 2: Straight Line Equation (Y=(m×x)+cY = (m \times x) + c)

Program StraighLine (input, output);
VAR Y, m, x, c: INTEGER;
BEGIN
    Writeln (‘Input the value of M’);
    Readln (M);
    Writeln (‘Input the value of X’);
    Readln (X);
    Writeln (‘Input the value of C’);
    Readln (C);
    Y: = (m * x) +c;
    Writeln (‘The value of y is:’, Y);
END.
  • INTEGER Type: Memory spaces set aside for whole numbers only.

Algorithms and Design Tools

  • Algorithm Qualities: Simple, few steps, accurate, unambiguous, executable, and possessing a clear stopping point.
  • Instruction Categories: Input, Processing (manipulating/comparing), Output.
  • Pseudocode:     * English-like phrases to describe steps; cannot be compiled.     * Keywords: INITIALIZE, SET, READ, INPUT, COMPUTE, CALCULATE, OUTPUT, PRINT.     * Guidelines: Short, unambiguous, indented, with a clear BEGIN and END.
  • Flowcharts:     * Diagrammatic representation of program logic.     * Symbols:         * Oval (Terminal): Start/Stop.         * Parallelogram (I/O): Read/Input or Output/Print.         * Rectangle (Process): Formula or math transformation.         * Rhombus (Decision): Logical comparison with Yes/No paths.         * Flow Lines (Arrows): Order of processing; should not cross.         * Circle (Connector): Links parts of a flowchart when it spans multiple pages.     * Rules: Only one entry and exit point; flow top-to-bottom/left-to-right.     * Pros: Good visual reference and documentation; easy understand logic flow.     * Cons: Time-consuming to draw; clumsy for complex logic; cannot be typed easily.

Program Control Structures

  • Sequence Control: Statements executed one after another in written order.
  • Selection (Decision) Control: Choosing statements based on Boolean (True/False) conditions.     * IF-THEN: Runs an action only if the condition is True.     * IF-THEN-ELSE: Choice between two options.     * Nested IF: Embedded structures for more than two options.     * CASE-OF: Multiple choice using Integer or Char labels.
  • Iteration (Looping) Control: Repeating blocks of code.     * Conditional Loop: Known number of repetitions is NOT predetermined.     * Unconditional Loop: Repeated a specified number of times.     * Continuous (Infinite) Loop: Never-ending repetition.
  • Specific Loop Types:     * FOR Loop: predetermined repetitions. Uses a counter, initialization, and incrementing.     * WHILE Loop: Condition tested before loop body; runs zero or many times.     * REPEAT…UNTIL: Condition tested at the end; runs at least once.

Mathematics and Formulae

  • Area of Circle: Area=extπimesr2Area = ext{\pi} imes r^2
  • Einstein Equation: E=MimesC2E = M imes C^2
  • Straight Line: Y=(mimesx)+cY = (m imes x) + c
  • Fahrenheit Conversion: F=32+(95imesC)F = 32 + (\frac{9}{5} imes {}^\circ C) (Note: in pseudocode often written as F := 32 + (C * 9 / 5))
  • Perimeter of Rectangle: Perimeter=2×(L+W)Perimeter = 2 \times (L + W)