Introduction to Computer Programming
Open in the Padhaiko app1.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.
Computer Program and Programming Language
- Computer Program: A finite, ordered, and unambiguous sequence of instructions written to perform a specific task or solve a well-defined problem on a computer. The process of designing, writing, testing, and maintaining such instructions is called computer programming.
- Programming Language: A formal notation consisting of a defined vocabulary (keywords, symbols, identifiers), syntax (grammatical rules specifying valid combinations of tokens), and semantics (the exact meaning and runtime behavior of each valid statement) used to express algorithms so a computer can execute them.
| Aspect | Syntax | Semantics |
|---|---|---|
| Definition | Grammatical rules governing how symbols and keywords are arranged into valid statements | Logical meaning and runtime behavior of a syntactically valid statement |
| Violation Example | Missing semicolon in int x = 5 or misspelled keyword whlie | Writing area = 2 * r instead of area = 3.14159 * r * r, or dividing by zero |
| Detection Stage | Caught automatically by the compiler or interpreter before execution | Often 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.
| Generation | Category | Representation & Features | Translation Needed | Examples |
|---|---|---|---|---|
| 1GL (First Generation) | Machine Language | Pure binary digits (0s and 1s) representing opcodes and memory addresses directly understood by the CPU | None (executed directly by hardware) | x86 / ARM raw machine code |
| 2GL (Second Generation) | Assembly Language | Short symbolic mnemonics (MOV, ADD, JMP) and symbolic labels instead of raw binary | Assembler (one-to-one mapping to machine code) | 8085 Assembly, x86 Assembly |
| 3GL (Third Generation) | Procedural High-Level Language | English-like keywords, algebraic expressions, loops, and functions; machine-independent | Compiler or Interpreter | C, C++, Java, Python, FORTRAN |
| 4GL (Fourth Generation) | Very High-Level / Non-Procedural | Specifies what result is wanted rather than step-by-step control flow; domain-focused | Query processor / interpreter / compiler | SQL, MATLAB, SAS, report generators |
| 5GL (Fifth Generation) | Constraint / Logic & AI Languages | Uses rules, facts, constraints, and inference engines rather than explicit algorithms | Inference engine / specialized compiler | Prolog, OPS5, Mercury |
| Aspect | Low-Level Languages (1GL, 2GL) | High-Level Languages (3GL–5GL) |
|---|---|---|
| Hardware Dependence | Machine-dependent; tied to a specific CPU instruction set architecture | Portable / machine-independent; runs across platforms with recompilation |
| Readability & Productivity | Hard to read, write, and debug; tedious memory and register management | Easy to read, write, and maintain; closer to human logic and math |
| Execution Speed & Memory | Maximum execution speed and minimal memory overhead | Slightly higher overhead, though optimizing compilers approach assembly speed |
| Typical Use Cases | Bootloaders, device drivers, real-time firmware, critical inner loops | Application software, operating systems (C), web backends, scientific computing |
High-level languages are further classified by programming paradigm:
- Procedural (Imperative) Languages: Organize code as a sequence of instructions and reusable functions operating on data (e.g., C, Pascal, FORTRAN).
- Object-Oriented Languages (OOP): Bundle data and behavior together into classes and objects (e.g., C++, Java, Python).
- Functional and Logic Languages: Express computation via mathematical function evaluation (e.g., Haskell, Lisp) or logical rules (e.g., Prolog).
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.
+------------------+ +--------------------+ +-------------+
| 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:
- Inputs: What raw data values must be supplied, their data types, units, and valid ranges.
- Outputs: What results must be produced and in what format.
- 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
Algorithm and Flowchart
- Algorithm: A finite, step-by-step, unambiguous procedure for solving a problem. Every valid algorithm must satisfy five properties:
- Input: Zero or more well-defined inputs supplied externally.
- Output: At least one meaningful result produced.
- Definiteness: Every instruction must be clear, exact, and free of ambiguity.
- Finiteness: It must terminate after a finite number of steps for all valid inputs.
- Effectiveness: Each step must be basic enough to be carried out mechanically in finite time.
- Flowchart: A graphical representation of an algorithm using standardized geometric symbols connected by directional flowlines (arrows) to illustrate control flow, branching, and looping.
| Symbol Shape | Name | Purpose in Flowchart |
|---|---|---|
| Oval / Rounded Capsule | Terminal (Start / Stop) | Marks the entry point (START) and termination point (STOP) of the program |
| Parallelogram | Input / Output | Represents reading data (READ n) or displaying output (PRINT sum) |
| Rectangle | Process | Represents arithmetic computations, assignments, or variable initialization (sum = sum + i) |
| Diamond | Decision | Represents a conditional test (a > b?) with two outgoing branches (Yes/True and No/False) |
| Arrows | Flowlines | Indicate the direction of sequential or branched execution |
| Small Circle | On-Page Connector | Connects 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.
| Stage | Tool | Input | Output | Key Activity |
|---|---|---|---|---|
| 1. Preprocessing | Preprocessor (cpp) | prog.c | Expanded source (prog.i) | Expands #include headers, substitutes #define macros, strips comments |
| 2. Compilation | Compiler (cc1) | prog.i | Assembly code (prog.s) | Performs lexical, syntax, and semantic checks; optimizes and generates target assembly |
| 3. Assembly | Assembler (as) | prog.s | Object file (prog.o / .obj) | Translates assembly mnemonics into relocatable binary machine code |
| 4. Linking | Linker (ld) | prog.o + libraries | Executable (a.out / prog.exe) | Resolves external function calls (like printf) by combining object files and standard libraries |
| 5. Loading & Execution | OS Loader & CPU | Executable file | Program output | Loads machine code and data segments into RAM, initializes stack/heap, and starts execution at main() |
| Aspect | Compiler | Interpreter |
|---|---|---|
| Translation Unit | Translates the entire source program into machine code at once | Translates and executes source code line by line (or statement by statement) |
| Output Artifact | Produces a standalone executable file on disk | Does not produce a standalone machine-code executable; runs via interpreter runtime |
| Execution Speed | Very fast at runtime because translation is already complete | Slower at runtime due to repeated translation overhead during loops |
| Error Reporting | Lists all syntax errors found across the file after scanning | Stops immediately at the first line containing an error |
| Examples | C (gcc, clang), C++, Rust | Python, 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:
- Testing: Running the program with carefully selected test inputs—including normal cases, boundary values (e.g.,
0, negative numbers, maximum limits), and invalid inputs—to verify that actual outputs match expected outputs. - Debugging: The process of locating, diagnosing, and correcting errors (bugs) uncovered during compilation or testing.
| Error Type | Cause | When Detected | Example in C |
|---|---|---|---|
| Syntax Error | Violation of language grammar rules | Compile time (by compiler) | Missing semicolon printf("Hi"), unmatched braces } |
| Runtime Error | Illegal operation attempted while program is running | Execution time (program crashes or aborts) | Dividing an integer by 0, accessing an out-of-bounds memory pointer |
| Logical Error | Flawed algorithm or wrong formula; syntax is completely valid | Testing 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.
- Internal Documentation: Clear comments (
//and/* ... */in C), descriptive identifier names, and structured formatting embedded inside the source files to explain why non-obvious logic is written. - External Documentation: User manuals, installation guides, input/output specifications, flowcharts, and API references kept outside the code for end users and future developers.
Worked Examples
1
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) andfact(product 1 * 2 * ... * N). - Constraints:
N >= 1; initialize accumulatorsum = 0(additive identity) andfact = 1(multiplicative identity) before the loop starts.
Algorithm:
START- Read the value of
N. - Initialize
sum = 0,fact = 1, and loop counteri = 1. - Check condition: if
i <= N, proceed to the next instruction; otherwise jump to printing results. - Update
sum = sum + iandfact = fact * i. - Increment
i = i + 1and repeat the loop test. - Display
sumandfact. STOP
( 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)For N = 5, the algorithm terminates cleanly after 5 iterations and outputs sum = 15 and factorial = 120.
2
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.
#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;:
- The preprocessor includes
<stdio.h>(declaringprintf). - The compiler translates
main()into object code. - The linker resolves the external reference to
printffrom the standard C library (libc) and produces the executable.
- Syntax Error: Missing semicolon after
float avgon line 4. - Logical Error: Missing parentheses and floating-point divisor in
a + b + c / 3(evaluates to40.00instead of20.00). - Fix: Write
float avg;andavg = (a + b + c) / 3.0;.
3
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:
- Translation method: Whole program at once (compiler) vs. line-by-line (interpreter).
- Executable output: Generates standalone machine-code binary (compiler) vs. no standalone binary (interpreter).
- Runtime speed: Fast native execution (compiler) vs. slower repeated translation (interpreter).
- 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.
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
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 = 10without 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.
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).
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:
- 1GL (Machine Language): Binary 0s and 1s; no translator needed; completely machine-dependent; e.g., x86 binary opcodes.
- 2GL (Assembly Language): Symbolic mnemonics (
MOV,ADD); translated by an assembler; machine-dependent; e.g., 8085 Assembly. - 3GL (High-Level Procedural): English-like statements and formulas; translated by a compiler or interpreter; machine-independent; e.g., C, FORTRAN, Java.
- 4GL (Very High-Level): Declarative/non-procedural task specification; processed by query engines or specialized compilers; e.g., SQL, MATLAB.
- 5GL (Logic / Constraint): Facts, rules, and constraints solved by an inference engine; e.g., Prolog.
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).
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:
- Preprocessor: Expands
#includedirectives and#definemacros incalc.cand removes comments. - 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:
- Linker: Combines
calc.owith standard library object modules (for example, resolvingprintforsqrt) and produces the final standalone executable (calcorcalc.exe). - Loader/Execution: The operating system loads the executable into RAM and starts execution at
main().
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.
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:
START- Set
sum = 0,count = 1. - While
count <= 5: read numberx, setsum = sum + x, setcount = count + 1. - Compute
avg = sum / 5.0. - Print
sumandavg. 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 <= 5is false; exit loop) - Compute
avg = 30 / 5.0 = 6.0.
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.
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 misspellingreturn) 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.
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.