CAPE Computer Science Unit 1 Notes
MODULE 1: COMPUTER ARCHITECTURE AND ORGANIZATION
1. Main Components of a Computer System
● Input Devices: Devices that allow users to send data into the computer for processing.
○ Examples: Keyboard (typing), Mouse (navigation), Scanner (digitizing
images/documents), Webcam (capturing video input).
● Output Devices: Devices that display or present data from the computer to the user.
○ Examples: Monitor (displays video and GUI), Printer (outputs hard copies),
Speakers (audio output).
● Storage Devices: Used to store data permanently or temporarily.
○ Examples: Hard drives (permanent internal storage), SSDs (faster permanent
storage), Flash drives (portable storage).
● Processing Unit (CPU): The brain of the computer that processes data and executes
instructions.
○ Contains ALU (Arithmetic Logic Unit), CU (Control Unit), and registers.
● Memory Types:
○ RAM (Random Access Memory): Temporary, volatile memory used during
processing.
○ ROM (Read-Only Memory): Permanent, non-volatile memory storing firmware.
○ Cache Memory: Very fast memory located close to the CPU to store frequently
accessed data.
○ EPROM/EEPROM: Types of ROM that can be erased and reprogrammed using
UV light or electricity.
🔹 Memory Types and Features
Memory Speed Word Vola
Type Size tility
ROM Slow Small Fixed Non-
(Read- (depends volati
Only on design) le
Memory)
RAM Very Medium to 8, 16, 32, Volat
(Random Fast Large or 64 bits ile
Access (common)
Memory)
EPROM Slower Small Fixed Non-
(Erasable than volati
Programm ROM le
able ROM) (can
be
eras
ed
with
UV
light)
EEPROM Faster Small Fixed Non-
(Electricall than volati
y Erasable EPROM le
PROM) but (elec
slower tricall
than y
RAM eras
able)
Comments:
● ROM/EPROM/EEPROM are used mainly for firmware and are not designed for frequent
writing.
● RAM is fast and supports large word sizes, making it ideal for system memory during
active processing.
● Word size affects how much data can be processed at once by the CPU.
🔹 Storage Devices and Their Characteristics
Device Access Speed Portability
Hard Very High (up Slow Direct/ Medium
Drives to several TB) (mechanical Sequential (fragile)
(HDDs) movement) access
Solid- High Very Fast (no Direct High
State (hundreds of moving parts) (random
Drives GB to TB) access)
(SSDs)
Flash Medium (few Fast (slower Direct Very High
Drives GB to 1 TB) than SSD) (random (compact and
(USB) access) portable)
Comments:
● HDDs are cheaper per GB but slower due to mechanical parts.
● SSDs offer much faster access speeds, suitable for OS and software loading.
● Flash drives are highly portable but not ideal for long-term or high-frequency writing
compared to SSDs.
2. Types of Computers and Their Uses
● Supercomputers: Extremely powerful, used for scientific simulations, weather
forecasting, and complex computations.
● Mainframes: High-capacity systems used in large organizations for bulk data
processing (e.g., banking systems).
● Minicomputers (Midrange Computers): Smaller than mainframes, used in
manufacturing and small organizations.
● Microcomputers (Personal Computers): Desktops and laptops used for personal or
business tasks.
● Laptops/Notebooks: Portable computers for mobile use.
● PDAs (Personal Digital Assistants): Older handheld devices used for personal
information management.
● Servers: Manage network resources and provide services to other computers (clients).
3. Basic Building Blocks of a Computer
● Logic Gates: Perform basic logical functions using binary input (0 or 1).
○ AND: Outputs 1 if both inputs are 1.
○ OR: Outputs 1 if at least one input is 1.
○ NOT: Outputs the opposite of input.
○ NAND, NOR, XOR, XNOR: Variations used in complex circuits.
● Flip-Flops: Digital circuits that store one bit of data; used in memory and registers.
● Registers: Small storage areas within the CPU for quick data access during processing.
● Counters: Devices that store and count pulses (e.g., clock ticks).
● Multiplexors: Select one input from several and forward it to the output line.
● Encoders: Convert data from one format to another, often reducing the number of input
lines.
● Decoders: Convert coded inputs back to original form or activate specific outputs.
4. Data Representation
● Binary Number System: Base 2 system using digits 0 and 1; used internally by all
digital computers.
● Number Representation:
○ Signed Magnitude: Uses the leftmost bit to indicate the sign (0 = positive, 1 =
negative).
○ One's Complement: Negative numbers are represented by inverting all bits.
○ Two's Complement: Most common method; invert bits and add 1 to get the
negative value.
○ Floating Point: Represents real numbers using a sign bit, mantissa, and
exponent (like scientific notation).
● Character Encoding:
○ ASCII: 7 or 8-bit codes representing characters (e.g., 'A' = 65).
○ Unicode: 16-bit (or more) encoding standard to represent characters in all major
languages.
5. Processor Characteristics
● Components:
○ ALU (Arithmetic Logic Unit): Performs arithmetic and logical operations.
○ CU (Control Unit): Directs the operation of the processor.
○ Registers: Temporarily hold data and instructions during processing.
● Instruction Cycle:
○ Fetch: Retrieve instruction from memory.
○ Decode: Interpret instruction.
○ Execute: Perform the operation.
● Instruction Types:
○ Data Manipulation: Arithmetic/logic instructions.
○ Control: Manage program flow (jumps, calls).
○ Input/Output: Read/write to peripherals.
● Clock Speed: Measured in GHz; determines how many cycles a CPU can execute per
second.
● Cache Memory: Reduces access time by storing frequently used data/instructions close
to the CPU.
🔹 1. CPU Components
Component Function
ALU Performs arithmetic operations (e.g., addition, subtraction) and
(Arithmeti logical operations (e.g., comparisons, AND, OR).
c Logic
Unit)
CU (Control Directs the operation of the processor; fetches, decodes, and
Unit) manages the execution of instructions.
Registers Small, high-speed storage locations within the CPU used to hold
data, instructions, addresses, and results temporarily.
Examples: accumulator, program counter, instruction register.
🔹 2. Instruction Format
Feature Details
Addresses per Instructions can have 0, 1, 2, or 3 addresses depending on the
instruction architecture (e.g., 2-address instruction: add A, B).
Fixed length vs - Fixed-length: All instructions use the same number of bits
Variable (e.g., 32 bits), making decoding simpler.
length
- Variable-length: Instructions use different sizes (e.g., 8, 16,
32 bits), allowing flexibility but requiring more decoding logic.
🔹 3. Instruction Types
Type Purpose
Data Manipulation Arithmetic, logic, shift operations (e.g., ADD, SUB, AND).
Control Instructions Branching, loops, function calls (e.g., JUMP, CALL,
RETURN).
Input/Output Handle communication with input and output devices (e.g.,
Instructions IN, OUT).
🔹 4. Instruction Cycle (Fetch-Decode-Execute Cycle)
1. Fetch: The CPU retrieves the next instruction from memory using the Program Counter
(PC).
2. Decode: The Control Unit interprets the instruction and determines what actions are
needed.
3. Execute: The instruction is carried out — data is processed in the ALU, or memory is
accessed, or an I/O action occurs.
4. (Store, if applicable): The result may be written back to a register or memory.
🔹 5. Performance Characteristics
Feature Explanation
Clock Measured in GHz (e.g., 3.2 GHz), it represents the number of cycles the
Spe CPU can perform per second. Higher speeds generally mean better
ed performance.
Cache Very fast memory located close to or inside the CPU. Stores frequently
Me used data and instructions to speed up processing. Levels: L1 (fastest,
mor smallest), L2, and L3 (larger, slower).
y
MODULE 2: PROBLEM SOLVING WITH COMPUTERS
1. Problem Solving Concept
Problem solving in computer science involves identifying a task, defining it clearly, devising a
strategy to solve it, and implementing that solution using a computer. It is the foundation for
developing algorithms and programs.
2. Stages of Problem Solving
1. Problem Definition: Clearly define what needs to be solved.
2. Analysis: Understand inputs, outputs, constraints, and relationships.
3. Identify & Evaluate Possible Solutions: Brainstorm approaches; compare efficiency.
4. Select Optimal Solution: Choose the most effective and feasible one.
5. Implement & Review: Code the solution and review it for correctness.
3. Algorithms
An algorithm is a finite set of steps or instructions to solve a problem.
● Properties of Good Algorithms:
○ Clearly defined inputs and outputs
○ Unambiguous steps
○ Finite number of steps
○ Efficient and scalable
4. Algorithm Representation
● Narrative: Verbal description of steps in solving the problem.
● Flowcharts: Diagrams showing steps using symbols (e.g., rectangles for processes,
diamonds for decisions).
● Pseudocode: Structured English that mimics code without syntax of a specific
language.
5. Programming Constructs
● Input/Output Statements: Read user input and display results (scanf, printf in C).
● Control Structures:
○ Sequence: Instructions executed in order.
○ Selection: Making decisions using if, else, switch.
○ Iteration: Repeating actions with for, while, do-while.
○ Assignment: Assign values using = operator.
6. Evaluating Algorithms
● Correctness: Does the algorithm solve the intended problem?
● Efficiency: Time and space usage
● Dry Run / Desk Check: Step-by-step tracing of algorithm using sample data to verify
logic and detect errors.
1. Top-Down Approach
Definition:
The top-down approach involves breaking a large, complex problem into smaller sub-
problems or modules, and solving each sub-problem individually.
Explanation:
● You start with a general overview of the problem.
● Then, you divide it into smaller, more manageable parts.
● Each sub-problem is further broken down until each part can be coded directly.
Example:
Creating a school management system:
● Start with the overall system.
● Break it down into modules like: Student Management, Teacher Records, Attendance
Tracking.
● Then divide further, e.g., Student Management → Add Student, Remove
Student, Update Student Info.
Advantages:
● Easier to manage complexity.
● Encourages modular programming and reuse.
● Facilitates team development.
2. Bottom-Up Approach
Definition:
The bottom-up approach builds complex systems by first developing and testing small parts
or modules, then integrating them to form the complete system.
Explanation:
● Start with the smallest, most basic operations.
● Develop and test them independently.
● Then combine them to form larger, more complex components.
Example:
Developing mathematical functions (e.g., square root, power) first, then combining them into a
calculator program.
Advantages:
● Modules are well-tested before integration.
● Focuses on reusability.
● Often useful when reusable components (like libraries) are available.
3. Step-by-Step (Linear) Approach
Definition:
The step-by-step approach involves solving the problem in a sequential manner, one step at
a time, from start to finish.
Explanation:
● The process follows a logical flow from the beginning to the end.
● Each step depends on the result of the previous one.
Example:
A program to calculate the average of 5 numbers:
1. Input numbers.
2. Add them.
3. Divide by 5.
4. Output the result.
Advantages:
● Simple and easy to follow.
● Suitable for small, straightforward problems.
● Good for beginners learning programming logic.
Summary Table
Approac Strategy Best For
h
Top- Break down big problem into Complex systems with many
Down parts features
Bottom- Build from small parts upward Systems with reusable
Up components
Step-by- Solve linearly from start to end Simple, straightforward problems
Step
1. Definition of Problem-Solving
Problem-solving is a systematic process of identifying a problem, analyzing it, developing
possible solutions, selecting the best one, and implementing it to achieve a desired result.
It is a critical skill in computer science and real-life scenarios.
2. Stages in the Problem-Solving Process
Stage Description
1. Problem Definition Clearly understand what the problem is and what the
desired outcome should be.
2. Problem Analysis Break the problem into parts and examine what
inputs, processes, and outputs are involved.
3. Identify and Evaluate Brainstorm different ways to solve the problem and
Possible Solutions consider pros and cons of each.
4. Select and Justify the Choose the best solution based on efficiency, cost,
Optimal Solution time, and feasibility.
5. Implementation Put the chosen solution into action (e.g., write code or
follow procedures).
6. Testing and Review Test to see if the solution works correctly and
efficiently. Review and make improvements.
3. Definition of an Algorithm
An algorithm is a step-by-step, well-defined procedure or set of rules for solving a problem
or completing a task. It serves as a blueprint for programming solutions.
4. Necessary Properties of Well-Designed Algorithms
A good algorithm must have the following properties:
Property Meaning
Clearly defined and Each instruction must be precise and easy to
unambiguous steps understand.
Finite number of steps It must terminate after a limited number of steps.
Well-ordered (flow of control) Steps must follow a logical sequence.
Input defined The algorithm must state the inputs it needs.
Output defined The result of the algorithm must be clearly stated.
General Solution Should be applicable to a class of problems, not
just one instance.
5. Ways of Representing Algorithms
Algorithms can be expressed in:
Representat Description
ion
Narrative A written description of each step in solving the problem.
Form
Flowcharts Diagrams that use symbols (ovals, parallelograms, rectangles,
diamonds) to represent the flow of processes.
Pseudocod A code-like, plain-English version of the logic that mimics real code
e but is not language-specific.
6. Programming Constructs Used to Interpret Algorithms
Construct Function Examples
Input/Output Handle data coming in input age, print total
Statement and results going out.
s
Assignment Stores a value in a sum ← num1 + num2
Statement variable.
Sequencing Instructions are executed Step-by-step flow.
in order.
Selection Chooses between IF, ELSE, SWITCH
(Decision- alternatives.
making)
Iteration Repeats steps either a <ul><li>Bounded (e.g., FOR i = 1
(Repetitio fixed number of times TO 10)</li><li>Unbounded (e.g.,
n) or until a condition is WHILE input ≠ -1)</li></ul>
met.
🔁 1. FOR Loop (Bounded Iteration)
Definition:
A FOR loop repeats a block of code a specific (known) number of times.
Format in Pseudocode:
pgsql
CopyEdit
FOR counter ← start TO end DO
<statements>
END FOR
Example:
vbnet
CopyEdit
FOR i ← 1 TO 5 DO
PRINT "Welcome"
END FOR
Explanation:
● Prints "Welcome" 5 times.
● The number of repetitions is known → this is bounded iteration.
🔁 2. WHILE Loop (Unbounded Iteration)
Definition:
A WHILE loop repeats as long as a condition is true. The number of repetitions is not known
in advance.
Format in Pseudocode:
vbnet
CopyEdit
WHILE condition DO
<statements>
END WHILE
Example:
vbnet
CopyEdit
SET count ← 0
WHILE count < 3 DO
PRINT "Hello"
count ← count + 1
END WHILE
Explanation:
● Repeats while count < 3.
● The loop ends when the condition becomes false.
● This is unbounded because the number of repetitions depends on the condition, not a
fixed number.
🔁 3. REPEAT...UNTIL Loop (Unbounded Iteration)
Definition:
A REPEAT...UNTIL loop continues until a specific condition becomes true. It always runs
at least once.
Format in Pseudocode:
php-template
CopyEdit
REPEAT
<statements>
UNTIL condition
Example:
typescript
CopyEdit
REPEAT
INPUT number
UNTIL number > 0
Explanation:
● The loop keeps asking for input until a positive number is entered.
● This is unbounded because we don’t know how many times the user might enter
negative numbers.
Summary Table
Loop Type Format Example Bounded/ Runs At Least
Unbounded Once?
FOR FOR i ← 1 TO 5 DO Bounded No
WHILE WHILE condition Unbounded No
DO
REPEAT...UN REPEAT ... UNTIL Unbounded Yes
TIL condition
7. Determining Output and Correctness of an Algorithm
To check correctness:
● Trace the algorithm with test inputs.
● Check whether the output matches the expected result.
● Confirm that all conditions and loops behave as intended.
● Use tools like desk checking, dry runs, or trace tables.
Algorithms in any form (narrative, flowchart, or pseudocode) should always produce:
● The correct output.
● In a finite amount of time.
● With clear logic and no ambiguity.
MODULE 3: PROGRAMMING
1. Programming Paradigms
● Procedural (Imperative): C, Pascal
● Object-Oriented: Java, Python
● Functional: Haskell
● Declarative: SQL, Prolog
2. Translation of High-Level Languages
● Assembler: Translates assembly language
● Compiler: Translates entire program at once
● Interpreter: Executes line-by-line
● Virtual Machine: Executes bytecode (e.g., Java)
● Translation Process:
Lexical Analysis
● Definition: This is the first stage of translation where the source code is scanned
to break it into meaningful sequences called tokens (e.g., keywords, operators,
identifiers).
● Processes:
○ Removes whitespace and comments.
○ Detects invalid characters or symbols.
● Output: A stream of tokens passed to the next stage.
● Example: Breaking int x = 10; into tokens: int, x, =, 10, ;.
Syntax Analysis
● Definition: This stage parses the tokens into a hierarchical structure called a
syntax tree based on the grammar of the programming language.
● Processes:
○ Ensures the code adheres to syntactical rules.
○ Detects syntax errors like a missing semicolon or misplaced braces.
● Output: A syntax tree representing the program structure.
● Example: Ensuring if (x > 0) { print(x); } is correctly structured.
Semantic Analysis
● Definition: This stage ensures the code makes logical sense beyond syntax,
focusing on the meaning of constructs.
● Processes:
○ Type checking (e.g., ensuring int x = "string"; is invalid).
○ Ensuring all variables are declared before use.
○ Checking for scope violations.
● : A validated syntax tree or intermediate representation.
● Example: Ensuring that x / y doesn’t divide by zero.
Code Generation and Optimization
Definition:
○ Code Generation: Produces machine code or assembly code from the
intermediate representation.
○ Code Optimization: Enhances the intermediate code or final machine code
for efficiency (e.g., reducing runtime or memory usage).
Processes:
○ Intermediate Code Generation: Converts validated code into a simpler,
platform-independent representation.
○ Optimization: Removes redundant operations, minimizes resource usage.
Output: Optimized machine code ready for execution.
Example: Translating x = (a + b) * c; into efficient assembly instructions for
the processor.
● 3. Programming Fundamentals
● Variables: Store data
● Data Types: int, float, char, string, bool
● Input/Output: scanf, printf (in C)
4. Control Structures
● Conditionals: if, else, switch
● Loops: for, while, do-while
● Nested Structures: Combine loops and conditions
5. Arrays and Strings
● Arrays: One-dimensional arrays for storing multiple values
● Strings: Arrays of characters, terminated by '\0'
6. Functions and Structured Programming
● Functions: Modular code, takes parameters and returns values
● Decomposition: Break large problems into smaller functions
7. File Handling
● Operations: Open, read, write, append, close
● Types: Text files, binary files
8. Good Programming Practices
● Style: Indentation, meaningful variable names
● Comments: Explain code
● Testing: Use test plans, trace tables, debug systematically
1. Programming Paradigms and Their Characteristics
a. Procedural / Imperative
● Focuses on procedures or routines.
● Follows step-by-step instructions.
● Uses control structures: sequence, selection, iteration.
● E.g., C, Pascal.
b. Object-Oriented (OOP)
● Based on "objects" which contain data (fields) and methods.
● Supports encapsulation, inheritance, polymorphism.
● E.g., Java, C++, Python.
c. Functional
● Computation is treated as the evaluation of mathematical functions.
● Avoids changing state and mutable data.
● E.g., Haskell, Lisp.
d. Declarative
● Focuses on what the program should accomplish rather than how.
● Includes logic and functional paradigms.
● E.g., SQL, Prolog.
e. Scripting
● Simplified syntax for automating tasks.
● Interpreted at runtime.
● E.g., JavaScript, Python, Bash.
f. Aspect-Oriented
● Separates cross-cutting concerns (e.g., logging, security).
● Works with other paradigms.
● E.g., AspectJ.
Appropriateness to Application
● Web apps: JavaScript, Python, PHP.
● Games: C++, C#, Unity.
● Mobile apps: Swift (iOS), Kotlin (Android).
● Formula translation: FORTRAN.
2. Why Different Programming Languages Are Needed
● Different applications require different features.
● Performance, readability, abstraction, platform compatibility.
● Ease of development, maintenance, community support.
3. Execution of High-Level Programming Languages
a. Assembler
● Converts assembly language to machine code.
b. Compiler
● Translates high-level code to machine code.
● Performs optimization.
c. Interpreter
● Executes code line-by-line.
● Slower but easier for debugging.
d. Virtual Machine
● Executes bytecode (e.g., Java Virtual Machine).
● Platform independent.
4. Stages in the Translation Process
1. Lexical Analysis: Tokenizes source code.
2. Syntax Analysis: Checks code structure (grammar).
3. Semantic Analysis: Ensures logic makes sense.
4. Intermediate Code Generation: Converts code to intermediate form.
5. Code Optimization: Improves efficiency.
6. Code Generation: Produces final machine code.
Preprocessors: Handle directives (e.g., #include). Linkers: Combine multiple object files into
one executable.
5. Basic Programming Skills
a. Variables
● Declare variables with meaningful names.
● Use appropriate primitive data types: int, float, double, char, enum.
b. Input/Output
● Input: INPUT, cin, scanf().
● Output: PRINT, cout, printf().
● Include headings, formatting.
c. Arrays
● Declare and initialize arrays.
● Input/output using loops.
● Modify elements.
● Character arrays (strings) for text.
d. Control Constructs
● Conditional: IF, IF-ELSE, SWITCH.
● Iteration:
○ FOR (bounded)
○ WHILE (unbounded)
○ REPEAT...UNTIL (unbounded, at least once)
6. Structured Decomposition
● Break complex programs into smaller subprograms.
● Easier to debug and maintain.
7. Algorithms and Problem Solving
● Use algorithms (e.g., searching, sorting).
● Implement using appropriate data structures.
8. Records and Files
a. Records
● Group related information (e.g., student with name, ID, grades).
b. Text Files
● Store data persistently.
● Operations: open, read, write, append, close.
9. Functions and Good Programming Style
● Write simple, reusable functions.
● Keep code clear, modular, orthogonal (independent blocks).
● Use comments, indentation, whitespace.
10. Testing and Debugging
● Errors:
○ Syntax: language rule violations.
○ Semantic: logic errors.
● Strategies:
○ Desk checks.
○ Trace tables.
○ Debuggers with "watch" on variables.
○ Use range tests.
11. struct in C
● Used to define a record:
struct Student {
int id;
char name[20];
float grade;
};