PadhaikoAll subjects

Introduction to Computer Programming

Computer Programming (ENCT 101)

Open in the Padhaiko app

1.1 Definition of a computer program and programming language

A digital computer cannot think or interpret ambiguous human instructions on its own; it executes operations only when directed by an exact sequence of encoded instructions.

Definition

Computer Program and Programming Language

AspectSyntaxSemantics
DefinitionGrammatical rules governing how symbols and keywords are arranged into valid statementsLogical meaning and runtime behavior of a syntactically valid statement
Violation ExampleMissing semicolon in int x = 5 or misspelled keyword whlieWriting area = 2 * r instead of area = 3.14159 * r * r, or dividing by zero
Detection StageCaught automatically by the compiler or interpreter before executionOften passes compilation and appears only as wrong output or runtime failure

1.2 Types and generations of programming languages

Programming languages have evolved from hardware-specific binary codes toward human-readable, problem-oriented abstractions. This evolution is commonly grouped into five generations (1GL to 5GL) and two broad levels: low-level and high-level languages.

Five Generations of Programming Languages
GenerationCategoryRepresentation & FeaturesTranslation NeededExamples
1GL (First Generation)Machine LanguagePure binary digits (0s and 1s) representing opcodes and memory addresses directly understood by the CPUNone (executed directly by hardware)x86 / ARM raw machine code
2GL (Second Generation)Assembly LanguageShort symbolic mnemonics (MOV, ADD, JMP) and symbolic labels instead of raw binaryAssembler (one-to-one mapping to machine code)8085 Assembly, x86 Assembly
3GL (Third Generation)Procedural High-Level LanguageEnglish-like keywords, algebraic expressions, loops, and functions; machine-independentCompiler or InterpreterC, C++, Java, Python, FORTRAN
4GL (Fourth Generation)Very High-Level / Non-ProceduralSpecifies what result is wanted rather than step-by-step control flow; domain-focusedQuery processor / interpreter / compilerSQL, MATLAB, SAS, report generators
5GL (Fifth Generation)Constraint / Logic & AI LanguagesUses rules, facts, constraints, and inference engines rather than explicit algorithmsInference engine / specialized compilerProlog, OPS5, Mercury
AspectLow-Level Languages (1GL, 2GL)High-Level Languages (3GL–5GL)
Hardware DependenceMachine-dependent; tied to a specific CPU instruction set architecturePortable / machine-independent; runs across platforms with recompilation
Readability & ProductivityHard to read, write, and debug; tedious memory and register managementEasy to read, write, and maintain; closer to human logic and math
Execution Speed & MemoryMaximum execution speed and minimal memory overheadSlightly higher overhead, though optimizing compilers approach assembly speed
Typical Use CasesBootloaders, device drivers, real-time firmware, critical inner loopsApplication software, operating systems (C), web backends, scientific computing

High-level languages are further classified by programming paradigm:


1.3 Problem-solving using a computer

Writing code immediately at the keyboard without planning leads to logic flaws and wasted effort. Systematic software development follows a structured problem-solving life cycle from understanding the problem to maintaining documentation.

Stages of Computer Problem SolvingText
+------------------+     +--------------------+     +-------------+
| 1. Problem       | --> | 2. Algorithm &     | --> | 3. Coding   |
|    Analysis      |     |    Flowchart       |     | (Programming)|
+------------------+     +--------------------+     +-------------+
                                                           |
                                                           v
+------------------+     +--------------------+     +-------------+
| 6. Documentation | <-- | 5. Debugging &     | <-- | 4. Compile, |
|    & Maintenance |     |    Testing         |     | Link & Run  |
+------------------+     +--------------------+     +-------------+

1.3.1 Problem analysis

Problem analysis is the initial phase of studying the problem statement thoroughly to understand what needs to be solved before deciding how to solve it. In this step, the programmer identifies:

  1. Inputs: What raw data values must be supplied, their data types, units, and valid ranges.
  2. Outputs: What results must be produced and in what format.
  3. Processing / Constraints: The mathematical formulas, business rules, edge cases (such as division by zero, negative inputs, or empty lists), and performance bounds connecting inputs to outputs.

1.3.2 Algorithm and flowchart

Definition

Algorithm and Flowchart

Standard Flowchart Symbols
Symbol ShapeNamePurpose in Flowchart
Oval / Rounded CapsuleTerminal (Start / Stop)Marks the entry point (START) and termination point (STOP) of the program
ParallelogramInput / OutputRepresents reading data (READ n) or displaying output (PRINT sum)
RectangleProcessRepresents arithmetic computations, assignments, or variable initialization (sum = sum + i)
DiamondDecisionRepresents a conditional test (a > b?) with two outgoing branches (Yes/True and No/False)
ArrowsFlowlinesIndicate the direction of sequential or branched execution
Small CircleOn-Page ConnectorConnects broken flowlines across different parts of the same page without crossing lines

1.3.3 Programming

Programming (Coding) is the phase of translating the verified algorithm or flowchart into source code using the exact syntax of a chosen language such as C. Good coding practice requires meaningful variable names, consistent indentation, modular functions, and adherence to language standards (such as ANSI C / C99 / C11).

1.3.4 Compilation, linking and execution

Because a CPU executes only binary machine instructions, C source code must pass through a multi-stage build toolchain before running.

C Program Translation Pipeline (Source to Execution)
StageToolInputOutputKey Activity
1. PreprocessingPreprocessor (cpp)prog.cExpanded source (prog.i)Expands #include headers, substitutes #define macros, strips comments
2. CompilationCompiler (cc1)prog.iAssembly code (prog.s)Performs lexical, syntax, and semantic checks; optimizes and generates target assembly
3. AssemblyAssembler (as)prog.sObject file (prog.o / .obj)Translates assembly mnemonics into relocatable binary machine code
4. LinkingLinker (ld)prog.o + librariesExecutable (a.out / prog.exe)Resolves external function calls (like printf) by combining object files and standard libraries
5. Loading & ExecutionOS Loader & CPUExecutable fileProgram outputLoads machine code and data segments into RAM, initializes stack/heap, and starts execution at main()
AspectCompilerInterpreter
Translation UnitTranslates the entire source program into machine code at onceTranslates and executes source code line by line (or statement by statement)
Output ArtifactProduces a standalone executable file on diskDoes not produce a standalone machine-code executable; runs via interpreter runtime
Execution SpeedVery fast at runtime because translation is already completeSlower at runtime due to repeated translation overhead during loops
Error ReportingLists all syntax errors found across the file after scanningStops immediately at the first line containing an error
ExamplesC (gcc, clang), C++, RustPython, Ruby, early BASIC

1.3.5 Debugging and testing

Even after a program compiles cleanly, it may fail to run properly or produce wrong answers. Testing and debugging address these issues systematically:

Three Fundamental Categories of Programming Errors
Error TypeCauseWhen DetectedExample in C
Syntax ErrorViolation of language grammar rulesCompile time (by compiler)Missing semicolon printf("Hi"), unmatched braces }
Runtime ErrorIllegal operation attempted while program is runningExecution time (program crashes or aborts)Dividing an integer by 0, accessing an out-of-bounds memory pointer
Logical ErrorFlawed algorithm or wrong formula; syntax is completely validTesting phase (wrong output produced)Computing average of a and b as a + b / 2 instead of (a + b) / 2

1.3.6 Documentation

Documentation is the written record explaining how a program works, how to build and run it, and how to maintain or extend it later.


Worked Examples

Example 1

1 (6 marks)

Apply the problem-solving steps to design an algorithm and flowchart to find the sum and factorial of the first N natural numbers (1 to N). Trace the algorithm for N = 5.

Problem Analysis:

  • Input: A positive integer N (number of terms).
  • Outputs: sum (integer sum 1 + 2 + ... + N) and fact (product 1 * 2 * ... * N).
  • Constraints: N >= 1; initialize accumulator sum = 0 (additive identity) and fact = 1 (multiplicative identity) before the loop starts.

Algorithm:

  1. START
  2. Read the value of N.
  3. Initialize sum = 0, fact = 1, and loop counter i = 1.
  4. Check condition: if i <= N, proceed to the next instruction; otherwise jump to printing results.
  5. Update sum = sum + i and fact = fact * i.
  6. Increment i = i + 1 and repeat the loop test.
  7. Display sum and fact.
  8. STOP
Flowchart Flow RepresentationText
  ( START )
      |
      v
 / READ N /
      |
      v
[ sum = 0, fact = 1, i = 1 ]
      |
      v
  < i <= N ? > --- No ---> / PRINT sum, fact / ---> ( STOP )
      |
     Yes
      |
      v
[ sum = sum + i; fact = fact * i; i = i + 1 ]
      |
      +--------(loop back to condition)
Answer:

For N = 5, the algorithm terminates cleanly after 5 iterations and outputs sum = 15 and factorial = 120.

Example 2

2 (6 marks)

A student writes the following C program to calculate the average of three numbers (10, 20, 30), but it fails to compile and later produces an incorrect result. Identify the syntax error, linking/build role, and logical error, and show the corrected program.

Buggy Average ProgramC
#include <stdio.h>
int main() {
    int a = 10, b = 20, c = 30;
    float avg
    avg = a + b + c / 3;
    printf("Average = %.2f\n", avg);
    return 0;
}

Identifying the Syntax Error: Line 4 declares float avg without a terminating semicolon (;). The C compiler detects this grammatical violation during compilation and refuses to generate an object file until ; is added.

Identifying the Logical Error: Line 5 writes avg = a + b + c / 3;. Because division (/) has higher precedence than addition (+), C evaluates 10 + 20 + (30 / 3) = 40.00 instead of (10 + 20 + 30) / 3.0 = 20.00. Moreover, dividing by integer 3 performs integer truncation if the numerator is not cast to float.

Role of Compilation and Linking After Fix: Once corrected to avg = (a + b + c) / 3.0;:

  1. The preprocessor includes <stdio.h> (declaring printf).
  2. The compiler translates main() into object code.
  3. The linker resolves the external reference to printf from the standard C library (libc) and produces the executable.
Answer:
  • Syntax Error: Missing semicolon after float avg on line 4.
  • Logical Error: Missing parentheses and floating-point divisor in a + b + c / 3 (evaluates to 40.00 instead of 20.00).
  • Fix: Write float avg; and avg = (a + b + c) / 3.0;.
Example 3

3 (5 marks)

A past exam question asks: "Differentiate between a compiler and an interpreter, and explain why C uses a compiler rather than an interpreter." Structure a complete, high-scoring exam answer.

Direct Comparison of Compiler and Interpreter: Present a crisp tabular comparison covering four standard criteria:

  1. Translation method: Whole program at once (compiler) vs. line-by-line (interpreter).
  2. Executable output: Generates standalone machine-code binary (compiler) vs. no standalone binary (interpreter).
  3. Runtime speed: Fast native execution (compiler) vs. slower repeated translation (interpreter).
  4. Error handling: Reports syntax errors across the whole unit before running (compiler) vs. halts at the first offending line (interpreter).

Why C Uses a Compiler: C was designed for systems programming (operating systems, compilers, embedded firmware) where direct hardware access, predictable memory layout, and maximum runtime speed are essential. Compiling C directly to native CPU machine instructions eliminates runtime translation overhead and allows standalone binaries to run without an interpreter installed.

Answer:

State the four-point comparison table (translation unit, executable output, runtime speed, error reporting) followed by C's systems-programming need for native speed and standalone binaries.


Exercises

Exercises — Introduction to Computer Programming

Question 1

Define a computer program and a programming language. Explain how syntax differs from semantics with one concrete example of each in C.

Definitions:

  • A computer program is a finite, ordered sequence of unambiguous instructions that directs a computer to accomplish a specific task.
  • A programming language is a formal system of symbols, grammatical rules (syntax), and meanings (semantics) used to write computer programs.

Syntax vs. Semantics with C Examples:

  • Syntax governs the legal structure of statements. Example: writing int x = 10 without a semicolon ; is a syntax error caught by the compiler.
  • Semantics governs the meaning and effect of a valid statement. Example: int avg = 10 + 20 / 2; is syntactically legal, so it compiles without error, but semantically wrong if the programmer intended (10 + 20) / 2.
Answer:

A computer program is a finite, ordered sequence of instructions; a programming language is the formal vocabulary, grammar (syntax), and meaning (semantics) used to write them. Syntax errors break grammar rules (e.g., missing ;) and are caught at compile time, whereas semantic/logical errors produce unintended meaning or results (e.g., 10 + 20 / 2 instead of (10 + 20) / 2).

Question 2

Compare the five generations of programming languages (1GL through 5GL) in terms of representation, translation tool, machine independence, and one example language for each.

Summary of 1GL to 5GL:

  1. 1GL (Machine Language): Binary 0s and 1s; no translator needed; completely machine-dependent; e.g., x86 binary opcodes.
  2. 2GL (Assembly Language): Symbolic mnemonics (MOV, ADD); translated by an assembler; machine-dependent; e.g., 8085 Assembly.
  3. 3GL (High-Level Procedural): English-like statements and formulas; translated by a compiler or interpreter; machine-independent; e.g., C, FORTRAN, Java.
  4. 4GL (Very High-Level): Declarative/non-procedural task specification; processed by query engines or specialized compilers; e.g., SQL, MATLAB.
  5. 5GL (Logic / Constraint): Facts, rules, and constraints solved by an inference engine; e.g., Prolog.
Answer:

Programming languages progress from hardware-specific binary machine code (1GL, no translator) and mnemonic assembly (2GL, assembler) to portable procedural high-level languages (3GL, compiler/interpreter like C), non-procedural query languages (4GL, like SQL), and rule-based logic languages (5GL, like Prolog).

Question 3

Trace the stages a C source file calc.c passes through from source code to an executable program, clearly distinguishing compilation from linking.

Preprocessing and Compilation:

  1. Preprocessor: Expands #include directives and #define macros in calc.c and removes comments.
  2. Compiler: Checks syntax and types, translates the preprocessed C code into assembly code, and the Assembler converts that assembly into a binary object file (calc.o).

Linking and Execution:

  1. Linker: Combines calc.o with standard library object modules (for example, resolving printf or sqrt) and produces the final standalone executable (calc or calc.exe).
  2. Loader/Execution: The operating system loads the executable into RAM and starts execution at main().
Answer:

calc.c goes through Preprocessing (header/macro expansion), Compilation + Assembly (translating source into object file calc.o), Linking (resolving external library symbols like printf into an executable binary), and Loading into RAM for execution.

Question 4

Write an algorithm and draw a text flowchart to compute the sum and average of 5 numbers entered by the user. Trace the algorithm for the input sequence 4, 8, 2, 10, 6.

Algorithm:

  1. START
  2. Set sum = 0, count = 1.
  3. While count <= 5: read number x, set sum = sum + x, set count = count + 1.
  4. Compute avg = sum / 5.0.
  5. Print sum and avg.
  6. STOP

Flowchart and Trace for 4, 8, 2, 10, 6:

  • After reading 4: sum = 4, count = 2
  • After reading 8: sum = 12, count = 3
  • After reading 2: sum = 14, count = 4
  • After reading 10: sum = 24, count = 5
  • After reading 6: sum = 30, count = 6 (count <= 5 is false; exit loop)
  • Compute avg = 30 / 5.0 = 6.0.
Answer:

The algorithm initializes sum = 0 and loops 5 times to accumulate inputs before dividing by 5.0. For inputs 4, 8, 2, 10, 6, the final output is sum = 30 and average = 6.0.

Question 5

Distinguish between syntax errors, runtime errors, and logical errors. Also explain the difference between internal documentation and external documentation.

Error Classification:

  • Syntax errors violate language grammar (e.g., missing ; or misspelling return) and prevent compilation.
  • Runtime errors occur during program execution due to illegal operations (e.g., integer division by zero or invalid memory access), causing crashes or abnormal termination.
  • Logical errors occur when a syntactically valid program executes without crashing but produces incorrect results due to flawed logic or wrong formulas.

Internal vs. External Documentation:

  • Internal documentation lives inside source files: meaningful variable/function names, clean indentation, and explanatory comments (//, /* ... */) aiding developers who read the code.
  • External documentation lives outside source files: user manuals, installation steps, flowcharts, and system design reports guiding users and maintainers.
Answer:

Syntax errors break grammar rules (detected at compile time), runtime errors cause illegal operations during execution (e.g., division by zero), and logical errors produce wrong outputs from flawed formulas. Internal documentation consists of code comments and clear naming inside source files, while external documentation comprises manuals, flowcharts, and specifications kept separately.

Overview of C Programming →