Study Notes BE Computer System Engineering At Dawood University is a rewarding experience that will open doors to numerous career opportunities in the field of technolog.Dawood University of Engineering and Technology is a prestigious institution known for its quality education and research facilities in the field of engineering. The faculty members are experts in their respective fields and provide hands-on training to prepare students for real-world challenges.
Study Notes BE Computer System Engineering At Dawood University.
CSE-1501: Computing Fundamentals – Comprehensive Study Notes
These notes provide a complete framework for Computing Fundamentals, covering the foundational concepts of computer systems, hardware, software, data representation, programming basics, and computational thinking. This course is typically designed for students from diverse academic backgrounds who need a solid grounding in computing principles before advancing to more specialized courses.
Part 1: Introduction to Computing
1.1 What is a Computer?
A computer is an electronic device that accepts data (input), processes it according to stored instructions, produces information (output), and stores results for future use. Modern computers are characterized by their speed, accuracy, diligence, versatility, and storage capacity.
1.2 Characteristics of Computers
| Characteristic | Description |
|---|---|
| Speed | Computers process millions to billions of instructions per second |
| Accuracy | Errors are typically due to human input or programming, not hardware |
| Diligence | Computers can work continuously without fatigue |
| Versatility | Can perform diverse tasks (word processing, gaming, scientific computing) |
| Storage | Vast amounts of data can be stored and retrieved instantly |
| Automation | Once programmed, computers execute tasks automatically |
1.3 Limitations of Computers
Despite their power, computers have inherent limitations:
-
No intelligence: They follow instructions blindly; they cannot think or reason independently
-
No emotional intelligence: Cannot understand feelings or make value judgments
-
Garbage In, Garbage Out (GIGO) : Output quality depends entirely on input quality
-
Dependency on power and programming: Cannot function without electricity or instructions
Part 2: Computer Hardware
2.1 Basic Hardware Components
Every computer system requires hardware—the physical, touchable components that make up the machine. The basic model follows the input-processing-output-storage paradigm:
Input Devices → System Unit (Processing) → Output Devices
↓
Storage Devices
2.2 Input Devices
Input devices allow users to enter data and commands into a computer.
| Device | Description | Common Uses |
|---|---|---|
| Keyboard | Primary text input device | Typing documents, data entry |
| Mouse | Pointing and selection device | Navigation, clicking, dragging |
| Touchscreen | Touch-sensitive display | Mobile devices, kiosks |
| Scanner | Converts physical documents to digital images | Document digitization, OCR |
| Microphone | Captures audio input | Voice commands, recording |
| Webcam | Captures video input | Video conferencing, streaming |
| Biometric devices | Reads biological characteristics | Fingerprint scanners, facial recognition |
2.3 Output Devices
Output devices display or present processed information to users.
| Device | Description | Common Uses |
|---|---|---|
| Monitor/Display | Visual output | Viewing documents, images, video |
| Printer | Paper output | Documents, photos, reports |
| Speakers/Headphones | Audio output | Music, notifications, calls |
| Projector | Large-screen display | Presentations, classrooms |
2.4 The System Unit
The system unit houses the main electronic components of a computer. Understanding these components is crucial for grasping how computers operate at a fundamental level.
Major Components Inside the System Unit:
| Component | Function |
|---|---|
| Motherboard | Main circuit board connecting all components |
| Central Processing Unit (CPU) | “Brain” of the computer; executes instructions |
| Memory (RAM) | Temporary storage for active programs and data |
| Storage Drives | Permanent storage (HDD, SSD) |
| Power Supply | Converts AC power to DC for components |
| Expansion Cards | Add functionality (graphics, sound, network) |
| Cooling System | Fans and heat sinks to prevent overheating |
2.5 The Central Processing Unit (CPU)
The CPU is the “brain” of the computer—it performs all calculations and executes instructions. A typical introductory computing course covers CPU fundamentals including its components, the fetch-execute cycle, and factors affecting performance .
CPU Components:
-
Control Unit (CU) : Directs the flow of instructions
-
Arithmetic Logic Unit (ALU) : Performs mathematical and logical operations
-
Registers: High-speed temporary storage within the CPU
-
Cache Memory: Very fast memory for frequently used data
The Fetch-Execute Cycle:
-
Fetch: The control unit retrieves the next instruction from memory
-
Decode: The instruction is interpreted to determine what operation to perform
-
Execute: The ALU performs the operation
-
Store: Results are written back to memory or registers
CPU Performance Factors:
-
Clock speed (GHz) – number of cycles per second
-
Number of cores – multiple processing units within one CPU
-
Cache size – larger cache means faster access to frequent data
-
Instruction set architecture (32-bit vs. 64-bit)
2.6 Memory and Storage
Understanding the memory hierarchy is crucial for comprehending computer performance.
| Type | Speed | Volatility | Purpose |
|---|---|---|---|
| CPU Registers | Fastest | Volatile | Immediate data for calculations |
| Cache Memory (L1, L2, L3) | Very fast | Volatile | Frequently accessed instructions/data |
| RAM (Random Access Memory) | Fast | Volatile | Active programs and data |
| ROM (Read-Only Memory) | Moderate | Non-volatile | Firmware, boot instructions |
| SSD (Solid State Drive) | Moderate | Non-volatile | Operating system, applications |
| HDD (Hard Disk Drive) | Slower | Non-volatile | Mass file storage |
| Cloud Storage | Network-dependent | Non-volatile | Off-site backup, file sharing |
RAM vs. ROM:
-
RAM: Temporary, loses data when power off, read/write capability
-
ROM: Permanent, retains data without power, primarily read-only
2.7 Storage Devices and Media
Storage devices hold data permanently or semi-permanently.
Magnetic Storage:
-
Hard Disk Drives (HDDs) – Large capacity, lower cost, mechanical parts
Solid-State Storage:
-
SSDs, USB flash drives, memory cards – Faster, no moving parts, more durable
Optical Storage:
-
CDs (700 MB), DVDs (4.7-8.5 GB), Blu-ray (25-50 GB) – Read/write with lasers
Cloud Storage:
-
Google Drive, OneDrive, Dropbox – Internet-based storage accessible from anywhere
Part 3: Computer Software
3.1 System Software vs. Application Software
Software is the set of instructions that tells hardware what to do. Computer Science I courses typically introduce the distinction between system software and application software, along with fundamental programming concepts .
| Type | Definition | Examples |
|---|---|---|
| System Software | Manages hardware and provides platform for applications | Operating systems, drivers, utilities |
| Application Software | Performs specific tasks for users | Word processors, browsers, games |
3.2 Operating Systems
The operating system (OS) is the most important system software. Introductory courses often use programming in a modern high-level language to illustrate how software interacts with the OS .
Functions of an Operating System:
-
Process Management: Manages running programs
-
Memory Management: Allocates RAM to programs
-
File System Management: Organizes data on storage devices
-
Device Management: Controls hardware through drivers
-
User Interface: Provides way for users to interact (GUI or command-line)
-
Security: Manages user accounts and permissions
Common Operating Systems:
| OS | Developer | Primary Use | Key Characteristics |
|---|---|---|---|
| Windows | Microsoft | PCs, laptops, servers | Most common, broad software support |
| macOS | Apple | Mac computers | User-friendly, creative applications |
| Linux | Open source | Servers, developers | Free, customizable, secure |
| Android | Mobile devices | Most common mobile OS | |
| iOS | Apple | iPhones, iPads | Integrated Apple ecosystem |
3.3 Programming Languages
Programming languages are the tools used to create software. Computing fundamentals courses often introduce the concepts of algorithm development, stepwise refinement, and elementary programming constructs .
Levels of Programming Languages:
| Level | Description | Examples |
|---|---|---|
| Machine Language | Binary code (0s and 1s) directly executed by CPU | 10110000 01100001 |
| Assembly Language | Human-readable mnemonics for machine instructions | MOV AL, 61h |
| High-Level Language | English-like syntax; compiled/interpreted to machine code | Python, Java, C++, JavaScript |
Programming Paradigms:
| Paradigm | Description | Languages |
|---|---|---|
| Procedural | Programs structured as sequences of procedures/functions | C, Pascal |
| Object-Oriented | Programs organized around objects containing data and methods | Java, C++, Python |
| Functional | Programs built around mathematical functions | Haskell, Lisp |
| Scripting | Programs written for automating tasks | Python, JavaScript, Bash |
3.4 Programming Fundamentals
Key Programming Concepts:
-
Variables: Named storage locations for data with specific data types
-
Data Types: Classification of data (integers, floats, characters, strings, booleans)
-
Control Structures: Mechanisms for controlling program flow (sequence, selection, iteration)
-
Functions/Procedures: Reusable blocks of code that perform specific tasks
-
Input/Output: Reading data from and writing data to external sources
Control Structures:
-
Sequence: Instructions executed in order
-
Selection (Branching) : Decision-making using
if,else,switch -
Iteration (Loops) : Repetition using
for,while,do-while
Part 4: Data Representation
4.1 Number Systems
Computers use the binary number system (base-2) because they operate using two states: on (1) and off (0).
| Number System | Base | Digits | Computer Relevance |
|---|---|---|---|
| Binary | 2 | 0, 1 | Native language of computers |
| Octal | 8 | 0-7 | Compact representation of binary |
| Decimal | 10 | 0-9 | Human-preferred system |
| Hexadecimal | 16 | 0-9, A-F | Compact, easier for programmers |
4.2 Converting Between Number Systems
Binary to Decimal:
Multiply each binary digit by 2 raised to its position power (from right, starting at 0).
Example: 10112=(1×23)+(0×22)+(1×21)+(1×20)=8+0+2+1=1110
Decimal to Binary:
Repeatedly divide by 2, recording remainders from bottom to top.
Example: 1310=11012
Binary to Hexadecimal:
Group binary into sets of 4 bits (nibbles), convert each group to hex digit.
Example: 110111102=(1101)(1110)=DE16
4.3 Data Storage Units
| Unit | Abbreviation | Size (bytes) | Approximate |
|---|---|---|---|
| Bit | b | 1/8 | Binary digit (0 or 1) |
| Byte | B | 1 | One character |
| Kilobyte | KB | 1,024 | Half a page of text |
| Megabyte | MB | 1,048,576 | One photo |
| Gigabyte | GB | ~1.07 × 10⁹ | One hour of video |
| Terabyte | TB | ~1.10 × 10¹² | 200,000 photos |
| Petabyte | PB | ~1.13 × 10¹⁵ | 500 billion pages of text |
4.4 Binary Representation of Negative Numbers
Two’s Complement is the most common method for representing signed integers in computers.
For 8-bit representation of -5:
-
5 in binary: 00000101
-
Invert all bits (one’s complement): 11111010
-
Add 1: 11111011 (-5)
Two’s complement advantage: Allows addition and subtraction using the same hardware as unsigned numbers, with a single representation for zero.
4.5 Character Encoding
ASCII (American Standard Code for Information Interchange) :
-
7-bit code (extended to 8-bit) for representing characters
-
128 standard characters (0-127)
| Character | ASCII (Decimal) | ASCII (Binary) |
|---|---|---|
| ‘A’ | 65 | 1000001 |
| ‘a’ | 97 | 1100001 |
| ‘0’ | 48 | 0110000 |
| Space | 32 | 0100000 |
Unicode: Extended character encoding supporting over 140,000 characters from all world languages, emojis, and symbols.
Part 5: Computer Networks
5.1 What is a Computer Network?
A computer network is two or more computers connected to share resources and communicate.
Benefits of Networking:
-
Resource sharing (printers, scanners, storage)
-
Communication (email, messaging, video calls)
-
Centralized data management
-
Collaboration tools
-
Internet access sharing
5.2 Types of Networks
| Type | Coverage | Description | Examples |
|---|---|---|---|
| PAN (Personal Area Network) | Within person’s reach | Bluetooth devices | Phone ↔ headset |
| LAN (Local Area Network) | Single building/campus | Connects computers in office, school | Office network |
| MAN (Metropolitan Area Network) | City-wide | Connects multiple buildings | University campus |
| WAN (Wide Area Network) | Country/global | Largest network type | The Internet |
5.3 The Internet and World Wide Web
Internet vs. World Wide Web:
| Internet | World Wide Web (WWW) | |
|---|---|---|
| Definition | Global network infrastructure | Information system on the internet |
| Analogy | The roads and highways | The vehicles and deliveries |
| Components | Routers, cables, servers, protocols | Web pages, websites, hyperlinks |
| Protocol | TCP/IP | HTTP/HTTPS |
5.4 Basic Internet Protocols
| Protocol | Full Name | Function |
|---|---|---|
| IP | Internet Protocol | Provides addressing and routing |
| TCP | Transmission Control Protocol | Reliable, connection-oriented delivery |
| UDP | User Datagram Protocol | Faster, connectionless delivery |
| HTTP/HTTPS | Hypertext Transfer Protocol (Secure) | Web page transfer |
| FTP | File Transfer Protocol | File upload/download |
| SMTP | Simple Mail Transfer Protocol | Sending email |
| DNS | Domain Name System | Domain to IP translation |
5.5 Network Hardware
| Device | Function |
|---|---|
| Network Interface Card (NIC) | Connects computer to network (wired or wireless) |
| Modem | Converts between digital computer signals and analog phone/cable signals |
| Router | Connects multiple networks; directs traffic between them |
| Switch | Connects devices on same network; forwards data to specific devices |
| Access Point | Provides wireless connectivity to wired network |
Part 6: Computational Thinking and Algorithms
6.1 What is an Algorithm?
An algorithm is a finite sequence of well-defined, unambiguous instructions for solving a specific problem. Algorithm development is a core component of computing fundamentals courses, emphasizing problem-solving approaches before implementation .
Properties of Algorithms:
| Property | Description |
|---|---|
| Input | Zero or more externally supplied values |
| Output | At least one value produced |
| Definiteness | Each instruction is clear and unambiguous |
| Finiteness | Algorithm terminates after a finite number of steps |
| Effectiveness | Instructions are basic enough to be carried out |
6.2 Computational Thinking
Computational thinking is the problem-solving approach that involves:
-
Decomposition: Breaking a complex problem into smaller, manageable parts
-
Pattern Recognition: Identifying similarities within and across problems
-
Abstraction: Focusing on essential information while ignoring irrelevant details
-
Algorithm Design: Developing step-by-step solutions
6.3 Algorithm Representation
Flowcharts: Visual representation of algorithms using standardized symbols
| Symbol | Shape | Meaning |
|---|---|---|
| Terminator | Oval | Start/End |
| Process | Rectangle | Operation/Assignment |
| Decision | Diamond | Conditional branch |
| Input/Output | Parallelogram | Read/Write data |
| Connector | Circle | Connects flowchart sections |
Pseudocode: Informal, human-readable algorithm description using natural language and programming conventions
6.4 Basic Algorithms
Search Algorithms:
| Algorithm | Description | Time Complexity |
|---|---|---|
| Linear Search | Check each element sequentially until target found | O(n) |
| Binary Search | Repeatedly divide sorted array in half | O(log n) |
Sorting Algorithms:
| Algorithm | Description | Best Case | Average Case | Worst Case |
|---|---|---|---|---|
| Bubble Sort | Repeatedly swap adjacent elements if out of order | O(n) | O(n²) | O(n²) |
| Selection Sort | Repeatedly select minimum and place at beginning | O(n²) | O(n²) | O(n²) |
| Insertion Sort | Build sorted array one element at a time | O(n) | O(n²) | O(n²) |
Part 7: Ethics and Security
7.1 Computer Ethics
Digital Citizenship: Using technology responsibly, ethically, and safely.
Key Ethical Issues:
-
Privacy: Protection of personal information
-
Intellectual Property: Respect for copyright and software licensing
-
Cyberbullying: Using digital devices to harass others
-
Digital Divide: Gap between those with and without technology access
7.2 Information Security
The CIA Triad (three core principles of information security):
| Principle | Definition | Example |
|---|---|---|
| Confidentiality | Ensuring only authorized parties can access information | Encryption, passwords |
| Integrity | Ensuring information is accurate and unaltered | Checksums, access controls |
| Availability | Ensuring information is accessible when needed | Backups, redundancy |
7.3 Common Cyber Threats
Malware Types:
| Type | Description | Signs |
|---|---|---|
| Virus | Attaches to legitimate programs; spreads when executed | Slow performance, crashes |
| Worm | Self-replicates without attaching to programs; spreads via networks | Network slowdown |
| Trojan Horse | Disguised as legitimate software; performs malicious actions | Unexpected behavior |
| Ransomware | Encrypts files; demands payment for decryption | Inaccessible files |
| Spyware | Secretly monitors user activity | Slow performance, unexpected ads |
Protection Measures:
-
Strong, unique passwords for each account
-
Two-factor authentication (2FA)
-
Antivirus/Antimalware software
-
Regular software updates
-
Data backups (3-2-1 rule)
-
Email caution (don’t click suspicious links)
Part 8: Key Formulas and Concepts Summary
| Concept | Formula/Description |
|---|---|
| Binary to Decimal | ∑(biti×2i) |
| Two’s complement | Invert bits + 1 |
| Data storage units | 1 KB = 1024 bytes, 1 MB = 1024 KB, etc. |
| Linear search complexity | O(n) |
| Binary search complexity | O(log n) |
| Bubble sort complexity | O(n²) |
| RAM vs. ROM | Volatile vs. non-volatile |
| CPU fetch-execute cycle | Fetch → Decode → Execute → Store |
Part 9: Study Tips for CSE-1501
-
Understand the hardware-software relationship – Software tells hardware what to do; hardware provides the physical platform for software execution.
-
Master binary and hexadecimal – Practice converting between number systems. This is fundamental to understanding how computers represent data.
-
Learn the fetch-execute cycle – The CPU’s operation cycle (Fetch → Decode → Execute → Store) is the foundation of computer operation.
-
Practice algorithm design – Before writing code, practice creating flowcharts and pseudocode. This develops computational thinking skills emphasized in introductory CS courses .
-
Know the difference between memory and storage – RAM is temporary (volatile) and fast; storage drives are permanent (non-volatile) and slower.
-
Understand basic programming concepts – Variables, data types, control structures (sequence, selection, iteration), and functions form the building blocks of all programs.
-
Connect to real-world applications – Relate each concept to practical applications (e.g., networks to internet browsing, security to online banking).
-
Create a glossary of terms – Computing has extensive terminology; maintaining a glossary helps with retention.
Part 10: Recommended Resources
| Resource | Focus |
|---|---|
| Computer Science Illuminated – Dale & Lewis | Comprehensive introduction |
| Code: The Hidden Language of Computer Hardware and Software – Petzold | Accessible explanations |
| Structure and Interpretation of Computer Programs – Abelson & Sussman | Advanced fundamentals |
| Khan Academy – Computer Science | Free online tutorials |
| Codecademy – Learn the Basics | Interactive programming exercises |
These notes provide a comprehensive framework for CSE-1501: Computing Fundamentals. Success requires understanding hardware components (CPU, memory, storage, input/output), mastering data representation (binary, hexadecimal, character encoding), learning basic programming concepts (algorithms, control structures, data types), and developing computational thinking skills (decomposition, pattern recognition, abstraction, algorithm design). This course builds the foundation for all subsequent computing and programming courses .
CSE-1101: Basic Electronics & Circuits
Here are detailed study notes for CSE-1101: Basic Electronics & Circuits, written from a Computer Science/Engineering perspective. These notes cover the fundamental principles of electronics and circuits—basic electrical quantities, circuit analysis, passive components, semiconductor devices, diodes, transistors, operational amplifiers, and digital logic fundamentals. The emphasis is on understanding how electronic circuits work and how they form the foundation of modern computing systems.
1. Introduction to Electronics
1.1. What is Electronics?
Electronics is the branch of physics and engineering that deals with the behavior, control, and movement of electrons in semiconductors, vacuum tubes, and other devices. Unlike electrical engineering (which focuses on power generation and distribution), electronics focuses on signal processing, amplification, switching, and computation.
The Core Question: How do we control the flow of electrons in semiconductors to create amplifiers, switches, logic gates, and complex integrated circuits?
1.2. Electronics in Computer Science
| Application | Electronic Components | Purpose |
|---|---|---|
| Processors | Transistors (billions) | Computation |
| Memory | Transistors, capacitors | Data storage |
| Power Supply | Diodes, transformers, capacitors | Voltage regulation |
| I/O Interfaces | Transistors, optocouplers | Signal conversion |
| Clocks/Timers | Crystals, oscillators | Timing |
| Sensors | Diodes, transistors, MEMS | Input devices |
1.3. Basic Electrical Quantities
| Quantity | Symbol | Unit | Unit Symbol | Definition |
|---|---|---|---|---|
| Voltage | V | Volt | V | Potential energy per unit charge |
| Current | I | Ampere | A | Rate of charge flow |
| Resistance | R | Ohm | Ω | Opposition to current |
| Capacitance | C | Farad | F | Charge storage capability |
| Inductance | L | Henry | H | Magnetic energy storage |
| Power | P | Watt | W | Energy per unit time |
| Frequency | f | Hertz | Hz | Cycles per second |
2. Basic Circuit Analysis
2.1. Ohm’s Law
The fundamental relationship between voltage, current, and resistance:
V=IRI=VRR=VI
2.2. Kirchhoff’s Laws
Kirchhoff’s Current Law (KCL):
The algebraic sum of currents entering a node is zero.
∑Iin=∑Iout
Kirchhoff’s Voltage Law (KVL):
The algebraic sum of voltages around any closed loop is zero.
∑V=0
2.3. Series Circuits
R1 ── R2 ── R3
| Property | Formula |
|---|---|
| Total Resistance | RT=R1+R2+R3 |
| Current | IT=I1=I2=I3 |
| Voltage Division | Vx=VT×RxRT |
2.4. Parallel Circuits
┌─ R1 ─┐
├─ R2 ─┤
└─ R3 ─┘
| Property | Formula |
|---|---|
| Total Resistance | 1RT=1R1+1R2+1R3 |
| Voltage | VT=V1=V2=V3 |
| Current Division | Ix=IT×RTRx |
2.5. Power in Circuits
P=VI=I2R=V2R
Units: 1 Watt = 1 Joule/second
Energy:
E=P×t(Joules or Watt-seconds)
2.6. Circuit Analysis Methods
Mesh Analysis (Loop Current Method):
-
Identify independent loops
-
Assign mesh currents
-
Apply KVL to each mesh
-
Solve simultaneous equations
Nodal Analysis (Node Voltage Method):
-
Identify nodes (choose reference node)
-
Assign node voltages
-
Apply KCL at each node
-
Solve simultaneous equations
3. Passive Components
3.1. Resistors
Resistors oppose current flow and dissipate energy as heat.
Resistor Color Code:
| Color | Digit | Multiplier | Tolerance |
|---|---|---|---|
| Black | 0 | ×1 | — |
| Brown | 1 | ×10 | ±1% |
| Red | 2 | ×100 | ±2% |
| Orange | 3 | ×1,000 | — |
| Yellow | 4 | ×10,000 | — |
| Green | 5 | ×100,000 | ±0.5% |
| Blue | 6 | ×1,000,000 | ±0.25% |
| Violet | 7 | — | ±0.1% |
| Gray | 8 | — | — |
| White | 9 | — | — |
| Gold | — | ×0.1 | ±5% |
| Silver | — | ×0.01 | ±10% |
Example: Red-Red-Brown-Gold = 22 × 10 = 220Ω ±5%
Resistor Types:
| Type | Characteristics | Application |
|---|---|---|
| Carbon composition | High noise, inexpensive | General purpose |
| Carbon film | Low noise, stable | General purpose |
| Metal film | Very low noise, precise | Precision circuits |
| Wirewound | High power | Power supplies |
| Surface mount (SMD) | Small size | PCBs |
3.2. Capacitors
Capacitors store energy in an electric field.
C=QV
Capacitance Formula (Parallel Plate):
C=εAd
Current-Voltage Relationship:
iC=CdvCdtvC=1C∫iCdt+vC(0)
Energy Stored:
E=12CV2=12Q2C
Capacitor Types:
| Type | Characteristics | Capacitance Range |
|---|---|---|
| Ceramic | Small, inexpensive | 1 pF – 1 μF |
| Electrolytic | High capacitance, polarized | 1 μF – 10,000 μF |
| Tantalum | Stable, polarized | 0.1 μF – 1000 μF |
| Film | Low loss, stable | 1 nF – 100 μF |
Capacitors in Series:
1CT=1C1+1C2+1C3
Capacitors in Parallel:
CT=C1+C2+C3
3.3. Inductors
Inductors store energy in a magnetic field.
L=N2μAl
Voltage-Current Relationship:
vL=LdiLdtiL=1L∫vLdt+iL(0)
Energy Stored:
E=12LI2
Inductor Types:
| Type | Core Material | Application |
|---|---|---|
| Air core | Air | High frequency |
| Iron core | Iron | Power applications |
| Ferrite core | Ferrite | Switching supplies |
| Toroidal | Ring-shaped core | High efficiency |
Inductors in Series:
LT=L1+L2+L3
Inductors in Parallel:
1LT=1L1+1L2+1L3
3.4. Transformers
Transformers transfer energy between circuits through magnetic induction.
Ideal Transformer Equations:
VpVs=NpNs=aIpIs=NsNp=1aVpIp=VsIs(power in = power out)
4. RC and RL Circuits (Time Response)
4.1. RC Circuits
Charging a Capacitor (RC circuit with DC source):
vC(t)=V(1−e−t/RC)i(t)=VRe−t/RC
Time Constant: τ=RC (seconds)
-
At t=τ: 63.2% charged
-
At t=3τ: 95% charged
-
At t=5τ: 99.3% charged (steady state)
Discharging a Capacitor:
vC(t)=V0e−t/RCi(t)=−V0Re−t/RC
4.2. RL Circuits
Current build-up in inductor:
iL(t)=VR(1−e−Rt/L)vL(t)=Ve−Rt/L
Time Constant: τ=L/R (seconds)
Current decay:
iL(t)=I0e−Rt/LvL(t)=−I0Re−Rt/L
5. Semiconductor Physics
5.1. Intrinsic Semiconductors
Silicon (Si): 4 valence electrons (Group IV)
-
Crystal structure: Diamond cubic
-
Band gap (Si): 1.12 eV
-
Band gap (Ge): 0.67 eV
Electron-Hole Pair Generation:
-
At absolute zero: insulator (no free electrons)
-
At room temperature: thermal energy excites electrons to conduction band
-
Creates free electrons and holes (positive charge carriers)
5.2. Extrinsic Semiconductors (Doping)
N-type (Donor Doping):
-
Add Group V elements (Phosphorus, Arsenic)
-
Extra free electrons (majority carriers)
-
Holes (minority carriers)
P-type (Acceptor Doping):
-
Add Group III elements (Boron, Aluminum)
-
Holes (majority carriers)
-
Electrons (minority carriers)
5.3. Carrier Concentrations
Intrinsic carrier concentration (Si at 300K):
ni≈1.5×1010 cm−3
N-type:
nn≈ND(majority)pn≈ni2ND(minority)
P-type:
pp≈NA(majority)np≈ni2NA(minority)
6. Diodes
6.1. PN Junction Diode
A PN junction diode allows current to flow in only one direction.
Structure:
P-type (Anode) ───┼─── N-type (Cathode)
│
Depletion region
I-V Characteristic:
Current (I)
↑
| Forward bias
| (conducting)
| /
| /
| /
|_____/_______→ Voltage (V)
| \
| \
| \
| Reverse bias (blocking)
|
Forward Bias: P positive, N negative → current flows
Reverse Bias: P negative, N positive → no current (except leakage)
6.2. Diode Equation
I=IS(eVnVT−1)
Where:
-
IS = reverse saturation current
-
n = ideality factor (1 for ideal, 1-2 for real)
-
VT=kTq≈25 mV at 300K (thermal voltage)
Simplified Model:
-
Forward voltage drop: VF≈0.7V (Si), 0.3V (Ge), 0.2V (Schottky)
6.3. Diode Applications
Rectifier Circuits:
| Type | Circuit | Output | Ripple |
|---|---|---|---|
| Half-wave | Single diode | Pulsating DC | High |
| Full-wave (center-tap) | 2 diodes | Full-wave DC | Medium |
| Full-wave (bridge) | 4 diodes | Full-wave DC | Medium |
Rectifier Calculations:
VDC=2Vmπ≈0.637Vm(half-wave)VDC=2Vmπ≈0.637Vm(full-wave)Ripple factor=Vrms,acVDC=143fRC
Other Diode Applications:
-
Clipper circuits: Remove portions of waveform
-
Clamper circuits: Add DC offset
-
Voltage multiplier: Generate high DC voltages
-
Protection diodes: Prevent reverse voltage damage
6.4. Special-Purpose Diodes
| Type | Symbol | Characteristics | Applications | |
|---|---|---|---|---|
| Zener Diode | ——— | —— | Maintains constant voltage in reverse breakdown | Voltage regulation |
| Schottky Diode | ——— | —— | Low forward voltage (~0.2V), fast switching | High-speed switching |
| LED (Light Emitting Diode) | ——— | —→ | Emits light when forward biased | Indicators, displays |
| Photodiode | ——— | —○— | Conducts when illuminated | Light sensing |
| Varactor (Varicap) | ——— | —— | Capacitance varies with reverse voltage | Tuning circuits |
Zener Diode Voltage Regulation:
Vout=VZR=Vin−VZIL+IZ
7. Transistors
7.1. Bipolar Junction Transistor (BJT)
BJT is a current-controlled current amplifier.
Types:
| Type | Structure | Symbol (arrow on emitter) |
|---|---|---|
| NPN | N-P-N | Arrow points out |
| PNP | P-N-P | Arrow points in |
BJT Terminals:
-
Emitter (E): Heavily doped, emits carriers
-
Base (B): Thin, lightly doped, controls current
-
Collector (C): Collects carriers
BJT Operating Regions:
| Region | BE Junction | BC Junction | Application |
|---|---|---|---|
| Cutoff | Reverse biased | Reverse biased | Off switch |
| Active (Linear) | Forward biased | Reverse biased | Amplifier |
| Saturation | Forward biased | Forward biased | On switch |
BJT Current Relationships:
IE=IB+ICIC=βIB(active region)β=current gain (typical 50-300)IC=αIE,α=ββ+1
Common Emitter Configuration:
VCE=VCC−ICRCIB=VBB−VBERB
Transistor as a Switch:
-
Cutoff: VBE<0.7V → transistor OFF → VCE≈VCC
-
Saturation: IB large → transistor ON → VCE≈0.2V
7.2. Field Effect Transistor (FET)
FET is a voltage-controlled device.
Types:
| Type | Channel | Operation | Symbol |
|---|---|---|---|
| JFET (Junction FET) | N or P | Depletion mode | — |
| MOSFET (Metal-Oxide-Semiconductor FET) | N or P | Enhancement or depletion | — |
MOSFET (Most Common in Digital Circuits):
| Type | Gate Bias | Channel | Enhancement/Depletion |
|---|---|---|---|
| NMOS | Positive gate | N-channel | Normally OFF (enhancement) |
| PMOS | Negative gate | P-channel | Normally OFF (enhancement) |
MOSFET Regions:
| Region | Condition | Behavior |
|---|---|---|
| Cutoff | VGS<VTH | No current (OFF) |
| Linear (Triode) | VGS>VTH,VDS<VGS−VTH | Variable resistor |
| Saturation | VGS>VTH,VDS≥VGS−VTH | Constant current |
MOSFET Current Equation (Saturation):
ID=12μnCoxWL(VGS−VTH)2
7.3. CMOS Technology
CMOS (Complementary MOS): Uses both NMOS and PMOS transistors.
CMOS Inverter:
VDD │ ┌┴┐ PMOS (pull-up) └┬┘ ┼─── Vout ┌┴┐ NMOS (pull-down) └┬┘ │ GND
CMOS Characteristics:
-
Very low static power (only leakage)
-
High noise immunity
-
Scalable (Moore’s Law)
-
Dominant technology for digital ICs
8. Operational Amplifiers (Op-Amps)
8.1. Op-Amp Basics
An operational amplifier is a high-gain differential voltage amplifier.
Symbol:
V+
│
Inverting (-) ──┤\
│ \
│ \─── Vout
│ /
Non-inverting (+)─┤/
│
V-
Ideal Op-Amp Characteristics:
| Parameter | Ideal Value |
|---|---|
| Open-loop gain (A_OL) | ∞ |
| Input impedance (Z_in) | ∞ |
| Output impedance (Z_out) | 0 |
| Bandwidth | ∞ |
| Input offset voltage | 0 |
| Common-mode rejection ratio (CMRR) | ∞ |
Golden Rules (for negative feedback):
-
Virtual short: V+=V− (input voltages equal)
-
Virtual open: No current flows into inputs (I+=I−=0)
8.2. Basic Op-Amp Configurations
Inverting Amplifier:
Vout=−RfRinVinZin=Rin
Non-Inverting Amplifier:
Vout=(1+RfRin)VinZin=∞
Voltage Follower (Buffer):
Vout=VinZin=∞,Zout=0
Summing Amplifier:
Vout=−(RfR1V1+RfR2V2+RfR3V3)
Differential Amplifier:
Vout=RfR1(V2−V1)(if R1=R2,Rf=Rg)
Integrator:
Vout(t)=−1RC∫Vin(t)dt
Differentiator:
Vout(t)=−RCdVin(t)dt
8.3. Practical Op-Amp Limitations
| Limitation | Effect | Mitigation |
|---|---|---|
| Finite gain | Gain less than ideal | Use high-gain op-amps |
| Input bias current | Offset voltage | Use FET input op-amps |
| Input offset voltage | DC error | Offset nulling |
| Slew rate | Limited output speed | Use faster op-amps |
| Bandwidth | Gain decreases at high frequency | Compensation |
9. Digital Logic Fundamentals
9.1. Logic Levels
| Logic Family | VIL (max) | VIH (min) | VOL (max) | VOH (min) |
|---|---|---|---|---|
| TTL | 0.8 V | 2.0 V | 0.4 V | 2.4 V |
| CMOS (5V) | 1.5 V | 3.5 V | 0.1 V | 4.9 V |
| LVTTL (3.3V) | 0.8 V | 2.0 V | 0.4 V | 2.4 V |
| LVCMOS (3.3V) | 0.9 V | 2.4 V | 0.4 V | 2.6 V |
9.2. Basic Logic Gates
| Gate | Symbol | Expression | Truth Table |
|---|---|---|---|
| NOT (Inverter) | —○— | Y=A‾ | 0→1, 1→0 |
| AND | —&— | Y=A⋅B | 00→0, 01→0, 10→0, 11→1 |
| OR | —≥1— | Y=A+B | 00→0, 01→1, 10→1, 11→1 |
| NAND | —&○— | Y=A⋅B‾ | 00→1, 01→1, 10→1, 11→0 |
| NOR | —≥1○— | Y=A+B‾ | 00→1, 01→0, 10→0, 11→0 |
| XOR | —=1— | Y=A⊕B | 00→0, 01→1, 10→1, 11→0 |
| XNOR | —=1○— | Y=A⊕B‾ | 00→1, 01→0, 10→0, 11→1 |
9.3. Boolean Algebra
Basic Laws:
-
Identity: A+0=A, A⋅1=A
-
Null: A+1=1, A⋅0=0
-
Idempotent: A+A=A, A⋅A=A
-
Complement: A+A‾=1, A⋅A‾=0
-
Double negation: A‾‾=A
Commutative: A+B=B+A, A⋅B=B⋅A
Associative: (A+B)+C=A+(B+C)
Distributive: A⋅(B+C)=A⋅B+A⋅C
DeMorgan’s Theorems:
A⋅B‾=A‾+B‾A+B‾=A‾⋅B‾
9.4. Logic Family Characteristics
| Parameter | TTL (74LS) | CMOS (74HC) | CMOS (74HCT) |
|---|---|---|---|
| Propagation delay | 9-15 ns | 8-15 ns | 8-15 ns |
| Power per gate | 2 mW | < 0.1 mW | < 0.1 mW |
| Fan-out | 20 | 50 | 50 |
| Supply voltage | 5V | 2-6V | 5V |
| Input compatibility | TTL | CMOS | TTL |
10. Power Supplies and Regulation
10.1. Linear Voltage Regulators
Series Regulator:
Vout=Vref(1+R1R2)
Common Regulators:
| Regulator | Output Voltage | Features |
|---|---|---|
| 7805 | +5V | Fixed positive |
| 7812 | +12V | Fixed positive |
| 7905 | -5V | Fixed negative |
| LM317 | 1.2-37V | Adjustable positive |
| LM337 | -1.2 to -37V | Adjustable negative |
10.2. Switching Regulators
Types:
-
Buck (Step-down): Vout<Vin
-
Boost (Step-up): Vout>Vin
-
Buck-Boost: Vout can be higher or lower
-
Inverting: Vout negative
Efficiency:
-
Linear regulators: 30-50%
-
Switching regulators: 80-95%
11. Summary Table: Key Equations
| Equation | Description |
|---|---|
| V=IR | Ohm’s law |
| P=VI=I2R | Power |
| iC=C dv/dt | Capacitor current |
| vL=L di/dt | Inductor voltage |
| τ=RC | RC time constant |
| I=IS(eV/nVT−1) | Diode equation |
| IC=βIB | BJT current gain |
| ID=12μnCox(W/L)(VGS−VTH)2 | MOSFET saturation |
| Vout=−(Rf/Rin)Vin | Inverting op-amp |
| A⋅B‾=A‾+B‾ | DeMorgan’s theorem |
12. Standard Textbooks
| Author | Title | Focus |
|---|---|---|
| Sedra & Smith | Microelectronic Circuits | Comprehensive electronics |
| Boylestad & Nashelsky | Electronic Devices and Circuit Theory | Practical |
| Malvino & Bates | Electronic Principles | Beginner-friendly |
| Horowitz & Hill | The Art of Electronics | Practical reference |
| Tocci, Widmer & Moss | Digital Systems | Digital logic |
13. Final Study Checklist
| Topic | Key Skills |
|---|---|
| Basic Circuits | Apply Ohm’s law; solve series/parallel circuits |
| Kirchhoff’s Laws | Apply KCL and KVL; use mesh and nodal analysis |
| Passive Components | Identify resistor values; calculate RC/RL time constants |
| Diodes | Analyze rectifier circuits; use Zener for regulation |
| BJTs | Bias transistors; use as amplifier and switch |
| MOSFETs | Understand CMOS operation; use as digital switch |
| Op-Amps | Design inverting, non-inverting, summing, integrating circuits |
| Digital Logic | Apply Boolean algebra; use DeMorgan’s theorem |
| Power Supplies | Design linear regulator; compare linear vs. switching |
CSE-1502 Computer Programming Principles – Detailed Study Notes
These study notes are designed for undergraduate students taking a first course in Computer Programming. The notes cover the fundamental principles of programming, algorithms, data types, control structures, functions, arrays, pointers, and basic data structures.
1. Introduction to Computer Programming
1.1 What is Programming?
| Aspect | Detail |
|---|---|
| Definition | Programming is the process of designing, writing, testing, and maintaining computer programs to solve problems or perform specific tasks. |
| Program | A set of instructions that a computer follows to perform a task. |
| Programming Language | A formal language used to communicate instructions to a computer (C, C++, Java, Python, etc.). |
1.2 Levels of Programming Languages
| Level | Description | Examples |
|---|---|---|
| Machine language | Binary code (0s and 1s) directly executed by CPU | 10110000 01100001 |
| Assembly language | Mnemonic codes, one-to-one with machine instructions | MOV AL, 61h |
| High-level language | Human-readable, compiled or interpreted | C, C++, Java, Python |
1.3 The Programming Process
1. Problem Analysis → Understand requirements 2. Algorithm Design → Step-by-step solution 3. Coding → Write program in programming language 4. Compilation/Interpretation → Translate to machine code 5. Testing & Debugging → Find and fix errors 6. Maintenance → Update and improve
1.4 Types of Errors
| Error Type | Description | Example |
|---|---|---|
| Syntax error | Violation of language rules | Missing semicolon, unmatched brace |
| Runtime error | Occurs during program execution | Division by zero, file not found |
| Logical error | Program runs but gives wrong result | Incorrect formula, wrong condition |
2. Algorithms and Flowcharts
2.1 Algorithm Definition
| Aspect | Detail |
|---|---|
| Definition | An algorithm is a finite sequence of well-defined, unambiguous instructions for solving a problem in a finite amount of time. |
| Properties | Finiteness, definiteness, input, output, effectiveness |
2.2 Flowchart Symbols
| Symbol | Name | Meaning |
|---|---|---|
| ┌───┐ | Oval (Terminal) | Start or end |
| ┌───┐ | Parallelogram (Input/Output) | Read or print data |
| ┌───┐ | Rectangle (Process) | Assignment or calculation |
| ◇ | Diamond (Decision) | Conditional branch (if-then-else) |
| ○ | Circle (Connector) | Connects flowchart sections |
| → | Arrow (Flow line) | Direction of flow |
2.3 Example Flowchart (Find largest of three numbers)
┌─────────┐
│ Start │
└────┬────┘
↓
┌─────────┐
│ Read A,B,C│
└────┬────┘
↓
◇─────┐
A > B? │Yes
│No ↓
↓ ┌─────┐
◇ │ max=A│
A > C? │ │
│No Yes│ │
↓ ↓ ↓
┌─────┐ ┌─────┐ │
│max=B│ │max=C│ │
└──┬──┘ └──┬──┘ │
│ │ │
└───────┴────┘
↓
┌─────────┐
│ Print max│
└────┬────┘
↓
┌─────────┐
│ Stop │
└─────────┘
3. C Programming Fundamentals
3.1 Structure of a C Program
/* Header file inclusion */ #include <stdio.h> #include <conio.h> /* Macro definition */ #define PI 3.14159 /* Global variable declaration */ int global_var = 10; /* Function declaration (prototype) */ int add(int a, int b); /* Main function – program entry point */ void main() { /* Variable declarations */ int x = 5, y = 10, result; /* Function call */ result = add(x, y); /* Output statement */ printf("Sum = %d", result); getch(); /* Wait for key press */ } /* Function definition */ int add(int a, int b) { return a + b; }
3.2 C Character Set
| Category | Characters |
|---|---|
| Alphabets | A-Z, a-z |
| Digits | 0-9 |
| Special symbols | ~ ` ! @ # $ % ^ & * ( ) _ – + = { } [ ] | : ; ” ‘ < > , . ? / | |
| White spaces | Space, tab, newline |
3.3 C Tokens
| Token Type | Examples |
|---|---|
| Keywords | int, float, char, if, else, while, for, return |
| Identifiers | variable names, function names (user-defined) |
| Constants | 10, 3.14, ‘A’, “Hello” |
| Operators | +, -, *, /, %, =, ==, <, > |
| Special symbols | ; , { } ( ) [ ] |
3.4 Data Types in C
| Data Type | Size (bytes) | Range | Format Specifier |
|---|---|---|---|
| char | 1 | -128 to 127 | %c |
| unsigned char | 1 | 0 to 255 | %c |
| int | 2 or 4 | -32,768 to 32,767 (2-byte) | %d, %i |
| unsigned int | 2 or 4 | 0 to 65,535 (2-byte) | %u |
| short int | 2 | -32,768 to 32,767 | %hd |
| long int | 4 | -2,147,483,648 to 2,147,483,647 | %ld |
| float | 4 | 3.4×10⁻³⁸ to 3.4×10³⁸ | %f |
| double | 8 | 1.7×10⁻³⁰⁸ to 1.7×10³⁰⁸ | %lf |
| void | 0 | No value | – |
3.5 Variable Declaration and Initialization
/* Declaration only */ int count; float price; char grade; /* Declaration with initialization */ int age = 25; float temperature = 98.6; char initial = 'J'; /* Multiple declarations */ int a = 5, b = 10, c;
3.6 Constants
/* Integer constants */ int decimal = 100; /* Decimal (base 10) */ int octal = 0144; /* Octal (base 8) – prefix 0 */ int hexadecimal = 0x64; /* Hexadecimal (base 16) – prefix 0x */ /* Floating-point constants */ float f1 = 3.14; float f2 = 3.14e-5; /* Scientific notation */ /* Character constants */ char ch1 = 'A'; char ch2 = '\n'; /* Escape sequence */ /* String constants (character arrays) */ char str[] = "Hello"; /* Escape sequences */ /* \n = newline, \t = tab, \r = carriage return */ /* \' = single quote, \" = double quote, \\ = backslash */
3.7 Input and Output Functions
| Function | Purpose | Format | Example |
|---|---|---|---|
| printf() | Formatted output | printf(“format”, variables); | printf(“Age: %d”, age); |
| scanf() | Formatted input | scanf(“format”, &variables); | scanf(“%d”, &age); |
| getch() | Get character (no echo) | ch = getch(); | – |
| getche() | Get character (with echo) | ch = getche(); | – |
| getchar() | Get character (buffer) | ch = getchar(); | – |
| putchar() | Put character | putchar(ch); | – |
printf() Format Specifiers:
| Specifier | Output | Example |
|---|---|---|
| %d or %i | Integer | printf(“%d”, 100); → 100 |
| %f | Float | printf(“%.2f”, 3.1416); → 3.14 |
| %c | Character | printf(“%c”, ‘A’); → A |
| %s | String | printf(“%s”, “Hello”); → Hello |
| %x | Hexadecimal | printf(“%x”, 255); → ff |
| %o | Octal | printf(“%o”, 8); → 10 |
| %p | Pointer address | printf(“%p”, &x); |
4. Operators and Expressions
4.1 Types of Operators
| Category | Operators | Example | ||
|---|---|---|---|---|
| Arithmetic | +, -, *, /, % | a + b | ||
| Relational | <, >, <=, >=, ==, != | a > b | ||
| Logical | &&, | , ! | (a > b) && (b > c) | |
| Assignment | =, +=, -=, *=, /=, %= | a += 5 (a = a + 5) | ||
| Increment/Decrement | ++, — | a++, ++a | ||
| Bitwise | &, | , ^, ~, <<, >> | a & b | |
| Conditional (ternary) | ? : | (a > b) ? a : b | ||
| Comma | , | a = 5, b = 10 | ||
| sizeof | sizeof() | sizeof(int) |
4.2 Operator Precedence and Associativity
| Precedence | Operators | Associativity |
|---|---|---|
| 1 (highest) | () [] . -> | Left to right |
| 2 | ++ — ! ~ + – (type) * & sizeof | Right to left |
| 3 | * / % | Left to right |
| 4 | + – | Left to right |
| 5 | << >> | Left to right |
| 6 | < <= > >= | Left to right |
| 7 | == != | Left to right |
| 8 | & | Left to right |
| 9 | ^ | Left to right |
| 10 | | | Left to right |
| 11 | && | Left to right |
| 12 | || | Left to right |
| 13 | ? : | Right to left |
| 14 (lowest) | = += -= etc. | Right to left |
4.3 Type Conversion
Implicit (Automatic) Conversion:
int a = 10; float b = 3.14; float c = a + b; /* a converted to float (10.0) */
Explicit (Type Casting):
float f = 3.14; int i = (int) f; /* i = 3 (truncated) */ int x = 5, y = 2; float z = (float) x / y; /* z = 2.5 */
5. Control Structures
5.1 Decision Making (Conditional Statements)
if statement:
if (condition) { /* statements executed if condition is true */ }
if-else statement:
if (condition) { /* executed if true */ } else { /* executed if false */ }
else-if ladder:
if (condition1) { /* block 1 */ } else if (condition2) { /* block 2 */ } else if (condition3) { /* block 3 */ } else { /* default block */ }
Nested if:
if (condition1) { if (condition2) { /* nested if block */ } }
switch statement:
switch (expression) { case constant1: /* statements */ break; case constant2: /* statements */ break; default: /* default statements */ }
Conditional (ternary) operator:
variable = (condition) ? expression1 : expression2; /* Example: max = (a > b) ? a : b; */
5.2 Loops (Iteration)
while loop:
while (condition) { /* statements */ /* loop variable update */ }
do-while loop:
do { /* statements */ } while (condition); /* executes at least once */
for loop:
for (initialization; condition; increment/decrement) { /* statements */ }
Example – Print numbers 1 to 10:
/* Using for loop */ for (int i = 1; i <= 10; i++) { printf("%d ", i); } /* Using while loop */ int i = 1; while (i <= 10) { printf("%d ", i); i++; } /* Using do-while loop */ int i = 1; do { printf("%d ", i); i++; } while (i <= 10);
5.3 Jump Statements
| Statement | Purpose | Example |
|---|---|---|
| break | Exit loop or switch | break; |
| continue | Skip to next iteration | continue; |
| goto | Jump to labeled statement | goto label; |
| return | Exit function | return value; |
6. Arrays
6.1 One-Dimensional Arrays
Declaration:
data_type array_name[size];
Examples:
int numbers[10]; /* Array of 10 integers */ float scores[5]; /* Array of 5 floats */ char name[20]; /* Array of 20 characters (string) */
Initialization:
int numbers[5] = {1, 2, 3, 4, 5}; /* Full initialization */ int numbers[5] = {1, 2}; /* Partial (rest = 0) */ int numbers[] = {1, 2, 3}; /* Size inferred (3) */
Accessing Elements:
numbers[0] = 10; /* First element (index 0) */ numbers[4] = 50; /* Fifth element (index 4) */ int x = numbers[2]; /* Read third element */
Array Traversal:
int arr[10]; for (int i = 0; i < 10; i++) { arr[i] = i * 10; printf("arr[%d] = %d\n", i, arr[i]); }
6.2 Two-Dimensional Arrays
Declaration:
data_type array_name[rows][columns];
Example:
int matrix[3][4]; /* 3 rows, 4 columns */
Initialization:
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
Accessing Elements:
matrix[0][0] = 1; /* First row, first column */ matrix[1][2] = 6; /* Second row, third column */
Matrix Traversal:
int matrix[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { matrix[i][j] = i * 3 + j + 1; printf("%d ", matrix[i][j]); } printf("\n"); }
6.3 Strings (Character Arrays)
Declaration and Initialization:
char str1[10] = "Hello"; /* Array of characters */ char str2[] = "World"; /* Size inferred (6) */ char str3[10] = {'H', 'e', 'l', 'l', 'o', '\0'}; /* With null terminator */
String Input/Output:
char name[50]; printf("Enter name: "); scanf("%s", name); /* Reads until whitespace */ gets(name); /* Reads entire line (unsafe) */ fgets(name, 50, stdin); /* Safe – reads with newline */ printf("%s", name); /* Print string */ puts(name); /* Print with newline */
Common String Functions (string.h):
| Function | Purpose | Example |
|---|---|---|
| strlen(str) | String length | len = strlen(“Hello”); // 5 |
| strcpy(dest, src) | Copy string | strcpy(dest, src); |
| strcat(dest, src) | Concatenate | strcat(str1, str2); |
| strcmp(str1, str2) | Compare (0 if equal) | if (strcmp(s1, s2) == 0) |
| strrev(str) | Reverse string | strrev(str); |
7. Functions
7.1 Function Definition and Declaration
Syntax:
return_type function_name(parameter_list) { /* function body */ return value; }
Example:
/* Function declaration (prototype) */ int add(int a, int b); /* Function definition */ int add(int a, int b) { return a + b; } /* Function call */ int result = add(5, 10);
7.2 Function Types
| Type | Description | Example |
|---|---|---|
| No arguments, no return | void function(void) | void printMessage(void) |
| No arguments, with return | int function(void) | int getNumber(void) |
| With arguments, no return | void function(int a) | void printSquare(int n) |
| With arguments, with return | int function(int a) | int square(int n) |
7.3 Parameter Passing
| Method | Description | C Implementation |
|---|---|---|
| Call by value | Copy of value passed | Default in C |
| Call by reference | Address passed (using pointers) | Using pointers |
Call by Value Example:
void swap(int x, int y) /* Does NOT swap actual arguments */ { int temp = x; x = y; y = temp; }
Call by Reference Example:
void swap(int *x, int *y) /* Swaps actual arguments */ { int temp = *x; *x = *y; *y = temp; } /* Call: swap(&a, &b); */
7.4 Recursion
Definition: A function that calls itself.
Example – Factorial:
int factorial(int n) { if (n == 0 || n == 1) return 1; else return n * factorial(n - 1); } /* factorial(5) = 5 × 4 × 3 × 2 × 1 = 120 */
Example – Fibonacci:
int fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); }
7.5 Storage Classes
| Class | Scope | Lifetime | Default Value | Storage |
|---|---|---|---|---|
| auto | Local | Function execution | Garbage | Stack |
| register | Local | Function execution | Garbage | CPU register (request) |
| static | Local | Program execution | Zero | Data segment |
| extern | Global | Program execution | Zero | Data segment |
8. Pointers
8.1 Pointer Basics
Definition: A pointer is a variable that stores the memory address of another variable.
int x = 10; int *ptr; /* Declaration: pointer to integer */ ptr = &x; /* ptr stores address of x */ printf("%d", x); /* Output: 10 (value) */ printf("%d", *ptr); /* Output: 10 (dereferencing) */ printf("%p", ptr); /* Output: address of x (e.g., 0x7ffd...) */
8.2 Pointer Operations
| Operator | Meaning | Example |
|---|---|---|
& |
Address of | ptr = &x; |
* |
Dereference (value at address) | value = *ptr; |
-> |
Member access (structures) | ptr->member |
8.3 Pointer Arithmetic
int arr[] = {10, 20, 30, 40, 50}; int *ptr = arr; /* Points to arr[0] */ ptr++; /* Now points to arr[1] (address + sizeof(int)) */ int value = *ptr; /* value = 20 */ ptr += 2; /* Points to arr[3] (address + 2×sizeof(int)) */
8.4 Pointers and Arrays
int arr[5] = {1, 2, 3, 4, 5}; int *ptr = arr; /* ptr points to arr[0] */ /* Equivalent ways to access array elements */ arr[i] == *(arr + i) == *(ptr + i) == ptr[i]
8.5 Pointers to Functions
int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int (*operation)(int, int); /* Function pointer declaration */ operation = add; /* Assign function address */ int result = operation(5, 3); /* result = 8 */ operation = subtract; result = operation(5, 3); /* result = 2 */
8.6 Dynamic Memory Allocation
| Function | Purpose | Header |
|---|---|---|
malloc(size) |
Allocate memory (uninitialized) | stdlib.h |
calloc(n, size) |
Allocate memory (initialized to zero) | stdlib.h |
realloc(ptr, new_size) |
Resize allocated memory | stdlib.h |
free(ptr) |
Deallocate memory | stdlib.h |
Example:
int *arr; int n = 10; /* Allocate memory for 10 integers */ arr = (int*) malloc(n * sizeof(int)); /* Check allocation */ if (arr == NULL) { printf("Memory allocation failed"); exit(1); } /* Use array */ for (int i = 0; i < n; i++) { arr[i] = i * 10; } /* Free memory */ free(arr);
9. Structures and Unions
9.1 Structures
Definition: A structure is a user-defined data type that groups related variables of different data types.
struct Student { int roll_no; char name[50]; float marks; char grade; }; /* Variable declaration */ struct Student s1; struct Student s2 = {101, "John", 85.5, 'A'}; /* Accessing members */ s1.roll_no = 102; strcpy(s1.name, "Jane"); s1.marks = 92.0; s1.grade = 'A';
9.2 typedef
typedef struct Student Student; Student s1; /* Now 'Student' instead of 'struct Student' */ /* Or combined declaration */ typedef struct { int roll_no; char name[50]; float marks; } Student;
9.3 Array of Structures
Student class[30]; /* Array of 30 students */ class[0].roll_no = 101; strcpy(class[0].name, "Alice"); class[0].marks = 85.5;
9.4 Nested Structures
struct Date { int day; int month; int year; }; struct Employee { int id; char name[50]; struct Date joining_date; }; struct Employee emp; emp.joining_date.day = 15; emp.joining_date.month = 6; emp.joining_date.year = 2023;
9.5 Unions
Definition: A union is similar to a structure but shares memory among all members (only one member can hold a value at a time).
union Data { int i; float f; char str[20]; }; union Data data; data.i = 10; /* Integer stored */ printf("%d", data.i); /* 10 */ data.f = 3.14; /* Overwrites integer memory */ printf("%f", data.f); /* 3.14 */ /* data.i is now invalid (garbage) */
Size of union = size of largest member
10. File Handling
10.1 File Operations
| Operation | Function | Mode |
|---|---|---|
| Open file | fopen() | r, w, a, r+, w+, a+ |
| Close file | fclose() | – |
| Read character | fgetc(), getc() | r, r+ |
| Write character | fputc(), putc() | w, w+, a, a+ |
| Read string | fgets() | r, r+ |
| Write string | fputs() | w, w+, a, a+ |
| Read formatted | fscanf() | r, r+ |
| Write formatted | fprintf() | w, w+, a, a+ |
| Read binary | fread() | rb, rb+ |
| Write binary | fwrite() | wb, wb+ |
10.2 File Opening Modes
| Mode | Description |
|---|---|
"r" |
Read (file must exist) |
"w" |
Write (creates new, overwrites existing) |
"a" |
Append (creates if not exists) |
"r+" |
Read and write (file must exist) |
"w+" |
Read and write (creates new, overwrites) |
"a+" |
Read and append (creates if not exists) |
"rb" |
Read binary |
"wb" |
Write binary |
10.3 File Handling Examples
Writing to a file:
FILE *fp; fp = fopen("data.txt", "w"); if (fp == NULL) { printf("Error opening file"); exit(1); } fprintf(fp, "Hello World\n"); fprintf(fp, "Number: %d", 100); fclose(fp);
Reading from a file:
FILE *fp; char line[100]; fp = fopen("data.txt", "r"); if (fp == NULL) { printf("Error opening file"); exit(1); } while (fgets(line, sizeof(line), fp) != NULL) { printf("%s", line); } fclose(fp);
Binary file operations:
struct Student s = {101, "John", 85.5}; /* Write structure to binary file */ FILE *fp = fopen("students.dat", "wb"); fwrite(&s, sizeof(struct Student), 1, fp); fclose(fp); /* Read structure from binary file */ struct Student s2; fp = fopen("students.dat", "rb"); fread(&s2, sizeof(struct Student), 1, fp); fclose(fp);
11. Sample Exam Questions
Short Answer (5 marks each)
-
Distinguish between syntax error, runtime error, and logical error. Give an example of each.
-
Explain the difference between call by value and call by reference with examples.
-
What is the difference between
malloc()andcalloc()? -
How does a structure differ from a union?
-
Write a function to calculate factorial using recursion.
Programming Problems (10-15 marks)
1. Array Operations:
Write a C program to find the largest element in an array.
Solution:
#include <stdio.h> void main() { int arr[100], n, i, max; printf("Enter number of elements: "); scanf("%d", &n); printf("Enter %d elements: ", n); for(i = 0; i < n; i++) scanf("%d", &arr[i]); max = arr[0]; for(i = 1; i < n; i++) { if(arr[i] > max) max = arr[i]; } printf("Largest element = %d", max); getch(); }
2. String Manipulation:
Write a C program to reverse a string without using strrev().
Solution:
#include <stdio.h> #include <string.h> void main() { char str[100], temp; int i, j, len; printf("Enter a string: "); gets(str); len = strlen(str); for(i = 0, j = len - 1; i < j; i++, j--) { temp = str[i]; str[i] = str[j]; str[j] = temp; } printf("Reversed string: %s", str); getch(); }
3. Matrix Multiplication:
Write a C program to multiply two matrices.
Solution:
#include <stdio.h> void main() { int A[10][10], B[10][10], C[10][10]; int r1, c1, r2, c2, i, j, k; printf("Enter rows and columns of first matrix: "); scanf("%d%d", &r1, &c1); printf("Enter rows and columns of second matrix: "); scanf("%d%d", &r2, &c2); if(c1 != r2) { printf("Matrix multiplication not possible"); getch(); return; } printf("Enter first matrix elements:\n"); for(i = 0; i < r1; i++) for(j = 0; j < c1; j++) scanf("%d", &A[i][j]); printf("Enter second matrix elements:\n"); for(i = 0; i < r2; i++) for(j = 0; j < c2; j++) scanf("%d", &B[i][j]); /* Matrix multiplication */ for(i = 0; i < r1; i++) for(j = 0; j < c2; j++) { C[i][j] = 0; for(k = 0; k < c1; k++) C[i][j] += A[i][k] * B[k][j]; } printf("Product matrix:\n"); for(i = 0; i < r1; i++) { for(j = 0; j < c2; j++) printf("%d ", C[i][j]); printf("\n"); } getch(); }
Quick Revision Table – C Keywords
| Category | Keywords |
|---|---|
| Data types | int, float, double, char, void |
| Storage classes | auto, register, static, extern |
| Type qualifiers | const, volatile |
| Control structures | if, else, switch, case, default, break, continue, goto |
| Loops | for, while, do |
| Functions | return |
| Structures | struct, union, typedef, enum |
| Memory | sizeof |
Quick Revision Table – Operator Precedence
| Precedence | Operators |
|---|---|
| 1 (highest) | () [] . -> |
| 2 | ++ -- ! ~ * & (unary) + - (type) sizeof |
| 3 | * / % |
| 4 | + - |
| 5 | << >> |
| 6 | < <= > >= |
| 7 | == != |
| 8 | & |
| 9 | ^ |
| 10 | | |
| 11 | && |
| 12 | || |
| 13 | ?: |
| 14 (lowest) | = += -= etc. |
CSE-2104: Data Structures & Algorithms – Comprehensive Study Notes
These notes provide a complete framework for Data Structures & Algorithms, covering fundamental data structures (arrays, linked lists, stacks, queues, trees, graphs, hash tables) and essential algorithms (sorting, searching, graph algorithms, and algorithmic paradigms). The focus is on understanding the time and space complexity of operations and selecting appropriate data structures for specific problems.
Part 1: Foundations of Algorithms
1.1 What is an Algorithm?
An algorithm is a finite sequence of well-defined instructions for solving a specific problem. Every algorithm must satisfy:
| Property | Description |
|---|---|
| Input | Zero or more externally supplied values |
| Output | At least one value produced |
| Definiteness | Each instruction is clear and unambiguous |
| Finiteness | Algorithm terminates after a finite number of steps |
| Effectiveness | Instructions are basic enough to be carried out |
1.2 Algorithmic Paradigms
| Paradigm | Description | Examples |
|---|---|---|
| Brute Force | Try all possibilities | Linear search, bubble sort |
| Divide and Conquer | Break problem into subproblems, solve recursively | Merge sort, quicksort, binary search |
| Dynamic Programming | Solve overlapping subproblems, store results | Fibonacci, shortest path |
| Greedy | Make locally optimal choice at each step | Dijkstra’s algorithm, Huffman coding |
| Backtracking | Incremental search, abandon dead ends | N-Queens, maze solving |
1.3 Pseudocode Conventions
-
←or=for assignment -
if condition then ... else ...for conditionals -
for i ← 1 to n do ...for counted loops -
while condition do ...for conditional loops -
return valuefor function output
Part 2: Complexity Analysis
2.1 Time Complexity
Time complexity measures how the running time of an algorithm grows as input size increases.
| Notation | Name | Meaning |
|---|---|---|
| O(g(n)) | Big-O | Upper bound (worst case) |
| Ω(g(n)) | Big-Omega | Lower bound (best case) |
| Θ(g(n)) | Theta | Tight bound (average case) |
2.2 Common Complexity Classes
| Complexity | Name | Example Algorithms |
|---|---|---|
| O(1) | Constant | Array access, push/pop |
| O(log n) | Logarithmic | Binary search |
| O(n) | Linear | Linear search, array traversal |
| O(n log n) | Linearithmic | Merge sort, quicksort (average) |
| O(n²) | Quadratic | Bubble sort, selection sort |
| O(2ⁿ) | Exponential | Recursive Fibonacci |
| O(n!) | Factorial | Traveling salesman (brute force) |
2.3 Space Complexity
Space complexity measures the additional memory an algorithm requires relative to input size.
-
In-place algorithms: O(1) extra space (bubble sort, selection sort)
-
Out-of-place algorithms: O(n) or more extra space (merge sort)
2.4 Recurrence Relations and Master Theorem
Master Theorem: For recurrence T(n)=aT(n/b)+f(n):
| Case | Condition | Solution |
|---|---|---|
| 1 | f(n)=O(nlogba−ε) | T(n)=Θ(nlogba) |
| 2 | f(n)=Θ(nlogbalogkn) | T(n)=Θ(nlogbalogk+1n) |
| 3 | f(n)=Ω(nlogba+ε) and af(n/b)≤cf(n) | T(n)=Θ(f(n)) |
Common recurrences:
-
Merge sort: T(n)=2T(n/2)+O(n) → O(nlogn)
-
Binary search: T(n)=T(n/2)+O(1) → O(logn)
-
Recursive Fibonacci: T(n)=T(n−1)+T(n−2)+O(1) → O(2n)
2.5 Algorithm Correctness
Loop Invariant: A condition that is true before each iteration of a loop and remains true after each iteration.
Proof of correctness using loop invariants:
-
Initialization: Invariant holds before first iteration
-
Maintenance: If invariant holds before an iteration, it holds after
-
Termination: When loop terminates, invariant gives useful property
Part 3: Linear Data Structures
3.1 Arrays
Array: Contiguous memory locations storing elements of the same type, accessible by index.
| Operation | Time Complexity |
|---|---|
| Access (by index) | O(1) |
| Search (unsorted) | O(n) |
| Search (sorted) | O(log n) – binary search |
| Insert at end | O(1) (amortized for dynamic arrays) |
| Insert at beginning/middle | O(n) |
| Delete at end | O(1) |
| Delete at beginning/middle | O(n) |
Dynamic Arrays (e.g., ArrayList, Vector):
-
Automatically resize when capacity is exceeded
-
Amortized O(1) for append
-
Typical growth factor: 2× (doubling)
3.2 Linked Lists
Singly Linked List: Each node contains data and a pointer to the next node.
[data|next] → [data|next] → [data|next] → NULL
Doubly Linked List: Each node has pointers to next and previous nodes.
NULL ← [prev|data|next] ↔ [prev|data|next] ↔ [prev|data|next] → NULL
| Operation | Singly Linked | Doubly Linked |
|---|---|---|
| Access by index | O(n) | O(n) |
| Search | O(n) | O(n) |
| Insert at head | O(1) | O(1) |
| Insert at tail (with tail pointer) | O(1) | O(1) |
| Delete at head | O(1) | O(1) |
| Delete at tail (with tail pointer) | O(n) | O(1) |
Linked List vs. Array:
| Feature | Array | Linked List |
|---|---|---|
| Random access | O(1) | O(n) |
| Insert/delete at ends | O(n) (static) / O(1) (dynamic) | O(1) |
| Memory overhead | None | Per-node pointer(s) |
| Cache locality | Excellent | Poor |
3.3 Stacks
Stack: LIFO (Last-In-First-Out) data structure.
| Operation | Description | Complexity |
|---|---|---|
push(x) |
Add element to top | O(1) |
pop() |
Remove and return top | O(1) |
peek() / top() |
Return top without removing | O(1) |
isEmpty() |
Check if empty | O(1) |
Applications:
-
Function call stack (recursion)
-
Expression evaluation (postfix conversion)
-
Undo/Redo operations
-
Backtracking algorithms
3.4 Queues
Queue: FIFO (First-In-First-Out) data structure.
| Operation | Description | Complexity |
|---|---|---|
enqueue(x) |
Add element to rear | O(1) |
dequeue() |
Remove and return front | O(1) |
front() |
Return front without removing | O(1) |
isEmpty() |
Check if empty | O(1) |
Circular Queue: Uses modulo arithmetic to wrap around:
rear = (rear + 1) % capacity front = (front + 1) % capacity
Applications:
-
Task scheduling
-
Breadth-First Search (BFS)
-
Print spooler
-
Message passing (producer-consumer)
3.5 Deque (Double-Ended Queue)
Deque: Elements can be added/removed from both ends.
| Operation | Complexity |
|---|---|
push_front(x), push_back(x) |
O(1) |
pop_front(), pop_back() |
O(1) |
Part 4: Recursion
4.1 Fundamentals
Recursion: A function that calls itself to solve smaller instances of the same problem.
Components of recursive function:
-
Base case: Condition that stops recursion
-
Recursive case: Function calls itself with modified parameters
Example: Factorial
function factorial(n):
if n ≤ 1: return 1 // base case
return n × factorial(n-1) // recursive case
4.2 Recursion vs. Iteration
| Aspect | Recursion | Iteration |
|---|---|---|
| Code length | Shorter, more readable | Longer |
| Memory usage | Higher (call stack) | Lower |
| Speed | Slower (function call overhead) | Faster |
| Risk | Stack overflow for deep recursion | No stack overflow |
4.3 Types of Recursion
| Type | Description | Example |
|---|---|---|
| Direct recursion | Function calls itself | factorial(n) |
| Tail recursion | Recursive call is last operation | Can be optimized by compiler |
| Tree recursion | Multiple recursive calls | Fibonacci: fib(n-1) + fib(n-2) |
4.4 Backtracking
Backtracking: Systematic trial-and-error search; abandon partial solutions when they cannot lead to a valid solution.
Algorithm template:
function backtrack(candidate):
if isSolution(candidate):
output(candidate)
return
for next in getCandidates(candidate):
if isValid(next):
makeMove(next)
backtrack(next)
undoMove(next)
Classic problems: N-Queens, Sudoku, maze solving, subset sum
Part 5: Sorting Algorithms
5.1 Comparison of Sorting Algorithms
| Algorithm | Best Case | Average Case | Worst Case | Space | Stable? | In-place? |
|---|---|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes | Yes |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No | Yes |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes | Yes |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes | No |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No | Yes |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No | Yes |
Comparison sort lower bound: Any comparison-based sorting algorithm requires Ω(nlogn) comparisons in the worst case.
5.2 Bubble Sort
function bubbleSort(arr):
n ← length(arr)
for i ← 0 to n-2:
swapped ← false
for j ← 0 to n-2-i:
if arr[j] > arr[j+1]:
swap(arr[j], arr[j+1])
swapped ← true
if not swapped: break
return arr
5.3 Selection Sort
function selectionSort(arr):
n ← length(arr)
for i ← 0 to n-2:
minIdx ← i
for j ← i+1 to n-1:
if arr[j] < arr[minIdx]:
minIdx ← j
swap(arr[i], arr[minIdx])
return arr
5.4 Insertion Sort
function insertionSort(arr):
for i ← 1 to n-1:
key ← arr[i]
j ← i-1
while j ≥ 0 and arr[j] > key:
arr[j+1] ← arr[j]
j ← j-1
arr[j+1] ← key
return arr
5.5 Merge Sort
function mergeSort(arr):
if length(arr) ≤ 1: return arr
mid ← length(arr) // 2
left ← mergeSort(arr[0:mid])
right ← mergeSort(arr[mid:length(arr)])
return merge(left, right)
function merge(L, R):
result ← []
i, j ← 0, 0
while i < length(L) and j < length(R):
if L[i] ≤ R[j]:
result.append(L[i]); i++
else:
result.append(R[j]); j++
result.extend(L[i:])
result.extend(R[j:])
return result
5.6 Quick Sort
function quickSort(arr, low, high):
if low < high:
pi ← partition(arr, low, high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
function partition(arr, low, high):
pivot ← arr[high]
i ← low - 1
for j ← low to high-1:
if arr[j] ≤ pivot:
i++
swap(arr[i], arr[j])
swap(arr[i+1], arr[high])
return i+1
Pivot selection strategies:
-
First/last element (worst for sorted arrays)
-
Random element (expected O(n log n))
-
Median-of-three (first, middle, last)
5.7 Heap Sort
function heapSort(arr):
buildMaxHeap(arr)
for i ← length(arr)-1 down to 1:
swap(arr[0], arr[i])
heapify(arr, 0, i)
return arr
Part 6: Searching Algorithms
6.1 Linear Search
function linearSearch(arr, target):
for i ← 0 to length(arr)-1:
if arr[i] == target:
return i
return -1
Time: O(n), Space: O(1)
6.2 Binary Search (for sorted arrays)
function binarySearch(arr, target):
left ← 0
right ← length(arr)-1
while left ≤ right:
mid ← left + (right-left)//2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left ← mid+1
else:
right ← mid-1
return -1
Time: O(log n), Space: O(1) (iterative) or O(log n) (recursive)
6.3 Exponential Search
Used for unbounded or infinite arrays:
-
Find range where target lies (double index)
-
Binary search within range
Time: O(log n)
Part 7: Hashing and Hash Tables
7.1 Hash Table Fundamentals
Hash table: Data structure mapping keys to values using a hash function.
| Operation | Average Case | Worst Case |
|---|---|---|
| Insert | O(1) | O(n) |
| Search | O(1) | O(n) |
| Delete | O(1) | O(n) |
7.2 Hash Functions
Properties of good hash function:
-
Deterministic (same key → same hash)
-
Uniform distribution (minimizes collisions)
-
Fast to compute
Common hash functions:
-
Division method: h(k)=kmod m
-
Multiplication method: h(k)=⌊m(kAmod 1)⌋
7.3 Collision Resolution
Chaining: Each bucket contains linked list of entries.
Open Addressing:
-
Linear probing: h(k,i)=(h′(k)+i)mod m
-
Quadratic probing: h(k,i)=(h′(k)+c1i+c2i2)mod m
-
Double hashing: h(k,i)=(h1(k)+i⋅h2(k))mod m
Load factor: α=n/m (n = entries, m = buckets)
7.4 Applications
-
Symbol tables (compilers)
-
Database indexing
-
Caches (e.g., LRU cache)
-
Sets and dictionaries
-
Counting frequencies
Part 8: Tree Data Structures
8.1 Binary Trees
Tree terminology:
| Term | Definition |
|---|---|
| Root | Topmost node |
| Parent | Node with child nodes |
| Child | Node connected to parent |
| Leaf | Node with no children |
| Depth | Number of edges from root |
| Height | Maximum depth of any node |
Binary Tree: Each node has at most two children (left, right).
Types:
-
Full binary tree: Every node has 0 or 2 children
-
Complete binary tree: All levels filled except possibly last (filled left to right)
-
Perfect binary tree: All internal nodes have 2 children, all leaves at same level
8.2 Binary Search Trees (BST)
BST Property: For every node:
-
Left subtree contains nodes with keys less than node’s key
-
Right subtree contains nodes with keys greater than node’s key
| Operation | Average | Worst Case |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
BST Operations:
function search(root, key):
if root is null or root.key == key: return root
if key < root.key: return search(root.left, key)
return search(root.right, key)
function insert(root, key):
if root is null: return newNode(key)
if key < root.key: root.left = insert(root.left, key)
else if key > root.key: root.right = insert(root.right, key)
return root
8.3 Tree Traversals
Depth-First Traversals:
| Traversal | Order | Uses |
|---|---|---|
| Preorder | Root → Left → Right | Copying tree, prefix expression |
| Inorder | Left → Root → Right | BST gives sorted order |
| Postorder | Left → Right → Root | Deleting tree, postfix expression |
preorder(root):
if root is null: return
visit(root)
preorder(root.left)
preorder(root.right)
inorder(root):
if root is null: return
inorder(root.left)
visit(root)
inorder(root.right)
postorder(root):
if root is null: return
postorder(root.left)
postorder(root.right)
visit(root)
Breadth-First Traversal (Level Order) :
levelOrder(root):
if root is null: return
queue ← new Queue()
queue.enqueue(root)
while queue not empty:
node ← queue.dequeue()
visit(node)
if node.left: queue.enqueue(node.left)
if node.right: queue.enqueue(node.right)
8.4 Balanced BSTs
| Structure | Guarantee | Height |
|---|---|---|
| AVL Tree | Balance factor = height(L) – height(R) ∈ {-1,0,1} | O(log n) |
| Red-Black Tree | Color properties | O(log n) |
AVL Rotations:
-
LL (Right rotation) : Left-left imbalance
-
RR (Left rotation) : Right-right imbalance
-
LR (Left-Right) : Left-right imbalance
-
RL (Right-Left) : Right-left imbalance
8.5 Heaps (Priority Queues)
Binary Heap: Complete binary tree satisfying heap property:
-
Max-Heap: Parent ≥ children
-
Min-Heap: Parent ≤ children
| Operation | Time Complexity |
|---|---|
| Insert | O(log n) |
| Extract Min/Max | O(log n) |
| Peek (find min/max) | O(1) |
| Build heap (from array) | O(n) |
Heapify (downward) :
function heapify(arr, n, i):
largest ← i
left ← 2*i + 1
right ← 2*i + 2
if left < n and arr[left] > arr[largest]: largest ← left
if right < n and arr[right] > arr[largest]: largest ← right
if largest ≠ i:
swap(arr[i], arr[largest])
heapify(arr, n, largest)
Applications:
-
Priority queues
-
Dijkstra’s algorithm
-
Huffman coding
-
K-way merge
8.6 Tries (Prefix Trees)
Trie: Tree structure for storing strings; each node represents a character.
| Operation | Time | Space |
|---|---|---|
| Insert | O(L) | O(1) per node |
| Search | O(L) | O(1) |
(L = length of string)
Applications: Autocomplete, spell checking, IP routing
Part 9: Graph Data Structures
9.1 Graph Fundamentals
Graph: G=(V,E) where V = vertices (nodes), E = edges (connections).
Graph Types:
| Type | Description |
|---|---|
| Undirected | Edges have no direction (bidirectional) |
| Directed | Edges have direction (arrows) |
| Weighted | Edges have numerical weights |
| Cyclic | Contains cycles |
| Acyclic | No cycles (DAG = Directed Acyclic Graph) |
Graph Representations:
| Representation | Space | Edge Check | Adjacent Vertices | Use Case |
|---|---|---|---|---|
| Adjacency Matrix | O(V²) | O(1) | O(V) | Dense graphs |
| Adjacency List | O(V+E) | O(V) (worst) | O(degree) | Sparse graphs |
9.2 Graph Traversals
Breadth-First Search (BFS) :
-
Uses queue
-
Finds shortest path in unweighted graphs
-
O(V+E) time
function BFS(graph, start):
visited ← set()
queue ← new Queue()
visited.add(start)
queue.enqueue(start)
while queue not empty:
vertex ← queue.dequeue()
for neighbor in graph[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.enqueue(neighbor)
Depth-First Search (DFS) :
-
Uses stack (or recursion)
-
O(V+E) time
function DFS(graph, start, visited):
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
DFS(graph, neighbor, visited)
9.3 Shortest Path Algorithms
| Algorithm | Graph Type | Time Complexity | Details |
|---|---|---|---|
| BFS | Unweighted | O(V+E) | Finds shortest path |
| Dijkstra | Non-negative weights | O((V+E) log V) with heap | Single source |
| Bellman-Ford | Any weights (no negative cycles) | O(VE) | Single source, detects negative cycles |
Dijkstra’s Algorithm:
function dijkstra(graph, start):
dist[start] ← 0
priorityQueue ← new MinHeap()
priorityQueue.insert(start, 0)
while priorityQueue not empty:
u ← priorityQueue.extractMin()
for each neighbor v of u:
if dist[u] + weight(u,v) < dist[v]:
dist[v] ← dist[u] + weight(u,v)
priorityQueue.decreaseKey(v, dist[v])
return dist
9.4 Minimum Spanning Tree (MST)
| Algorithm | Method | Time Complexity |
|---|---|---|
| Kruskal | Sort edges, use Union-Find | O(E log E) |
| Prim | Grow tree from vertex | O((V+E) log V) with heap |
Kruskal’s Algorithm:
function kruskal(graph):
sort edges by weight
initialize Union-Find (each vertex separate)
MST ← []
for each edge (u,v) in sorted order:
if find(u) ≠ find(v):
MST.append(edge)
union(u,v)
return MST
9.5 Topological Sort (DAGs)
Orders vertices such that for every edge u→v, u comes before v.
function topologicalSort(graph):
visited ← set()
stack ← []
for each vertex in graph:
if vertex not visited:
DFS_Topological(vertex, visited, stack)
return stack reversed
Kahn’s Algorithm (BFS based on indegree):
function topologicalSortKahn(graph):
indegree ← compute indegrees
queue ← vertices with indegree 0
result ← []
while queue not empty:
u ← queue.dequeue()
result.append(u)
for neighbor in graph[u]:
indegree[neighbor]--
if indegree[neighbor] == 0:
queue.enqueue(neighbor)
if length(result) < number of vertices: cycle detected
return result
Part 10: Algorithm Design Techniques
10.1 Divide and Conquer
Pattern:
-
Divide problem into smaller subproblems
-
Conquer by solving subproblems recursively
-
Combine solutions
Examples: Merge sort, quicksort, binary search
10.2 Dynamic Programming (DP)
Key insight: Solve overlapping subproblems, store results (memoization or tabulation).
Optimal substructure: Optimal solution can be constructed from optimal solutions of subproblems.
Overlapping subproblems: Same subproblem occurs multiple times.
Example: Fibonacci (DP) :
function fibDP(n):
if n ≤ 1: return n
dp ← array of size n+1
dp[0] = 0; dp[1] = 1
for i ← 2 to n:
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
Example: 0/1 Knapsack:
function knapsack(W, weights, values, n):
dp ← 2D array of size (n+1) × (W+1)
for i ← 0 to n:
for w ← 0 to W:
if i == 0 or w == 0: dp[i][w] = 0
elif weights[i-1] ≤ w:
dp[i][w] = max(values[i-1] + dp[i-1][w-weights[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
return dp[n][W]
Common DP Problems:
-
Longest Common Subsequence (LCS)
-
Longest Increasing Subsequence (LIS)
-
Edit Distance (Levenshtein distance)
-
Matrix Chain Multiplication
-
Coin Change
10.3 Greedy Algorithms
Principle: Make locally optimal choice at each step, hoping for globally optimal solution.
Examples:
-
Activity selection (earliest finish time)
-
Huffman coding
-
Fractional knapsack
-
Minimum spanning trees (Prim, Kruskal)
10.4 Backtracking
Principle: Incremental search; abandon partial solution when invalid.
Classic problems: N-Queens, Sudoku, subset sum, maze solving
Part 11: Key Formulas and Complexities Summary
| Data Structure | Access | Search | Insert | Delete | Space |
|---|---|---|---|---|---|
| Array (static) | O(1) | O(n) | N/A | N/A | O(n) |
| Dynamic Array | O(1) | O(n) | O(1)* | O(n) | O(n) |
| Linked List | O(n) | O(n) | O(1) | O(1) | O(n) |
| Stack (array) | O(1) top | O(n) | O(1) | O(1) | O(n) |
| Queue (array) | O(1) front | O(n) | O(1) | O(1) | O(n) |
| Hash Table (avg) | O(1) | O(1) | O(1) | O(1) | O(n) |
| BST (balanced) | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Heap | O(1) min | O(n) | O(log n) | O(log n) | O(n) |
(* Amortized for dynamic array append)
Part 12: Study Tips for CSE-2104
-
Master complexity analysis – Practice calculating time and space complexity for algorithms. Big-O notation appears in every exam.
-
Implement data structures from scratch – Understanding implementation details helps with debugging and optimization.
-
Practice recursion – Many algorithms (tree traversals, DFS, divide and conquer) rely on recursion. Understand base cases and recursive cases.
-
Learn to draw – Draw BST rotations, graph traversals, heap operations, and recursion trees to visualize algorithms.
-
Know the trade-offs – Every data structure has strengths and weaknesses. Be able to explain why to choose one over another.
-
Study pseudocode – Exams often use pseudocode; be comfortable reading and writing it.
-
Connect to real applications – Understanding where each data structure is used helps with retention.
Part 13: Recommended Resources
| Resource | Focus |
|---|---|
| Introduction to Algorithms (CLRS) | Comprehensive, rigorous |
| The Algorithm Design Manual | Practical, problem-focused |
| Grokking Algorithms | Visual, beginner-friendly |
| LeetCode | Coding practice |
| GeeksforGeeks | Reference and examples |
CSE-2103: Digital Logic Design
Here are detailed study notes for CSE-2103: Digital Logic Design, written from a Computer Science/Computer Engineering perspective. These notes cover the fundamental principles of digital logic—number systems, Boolean algebra, logic gates, combinational circuits, sequential circuits, finite state machines, memory elements, and programmable logic devices. The emphasis is on understanding how to design, analyze, and optimize digital systems that form the foundation of modern computers.
1. Introduction to Digital Logic Design
1.1. What is Digital Logic Design?
Digital Logic Design is the foundation of computer engineering that deals with the design and analysis of digital circuits using binary logic. It forms the basis for all digital systems, from simple calculators to complex microprocessors.
The Core Question: How do we represent and manipulate information using binary signals (0 and 1) to build circuits that perform arithmetic, storage, and control functions?
1.2. Analog vs. Digital Signals
| Aspect | Analog | Digital |
|---|---|---|
| Signal values | Continuous range | Discrete (0 and 1) |
| Noise immunity | Low | High |
| Accuracy | Limited by components | Limited by resolution |
| Storage | Difficult | Easy |
| Processing | Limited | Versatile |
| Examples | Audio, temperature | Computers, smartphones |
1.3. Digital Logic Levels
Voltage
↑
5V ─┼─────────┐
│ │ High (logic 1)
│ │
│ │
│ │
│ │
│ │
│ │
│ │ Low (logic 0)
│ │
0V ─┴─────────┴──→
Time
| Logic Family | V_IL (max) | V_IH (min) | V_OL (max) | V_OH (min) |
|---|---|---|---|---|
| TTL | 0.8 V | 2.0 V | 0.4 V | 2.4 V |
| CMOS (5V) | 1.5 V | 3.5 V | 0.1 V | 4.9 V |
| LVTTL (3.3V) | 0.8 V | 2.0 V | 0.4 V | 2.4 V |
2. Number Systems and Codes
2.1. Number Systems
| Base | System | Digits | Example |
|---|---|---|---|
| 2 | Binary | 0, 1 | 1011₂ |
| 8 | Octal | 0-7 | 173₈ |
| 10 | Decimal | 0-9 | 123₁₀ |
| 16 | Hexadecimal | 0-9, A-F | 7B₍₁₆₎ |
2.2. Conversion Between Bases
Binary to Decimal:
(1011)2=1×23+0×22+1×21+1×20=8+0+2+1=1110
Decimal to Binary (Repeated Division):
-
Divide by 2 repeatedly, collect remainders from last to first
Binary to Hexadecimal:
-
Group binary digits in groups of 4 (from right)
-
Convert each group to hex digit
Binary to Octal:
-
Group binary digits in groups of 3 (from right)
2.3. Binary Arithmetic
Addition:
| 0+0=0 | 0+1=1 | 1+0=1 | 1+1=0 carry 1 |
Subtraction:
| 0-0=0 | 1-0=1 | 1-1=0 | 0-1=1 borrow 1 |
2.4. Signed Number Representations
Sign-Magnitude:
-
Most significant bit = sign (0=positive, 1=negative)
-
Remaining bits = magnitude
-
Range: −(2n−1−1) to +(2n−1−1)
-
Two representations for zero (+0 and -0)
1’s Complement:
-
Positive: same as binary
-
Negative: complement all bits
-
Range: −(2n−1−1) to +(2n−1−1)
-
Two zeros
2’s Complement (Most Common):
-
Positive: same as binary
-
Negative: complement all bits and add 1
-
Range: −2n−1 to +(2n−1−1)
-
Single zero representation
| n-bit | Sign-Magnitude | 1’s Complement | 2’s Complement |
|---|---|---|---|
| Range | −(2n−1−1) to +(2n−1−1) | −(2n−1−1) to +(2n−1−1) | −2n−1 to +(2n−1−1) |
| Zeros | 2 | 2 | 1 |
Example (4-bit):
| Decimal | Sign-Magnitude | 1’s Complement | 2’s Complement |
|---|---|---|---|
| +5 | 0101 | 0101 | 0101 |
| -5 | 1101 | 1010 | 1011 |
2.5. Binary Codes
BCD (Binary Coded Decimal):
-
Each decimal digit represented by 4-bit binary
-
Example: 123₁₀ = 0001 0010 0011 (BCD)
ASCII (American Standard Code for Information Interchange):
-
7-bit code for characters
-
128 characters (0-127)
| ASCII | Binary | Character |
|---|---|---|
| ‘0’ | 0110000 | 48 decimal |
| ‘A’ | 1000001 | 65 decimal |
| ‘a’ | 1100001 | 97 decimal |
Gray Code:
-
Successive codes differ in only one bit
-
Used in shaft encoders, Karnaugh maps
| Decimal | Binary | Gray |
|---|---|---|
| 0 | 000 | 000 |
| 1 | 001 | 001 |
| 2 | 010 | 011 |
| 3 | 011 | 010 |
| 4 | 100 | 110 |
Conversion:
-
Binary to Gray: Gi=Bi⊕Bi+1
-
Gray to Binary: Bi=Gi⊕Bi+1
3. Boolean Algebra and Logic Gates
3.1. Basic Logic Gates
| Gate | Symbol | Expression | Truth Table |
|---|---|---|---|
| NOT | —○— | Y=A‾ | 0→1, 1→0 |
| AND | —&— | Y=A⋅B | 00→0, 01→0, 10→0, 11→1 |
| OR | —≥1— | Y=A+B | 00→0, 01→1, 10→1, 11→1 |
| NAND | —&○— | Y=A⋅B‾ | 00→1, 01→1, 10→1, 11→0 |
| NOR | —≥1○— | Y=A+B‾ | 00→1, 01→0, 10→0, 11→0 |
| XOR | —=1— | Y=A⊕B | 00→0, 01→1, 10→1, 11→0 |
| XNOR | —=1○— | Y=A⊕B‾ | 00→1, 01→0, 10→0, 11→1 |
3.2. Boolean Algebra Laws
Basic Laws:
| Law | AND Form | OR Form |
|---|---|---|
| Identity | A⋅1=A | A+0=A |
| Null | A⋅0=0 | A+1=1 |
| Idempotent | A⋅A=A | A+A=A |
| Complement | A⋅A‾=0 | A+A‾=1 |
| Involution | A‾‾=A | A‾‾=A |
Commutative:
A+B=B+A,A⋅B=B⋅A
Associative:
(A+B)+C=A+(B+C),(A⋅B)⋅C=A⋅(B⋅C)
Distributive:
A⋅(B+C)=A⋅B+A⋅CA+(B⋅C)=(A+B)⋅(A+C)
Absorption:
A+A⋅B=A,A⋅(A+B)=A
DeMorgan’s Theorems:
A⋅B‾=A‾+B‾A+B‾=A‾⋅B‾
3.3. Universal Gates
NAND Gate as Universal Gate:
-
NOT: A‾=A⋅A (NAND with inputs tied)
-
AND: A⋅B=A⋅B‾‾ (NAND followed by NAND)
-
OR: A+B=A‾⋅B‾‾ (NAND with inverted inputs)
NOR Gate as Universal Gate:
-
NOT: A‾=A+A (NOR with inputs tied)
-
OR: A+B=A+B‾‾ (NOR followed by NOR)
-
AND: A⋅B=A‾+B‾‾ (NOR with inverted inputs)
3.4. Logic Gate IC Families
| Family | Speed | Power | Characteristics |
|---|---|---|---|
| TTL (74xx) | Medium | High | Standard logic |
| LS-TTL (74LSxx) | Medium | Low | Low power Schottky |
| CMOS (74HCxx) | Medium | Very low | High speed CMOS |
| HCT (74HCTxx) | Medium | Very low | TTL-compatible CMOS |
| ECL (10xxx) | Very fast | Very high | Emitter-coupled logic |
4. Combinational Logic Circuits
4.1. Boolean Function Simplification
Sum-of-Products (SOP):
F=A‾B+AB‾+AB
Product-of-Sums (POS):
F=(A+B‾)(A‾+B)
4.2. Karnaugh Maps (K-Maps)
2-Variable K-Map:
B 0 1 A 0|m0|m1| 1|m2|m3|
3-Variable K-Map:
BC
00 01 11 10
A 0 | m0| m1| m3| m2|
1 | m4| m5| m7| m6|
4-Variable K-Map:
CD
00 01 11 10
AB 00 | m0| m1| m3| m2|
01 | m4| m5| m7| m6|
11 | m12|m13|m15|m14|
10 | m8| m9| m11|m10|
K-Map Rules:
-
Groups must be rectangular (powers of 2: 1, 2, 4, 8, 16)
-
Groups can wrap around edges
-
Larger groups = simpler expression
-
Don’t cares (X) can be used as 0 or 1
Don’t Cares: Represented by X (can be used as 0 or 1 for simplification)
4.3. Quine-McCluskey Tabular Method
Used for simplifying Boolean functions with many variables.
Steps:
-
List minterms in binary
-
Group by number of 1’s
-
Compare adjacent groups, combine terms
-
Create prime implicant chart
-
Find minimal cover
4.4. Combinational Logic Design
Design Process:
-
Define problem (specification)
-
Determine inputs and outputs
-
Create truth table
-
Derive Boolean expression
-
Simplify expression (K-map or Q-M)
-
Implement with logic gates
4.5. Common Combinational Circuits
Half Adder:
| A | B | Sum | Carry |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0 | 1 | 1 | 0 |
| 1 | 0 | 1 | 0 |
| 1 | 1 | 0 | 1 |
S=A⊕B,C=A⋅B
Full Adder:
| A | B | Cin | Sum | Cout |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 1 | 1 | 0 |
| 0 | 1 | 0 | 1 | 0 |
| 0 | 1 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 | 0 |
| 1 | 0 | 1 | 0 | 1 |
| 1 | 1 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 | 1 |
S=A⊕B⊕CinCout=AB+ACin+BCin
Ripple Carry Adder: Multiple full adders cascaded
Carry Lookahead Adder:
-
Generate: Gi=Ai⋅Bi
-
Propagate: Pi=Ai⊕Bi
-
Carry: Ci=Gi−1+Pi−1⋅Ci−1
Multiplexer (MUX):
-
Selects one of many inputs
-
2-to-1 MUX: Y=S‾⋅I0+S⋅I1
Demultiplexer (DEMUX):
-
Routes one input to one of many outputs
Decoder:
-
Converts n-bit input to 2n outputs (one active)
-
Example: 2-to-4 decoder
Encoder:
-
Converts active input to n-bit output
-
Priority encoder: highest priority input encoded
Comparator:
-
Compares two binary numbers
-
Outputs: A=B, A>B, A<B
5. Sequential Logic Circuits
5.1. Latches vs. Flip-Flops
| Feature | Latch | Flip-Flop |
|---|---|---|
| Triggering | Level-sensitive | Edge-triggered |
| Transparency | Transparent when enabled | Not transparent |
| Timing | Output changes while enable is active | Output changes only at clock edge |
| Usage | Simple storage | Registers, counters |
5.2. Latches
SR Latch (NOR-based):
S ──┬──[NOR]── Q
│ │
└────┤
│
R ──┬──[NOR]── Q̄
│ │
└────┘
| S | R | Q | Q̄ | State |
|---|---|---|---|---|
| 0 | 0 | Q | Q̄ | Hold |
| 0 | 1 | 0 | 1 | Reset |
| 1 | 0 | 1 | 0 | Set |
| 1 | 1 | 0 | 0 | Invalid |
SR Latch (NAND-based):
-
Active low inputs (S̄, R̄)
D Latch:
-
Transparent when enable = 1
-
Q=D when enable = 1
-
Holds when enable = 0
5.3. Flip-Flops
SR Flip-Flop (Edge-Triggered):
-
Same truth table as SR latch, but changes only at clock edge
D Flip-Flop (Edge-Triggered):
-
Simplest flip-flop
-
Q(t+1)=D
-
Used for registers
JK Flip-Flop:
| J | K | Q(t+1) |
|---|---|---|
| 0 | 0 | Q(t) (hold) |
| 0 | 1 | 0 (reset) |
| 1 | 0 | 1 (set) |
| 1 | 1 | Q(t)‾ (toggle) |
T Flip-Flop (Toggle):
-
T=1 → toggle
-
T=0 → hold
-
Can be made from JK (J=K=T)
5.4. Flip-Flop Timing Parameters
| Parameter | Description |
|---|---|
| Setup time (t_su) | Minimum time D must be stable before clock edge |
| Hold time (t_h) | Minimum time D must be stable after clock edge |
| Propagation delay (t_pd) | Time from clock edge to output change |
| Clock-to-Q delay (t_cq) | Same as propagation delay |
| Clock period (T) | Minimum time between clock edges |
Timing Constraint:
T≥tpd,FF+tpd,logic+tsu
5.5. Sequential Circuit Analysis
State Transition Table:
-
Present state, input → next state, output
State Diagram:
-
Circles = states
-
Arrows = transitions (labeled with input/output)
State Equations:
-
Derived from flip-flop input equations
5.6. Sequential Circuit Design
Design Steps:
-
Define problem (specification)
-
Create state diagram
-
Create state transition table
-
Choose flip-flop type
-
Derive flip-flop input equations
-
Derive output equations
-
Implement with logic gates
6. Counters and Registers
6.1. Registers
Parallel Load Register:
-
Loads all bits simultaneously
-
Used as temporary storage
Shift Register:
-
Shifts bits left or right on each clock
-
Types:
-
Serial-In, Serial-Out (SISO)
-
Serial-In, Parallel-Out (SIPO)
-
Parallel-In, Serial-Out (PISO)
-
Parallel-In, Parallel-Out (PIPO)
-
Universal Shift Register:
-
Can shift left, shift right, load parallel, hold
-
Control signals determine operation
6.2. Counters
Ripple (Asynchronous) Counter:
-
Flip-flops change sequentially (not simultaneously)
-
Simpler but slower
Synchronous Counter:
-
All flip-flops change simultaneously
-
More complex but faster
Up/Down Counter:
-
Can count up or down
-
Direction control input
BCD Counter (Decade Counter):
-
Counts 0-9, then resets to 0
-
Mod-10 counter
Mod-N Counter:
-
Counts 0 to N-1
-
Reset logic to reset after N states
6.3. Counter Design Example
Mod-4 Synchronous Up Counter:
-
States: 00 → 01 → 10 → 11 → 00
-
Use JK flip-flops
-
J₀ = 1, K₀ = 1
-
J₁ = Q₀, K₁ = Q₀
7. Finite State Machines (FSM)
7.1. Types of FSMs
| Type | Output | Equation |
|---|---|---|
| Mealy Machine | Depends on state and input | Output=f(state,input) |
| Moore Machine | Depends only on state | Output=f(state) |
Mealy vs. Moore Comparison:
| Aspect | Mealy | Moore |
|---|---|---|
| Output timing | After input changes | After clock edge |
| Number of states | Fewer | More |
| Combinational output logic | Yes | No |
| Speed | Faster | Slower (synchronous) |
7.2. FSM Design Steps
-
Define states and transitions
-
Draw state diagram
-
Create state transition table
-
State assignment (assign binary codes)
-
Derive next-state logic
-
Derive output logic
-
Implement with flip-flops and gates
7.3. State Reduction
-
Equivalent states can be merged
-
Use implication table or row matching
7.4. State Assignment
| Method | Description |
|---|---|
| Sequential | 00, 01, 10, 11 |
| Gray code | 00, 01, 11, 10 |
| One-hot | One flip-flop per state (n states = n flip-flops) |
| Johnson | Shift register encoding |
One-hot Encoding Advantages:
-
Simplified next-state logic
-
Faster (no decoding)
-
More flip-flops (but simpler logic)
8. Memory and Programmable Logic
8.1. Memory Types
RAM (Random Access Memory):
| Type | Volatile | Speed | Use |
|---|---|---|---|
| SRAM (Static) | Yes | Very fast | Cache |
| DRAM (Dynamic) | Yes | Fast | Main memory |
ROM (Read-Only Memory):
| Type | Programmable | Erasable | Use |
|---|---|---|---|
| Mask ROM | No | No | Mass production |
| PROM | Once | No | Prototyping |
| EPROM | Yes | UV light | Development |
| EEPROM | Yes | Electrically | Firmware |
| Flash | Yes | Electrically | Storage |
8.2. Memory Organization
Addressing:
Memory size=2n×m
Where:
-
n = number of address lines
-
m = bits per word
Example: 64K × 8 memory → 64K = 216 → 16 address lines, 8 data lines
8.3. Programmable Logic Devices (PLDs)
| Device | Logic | Complexity |
|---|---|---|
| PROM | Fixed AND, programmable OR | Low |
| PLA | Programmable AND, programmable OR | Medium |
| PAL | Programmable AND, fixed OR | Medium |
| GAL | Electrically erasable PAL | Medium |
| CPLD | Multiple PLDs on one chip | High |
| FPGA | Configurable logic blocks + interconnect | Very high |
PROM Architecture:
-
Address lines → fixed AND array (decoder)
-
Programmable OR array
-
Used as look-up table (LUT)
PLA Architecture:
-
Programmable AND array
-
Programmable OR array
-
Most flexible but expensive
PAL Architecture:
-
Programmable AND array
-
Fixed OR array
-
Less flexible but cheaper
8.4. FPGA (Field Programmable Gate Array)
FPGA Architecture:
┌─────────────────────────────────────────────────────┐ │ I/O Blocks ┌─────────────────────────────┐ │ │ ┌─────────┐ │ Configurable Logic │ │ │ │ CLB │ │ Blocks (CLBs) │ │ │ ├─────────┤ │ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │ │ │ │ CLB │ │ │CLB│ │CLB│ │CLB│ │CLB│ │ │ │ ├─────────┤ │ └───┘ └───┘ └───┘ └───┘ │ │ │ │ CLB │ │ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │ │ │ ├─────────┤ │ │CLB│ │CLB│ │CLB│ │CLB│ │ │ │ │ CLB │ │ └───┘ └───┘ └───┘ └───┘ │ │ │ └─────────┘ └─────────────────────────────┘ │ │ ↑ │ │ Programmable Interconnect │ └─────────────────────────────────────────────────────┘
FPGA Components:
-
CLB (Configurable Logic Block): Contains LUTs, flip-flops, multiplexers
-
LUT (Look-Up Table): Implements any Boolean function of 4-6 inputs
-
Flip-flops: For sequential logic
-
Programmable interconnect: Connects CLBs
-
I/O blocks: Interface to external pins
9. Hazards and Timing
9.1. Static Hazards
| Type | Description | Detection |
|---|---|---|
| Static-1 | Output temporarily goes to 0 when should be 1 | Adjacent minterms not covered by same product term |
| Static-0 | Output temporarily goes to 1 when should be 0 | Adjacent maxterms not covered |
Static-1 Hazard Example:
F=A+A‾B
Elimination: Add redundant term A‾⋅B
9.2. Dynamic Hazards
-
Output changes multiple times
-
Caused by multiple paths with different delays
-
More difficult to eliminate
9.3. Hazard-Free Design
Methods:
-
Use synchronous design (clocked circuits)
-
Add redundant gates (cover overlapping minterms)
-
Use flip-flops to sample stable outputs
10. Algorithmic State Machines (ASM)
10.1. ASM Chart
ASM chart is a flowchart representation of a finite state machine.
Symbols:
-
State box: Rectangle (Moore output)
-
Decision box: Diamond (condition)
-
Conditional output box: Oval (Mealy output)
┌─────────────┐
│ State │ ← Moore outputs
│ S1 │
└──────┬──────┘
│
┌────▼────┐
│ X ? │ ← Decision
└────┬────┘
│
┌──────▼──────┐
│ Conditional │ ← Mealy outputs
│ Output │
└─────────────┘
10.2. ASM to Hardware
-
Identify states
-
Assign state codes
-
Derive next-state logic
-
Derive output logic
11. Summary Table: Flip-Flop Truth Tables
| FF | Inputs | Q(t+1) |
|---|---|---|
| D | D=0 | 0 |
| D=1 | 1 | |
| JK | J=0,K=0 | Q(t) |
| J=0,K=1 | 0 | |
| J=1,K=0 | 1 | |
| J=1,K=1 | Q(t)‾ | |
| T | T=0 | Q(t) |
| T=1 | Q(t)‾ |
12. Key Equations Reference Sheet
| Equation | Description |
|---|---|
| Gi=Ai⋅Bi | Carry generate |
| Pi=Ai⊕Bi | Carry propagate |
| Ci+1=Gi+PiCi | Carry lookahead |
| S=A⊕B⊕Cin | Full adder sum |
| Cout=AB+ACin+BCin | Full adder carry |
| A⋅B‾=A‾+B‾ | DeMorgan’s theorem |
| A+B‾=A‾⋅B‾ | DeMorgan’s theorem |
| Q(t+1)=D | D flip-flop |
| Q(t+1)=JQ‾+K‾Q | JK flip-flop |
| Q(t+1)=T⊕Q | T flip-flop |
13. Standard Textbooks
| Author | Title | Focus |
|---|---|---|
| Mano & Ciletti | Digital Design | Comprehensive |
| Morris Mano | Digital Logic and Computer Design | Classic |
| Brown & Vranesic | Fundamentals of Digital Logic with VHDL Design | Modern approach |
| Wakerly | Digital Design: Principles and Practices | Practical |
| Roth | Fundamentals of Logic Design | Beginner-friendly |
14. Final Study Checklist
| Topic | Key Skills |
|---|---|
| Number Systems | Convert between binary, octal, decimal, hex |
| Boolean Algebra | Simplify expressions; apply DeMorgan’s theorem |
| K-Maps | Simplify 3, 4 variable expressions; handle don’t cares |
| Combinational Circuits | Design adder, multiplexer, decoder, comparator |
| Sequential Circuits | Analyze state diagrams; design counters and FSMs |
| Flip-Flops | Convert between flip-flop types; calculate timing |
| FSM Design | Design Mealy and Moore machines; perform state reduction |
| Memory/PLDs | Understand PROM, PLA, PAL, FPGA architectures |
CSE-2201: Computer Architecture & Organization – Comprehensive Study Notes
These notes provide a complete framework for Computer Architecture & Organization, covering the fundamental principles of how computer systems are structured, how they execute instructions, and how their components interact. The focus is on understanding the hardware-software interface, processor design, memory hierarchy, I/O systems, and performance evaluation.
Part 1: Introduction to Computer Architecture
1.1 What is Computer Architecture?
Computer architecture is the design of the functional behavior of a computer system, including the instruction set, hardware components, and their interconnections. It serves as the interface between hardware and software.
Computer organization deals with the physical implementation of the architectural specifications—how the components are arranged and connected.
| Aspect | Computer Architecture | Computer Organization |
|---|---|---|
| Focus | What the computer does | How the computer does it |
| Level | High-level, visible to programmer | Low-level, implementation details |
| Examples | Instruction set, addressing modes | Data paths, control signals, memory technology |
1.2 The Von Neumann Architecture
The Von Neumann architecture is the foundational design for most modern computers. It consists of:
┌─────────────────────────────────────┐
│ Central Processing │
│ Unit (CPU) │
│ ┌─────────┐ ┌─────────────┐ │
│ │ ALU │ │ Control │ │
│ │ │ │ Unit │ │
│ └────┬────┘ └──────┬──────┘ │
│ │ │ │
│ ┌────┴────────────────┴────┐ │
│ │ Registers │ │
│ └────────────┬─────────────┘ │
└───────────────┼─────────────────────┘
│
┌───────────────┼───────────────┐
│ │ │
┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐
│ Memory │ │ Input │ │ Output │
│ (RAM) │ │ Devices │ │ Devices │
└───────────┘ └───────────┘ └───────────┘
Key Characteristics of Von Neumann Architecture:
| Characteristic | Description |
|---|---|
| Single memory | Instructions and data share the same memory space |
| Stored program | Instructions are stored in memory and executed sequentially |
| Sequential execution | Instructions are fetched and executed one at a time |
| Control unit | Decodes instructions and generates control signals |
The Von Neumann Bottleneck: The single bus between CPU and memory limits throughput because instructions and data must travel over the same path.
1.3 Harvard Architecture
Harvard architecture has separate memory and buses for instructions and data, allowing simultaneous fetch of instructions and data.
| Feature | Von Neumann | Harvard |
|---|---|---|
| Memory | Single (instructions + data) | Separate (instruction memory, data memory) |
| Buses | One | Two (or more) |
| Parallelism | Sequential fetch/execute | Simultaneous fetch/execute |
| Applications | General-purpose computers | Embedded systems, DSPs |
1.4 RISC vs. CISC Architectures
| Feature | RISC (Reduced Instruction Set Computer) | CISC (Complex Instruction Set Computer) |
|---|---|---|
| Instructions | Simple, fixed-length (32 bits) | Complex, variable-length (1-15 bytes) |
| Number of instructions | Few (typically <100) | Many (200-300+) |
| Addressing modes | Few (typically 1-2) | Many (5-10+) |
| Memory access | Only load/store instructions | Many instructions can access memory |
| Register count | Many (32-64 registers) | Few (8-16 registers) |
| Compiler complexity | Higher (more optimization needed) | Lower |
| Hardware complexity | Simpler control unit | Complex control unit (microcoded) |
| Examples | ARM, MIPS, RISC-V, PowerPC | x86 (Intel, AMD) |
Part 2: CPU Organization
2.1 Basic CPU Components
| Component | Function |
|---|---|
| Arithmetic Logic Unit (ALU) | Performs arithmetic (add, subtract) and logical (AND, OR, NOT) operations |
| Control Unit (CU) | Decodes instructions and generates control signals |
| Registers | High-speed storage locations within CPU |
| Internal bus | Connects CPU components |
2.2 The Fetch-Execute Cycle
The CPU repeatedly executes the fetch-decode-execute cycle:
┌─────────────────────────────────────────────────────────────────┐ │ FETCH-EXECUTE CYCLE │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ FETCH │───▶│ DECODE │───▶│ EXECUTE │───▶│ STORE │ │ │ │ │ │ │ │ │ │ │ │ │ │ PC → MAR │ │ Decode │ │ ALU │ │ Result │ │ │ │ Read │ │ opcode │ │ operation│ │ → MDR │ │ │ │ MDR → IR │ │ │ │ │ │ → memory │ │ │ │ PC + 4 │ │ │ │ │ │ (if needed│ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘
Detailed Steps:
| Step | Operation | Registers Involved |
|---|---|---|
| 1. Fetch | Instruction address from PC → MAR; read memory; instruction → MDR → IR; PC increments | PC, MAR, MDR, IR |
| 2. Decode | Control unit interprets instruction (opcode and operands) | IR, Control Unit |
| 3. Execute | ALU performs operation; may access memory for data | ALU, Registers, MAR, MDR |
| 4. Store | Write result back to register or memory | Registers, MDR |
2.3 CPU Registers
| Register | Size (bits) | Function |
|---|---|---|
| Program Counter (PC) | 32/64 | Holds address of next instruction to execute |
| Instruction Register (IR) | 32/64 | Holds current instruction being executed |
| Memory Address Register (MAR) | 32/64 | Holds address for memory read/write |
| Memory Data Register (MDR) | 32/64 | Holds data to/from memory |
| Accumulator (ACC) | 32/64 | Holds ALU results (some architectures) |
| General Purpose Registers (GPRs) | 32/64 | Hold data and addresses for computations |
| Stack Pointer (SP) | 32/64 | Points to top of stack |
| Status Register (Flags) | 8-32 | Holds condition flags (zero, carry, overflow, negative) |
2.4 Instruction Formats
Instructions typically contain:
| Field | Description | Bits |
|---|---|---|
| Opcode | Operation to perform (ADD, SUB, LOAD, etc.) | Variable (6-10 bits) |
| Source operand(s) | Register or memory address of data | 3-5 bits per operand |
| Destination operand | Where to store result | 3-5 bits |
Common Instruction Formats:
| Format | Fields | Example |
|---|---|---|
| Zero-address | Only opcode (stack machines) | ADD |
| One-address | Opcode + one operand (accumulator) | LOAD X |
| Two-address | Opcode + two operands (dest = src1 op src2) | ADD R1, R2 |
| Three-address | Opcode + three operands | ADD R1, R2, R3 |
2.5 Addressing Modes
Addressing modes specify how to compute the effective address of an operand.
| Mode | Syntax | Effective Address | Example |
|---|---|---|---|
| Immediate | #value |
Value is operand | ADD #5, R1 |
| Register | R1 |
Operand in register | ADD R1, R2 |
| Direct (Absolute) | [address] |
Address from instruction | LOAD [1000] |
| Indirect | [[R1]] |
Memory address from register | LOAD [[R1]] |
| Indexed | [R1 + offset] |
Register + offset | LOAD [R1 + 4] |
| Base + Index | [R1 + R2] |
Register + register | LOAD [R1 + R2] |
| Relative | [PC + offset] |
PC + offset | JMP 100 |
Part 3: Memory Hierarchy
3.1 The Memory Hierarchy
The memory hierarchy balances speed, cost, and capacity:
┌─────────────────────────────────────────────────────────────────────┐ │ MEMORY HIERARCHY │ │ │ │ ┌─────────────────────────────────────────────────────────────┐ │ │ │ CPU Registers (1 ns, <1 KB) │ │ │ │ ↑ Cost: highest │ Speed: fastest │ Size: smallest │ │ │ ├─────────────────────────────────────────────────────────────┤ │ │ │ Cache (L1/L2/L3) (2-10 ns, 1-20 MB) │ │ │ ├─────────────────────────────────────────────────────────────┤ │ │ │ Main Memory (DRAM) (50-100 ns, 4-64 GB) │ │ │ ├─────────────────────────────────────────────────────────────┤ │ │ │ SSD (10-50 μs, 256 GB - 4 TB) │ │ │ ├─────────────────────────────────────────────────────────────┤ │ │ │ HDD (5-10 ms, 1-20 TB) │ │ │ └─────────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────────┘
3.2 Cache Memory
Cache is a small, fast memory that stores frequently accessed data and instructions to reduce average memory access time.
Cache Principles:
| Principle | Description |
|---|---|
| Locality of reference | Programs tend to access memory locations that are near recently accessed locations |
| Temporal locality | Recently accessed data is likely to be accessed again |
| Spatial locality | Data near recently accessed data is likely to be accessed |
Cache Organization:
| Aspect | Description |
|---|---|
| Block (Line) | Smallest unit of data transferred between cache and memory (typically 32-128 bytes) |
| Hit | Data found in cache |
| Miss | Data not found in cache (must fetch from memory) |
Cache Mapping Schemes:
| Scheme | Description | Advantages | Disadvantages |
|---|---|---|---|
| Direct Mapped | Each memory block maps to exactly one cache line | Simple, fast | High conflict miss rate |
| Fully Associative | Any block can go anywhere in cache | Lowest miss rate | Complex, expensive hardware |
| Set Associative | Cache divided into sets; block maps to any line in a set | Balanced performance/cost | Moderate complexity |
Cache Write Policies:
| Policy | Description | When Used |
|---|---|---|
| Write-through | Write to cache and memory simultaneously | Simple, ensures consistency |
| Write-back | Write only to cache; mark dirty; write to memory on eviction | Reduces memory traffic |
Cache Replacement Policies:
| Policy | Description |
|---|---|
| LRU (Least Recently Used) | Replace the block that hasn’t been used for the longest time |
| FIFO (First-In-First-Out) | Replace the oldest block |
| Random | Replace a random block |
| LFU (Least Frequently Used) | Replace the least frequently accessed block |
3.3 Main Memory (DRAM)
DRAM (Dynamic Random Access Memory) is the primary memory technology for main memory.
| Feature | Description |
|---|---|
| Volatile | Data lost when power removed |
| Dynamic | Requires periodic refresh (every 64 ms) |
| Density | High (billions of cells per chip) |
| Access time | 50-100 ns |
DRAM Organization:
| Component | Function |
|---|---|
| Row address | Selects which row in memory array |
| Column address | Selects which column in the row |
| RAS (Row Address Strobe) | Control signal for row address |
| CAS (Column Address Strobe) | Control signal for column address |
Memory Modules:
| Type | Description | Data width |
|---|---|---|
| DIMM (Dual Inline Memory Module) | Standard for desktop/server | 64 bits + ECC |
| SO-DIMM | Smaller form factor for laptops | 64 bits |
| SDRAM | Synchronous DRAM (clocked) | Variable |
| DDR SDRAM | Double Data Rate (data on both clock edges) | Variable |
3.4 Virtual Memory
Virtual memory allows programs to use more memory than physically available by using disk storage as an extension of RAM.
Key Concepts:
| Concept | Description |
|---|---|
| Virtual address | Address generated by CPU (program’s view) |
| Physical address | Actual address in RAM |
| Page | Fixed-size block of virtual memory (typically 4 KB) |
| Frame | Fixed-size block of physical memory (same size as page) |
| Page fault | Access to page not in physical memory (must load from disk) |
| Page table | Maps virtual pages to physical frames |
| TLB (Translation Lookaside Buffer) | Cache for page table entries |
Page Table Structure:
| Field | Description |
|---|---|
| Frame number | Physical frame address |
| Valid bit | Indicates if page is in memory |
| Dirty bit | Page has been modified (must be written back) |
| Reference bit | Page has been accessed (used for replacement) |
| Protection bits | Read/write/execute permissions |
Part 4: Instruction Pipelining
4.1 Pipeline Concepts
Instruction pipelining overlaps the execution of multiple instructions to improve throughput.
Classic 5-Stage Pipeline:
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ IF │ │ ID │ │ EX │ │ MEM │ │ WB │ │ Instruction│→│ Instruction│→│ Execute │→│ Memory │→│ Write │ │ Fetch │ │ Decode │ │ │ │ Access │ │ Back │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘
| Stage | Operation | Active Components |
|---|---|---|
| IF (Instruction Fetch) | Fetch instruction from memory | PC, Instruction cache, MAR, MDR |
| ID (Instruction Decode) | Decode instruction, read registers | Control unit, Register file |
| EX (Execute) | Perform ALU operation | ALU |
| MEM (Memory Access) | Read/write data memory | Data cache, MAR, MDR |
| WB (Write Back) | Write result to register | Register file |
Pipeline Speedup:
Speedup=Time without pipelineTime with pipeline≈Number of stages
4.2 Pipeline Hazards
Hazards prevent the next instruction from executing in the next clock cycle.
4.2.1 Structural Hazards
Definition: Hardware resource conflicts when two instructions need the same resource simultaneously.
| Example | Solution |
|---|---|
| Single memory for instructions and data | Separate instruction and data caches (Harvard architecture) |
| Single ALU for multiple operations | Duplicate resources |
4.2.2 Data Hazards
Definition: Instruction depends on result of previous instruction that hasn’t completed.
| Type | Example | Description |
|---|---|---|
| RAW (Read After Write) | ADD R1, R2, R3 → SUB R4, R1, R5 |
Reads value before it’s written |
| WAR (Write After Read) | SUB R4, R1, R5 → ADD R1, R2, R3 |
Writes value before it’s read (rare in simple pipelines) |
| WAW (Write After Write) | ADD R1, R2, R3 → SUB R1, R4, R5 |
Writes in wrong order (rare in simple pipelines) |
Data Hazard Solutions:
| Technique | Description | Overhead |
|---|---|---|
| Stalling (Bubbles) | Insert no-op instructions until hazard resolved | Performance loss |
| Forwarding (Bypassing) | Forward result from EX stage to next instruction | Hardware complexity |
| Compiler scheduling | Reorder instructions to avoid hazards | Software complexity |
Forwarding Example:
ADD R1, R2, R3 (EX stage produces result) SUB R4, R1, R5 (needs R1 before WB)
Without forwarding: SUB must wait 2 cycles
With forwarding: Result from ADD’s EX stage forwarded directly to SUB’s EX stage
4.2.3 Control Hazards (Branch Hazards)
Definition: Pipeline incorrectly fetches instructions after a branch before knowing branch outcome.
Branch Prediction:
| Technique | Description | Accuracy |
|---|---|---|
| Static (always not taken) | Assume branch not taken | 50-60% |
| Static (always taken) | Assume branch taken | 50-60% |
| Branch target buffer (BTB) | Cache of branch targets | 80-90% |
| 2-bit predictor | History-based prediction | 90-95% |
2-Bit Saturated Counter:
Taken
00 (Strongly) ───────► 01 (Weakly)
Not Taken Not Taken
▲ │
│ ▼ Taken
│ 10 (Weakly)
│ │ Taken
│ ▼
└─────────────────── 11 (Strongly)
Not Taken
4.3 Pipeline Performance
CPI (Cycles Per Instruction):
CPIpipelined=1+Stall cycles per instruction
Speedup:
Speedup=CPInon-pipelinedCPIpipelined×Clock periodnon-pipelinedClock periodpipelined
Throughput:
Throughput=Number of instructionsTime=1CPI×Clock period
Part 5: Instruction Set Architecture (ISA)
5.1 ISA Components
The ISA is the contract between hardware and software, defining:
| Component | Description |
|---|---|
| Instruction set | Operations the processor can perform |
| Data types | Sizes and representations (byte, word, float) |
| Registers | Number, size, and purpose |
| Addressing modes | How to compute operand addresses |
| Memory model | Byte ordering, alignment requirements |
| I/O model | How to interact with devices |
5.2 MIPS ISA Example
MIPS (Microprocessor without Interlocked Pipeline Stages) is a classic RISC architecture.
MIPS Registers:
| Register | Number | Purpose |
|---|---|---|
$zero |
0 | Always 0 |
$at |
1 | Assembler temporary |
$v0-$v1 |
2-3 | Return values |
$a0-$a3 |
4-7 | Arguments |
$t0-$t7 |
8-15 | Temporaries (caller-saved) |
$s0-$s7 |
16-23 | Saved (callee-saved) |
$t8-$t9 |
24-25 | More temporaries |
$k0-$k1 |
26-27 | Kernel (OS) |
$gp |
28 | Global pointer |
$sp |
29 | Stack pointer |
$fp |
30 | Frame pointer |
$ra |
31 | Return address |
MIPS Instruction Formats:
| Format | 31-26 | 25-21 | 20-16 | 15-11 | 10-6 | 5-0 |
|---|---|---|---|---|---|---|
| R-type | opcode | rs | rt | rd | shamt | funct |
| I-type | opcode | rs | rt | immediate (16 bits) | ||
| J-type | opcode | address (26 bits) |
MIPS Instruction Examples:
| Instruction | Format | Operation | |
|---|---|---|---|
ADD rd, rs, rt |
R | rd = rs + rt | |
SUB rd, rs, rt |
R | rd = rs – rt | |
ADDI rt, rs, imm |
I | rt = rs + imm | |
LW rt, offset(rs) |
I | rt = Memory[rs + offset] | |
SW rt, offset(rs) |
I | Memory[rs + offset] = rt | |
BEQ rs, rt, label |
I | if (rs == rt) PC += offset | |
J label |
J | PC = (PC & 0xF0000000) | (address << 2) |
Part 6: Control Unit Design
6.1 Hardwired Control Unit
Hardwired control uses combinational logic to generate control signals directly from the instruction opcode.
| Aspect | Description |
|---|---|
| Implementation | Logic gates (AND, OR, NOT) |
| Speed | Fast |
| Flexibility | Difficult to modify |
| Complexity | Increases with instruction count |
| Applications | RISC processors, simple designs |
6.2 Microprogrammed Control Unit
Microprogrammed control uses a microcode ROM to generate control signals.
| Aspect | Description |
|---|---|
| Implementation | Microcode ROM + sequencer |
| Speed | Slower (ROM access time) |
| Flexibility | Easy to modify (update microcode) |
| Complexity | Regular, structured |
| Applications | CISC processors (x86), complex designs |
Microinstruction Fields:
| Field | Purpose |
|---|---|
| Control signals | Enable lines for ALU, registers, memory |
| Next address | Address of next microinstruction |
| Sequencing control | Conditional branching in microcode |
Part 7: Input/Output (I/O) Systems
7.1 I/O Interface
I/O devices connect to the computer through interfaces that handle:
-
Data formatting
-
Speed matching (buffering)
-
Protocol conversion
-
Error detection
7.2 I/O Communication Methods
| Method | Description | CPU Involvement | Performance |
|---|---|---|---|
| Programmed I/O | CPU polls device status register | High (busy-wait) | Low |
| Interrupt-driven I/O | Device interrupts CPU when ready | Moderate | Medium |
| Direct Memory Access (DMA) | Device transfers directly to/from memory | Low (only setup) | High |
Programmed I/O Flow:
1. CPU reads device status register 2. If device not ready, loop to step 1 3. CPU transfers data (one byte/word) 4. Repeat for next data
Interrupt-driven I/O Flow:
1. CPU continues other work 2. Device sends interrupt signal when ready 3. CPU saves context, executes interrupt handler 4. CPU transfers data 5. CPU restores context, resumes previous work
DMA I/O Flow:
1. CPU sets up DMA controller (memory address, count, direction) 2. DMA controller transfers data without CPU involvement 3. DMA controller interrupts CPU when complete
7.3 Interrupt Handling
Interrupt Types:
| Type | Source | Example |
|---|---|---|
| Hardware interrupt | External device | Keyboard, mouse, disk |
| Software interrupt (trap) | Program instruction | System call, divide by zero |
| Timer interrupt | Internal timer | Scheduling, timekeeping |
Interrupt Processing Steps:
| Step | Operation |
|---|---|
| 1 | Device asserts interrupt request line |
| 2 | CPU completes current instruction |
| 3 | CPU saves PC and status (to stack) |
| 4 | CPU disables interrupts (optional) |
| 5 | CPU jumps to interrupt vector address |
| 6 | Interrupt service routine (ISR) executes |
| 7 | CPU restores saved state |
| 8 | CPU re-enables interrupts |
| 9 | CPU resumes interrupted program |
7.4 Bus Architecture
System bus connects CPU, memory, and I/O devices.
| Bus Type | Function | Typical Width | Speed |
|---|---|---|---|
| Address bus | Carries memory addresses | 32-64 bits | Match CPU |
| Data bus | Carries data | 32-64 bits | Match CPU |
| Control bus | Carries control signals | 8-16 bits | Match CPU |
Bus Arbitration:
| Method | Description |
|---|---|
| Daisy chaining | Devices have priority based on physical position |
| Centralized (controller) | Single arbiter grants bus access |
| Distributed | Devices self-arbitrate |
Part 8: Performance Evaluation
8.1 Performance Metrics
| Metric | Formula | Interpretation |
|---|---|---|
| Clock rate | Frequency (GHz) | Higher = faster (but not directly comparable across architectures) |
| CPI (Cycles Per Instruction) | Total cycles / Instructions executed | Lower = better |
| IPC (Instructions Per Cycle) | 1 / CPI | Higher = better |
| Execution time | Instructions×CPIClock rate | Lower = better |
| MIPS (Millions Instructions Per Second) | Clock rateCPI×106 | Higher = better (architecture-dependent) |
| FLOPS (Floating Point Ops Per Second) | Floating point opsTime | Used for scientific computing |
CPU Time Calculation:
CPU Time=Instruction Count×CPI×Clock Cycle TimeCPU Time=Instruction Count×CPIClock Rate
8.2 Amdahl’s Law
Speedup=1(1−F)+FS
Where:
-
F = fraction of execution time that can be improved
-
S = speedup of that fraction
Example: If 80% of program can be parallelized (F=0.8) and parallel portion runs 4× faster (S=4):
Speedup=1(1−0.8)+0.84=10.2+0.2=2.5×
8.3 Performance Benchmarks
| Benchmark | Description | Use |
|---|---|---|
| SPEC (Standard Performance Evaluation Corp) | Industry standard for CPU performance | Comparing different processors |
| Dhrystone | Integer performance | Embedded systems |
| Whetstone | Floating-point performance | Scientific computing |
| Linpack | Linear algebra (matrix operations) | Supercomputers |
| CoreMark | Embedded processor benchmark | Microcontrollers |
Part 9: Key Formulas Summary
| Concept | Formula |
|---|---|
| CPU Time | Instruction Count × CPI × Clock Cycle Time |
| Clock Rate | 1 / Clock Cycle Time |
| MIPS | Clock Rate / (CPI × 10⁶) |
| Amdahl’s Law | Speedup = 1 / [(1-F) + F/S] |
| Pipeline Speedup | ≈ Number of pipeline stages (ideal) |
| Cache Hit Rate | Hits / (Hits + Misses) |
| Average Memory Access Time | Hit Time + Miss Rate × Miss Penalty |
| CPI with stalls | 1 + Stall cycles per instruction |
| Page Fault Rate | Page faults / Memory accesses |
Part 10: Study Tips for CSE-2201
-
Master the fetch-execute cycle – Understand each step (fetch, decode, execute, store) and which registers are involved.
-
Learn the memory hierarchy – Know the trade-offs between registers, cache, main memory, and disk (speed, cost, capacity).
-
Understand pipelining – Draw pipeline diagrams. Identify hazards (structural, data, control) and their solutions (forwarding, stalling, branch prediction).
-
Know RISC vs. CISC – Differences in instruction complexity, register count, addressing modes, and hardware complexity.
-
Practice with a specific ISA – MIPS is commonly used. Learn instruction formats, addressing modes, and basic assembly.
-
Calculate performance – Practice CPU time, CPI, MIPS, and Amdahl’s Law problems.
-
Connect to other courses – CSE-2201 builds on CSE-1501 (computing fundamentals) and CSE-2104 (data structures & algorithms).
-
Use the search results – The course syllabi provide detailed topics: CPU organization, memory hierarchy, I/O systems, and the fetch-execute cycle.
Part 11: Recommended Resources
| Resource | Focus |
|---|---|
| Computer Organization and Design – Patterson & Hennessy | RISC-V/MIPS focus |
| Computer Architecture: A Quantitative Approach – Hennessy & Patterson | Advanced topics |
| Structured Computer Organization – Tanenbaum | Accessible introduction |
| Digital Design and Computer Architecture – Harris & Harris | Hardware focus |
These notes provide a comprehensive framework for CSE-2201: Computer Architecture & Organization. Success requires understanding the fetch-execute cycle, mastering the memory hierarchy (registers, cache, main memory, disk), learning instruction pipelining (hazards and solutions), knowing RISC vs. CISC architectures, and evaluating performance (CPU time, CPI, MIPS, Amdahl’s Law). This course is fundamental for understanding how computers execute programs—essential for systems programming, compiler design, and performance optimization.
BS-2009 Complex Variable & Transform – Detailed Study Notes
These study notes are designed for undergraduate engineering and science students taking a course in Complex Variables and Transforms. The notes cover the fundamental principles of complex numbers, analytic functions, complex integration, series expansions, residues, Fourier transforms, Laplace transforms, and Z-transforms.
1. Complex Numbers
1.1 Definition and Representation
| Aspect | Detail |
|---|---|
| Definition | A complex number is of the form z=x+iy, where x,y∈R and i=−1. |
| Real part | Re(z)=x |
| Imaginary part | Im(z)=y |
| Geometric representation | Point (x,y) in the complex plane (Argand diagram) |
1.2 Forms of Complex Numbers
| Form | Expression | Relationships |
|---|---|---|
| Cartesian (Rectangular) | z=x+iy | x=rcosθ, y=rsinθ |
| Polar | z=r(cosθ+isinθ) | r=x2+y2, θ=tan−1(y/x) |
| Exponential (Euler) | z=reiθ | eiθ=cosθ+isinθ |
1.3 Modulus and Argument
| Term | Definition | Range | ||
|---|---|---|---|---|
| Modulus | ( | z | = r = \sqrt{x^2 + y^2} ) | [0,∞) |
| Argument | arg(z)=θ=tan−1(y/x) | Principal value: (−π,π] |
1.4 Complex Conjugate
| Aspect | Detail | ||
|---|---|---|---|
| Definition | zˉ=x−iy=re−iθ | ||
| Properties | z1±z2‾=z1ˉ±z2ˉ | ||
| z1z2‾=z1ˉz2ˉ | |||
| (z1/z2)‾=z1ˉ/z2ˉ | |||
| ( z\bar{z} = | z | ^2 ) | |
| z+zˉ=2Re(z) | |||
| z−zˉ=2iIm(z) |
1.5 Operations on Complex Numbers
Addition/Subtraction:
(x1+iy1)±(x2+iy2)=(x1±x2)+i(y1±y2)
Multiplication:
(x1+iy1)(x2+iy2)=(x1x2−y1y2)+i(x1y2+x2y1)r1eiθ1⋅r2eiθ2=r1r2ei(θ1+θ2)
Division:
x1+iy1x2+iy2=(x1+iy1)(x2−iy2)x22+y22r1eiθ1r2eiθ2=r1r2ei(θ1−θ2)
1.6 De Moivre’s Theorem
(cosθ+isinθ)n=cos(nθ)+isin(nθ)(reiθ)n=rneinθ
Applications:
-
Powers of complex numbers
-
Roots of unity: zn=1⇒z=e2πik/n, k=0,1,…,n−1
2. Analytic Functions
2.1 Functions of a Complex Variable
A complex function w=f(z)=u(x,y)+iv(x,y), where u and v are real-valued functions of x and y.
2.2 Limit and Continuity
limz→z0f(z)=L ⟺ lim(x,y)→(x0,y0)u(x,y)=u0 and lim(x,y)→(x0,y0)v(x,y)=v0
2.3 Differentiability
f′(z0)=limΔz→0f(z0+Δz)−f(z0)Δz
The limit must be independent of the path of Δz→0.
2.4 Cauchy-Riemann Equations (Necessary and Sufficient Conditions)
In Cartesian coordinates:
∂u∂x=∂v∂y,∂u∂y=−∂v∂x
In polar coordinates (z=reiθ):
∂u∂r=1r∂v∂θ,∂v∂r=−1r∂u∂θ
2.5 Analytic Function
Definition: f(z) is analytic at z0 if it is differentiable in some neighborhood of z0.
Properties:
-
Sum, product, quotient (non-zero denominator) of analytic functions are analytic
-
Composition of analytic functions is analytic
-
If f(z)=u+iv is analytic, then u and v are harmonic functions
2.6 Harmonic Functions
Definition: u(x,y) is harmonic if it satisfies Laplace’s equation:
∂2u∂x2+∂2u∂y2=0
Harmonic Conjugate: If f(z)=u+iv is analytic, then v is the harmonic conjugate of u.
Finding harmonic conjugate: Use Cauchy-Riemann equations:
∂v∂y=∂u∂x,∂v∂x=−∂u∂y
2.7 Elementary Analytic Functions
| Function | Definition | Derivative | ||
|---|---|---|---|---|
| Polynomial | f(z)=a0+a1z+⋯+anzn | f′(z)=a1+2a2z+⋯+nanzn−1 | ||
| Exponential | ez=ex(cosy+isiny) | ddzez=ez | ||
| Trigonometric | sinz=eiz−e−iz2i | ddzsinz=cosz | ||
| cosz=eiz+e−iz2 | ddzcosz=−sinz | |||
| Hyperbolic | sinhz=ez−e−z2 | ddzsinhz=coshz | ||
| coshz=ez+e−z2 | ddzcoshz=sinhz | |||
| Logarithmic | ( \text{Log } z = \ln | z | + i\arg(z) ) (principal value) | ddzlogz=1z |
| Power | za=ealogz | ddzza=aza−1 |
3. Complex Integration
3.1 Line Integral
∫Cf(z) dz=∫C(u dx−v dy)+i∫C(v dx+u dy)
3.2 Cauchy-Goursat Theorem (Cauchy’s Integral Theorem)
If f(z) is analytic in a simply connected domain D and on its boundary C, then:
∮Cf(z) dz=0
3.3 Cauchy’s Integral Formula
If f(z) is analytic inside and on a simple closed contour C and a is inside C, then:
f(a)=12πi∮Cf(z)z−a dz
Derivatives formula:
f(n)(a)=n!2πi∮Cf(z)(z−a)n+1 dz
3.4 Cauchy’s Inequality
If f(z) is analytic in ∣z−a∣<R and ∣f(z)∣≤M, then:
∣f(n)(a)∣≤n!MRn
3.5 Liouville’s Theorem
If f(z) is entire (analytic everywhere) and bounded, then f(z) is constant.
3.6 Fundamental Theorem of Algebra
Every polynomial of degree n≥1 has exactly n roots in the complex plane (counting multiplicities).
4. Series Expansions
4.1 Taylor Series
If f(z) is analytic at z=a, then:
f(z)=∑n=0∞f(n)(a)n!(z−a)n
valid for ∣z−a∣<R, where R is the distance from a to the nearest singularity.
4.2 Maclaurin Series (Taylor series at z=0)
ez=∑n=0∞znn!=1+z+z22!+z33!+⋯sinz=∑n=0∞(−1)nz2n+1(2n+1)!=z−z33!+z55!−⋯cosz=∑n=0∞(−1)nz2n(2n)!=1−z22!+z44!−⋯sinhz=∑n=0∞z2n+1(2n+1)!=z+z33!+z55!+⋯coshz=∑n=0∞z2n(2n)!=1+z22!+z44!+⋯11−z=∑n=0∞zn=1+z+z2+z3+⋯(∣z∣<1)log(1+z)=∑n=1∞(−1)n−1znn=z−z22+z33−⋯(∣z∣<1)
4.3 Laurent Series
If f(z) has an isolated singularity at z=a, then in an annulus r<∣z−a∣<R:
f(z)=∑n=−∞∞an(z−a)n
where:
an=12πi∮Cf(z)(z−a)n+1 dz
4.4 Classification of Isolated Singularities
| Type | Laurent Series | Behavior | Example | ||
|---|---|---|---|---|---|
| Removable | No negative powers | limz→af(z) exists | sinzz at z=0 | ||
| Pole of order m | Finite number of negative powers (up to −m) | ( \lim_{z \to a} | f(z) | = \infty ) | 1(z−1)2 at z=1 |
| Essential | Infinite negative powers | Does not have a limit | e1/z at z=0 |
5. Residue Theory
5.1 Residue Definition
For a function f(z) with an isolated singularity at z=a, the residue is:
Res(f,a)=a−1=12πi∮Cf(z) dz
5.2 Calculating Residues
For a simple pole (order 1):
Res(f,a)=limz→a(z−a)f(z)
For a pole of order m:
Res(f,a)=1(m−1)!limz→adm−1dzm−1[(z−a)mf(z)]
Special case – simple pole from quotient:
If f(z)=p(z)q(z) with p(a)≠0, q(a)=0, q′(a)≠0, then:
Res(f,a)=p(a)q′(a)
5.3 Residue Theorem
If f(z) is analytic inside and on a simple closed contour C except for isolated singularities z1,z2,…,zn inside C, then:
∮Cf(z) dz=2πi∑k=1nRes(f,zk)
5.4 Application: Real Definite Integrals
Type I: ∫02πR(cosθ,sinθ) dθ
Let z=eiθ, then cosθ=z+z−12, sinθ=z−z−12i, dθ=dziz.
Type II: ∫−∞∞f(x) dx
If f(z) is analytic in the upper half-plane except for poles and ∣zf(z)∣→0 as ∣z∣→∞, then:
∫−∞∞f(x) dx=2πi∑Res(f) in upper half-plane
Type III: ∫−∞∞f(x)eiax dx (Fourier-type integrals)
For a>0, close contour in upper half-plane.
6. Fourier Transform
6.1 Definition
Fourier Transform (FT):
F(ω)=F[f(t)]=∫−∞∞f(t)e−iωt dt
Inverse Fourier Transform:
f(t)=F−1[F(ω)]=12π∫−∞∞F(ω)eiωt dω
6.2 Properties of Fourier Transform
| Property | Time Domain | Frequency Domain | ||
|---|---|---|---|---|
| Linearity | af(t)+bg(t) | aF(ω)+bG(ω) | ||
| Time shifting | f(t−t0) | e−iωt0F(ω) | ||
| Frequency shifting | eiω0tf(t) | F(ω−ω0) | ||
| Time scaling | f(at) | ( \frac{1}{ | a | } F\left(\frac{\omega}{a}\right) ) |
| Conjugation | f(t)‾ | F(−ω)‾ | ||
| Time reversal | f(−t) | F(−ω) | ||
| Differentiation | f′(t) | iωF(ω) | ||
| Integration | ∫−∞tf(τ)dτ | F(ω)iω+πF(0)δ(ω) | ||
| Convolution | (f∗g)(t) | F(ω)G(ω) | ||
| Multiplication | f(t)g(t) | 12π(F∗G)(ω) |
6.3 Fourier Transforms of Common Functions
| Function | Fourier Transform | ||
|---|---|---|---|
| δ(t) (Dirac delta) | 1 | ||
| 1 | 2πδ(ω) | ||
| δ(t−t0) | e−iωt0 | ||
| eiω0t | 2πδ(ω−ω0) | ||
| cos(ω0t) | π[δ(ω−ω0)+δ(ω+ω0)] | ||
| sin(ω0t) | πi[δ(ω+ω0)−δ(ω−ω0)] | ||
| ( e^{-a | t | }, a>0 ) | 2aa2+ω2 |
| e−at2 | πae−ω2/(4a) | ||
| Rectangular pulse: Π(t/T) | T⋅sinc(ωT2) | ||
| Sinc function | Rectangular pulse |
6.4 Parseval’s Theorem (Plancherel’s Theorem)
∫−∞∞∣f(t)∣2dt=12π∫−∞∞∣F(ω)∣2dω
7. Laplace Transform
7.1 Definition
Laplace Transform (LT):
F(s)=L[f(t)]=∫0∞f(t)e−st dt,s=σ+iω
Inverse Laplace Transform:
f(t)=L−1[F(s)]=12πi∫c−i∞c+i∞F(s)est ds(Bromwich integral)
7.2 Properties of Laplace Transform
| Property | Time Domain | s-Domain |
|---|---|---|
| Linearity | af(t)+bg(t) | aF(s)+bG(s) |
| First shifting | eatf(t) | F(s−a) |
| Second shifting | f(t−a)u(t−a) | e−asF(s) |
| Time scaling | f(at) | 1aF(sa) |
| Differentiation | f′(t) | sF(s)−f(0) |
| f′′(t) | s2F(s)−sf(0)−f′(0) | |
| Integration | ∫0tf(τ)dτ | F(s)s |
| Convolution | (f∗g)(t)=∫0tf(τ)g(t−τ)dτ | F(s)G(s) |
| Initial value | f(0+)=lims→∞sF(s) | – |
| Final value | limt→∞f(t)=lims→0sF(s) | – |
7.3 Laplace Transforms of Common Functions
| Function | Laplace Transform |
|---|---|
| δ(t) (Dirac delta) | 1 |
| u(t) (unit step) | 1s |
| tn (n = 0,1,2,…) | n!sn+1 |
| ta (a > -1) | Γ(a+1)sa+1 |
| eat | 1s−a |
| sin(ωt) | ωs2+ω2 |
| cos(ωt) | ss2+ω2 |
| sinh(at) | as2−a2 |
| cosh(at) | ss2−a2 |
| teat | 1(s−a)2 |
| eatsin(ωt) | ω(s−a)2+ω2 |
| eatcos(ωt) | s−a(s−a)2+ω2 |
7.4 Solving ODEs with Laplace Transform
Procedure:
-
Take Laplace transform of both sides of the ODE
-
Use initial conditions
-
Solve for F(s)
-
Find inverse Laplace transform to get f(t)
Example: y′′+3y′+2y=0, y(0)=1, y′(0)=0
L[y′′]=s2Y(s)−sy(0)−y′(0)=s2Y(s)−sL[3y′]=3[sY(s)−y(0)]=3sY(s)−3L[2y]=2Y(s)s2Y(s)−s+3sY(s)−3+2Y(s)=0(s2+3s+2)Y(s)=s+3Y(s)=s+3(s+1)(s+2)=2s+1−1s+2y(t)=2e−t−e−2t
8. Z-Transform
8.1 Definition
Z-Transform (ZT):
X(z)=Z[x[n]]=∑n=−∞∞x[n]z−n
For causal sequences (x[n]=0 for n<0):
X(z)=∑n=0∞x[n]z−n
Inverse Z-Transform:
x[n]=Z−1[X(z)]=12πi∮CX(z)zn−1dz
8.2 Properties of Z-Transform
| Property | Time Domain | z-Domain |
|---|---|---|
| Linearity | ax[n]+by[n] | aX(z)+bY(z) |
| Time shifting | x[n−n0] | z−n0X(z) |
| Time reversal | x[−n] | X(z−1) |
| Scaling in z | anx[n] | X(z/a) |
| Differentiation | nx[n] | −zdX(z)dz |
| Convolution | x[n]∗y[n]=∑k=−∞∞x[k]y[n−k] | X(z)Y(z) |
8.3 Z-Transforms of Common Sequences
| Sequence | Z-Transform | ROC | ||||
|---|---|---|---|---|---|---|
| δ[n] | 1 | All z | ||||
| δ[n−n0] | z−n0 | z≠0 | ||||
| u[n] (unit step) | 11−z−1=zz−1 | ( | z | > 1 ) | ||
| anu[n] | 11−az−1=zz−a | ( | z | > | a | ) |
| nanu[n] | az−1(1−az−1)2=az(z−a)2 | ( | z | > | a | ) |
| sin(ωn)u[n] | z−1sinω1−2z−1cosω+z−2 | ( | z | > 1 ) | ||
| cos(ωn)u[n] | 1−z−1cosω1−2z−1cosω+z−2 | ( | z | > 1 ) | ||
| rnsin(ωn)u[n] | rz−1sinω1−2rz−1cosω+r2z−2 | ( | z | > | r | ) |
| rncos(ωn)u[n] | 1−rz−1cosω1−2rz−1cosω+r2z−2 | ( | z | > | r | ) |
8.4 Region of Convergence (ROC)
-
The ROC is the set of z for which the Z-transform converges
-
For causal sequences, ROC is outside a circle (∣z∣>R)
-
For anti-causal sequences, ROC is inside a circle (∣z∣<R)
-
For two-sided sequences, ROC is an annulus (R1<∣z∣<R2)
-
ROC cannot contain poles
8.5 Inverse Z-Transform Methods
| Method | Description |
|---|---|
| Power series expansion | Expand X(z) in powers of z−1 |
| Partial fraction expansion | Decompose X(z) into simpler terms |
| Residue theorem | x[n]=∑Res[X(z)zn−1] |
9. Sample Exam Questions
Short Answer (5 marks each)
-
State the Cauchy-Riemann equations in Cartesian and polar forms.
-
What is the residue of a function at a pole? How is it calculated for a simple pole?
-
State Cauchy’s integral theorem and Cauchy’s integral formula.
-
Distinguish between a removable singularity, a pole, and an essential singularity.
-
State Parseval’s theorem for Fourier transforms.
Numerical Problems (10-15 marks)
1. Complex Numbers:
Find all cube roots of z=−8.
Solution:
z=−8=8eiπ=8ei(π+2kπ)z1/3=2ei(π+2kπ)/3,k=0,1,2k=0:2eiπ/3=2(cos60∘+isin60∘)=1+i3k=1:2eiπ=−2k=2:2ei5π/3=2(cos300∘+isin300∘)=1−i3
2. Residue Calculation:
Find the residue of f(z)=ez(z−1)(z−2)2 at z=2.
Solution:
Res(f,2)=1(2−1)!limz→2ddz[(z−2)2f(z)]=limz→2ddz[ezz−1]=limz→2(z−1)ez−ez(z−1)2=(2−1)e2−e2(2−1)2=e2−e21=0
3. Fourier Transform:
Find the Fourier transform of f(t)=e−a∣t∣,a>0.
Solution:
F(ω)=∫−∞∞e−a∣t∣e−iωtdt=∫−∞0eate−iωtdt+∫0∞e−ate−iωtdt=∫−∞0e(a−iω)tdt+∫0∞e−(a+iω)tdt=[e(a−iω)ta−iω]−∞0+[e−(a+iω)t−(a+iω)]0∞=1a−iω+1a+iω=2aa2+ω2
4. Laplace Transform:
Solve the differential equation y′′+4y=8, y(0)=0, y′(0)=4 using Laplace transform.
Solution:
L[y′′]=s2Y(s)−sy(0)−y′(0)=s2Y(s)−4L[4y]=4Y(s)L[8]=8ss2Y(s)−4+4Y(s)=8s(s2+4)Y(s)=8s+4=8+4ssY(s)=4s+8s(s2+4)=4(s+2)s(s2+4)
Partial fractions:
4(s+2)s(s2+4)=As+Bs+Cs2+44(s+2)=A(s2+4)+(Bs+C)s=As2+4A+Bs2+Cs4s+8=(A+B)s2+Cs+4A
Comparing: A+B=0, C=4, 4A=8⇒A=2, B=−2
Y(s)=2s+−2s+4s2+4=2s−2ss2+4+4s2+4y(t)=2−2cos(2t)+2sin(2t)
Quick Revision Table – Transform Comparisons
| Transform | Domain | Time/Frequency | Inverse | Common Use |
|---|---|---|---|---|
| Fourier | Continuous, infinite | Time ↔ Frequency | Integral | Signal analysis |
| Laplace | Continuous, causal | Time ↔ s-domain | Integral | Control systems, ODEs |
| Z | Discrete, causal | Discrete time ↔ z-domain | Integral/Series | Digital signal processing |
Quick Revision Table – Singularities
| Type | Laurent Series | Residue | Example |
|---|---|---|---|
| Removable | No negative powers | 0 | sinzz |
| Pole of order m | Finite negative terms | Non-zero | 1(z−1)2 |
| Essential | Infinite negative terms | Can be anything | e1/z |
CSE-241: Electrical Network Analysis
Here are detailed study notes for CSE-241: Electrical Network Analysis, written from a Computer Science/Electrical Engineering perspective. These notes cover the fundamental principles of electrical network analysis—circuit variables, circuit laws, network theorems, transient analysis, sinusoidal steady-state analysis, frequency response, network functions, and two-port networks. The emphasis is on understanding how to analyze and solve complex electrical networks using systematic mathematical techniques.
1. Introduction to Electrical Network Analysis
1.1. What is Electrical Network Analysis?
Electrical Network Analysis is the systematic study of electrical circuits to determine voltages, currents, and power in various parts of the network. It involves applying fundamental circuit laws and theorems to solve for unknown quantities.
The Core Question: Given an electrical network with sources and passive elements, how do we determine the voltage across and current through every element?
1.2. Basic Electrical Quantities
| Quantity | Symbol | Unit | Symbol | Definition |
|---|---|---|---|---|
| Charge | Q | Coulomb | C | ∫ i dt |
| Current | I | Ampere | A | dQ/dt |
| Voltage | V | Volt | V | dW/dQ |
| Resistance | R | Ohm | Ω | V/I |
| Conductance | G | Siemens | S | 1/R |
| Capacitance | C | Farad | F | Q/V |
| Inductance | L | Henry | H | λ/I |
| Power | P | Watt | W | VI |
| Energy | W | Joule | J | ∫ P dt |
1.3. Passive Sign Convention
Passive Sign Convention: Current enters the positive terminal of a passive element.
I →
┌───┐
│ │
+ ─
│ │
└───┘
V
-
Power absorbed = P=+VI (if current enters positive terminal)
-
Power delivered = P=−VI (if current leaves positive terminal)
1.4. Ideal Circuit Elements
| Element | Symbol | V-I Relationship | Power | Energy | ||
|---|---|---|---|---|---|---|
| Resistor | —///— | V=IR | I2R=V2/R | Dissipated | ||
| Capacitor | — | — | I=CdV/dt | VI | 12CV2 | |
| Inductor | —○○○— | V=LdI/dt | VI | 12LI2 | ||
| Voltage Source | —○—○— | V=Vs | Depends on circuit | — | ||
| Current Source | —○—○— | I=Is | Depends on circuit | — |
2. Circuit Laws
2.1. Ohm’s Law
V=IR
2.2. Kirchhoff’s Current Law (KCL)
The algebraic sum of currents entering a node is zero.
∑k=1nIk=0
Alternative: Sum of currents entering = sum of currents leaving.
2.3. Kirchhoff’s Voltage Law (KVL)
The algebraic sum of voltages around any closed loop is zero.
∑k=1nVk=0
2.4. Voltage Division
Series Resistors:
Vx=VT⋅RxRT
Series Capacitors:
Vx=VT⋅CTCx
2.5. Current Division
Parallel Resistors:
Ix=IT⋅GxGT=IT⋅RTRx
Parallel Inductors:
Ix=IT⋅LTLx
3. Network Topology
3.1. Graph Theory Fundamentals
| Term | Definition |
|---|---|
| Graph | Network of branches connected at nodes |
| Node | Point where two or more branches meet |
| Branch | Path between two nodes containing one element |
| Loop | Closed path that does not contain any node more than once |
| Mesh | Loop that does not contain any other loop inside |
3.2. Graph Terminology
-
Connected Graph: Path exists between any two nodes
-
Tree: Connected subgraph containing all nodes but no loops
-
Co-tree: Complement of tree (branches not in tree)
-
Twigs: Branches in tree (n-1 branches)
-
Links: Branches in co-tree (b – n + 1 branches)
3.3. Network Equations
Number of independent equations:
-
KCL equations: n−1
-
KVL equations: b−n+1
Where:
-
n = number of nodes
-
b = number of branches
4. Circuit Analysis Methods
4.1. Mesh Analysis (Loop Current Method)
Mesh analysis applies KVL to independent meshes.
Steps:
-
Identify independent meshes
-
Assign mesh currents (clockwise direction)
-
Apply KVL to each mesh
-
Solve simultaneous equations
Mesh Equation (General form for mesh i):
∑RiiIi−∑RijIj=∑Vsi
Where:
-
Rii = sum of resistances in mesh i
-
Rij = common resistances between meshes i and j
-
Ij = mesh current in adjacent mesh j
-
∑Vsi = sum of voltage sources in mesh i
Example (2 meshes):
[R1+R2−R2−R2R2+R3][I1I2]=[V1−V2]
4.2. Nodal Analysis (Node Voltage Method)
Nodal analysis applies KCL to independent nodes.
Steps:
-
Select reference node (ground)
-
Assign node voltages (V₁, V₂, …)
-
Apply KCL at each non-reference node
-
Solve simultaneous equations
Nodal Equation (General form for node i):
∑GiiVi−∑GijVj=∑Isi
Where:
-
Gii = sum of conductances connected to node i
-
Gij = conductances between nodes i and j
-
Vj = voltage at adjacent node j
-
∑Isi = sum of current sources entering node i
Example (2 nodes):
[G1+G2−G2−G2G2+G3][V1V2]=[I1−I2]
4.3. Mesh vs. Nodal Analysis
| Aspect | Mesh Analysis | Nodal Analysis |
|---|---|---|
| Variables | Mesh currents | Node voltages |
| Equations | b−n+1 | n−1 |
| Best for | Fewer meshes than nodes | Fewer nodes than meshes |
| Voltage sources | Easy | Convert to current sources |
| Current sources | Convert to voltage sources | Easy |
5. Network Theorems
5.1. Superposition Theorem
In a linear network with multiple independent sources, the response (voltage or current) is the sum of responses from each source acting alone.
Procedure:
-
Consider one source at a time
-
Deactivate other sources:
-
Voltage sources → short circuit (0V)
-
Current sources → open circuit (0A)
-
-
Calculate response from active source
-
Repeat for each source
-
Sum all responses (consider polarity/direction)
Limitations: Only for linear circuits (resistors, capacitors, inductors, linear dependent sources)
5.2. Thevenin’s Theorem
Any linear two-terminal network can be replaced by an equivalent voltage source VTh in series with a resistance RTh.
Procedure:
-
Remove the load resistor (where VTh is measured)
-
Calculate VTh = open-circuit voltage at terminals
-
Calculate RTh:
-
Deactivate all independent sources
-
Find equivalent resistance looking into terminals
-
-
Draw Thevenin equivalent circuit
For dependent sources:
-
RTh=Voc/Isc
-
Apply test voltage/current to find resistance
5.3. Norton’s Theorem
Any linear two-terminal network can be replaced by an equivalent current source IN in parallel with a resistance RN.
Relationships:
VTh=IN⋅RNRTh=RNIN=VThRTh=Isc
5.4. Maximum Power Transfer Theorem
Maximum power is transferred from a source to a load when the load resistance equals the Thevenin resistance.
RL=RTh
Maximum Power:
Pmax=VTh24RTh
For AC circuits (resistive load):
RL=∣ZTh∣
For AC circuits (complex load):
ZL=ZTh‾
5.5. Reciprocity Theorem
In a linear passive network, the ratio of response to excitation is unchanged if the positions of the source and response are interchanged.
5.6. Tellegen’s Theorem
For any network, the sum of power across all branches is zero.
∑k=1bvkik=0
6. Transient Analysis
6.1. First-Order Circuits
RC Circuit (Charging):
vC(t)=Vf+(Vi−Vf)e−t/ττ=RC
RC Circuit (Discharging):
vC(t)=V0e−t/τ
RL Circuit (Current build-up):
iL(t)=If+(Ii−If)e−t/ττ=L/R
RL Circuit (Current decay):
iL(t)=I0e−t/τ
6.2. General Solution for First-Order Circuits
y(t)=y(∞)+[y(0+)−y(∞)]e−t/τ
Where:
-
y(t) = voltage or current
-
y(0+) = initial value (t=0⁺)
-
y(∞) = final value (steady-state)
-
τ = time constant
6.3. Second-Order Circuits (RLC)
Series RLC Circuit:
Ldidt+Ri+1C∫idt=vs(t)
Differential Equation:
d2idt2+RLdidt+1LCi=1Ldvsdt
Characteristic Equation:
s2+RLs+1LC=0
Roots:
s1,2=−α±α2−ω02
Where:
-
α=R/(2L) = damping factor (neper frequency)
-
ω0=1/LC = resonant frequency
6.4. Response Types
| Case | Condition | Damping | Response |
|---|---|---|---|
| Overdamped | α>ω0 | High | y(t)=A1es1t+A2es2t |
| Critically damped | α=ω0 | Critical | y(t)=(A1+A2t)e−αt |
| Underdamped | α<ω0 | Low | y(t)=e−αt(A1cosωdt+A2sinωdt) |
Where ωd=ω02−α2 = damped natural frequency
6.5. Initial and Final Conditions
Capacitor:
-
vC(0−)=vC(0+) (voltage continuous)
-
Capacitor behaves as voltage source at t=0⁺
-
Capacitor behaves as open circuit at t=∞
Inductor:
-
iL(0−)=iL(0+) (current continuous)
-
Inductor behaves as current source at t=0⁺
-
Inductor behaves as short circuit at t=∞
7. Sinusoidal Steady-State Analysis
7.1. Sinusoidal Waveforms
v(t)=Vmsin(ωt+ϕ)
Where:
-
Vm = amplitude (peak value)
-
ω=2πf = angular frequency (rad/s)
-
f = frequency (Hz)
-
T=1/f=2π/ω = period (s)
-
ϕ = phase angle (rad)
7.2. RMS Values
Vrms=1T∫0Tv2(t)dt
For sinusoid:
Vrms=Vm2≈0.707Vm
7.3. Phasor Representation
A phasor is a complex number representing the magnitude and phase of a sinusoid.
V=Vrms∠ϕ=Vrmsejϕ
Time-domain to Phasor:
v(t)=Vmsin(ωt+ϕ)→V=Vm2∠ϕ
Phasor to Time-domain:
V=V∠ϕ→v(t)=2Vsin(ωt+ϕ)
7.4. Impedance
Impedance is the AC equivalent of resistance.
Z=VI=R+jX∣Z∣=R2+X2θ=tan−1(XR)
Element Impedances:
| Element | Impedance | Phase |
|---|---|---|
| Resistor | ZR=R | 0° |
| Inductor | ZL=jωL | +90° |
| Capacitor | ZC=1jωC=−j1ωC | -90° |
7.5. Admittance
Y=1Z=G+jB
Element Admittances:
| Element | Admittance |
|---|---|
| Resistor | YR=G=1/R |
| Inductor | YL=1jωL=−j1ωL |
| Capacitor | YC=jωC |
7.6. Phasor Analysis
Steps:
-
Convert time-domain sources to phasors
-
Replace elements with impedances
-
Solve using DC circuit analysis techniques
-
Convert phasor results back to time-domain
KCL in Phasor Form:
∑Ik=0
KVL in Phasor Form:
∑Vk=0
Ohm’s Law in Phasor Form:
V=IZ
8. AC Power Analysis
8.1. Instantaneous Power
p(t)=v(t)i(t)=VmImsin(ωt+θv)sin(ωt+θi)
8.2. Average Power (Real Power)
P=1T∫0Tp(t)dt=VrmsIrmscos(θv−θi)P=VrmsIrmscosϕ
Where ϕ=θv−θi = power factor angle
8.3. Reactive Power
Q=VrmsIrmssin(θv−θi)=VrmsIrmssinϕ
Units: Volt-Ampere Reactive (VAR)
8.4. Apparent Power
S=VrmsIrms=P2+Q2
Units: Volt-Ampere (VA)
8.5. Power Factor
PF=PS=cosϕ
-
Lagging PF: Inductive load (Q > 0, current lags voltage)
-
Leading PF: Capacitive load (Q < 0, current leads voltage)
8.6. Complex Power
S=VI∗=P+jQS=VrmsIrms∠(θv−θi)
8.7. Power Factor Correction
Adding capacitors in parallel to inductive loads:
Required capacitance:
QC=P(tanϕ1−tanϕ2)C=QCωVrms2
9. Frequency Response
9.1. Transfer Function
H(jω)=Y(jω)X(jω)
Where:
-
X(jω) = input phasor
-
Y(jω) = output phasor
9.2. Magnitude and Phase Response
∣H(jω)∣=magnitude response∠H(jω)=phase response
9.3. Bode Plots
Magnitude Plot: 20log10∣H(jω)∣ (dB) vs. log10ω
Phase Plot: ∠H(jω) vs. log10ω
First-Order Factor (1+jω/ωc):
-
Low frequency: 0 dB
-
High frequency: +20 dB/decade
-
Corner frequency: ωc, -45° phase
First-Order Factor 1/(1+jω/ωc):
-
Low frequency: 0 dB
-
High frequency: -20 dB/decade
-
Corner frequency: ωc, +45° phase
9.4. Resonance
Series RLC Resonance:
ω0=1LC,f0=12πLC
Quality Factor:
Q=ω0LR=1ω0RC=1RLC
Bandwidth:
BW=ω0Q=RL
Half-Power Frequencies:
ω1,2=ω0(1+14Q2±12Q)
Parallel RLC Resonance:
ω0=1LCQ=RCLBW=1RC
10. Network Functions
10.1. Types of Network Functions
| Type | Input | Output |
|---|---|---|
| Driving point impedance | Current | Voltage |
| Driving point admittance | Voltage | Current |
| Transfer impedance | Current (port 1) | Voltage (port 2) |
| Transfer admittance | Voltage (port 1) | Current (port 2) |
| Voltage transfer ratio | Voltage (port 1) | Voltage (port 2) |
| Current transfer ratio | Current (port 1) | Current (port 2) |
10.2. Poles and Zeros
Network function:
H(s)=K(s−z1)(s−z2)⋯(s−p1)(s−p2)⋯
-
Zeros: Roots of numerator (s=zi)
-
Poles: Roots of denominator (s=pi)
Pole locations and stability:
| Pole Location | Time Response | Stability |
|---|---|---|
| Re(p)<0 | Decaying exponential | Stable |
| Re(p)=0 | Oscillatory (undamped) | Marginally stable |
| Re(p)>0 | Growing exponential | Unstable |
10.3. Frequency Response from Poles/Zeros
∣H(jω)∣=K∏∣jω−zi∣∏∣jω−pi∣∠H(jω)=∑∠(jω−zi)−∑∠(jω−pi)
11. Two-Port Networks
11.1. Two-Port Network Parameters
| Parameter | Equations | Matrix |
|---|---|---|
| Impedance (z) | V1=z11I1+z12I2 | [z11z12z21z22] |
| V2=z21I1+z22I2 | ||
| Admittance (y) | I1=y11V1+y12V2 | [y11y12y21y22] |
| I2=y21V1+y22V2 | ||
| Hybrid (h) | V1=h11I1+h12V2 | [h11h12h21h22] |
| I2=h21I1+h22V2 | ||
| Transmission (ABCD) | V1=AV2−BI2 | [ABCD] |
| I1=CV2−DI2 |
11.2. Parameter Relationships
| z | y | h | ABCD | |
|---|---|---|---|---|
| z | z | y−1 | h11/h21? | — |
| y | z−1 | y | — | — |
| h | — | — | h | — |
| ABCD | — | — | — | ABCD |
11.3. Interconnection of Two-Ports
| Connection | Equivalent Parameter |
|---|---|
| Series | z=za+zb |
| Parallel | y=ya+yb |
| Cascade | T=TaTb |
11.4. Reciprocity and Symmetry
Reciprocal Network: z12=z21 (or y12=y21, h12=−h21, AD−BC=1)
Symmetric Network: z11=z22 (or y11=y22, h11h22−h12h21=1, A=D)
12. Laplace Transform in Circuit Analysis
12.1. Laplace Transform Definition
L{f(t)}=F(s)=∫0∞f(t)e−stdt
12.2. Laplace Transforms of Common Functions
| f(t) | F(s) |
|---|---|
| δ(t) | 1 |
| u(t) | 1/s |
| t | 1/s2 |
| e−at | 1/(s+a) |
| sinωt | ω/(s2+ω2) |
| cosωt | s/(s2+ω2) |
12.3. Element Models in s-Domain
| Element | Time Domain | s-Domain (Zero initial conditions) |
|---|---|---|
| Resistor | v=iR | V(s)=I(s)R |
| Inductor | v=Ldi/dt | V(s)=sLI(s) |
| Capacitor | i=Cdv/dt | I(s)=sCV(s) |
12.4. Circuit Analysis Using Laplace
-
Convert circuit to s-domain
-
Write equations (nodal/mesh)
-
Solve for output Y(s)
-
Inverse Laplace transform to find y(t)
13. Summary Table: Network Parameters
| Parameter | Units | Best For | Key Relation |
|---|---|---|---|
| z | Ω | Series connection | z12=z21 (reciprocal) |
| y | S | Parallel connection | y12=y21 (reciprocal) |
| h | Mixed | Transistor circuits | hfe=h21 |
| ABCD | Mixed | Cascade connection | AD−BC=1 (reciprocal) |
14. Key Equations Reference Sheet
| Equation | Description |
|---|---|
| V=IR | Ohm’s law |
| ∑I=0 | KCL |
| ∑V=0 | KVL |
| y(t)=y(∞)+[y(0+)−y(∞)]e−t/τ | First-order transient |
| s2+(R/L)s+1/LC=0 | RLC characteristic equation |
| V=IZ | Ohm’s law (phasor) |
| S=VI∗=P+jQ | Complex power |
| H(s)=Y(s)/X(s) | Transfer function |
| AD−BC=1 | Reciprocal two-port |
15. Standard Textbooks
| Author | Title | Focus |
|---|---|---|
| Alexander & Sadiku | Fundamentals of Electric Circuits | Comprehensive |
| Nilsson & Riedel | Electric Circuits | Classic |
| Hayt, Kemmerly & Durbin | Engineering Circuit Analysis | Problem-solving |
| Van Valkenburg | Network Analysis | Theoretical |
16. Final Study Checklist
| Topic | Key Skills |
|---|---|
| Circuit Laws | Apply Ohm’s law, KCL, KVL to any circuit |
| Mesh/Nodal Analysis | Write and solve simultaneous equations |
| Network Theorems | Apply superposition, Thevenin, Norton, maximum power |
| Transient Analysis | Solve first and second order circuits |
| Phasor Analysis | Convert to phasors; solve AC circuits |
| AC Power | Calculate P, Q, S, PF; perform PF correction |
| Frequency Response | Draw Bode plots; calculate resonance |
| Two-Port Networks | Calculate z, y, h, ABCD parameters |
| Laplace Transform | Solve circuits using s-domain analysis |
CSE-3207: Digital System Design & CSE-342: Digital Signal Processing – Comprehensive Study Notes
These notes combine two complementary courses: Digital System Design (hardware focus on designing digital circuits and systems using HDLs) and Digital Signal Processing (algorithmic focus on processing discrete-time signals). Together, they provide a complete foundation for understanding how digital systems are built and how signals are processed in the digital domain.
Part 1: Digital System Design (CSE-3207)
1.1 Introduction to Digital Systems
1.1.1 What is a Digital System?
A digital system is a system that processes discrete (quantized) values, typically represented as binary digits (0 and 1). Unlike analog systems that handle continuous signals, digital systems offer advantages in noise immunity, storage, precision, and programmability.
| Aspect | Analog System | Digital System |
|---|---|---|
| Signal representation | Continuous | Discrete (quantized) |
| Noise immunity | Poor (noise directly affects signal) | Excellent (only threshold detection) |
| Storage | Difficult (capacitors, tape) | Easy (memory cells) |
| Precision | Limited by components | Limited by number of bits |
| Reproducibility | Component-dependent | Exact |
| Examples | Vinyl records, analog radio | Computers, digital audio, smartphones |
1.1.2 Digital System Design Flow
┌─────────────────────────────────────┐
│ Design Specification │
│ (Requirements, features, timing) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ High-Level Design │
│ (Block diagram, architecture) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ RTL Design (HDL) │
│ (Verilog/VHDL description) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Functional Simulation │
│ (Verify logic behavior) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Synthesis │
│ (HDL → Gate-level netlist) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Gate-level Simulation │
│ (Verify synthesized logic) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Place & Route (P&R) │
│ (Floorplan, placement, routing) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Timing Analysis & Closure │
│ (Meet setup/hold timing) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Bitstream Generation │
│ (FPGA configuration file) │
└─────────────────┬───────────────────┘
│
▼
┌─────────────────────────────────────┐
│ Hardware Testing │
└─────────────────────────────────────┘
1.1.3 Implementation Technologies
| Technology | Description | Applications | Reconfigurability |
|---|---|---|---|
| FPGA (Field Programmable Gate Array) | Programmable logic blocks and interconnects | Prototyping, DSP, low-volume production | Yes |
| CPLD (Complex Programmable Logic Device) | Smaller than FPGA, faster propagation | Glue logic, simple control | Yes |
| ASIC (Application Specific IC) | Custom-designed for specific application | High-volume production | No |
| Standard Cells | Pre-designed logic cells placed/routed | Medium-volume, cost-sensitive | No |
| Gate Arrays | Pre-fabricated transistors, custom metal layers | Medium-volume | No |
1.2 Boolean Algebra and Logic Gates
1.2.1 Basic Logic Gates
| Gate | Symbol | Expression | Truth Table | CMOS Implementation |
|---|---|---|---|---|
| NOT | Triangle with bubble | Y=A‾ | 0→1, 1→0 | Single NMOS + PMOS |
| AND | D-shape | Y=A⋅B | 00→0,01→0,10→0,11→1 | Series NMOS, parallel PMOS |
| OR | Shield shape | Y=A+B | 00→0,01→1,10→1,11→1 | Parallel NMOS, series PMOS |
| NAND | AND with bubble | Y=AB‾ | 00→1,01→1,10→1,11→0 | Preferred for CMOS |
| NOR | OR with bubble | Y=A+B‾ | 00→1,01→0,10→0,11→0 | Preferred for CMOS |
| XOR | AND with curved lines | Y=A⊕B | 00→0,01→1,10→1,11→0 | Built from NAND gates |
| XNOR | XOR with bubble | Y=A⊕B‾ | 00→1,01→0,10→0,11→1 | Built from NAND gates |
1.2.2 Boolean Algebra Laws
| Law | AND Form | OR Form |
|---|---|---|
| Identity | A⋅1=A | A+0=A |
| Null | A⋅0=0 | A+1=1 |
| Idempotent | A⋅A=A | A+A=A |
| Complement | A⋅A‾=0 | A+A‾=1 |
| Double Negation | A‾‾=A | |
| Commutative | A⋅B=B⋅A | A+B=B+A |
| Associative | (AB)C=A(BC) | (A+B)+C=A+(B+C) |
| Distributive | A(B+C)=AB+AC | A+BC=(A+B)(A+C) |
| Absorption | A(A+B)=A | A+AB=A |
| DeMorgan’s | AB‾=A‾+B‾ | A+B‾=A‾⋅B‾ |
1.2.3 DeMorgan’s Theorems
DeMorgan’s theorems are essential for simplifying Boolean expressions and converting between gate types:
First Theorem: The complement of a product equals the sum of the complements.
AB‾=A‾+B‾
Second Theorem: The complement of a sum equals the product of the complements.
A+B‾=A‾⋅B‾
Generalized DeMorgan’s:
A⋅B⋅C⋯‾=A‾+B‾+C‾+⋯A+B+C+⋯‾=A‾⋅B‾⋅C‾⋯
1.2.4 Universal Gates (NAND and NOR)
NAND and NOR gates are universal—any Boolean function can be implemented using only NAND gates or only NOR gates.
NAND as NOT: A‾=A⋅A‾
NAND as AND: A⋅B=AB‾‾
NAND as OR: A+B=A‾⋅B‾‾
NOR as NOT: A‾=A+A‾
NOR as OR: A+B=A+B‾‾
NOR as AND: A⋅B=A‾+B‾‾
1.3 Combinational Logic Design
1.3.1 Combinational vs. Sequential Logic
| Aspect | Combinational Logic | Sequential Logic |
|---|---|---|
| Output depends on | Current inputs only | Current inputs + past state (memory) |
| Memory | No | Yes (flip-flops) |
| Timing | Propagation delay only | Clock-dependent |
| Examples | Adders, MUX, decoders | Counters, registers, state machines |
1.3.2 Sum of Products (SOP) and Product of Sums (POS)
Sum of Products (SOP) : OR of AND terms
F=AB+A‾C+BC‾
Product of Sums (POS) : AND of OR terms
F=(A+B)(A‾+C)(B+C‾)
1.3.3 Karnaugh Maps (K-Maps)
K-maps provide a graphical method for simplifying Boolean expressions.
3-Variable K-Map (Gray code order: 00, 01, 11, 10):
BC00011110A=0m0m1m3m2A=1m4m5m7m6
4-Variable K-Map:
CD00011110AB00m0m1m3m201m4m5m7m611m12m13m15m1410m8m9m11m10
K-Map Simplification Rules:
-
Groups must be powers of 2 (1, 2, 4, 8, 16…)
-
Groups can wrap around edges
-
Groups should be as large as possible
-
Each 1 must be covered at least once
-
Don’t care conditions (X) can be used as 0 or 1 to maximize groups
1.3.4 Combinational Building Blocks
Adders
Half Adder (adds 2 bits):
| A | B | Sum | Carry |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0 | 1 | 1 | 0 |
| 1 | 0 | 1 | 0 |
| 1 | 1 | 0 | 1 |
S=A⊕B,C=A⋅B
Full Adder (adds 3 bits: A, B, Carry-in):
S=A⊕B⊕CinCout=AB+ACin+BCin
Ripple Carry Adder: Cascade full adders. Limitation: speed limited by carry propagation.
Multiplexers (MUX)
A multiplexer selects one of several input lines and routes it to a single output.
2-to-1 MUX:
Y=S‾⋅I0+S⋅I1
4-to-1 MUX:
Y=S1‾S0‾I0+S1‾S0I1+S1S0‾I2+S1S0I3
Decoders
A decoder converts binary input to active output line (n inputs → 2ⁿ outputs).
2-to-4 Decoder:
| A | B | Y0 | Y1 | Y2 | Y3 |
|---|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 0 | 0 |
| 1 | 0 | 0 | 0 | 1 | 0 |
| 1 | 1 | 0 | 0 | 0 | 1 |
Comparators
1-bit comparator:
| A | B | A>B | A=B | A<B |
|---|---|---|---|---|
| 0 | 0 | 0 | 1 | 0 |
| 0 | 1 | 0 | 0 | 1 |
| 1 | 0 | 1 | 0 | 0 |
| 1 | 1 | 0 | 1 | 0 |
1.4 Sequential Logic Design
1.4.1 Latches vs. Flip-Flops
| Feature | Latch | Flip-Flop |
|---|---|---|
| Triggering | Level-sensitive | Edge-triggered |
| Transparency | Transparent when enabled | Changes only at clock edge |
| Timing constraints | Setup/hold on enable | Setup/hold on clock edge |
1.4.2 Latches
SR Latch (NOR-based) :
| S | R | Q | Q’ |
|---|---|---|---|
| 0 | 0 | Q (hold) | Q’ (hold) |
| 0 | 1 | 0 | 1 |
| 1 | 0 | 1 | 0 |
| 1 | 1 | 0 | 0 (invalid) |
Gated D Latch:
-
Enable = 0: hold
-
Enable = 1: Q = D
1.4.3 Flip-Flops
D Flip-Flop (positive edge-triggered):
-
On rising clock edge: Q = D
JK Flip-Flop:
| J | K | Q_next |
|---|---|---|
| 0 | 0 | Q (hold) |
| 0 | 1 | 0 (reset) |
| 1 | 0 | 1 (set) |
| 1 | 1 | Q‾ (toggle) |
T Flip-Flop (Toggle):
-
T = 0: hold
-
T = 1: toggle each clock edge
Conversion between flip-flops:
-
D to T: D=T⊕Q
-
D to JK: D=JQ‾+K‾Q
-
JK to T: J=1, K=1
1.4.4 Timing Parameters
| Parameter | Description |
|---|---|
| Setup time (tsu) | Time data must be stable before clock edge |
| Hold time (th) | Time data must remain stable after clock edge |
| Propagation delay (tpd) | Time from clock edge to output change |
| Clock-to-Q delay (tcq) | Similar to propagation delay |
| Clock skew | Difference in clock arrival time at different flip-flops |
1.4.5 Sequential Building Blocks
Registers:
| Type | Description |
|---|---|
| SISO (Serial In, Serial Out) | Data enters and exits serially |
| SIPO (Serial In, Parallel Out) | Serial input, parallel output |
| PISO (Parallel In, Serial Out) | Parallel load, serial output |
| PIPO (Parallel In, Parallel Out) | Parallel load and output |
Counters:
| Type | Description |
|---|---|
| Ripple (Asynchronous) counter | Slower, simpler |
| Synchronous counter | Faster, more complex |
| Binary up counter | Counts 0,1,2,…,2ⁿ-1 |
| Binary down counter | Counts 2ⁿ-1,…,2,1,0 |
| Up/down counter | Direction controlled by input |
| BCD counter | Counts 0-9, resets to 0 |
| Ring counter | Single 1 circulates around |
| Johnson counter | Twisted ring (2n states) |
1.5 Finite State Machines (FSM)
1.5.1 Mealy vs. Moore Machines
| Aspect | Mealy Machine | Moore Machine |
|---|---|---|
| Output depends on | Current state AND inputs | Current state only |
| Number of states | Typically fewer | Typically more |
| Output timing | Asynchronous (input change → output change) | Synchronous (clock edge) |
| Glitches | Possible | None |
1.5.2 FSM Design Steps
-
Define states and state diagram
-
Create state transition table
-
State assignment (assign binary codes to states)
-
Derive next state logic and output logic
-
Implement with flip-flops and combinational logic
Example: Sequence Detector (detects 1101) :
State Diagram:
┌───┐
│S0 │──0/0──►S1
└─┬─┘
│1/0
▼
┌───┐
│S1 │──1/0──►S2
└─┬─┘
│0/0
▼
┌───┐
│S2 │──0/0──►S3
└─┬─┘
│1/1 (output on 1101)
1.6 Hardware Description Languages (HDL)
1.6.1 Verilog vs. VHDL
| Aspect | Verilog | VHDL |
|---|---|---|
| Syntax | C-like | Ada-like |
| Typing | Weak (implicit) | Strong (explicit) |
| Learning curve | Easier | Steeper |
| Popularity in US | More common | Less common |
| Popularity in Europe | Less common | More common |
| Used for | RTL design, verification | RTL design, verification |
1.6.2 Verilog Basics
Module Declaration:
module adder ( input [3:0] a, b, // 4-bit inputs output [3:0] sum, // 4-bit sum output carry // 1-bit carry out ); assign {carry, sum} = a + b; endmodule
Always Block (Combinational) :
always @(*) begin y = a & b; // Continuous assignment end
Always Block (Sequential) :
always @(posedge clk or negedge rst_n) begin if (!rst_n) q <= 1'b0; else q <= d; end
Structural Description:
module full_adder ( input a, b, cin, output sum, cout ); wire s1, c1, c2; half_adder ha1 (.a(a), .b(b), .sum(s1), .carry(c1)); half_adder ha2 (.a(s1), .b(cin), .sum(sum), .carry(c2)); assign cout = c1 | c2; endmodule
1.6.3 Testbench Example
module testbench; reg [3:0] a, b; wire [3:0] sum; wire carry; adder uut (.a(a), .b(b), .sum(sum), .carry(carry)); initial begin a = 4'b0011; b = 4'b0101; // 3 + 5 = 8 #10; a = 4'b1000; b = 4'b1000; // 8 + 8 = 16 (carry out) #10; $finish; end initial begin $monitor("Time=%0t: a=%b b=%b sum=%b carry=%b", $time, a, b, sum, carry); end endmodule
1.7 FPGA Architecture
1.7.1 Basic FPGA Architecture
┌─────────────────────────────────────────────────────────────────┐ │ FPGA ARCHITECTURE │ │ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ I/O Blocks I/O Blocks I/O Blocks │ │ │ └─────────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ │ │ │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ │ │ │ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │ │ │ │ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ │ │ │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ │ │ │ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │ │ │ │ │ │ │ │ (Programmable Interconnect Matrix) │ │ │ │ │ │ │ │ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ │ │ │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ CLB │ │ │ │ │ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘ │ │ │ └─────────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ Block RAM DSP Slices Block RAM │ │ │ └─────────────────────────────────────────────────────────┘ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ I/O Blocks I/O Blocks I/O Blocks │ │ │ └─────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘
1.7.2 Configurable Logic Block (CLB)
A typical CLB contains:
| Component | Description |
|---|---|
| LUT (Look-Up Table) | Implements combinational logic (4-6 inputs) |
| Flip-flop | Stores output for sequential logic |
| Multiplexers | Configure routing |
| Carry chain | Fast arithmetic operations |
1.7.3 FPGA Design Flow for DSP Applications
Modern FPGA design flows for DSP applications integrate high-level languages like C/C++ with traditional RTL design .
Part 2: Digital Signal Processing (CSE-342)
2.1 Introduction to DSP
2.1.1 What is Digital Signal Processing?
Digital Signal Processing (DSP) is the mathematical manipulation of discrete-time signals using digital computers or specialized hardware. DSP has revolutionized many fields including audio, communications, radar, biomedical engineering, and image processing.
Advantages of Digital over Analog Processing:
| Advantage | Description |
|---|---|
| Reproducibility | No component tolerance variations |
| Flexibility | Easily reprogrammable |
| Precision | Limited only by word length |
| No drift | No aging or temperature effects |
| Complex algorithms | Can implement functions impossible in analog |
2.1.2 Signal Classification
| Signal Type | Continuous Domain | Discrete Domain |
|---|---|---|
| Time | Continuous-time | Discrete-time |
| Amplitude | Continuous-amplitude | Quantized (digital) |
Analog Signal: Continuous in both time and amplitude
Discrete-time Signal: Discrete in time, continuous in amplitude
Digital Signal: Discrete in both time and amplitude
2.2 Discrete-Time Signals and Systems
2.2.1 Discrete-Time Signal Representation
A discrete-time signal is represented as a sequence: x[n], where n is an integer index.
Common Discrete-Time Signals:
| Signal | Notation | Example |
|---|---|---|
| Unit impulse (Kronecker delta) | δ[n]={1,n=00,n≠0 | […,0,1,0,… ] |
| Unit step | u[n]={1,n≥00,n<0 | […,0,1,1,1,… ] |
| Exponential | x[n]=an | […,a−2,a−1,1,a,a2,… ] |
| Sinusoidal | x[n]=Acos(ωn+ϕ) | Sampled sinusoid |
2.2.2 Basic Operations on Signals
| Operation | Mathematical Definition | Example |
|---|---|---|
| Shift | y[n]=x[n−k] | Delay by k samples |
| Scale (time) | y[n]=x[kn] | Downsampling (k integer) |
| Reflection | y[n]=x[−n] | Time reversal |
| Addition | y[n]=x1[n]+x2[n] | Superposition |
| Multiplication | y[n]=x1[n]⋅x2[n] | Modulation |
2.2.3 Linear Time-Invariant (LTI) Systems
Properties of LTI Systems:
| Property | Mathematical Condition |
|---|---|
| Linearity | T{ax1[n]+bx2[n]}=aT{x1[n]}+bT{x2[n]} |
| Time Invariance | If y[n]=T{x[n]}, then y[n−k]=T{x[n−k]} |
Convolution (time-domain I/O relationship):
y[n]=x[n]∗h[n]=∑k=−∞∞x[k]h[n−k]
Where h[n] is the impulse response (system output when input is δ[n]).
2.2.4 System Properties from Impulse Response
| Property | Condition on h[n] | ||
|---|---|---|---|
| Causal | h[n]=0 for n<0 | ||
| Stable (BIBO) | ( \sum_{n=-\infty}^{\infty} | h[n] | < \infty ) |
| Finite Impulse Response (FIR) | h[n]=0 outside finite interval | ||
| Infinite Impulse Response (IIR) | h[n] infinite duration |
2.3 The Z-Transform
2.3.1 Definition
The Z-transform is the discrete-time equivalent of the Laplace transform.
Bilateral Z-transform:
X(z)=Z{x[n]}=∑n=−∞∞x[n]z−n
Unilateral Z-transform (for causal signals):
X(z)=∑n=0∞x[n]z−n
Where z is a complex variable.
2.3.2 Region of Convergence (ROC)
The ROC is the set of z for which the Z-transform converges. The ROC is essential for uniqueness of the inverse Z-transform.
ROC Properties:
-
ROC is a ring or disk centered at origin
-
ROC cannot contain poles
-
For causal sequences, ROC is outside the outermost pole
-
For anti-causal sequences, ROC is inside the innermost pole
2.3.3 Common Z-Transform Pairs
| Signal x[n] | Z-transform X(z) | ROC | ||||
|---|---|---|---|---|---|---|
| δ[n] | 1 | All z | ||||
| δ[n−k] | z−k | All z, z≠0 | ||||
| u[n] | 11−z−1 | ( | z | > 1 ) | ||
| anu[n] | 11−az−1 | ( | z | > | a | ) |
| nanu[n] | az−1(1−az−1)2 | ( | z | > | a | ) |
| cos(ω0n)u[n] | 1−cos(ω0)z−11−2cos(ω0)z−1+z−2 | ( | z | > 1 ) | ||
| sin(ω0n)u[n] | sin(ω0)z−11−2cos(ω0)z−1+z−2 | ( | z | > 1 ) |
2.3.4 Z-Transform Properties
| Property | Time Domain | Z-Domain |
|---|---|---|
| Linearity | ax1[n]+bx2[n] | aX1(z)+bX2(z) |
| Time shift | x[n−k] | z−kX(z) |
| Convolution | x1[n]∗x2[n] | X1(z)X2(z) |
| Multiplication by n | nx[n] | −zdX(z)dz |
| Time reversal | x[−n] | X(z−1) |
| Initial value | x[0]=limz→∞X(z) |
2.4 The Discrete-Time Fourier Transform (DTFT)
2.4.1 Definition
The Discrete-Time Fourier Transform (DTFT) is the frequency-domain representation of a discrete-time signal.
X(ejω)=∑n=−∞∞x[n]e−jωn
Inverse DTFT:
x[n]=12π∫−ππX(ejω)ejωndω
2.4.2 Properties of DTFT
| Property | Time Domain | Frequency Domain |
|---|---|---|
| Periodicity | — | X(ej(ω+2π))=X(ejω) |
| Symmetry (real x[n]) | x[n] real | X(e−jω)=X∗(ejω) |
| Convolution | x[n]∗h[n] | X(ejω)H(ejω) |
| Modulation | x[n]ejω0n | X(ej(ω−ω0)) |
2.5 The Discrete Fourier Transform (DFT)
2.5.1 Definition
The Discrete Fourier Transform (DFT) is a sampled version of the DTFT, computed for a finite-length sequence.
X[k]=∑n=0N−1x[n]e−j2πkn/N,k=0,1,…,N−1
Inverse DFT (IDFT) :
x[n]=1N∑k=0N−1X[k]ej2πkn/N,n=0,1,…,N−1
2.5.2 Fast Fourier Transform (FFT)
The FFT is an efficient algorithm to compute the DFT with complexity O(NlogN) instead of O(N2).
Radix-2 FFT (N is power of 2):
-
Decimation-in-time (DIT): Split into even and odd indices
-
Decimation-in-frequency (DIF): Split into first and second halves
FFT Complexity Comparison:
| N | Direct DFT (O(N²)) | FFT (O(N log₂ N)) |
|---|---|---|
| 64 | 4,096 | 384 |
| 256 | 65,536 | 2,048 |
| 1,024 | 1,048,576 | 10,240 |
| 4,096 | 16,777,216 | 49,152 |
2.5.3 Windowing
Windowing reduces spectral leakage when taking DFT of finite-length signals.
| Window | Time Domain | Frequency Characteristics |
|---|---|---|
| Rectangular | 1 for 0≤n<N | Narrow main lobe, high sidelobes |
| Hamming | 0.54−0.46cos(2πn/(N−1)) | Moderate main lobe, lower sidelobes |
| Hanning | 0.5−0.5cos(2πn/(N−1)) | Similar to Hamming |
| Blackman | 0.42−0.5cos(2πn/(N−1))+0.08cos(4πn/(N−1)) | Wide main lobe, very low sidelobes |
| Kaiser | I0(β1−(2n/(N−1)−1)2)/I0(β) | Adjustable main lobe/sidelobe tradeoff |
2.6 Digital Filters
2.6.1 Filter Classification
| Classification | Types |
|---|---|
| By length | FIR (Finite Impulse Response), IIR (Infinite Impulse Response) |
| By frequency response | Low-pass, High-pass, Band-pass, Band-stop, All-pass |
| By implementation | Direct form, Cascade form, Parallel form, Lattice |
CSE-3205: Data Communication and Computer Networks
1. Introduction to Data Communication and Networks
1.1. What is Data Communication?
Data Communication is the exchange of data between two devices via some form of transmission medium (such as wire, cable, or wireless). The fundamental purpose is to transfer information from one place to another reliably and efficiently.
The Core Question: How do we transfer digital information accurately and efficiently from one point to another across various physical media and network architectures?
1.2. Fundamental Characteristics of Data Communication
| Characteristic | Description |
|---|---|
| Delivery | Data must be delivered to the correct destination |
| Accuracy | Data must be delivered accurately (no corruption) |
| Timeliness | Data must be delivered in a timely manner |
| Jitter | Variation in packet arrival time (affects real-time applications) |
1.3. Components of Data Communication
┌─────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────┐
│ Message │───►│ Sender │───►│ Medium │───►│ Receiver │───►│ Message │
└─────────┘ └─────────────┘ └─────────────┘ └─────────────┘ └─────────┘
│ │
└─────────────── Protocol ──────────┘
| Component | Description |
|---|---|
| Message | Information to be transmitted (text, numbers, images, audio, video) |
| Sender | Device that sends the message (computer, phone, camera) |
| Receiver | Device that receives the message |
| Medium | Physical path (twisted pair, coaxial cable, fiber optics, radio waves) |
| Protocol | Set of rules governing communication |
1.4. Data Communication Modes
| Mode | Direction | Example |
|---|---|---|
| Simplex | One-way only | Radio broadcast, TV |
| Half-Duplex | Both directions, one at a time | Walkie-talkie |
| Full-Duplex | Both directions simultaneously | Telephone, Internet |
1.5. Network Criteria
| Criteria | Description |
|---|---|
| Performance | Transit time, response time, throughput, delay |
| Reliability | Frequency of failure, recovery time, robustness |
| Security | Protection from unauthorized access, data integrity |
1.6. Network Types
| Type | Geographic Area | Speed | Example |
|---|---|---|---|
| PAN (Personal Area Network) | Within person (meters) | Low | Bluetooth, USB |
| LAN (Local Area Network) | Building/campus (km) | High | Ethernet, Wi-Fi |
| MAN (Metropolitan Area Network) | City (10-100 km) | Medium | Cable TV network |
| WAN (Wide Area Network) | Country/continent (1000+ km) | Variable | Internet |
2. Network Models and Protocols
2.1. OSI Reference Model (7 Layers)
┌─────────────────────────────────────────────────────────────┐ │ 7 │ Application Layer │ User interface, email, web │ ├───┼──────────────────────┼─────────────────────────────────┤ │ 6 │ Presentation Layer │ Encryption, compression, format│ ├───┼──────────────────────┼─────────────────────────────────┤ │ 5 │ Session Layer │ Session management, sync │ ├───┼──────────────────────┼─────────────────────────────────┤ │ 4 │ Transport Layer │ End-to-end reliability, TCP/UDP│ ├───┼──────────────────────┼─────────────────────────────────┤ │ 3 │ Network Layer │ Routing, IP addressing │ ├───┼──────────────────────┼─────────────────────────────────┤ │ 2 │ Data Link Layer │ Framing, error control, MAC │ ├───┼──────────────────────┼─────────────────────────────────┤ │ 1 │ Physical Layer │ Bits over medium │ └─────────────────────────────────────────────────────────────┘
| Layer | Function | PDU | Devices |
|---|---|---|---|
| Application | Network services to user | Data | Gateway |
| Presentation | Data translation, encryption | Data | Gateway |
| Session | Session establishment, sync | Data | Gateway |
| Transport | End-to-end connection | Segment | Gateway |
| Network | Routing, addressing | Packet | Router |
| Data Link | Framing, error control | Frame | Switch, Bridge |
| Physical | Bit transmission | Bit | Hub, Repeater |
2.2. TCP/IP Model (4 Layers)
┌─────────────────────────────────────────────────────────────┐ │ 4 │ Application Layer │ HTTP, FTP, SMTP, DNS, Telnet │ ├───┼──────────────────────┼─────────────────────────────────┤ │ 3 │ Transport Layer │ TCP, UDP │ ├───┼──────────────────────┼─────────────────────────────────┤ │ 2 │ Internet Layer │ IP, ICMP, ARP, RARP │ ├───┼──────────────────────┼─────────────────────────────────┤ │ 1 │ Network Access Layer│ Ethernet, Wi-Fi, PPP │ └─────────────────────────────────────────────────────────────┘
OSI vs. TCP/IP:
| OSI Layer | TCP/IP Layer |
|---|---|
| Application, Presentation, Session | Application |
| Transport | Transport |
| Network | Internet |
| Data Link, Physical | Network Access |
2.3. Encapsulation
Data (Application) → Segment (Transport) → Packet (Network) → Frame (Data Link) → Bits (Physical)
At each layer, headers are added (and trailers at data link layer).
3. Physical Layer
3.1. Transmission Media
Guided Media (Wired):
| Medium | Speed | Distance | Cost | Interference |
|---|---|---|---|---|
| Twisted Pair (UTP/STP) | 10 Mbps – 10 Gbps | 100 m | Low | High |
| Coaxial Cable | 10-100 Mbps | 500 m | Medium | Medium |
| Fiber Optic | 100 Mbps – 100 Gbps+ | 2-80 km | High | Very low |
Unshielded Twisted Pair (UTP) Categories:
| Category | Speed | Application |
|---|---|---|
| Cat 5e | 1 Gbps | Ethernet |
| Cat 6 | 10 Gbps (55m) | Gigabit Ethernet |
| Cat 6a | 10 Gbps (100m) | 10 Gigabit Ethernet |
| Cat 7 | 10 Gbps+ | Data centers |
Unguided Media (Wireless):
| Type | Frequency | Range | Application |
|---|---|---|---|
| Radio Waves | 3 kHz – 3 GHz | Long | AM/FM radio, TV |
| Microwaves | 3-300 GHz | Line of sight | Satellite, WiMAX |
| Infrared | 300 GHz – 400 THz | Short | Remote controls |
3.2. Switching Techniques
| Technique | Description | Advantages | Disadvantages |
|---|---|---|---|
| Circuit Switching | Dedicated path for entire communication | Guaranteed bandwidth | Inefficient |
| Message Switching | Store-and-forward entire message | No dedicated path | Delays, large buffer |
| Packet Switching | Store-and-forward packets | Efficient, robust | Variable delay |
Packet Switching Types:
| Type | Path | Delay | Overhead |
|---|---|---|---|
| Datagram | Each packet independent | Variable | Lower |
| Virtual Circuit | Pre-established path | More consistent | Higher |
4. Data Link Layer
4.1. Functions of Data Link Layer
| Function | Description |
|---|---|
| Framing | Dividing bit stream into frames |
| Physical Addressing | MAC addresses |
| Error Control | Detection and retransmission |
| Flow Control | Preventing fast sender from overwhelming slow receiver |
| Access Control | Medium access control (MAC) |
4.2. Error Detection and Correction
Error Detection Methods:
| Method | Description | Detection Capability |
|---|---|---|
| Parity Check (VRC) | Single parity bit | Odd number of errors |
| LRC (Longitudinal Redundancy Check) | Parity per character | Limited |
| Checksum | Sum of data units | Moderate |
| CRC (Cyclic Redundancy Check) | Polynomial division | Very high |
CRC Calculation:
-
Data: D(x)
-
Divisor: G(x) (generator polynomial)
-
Frame: D(x)⋅xr+R(x) where R(x) is remainder
Common CRC Polynomials:
| Standard | Polynomial |
|---|---|
| CRC-12 | x12+x11+x3+x2+x+1 |
| CRC-16 | x16+x15+x2+1 |
| CRC-CCITT | x16+x12+x5+1 |
| CRC-32 (Ethernet) | x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1 |
4.3. Flow Control Protocols
| Protocol | Description | Sender Window | Receiver Window |
|---|---|---|---|
| Stop-and-Wait | Send one frame, wait for ACK | 1 | 1 |
| Go-Back-N | Send up to N frames, retransmit all after loss | N | 1 |
| Selective Repeat | Retransmit only lost frames | N | N |
Sliding Window Protocol:
-
Sender window size: maximum frames sent without ACK
-
Receiver window size: maximum frames buffered
4.4. Medium Access Control (MAC) Protocols
Random Access Protocols:
| Protocol | Collision Handling | Efficiency |
|---|---|---|
| ALOHA | Transmit anytime, retransmit after random delay | 18% |
| Slotted ALOHA | Transmit in slots | 37% |
| CSMA | Listen before transmit | Higher |
| CSMA/CD | CSMA + Collision Detection | Ethernet |
| CSMA/CA | CSMA + Collision Avoidance | Wi-Fi |
Controlled Access Protocols:
| Protocol | Description |
|---|---|
| Reservation | Reserve time slots |
| Polling | Master polls slaves |
| Token Passing | Token circulates, only token holder transmits |
Channelization Protocols:
| Protocol | Description |
|---|---|
| FDMA | Different frequencies |
| TDMA | Different time slots |
| CDMA | Different codes (spread spectrum) |
4.5. Ethernet (IEEE 802.3)
Ethernet Frame Format:
| Preamble (7) | SFD (1) | Dest MAC (6) | Src MAC (6) | Type/Len (2) | Data (46-1500) | FCS (4) |
-
Preamble: Synchronization (10101010)
-
SFD (Start Frame Delimiter): 10101011
-
MAC Addresses: 48-bit unique addresses
-
Type/Length: Ethernet type or frame length
-
FCS: CRC-32
Ethernet Standards:
| Standard | Speed | Medium | Max Distance |
|---|---|---|---|
| 10Base-T | 10 Mbps | UTP Cat 3+ | 100 m |
| 100Base-TX | 100 Mbps | UTP Cat 5+ | 100 m |
| 1000Base-T | 1 Gbps | UTP Cat 5e+ | 100 m |
| 10GBase-T | 10 Gbps | UTP Cat 6a | 100 m |
| 1000Base-SX | 1 Gbps | Multimode fiber | 550 m |
| 10GBase-SR | 10 Gbps | Multimode fiber | 300 m |
| 10GBase-LR | 10 Gbps | Single-mode fiber | 10 km |
4.6. Wireless LAN (IEEE 802.11/Wi-Fi)
Wi-Fi Standards:
| Standard | Frequency | Max Speed | Range |
|---|---|---|---|
| 802.11b | 2.4 GHz | 11 Mbps | 50 m |
| 802.11g | 2.4 GHz | 54 Mbps | 50 m |
| 802.11n | 2.4/5 GHz | 600 Mbps | 70 m |
| 802.11ac | 5 GHz | 3.5 Gbps | 50 m |
| 802.11ax (Wi-Fi 6) | 2.4/5 GHz | 9.6 Gbps | 70 m |
CSMA/CA (Collision Avoidance):
-
RTS/CTS (Request to Send / Clear to Send) handshake
-
Network Allocation Vector (NAV) for virtual carrier sensing
5. Network Layer
5.1. Functions of Network Layer
| Function | Description |
|---|---|
| Logical Addressing | IP addressing |
| Routing | Path determination |
| Packet Forwarding | Moving packets between interfaces |
| Fragmentation | Breaking packets for smaller MTU |
5.2. IP Addressing (IPv4)
IPv4 Address Format: 32 bits, dotted decimal notation (e.g., 192.168.1.1)
Classes of IP Addresses:
| Class | Leading Bits | Range | Network Bits | Host Bits | Use |
|---|---|---|---|---|---|
| A | 0 | 1-126 | 8 | 24 | Large networks |
| B | 10 | 128-191 | 16 | 16 | Medium networks |
| C | 110 | 192-223 | 24 | 8 | Small networks |
| D | 1110 | 224-239 | — | — | Multicast |
| E | 1111 | 240-255 | — | — | Experimental |
Private IP Addresses (RFC 1918):
| Class | Range | Subnet Mask |
|---|---|---|
| A | 10.0.0.0 – 10.255.255.255 | 255.0.0.0 |
| B | 172.16.0.0 – 172.31.255.255 | 255.240.0.0 |
| C | 192.168.0.0 – 192.168.255.255 | 255.255.0.0 |
Special IP Addresses:
| Address | Purpose |
|---|---|
| 0.0.0.0 | Default route, any address |
| 127.0.0.1 | Localhost (loopback) |
| 255.255.255.255 | Limited broadcast |
| Network address (host bits all 0) | Network identifier |
| Broadcast address (host bits all 1) | Broadcast to all hosts on network |
5.3. Subnetting and CIDR
Subnet Mask: 32-bit mask separating network and host portions
CIDR Notation: IP address followed by /prefix length (e.g., 192.168.1.0/24)
Subnetting Formulas:
-
Number of subnets = 2n (where n = borrowed bits)
-
Number of hosts per subnet = 2m−2 (where m = remaining host bits)
VLSM (Variable Length Subnet Masking): Using different subnet masks for different subnets
5.4. IPv6
IPv6 Address: 128 bits, hexadecimal notation (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334)
IPv6 Advantages:
-
Larger address space (2128 addresses)
-
No NAT required
-
Built-in security (IPsec)
-
Simplified header
-
Autoconfiguration
IPv6 Address Types:
| Type | Description |
|---|---|
| Unicast | Single interface |
| Multicast | Group of interfaces |
| Anycast | Nearest of multiple interfaces |
| Link-local | FE80::/10 (local link only) |
| Unique local | FC00::/7 (private) |
| Global unicast | 2000::/3 (public internet) |
5.5. IP Protocol
IPv4 Header Format:
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Version| IHL |Type of Service| Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identification |Flags| Fragment Offset | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Time to Live | Protocol | Header Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Destination Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options (if any) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Field | Size | Description |
|---|---|---|
| Version | 4 bits | IPv4 or IPv6 |
| IHL | 4 bits | Header length (in 32-bit words) |
| ToS | 8 bits | Quality of Service |
| Total Length | 16 bits | Header + data length |
| Identification | 16 bits | Fragment identification |
| Flags | 3 bits | Don’t fragment, more fragments |
| Fragment Offset | 13 bits | Position of fragment |
| TTL | 8 bits | Maximum hops (decremented each router) |
| Protocol | 8 bits | TCP (6), UDP (17), ICMP (1) |
| Header Checksum | 16 bits | Error detection for header |
| Source/Dest Address | 32 bits each | IP addresses |
5.6. Routing Algorithms
Static vs. Dynamic Routing:
| Type | Advantages | Disadvantages |
|---|---|---|
| Static | Simple, secure | No adaptation to failures |
| Dynamic | Adaptive, resilient | Complex, overhead |
Distance Vector Routing (RIP):
-
Each router shares entire routing table with neighbors
-
Bellman-Ford algorithm
-
Metric: hop count (max 15)
-
Count to infinity problem
-
Routing Information Protocol (RIP)
Link State Routing (OSPF):
-
Each router shares link state information with all routers
-
Dijkstra’s shortest path algorithm
-
Metric: cost (bandwidth based)
-
Faster convergence
-
Open Shortest Path First (OSPF)
Path Vector Routing (BGP):
-
Used between autonomous systems
-
Policy-based routing
-
Border Gateway Protocol (BGP)
5.7. Routing Protocols Comparison
| Protocol | Type | Metric | Algorithm | Convergence | Scalability |
|---|---|---|---|---|---|
| RIP | Distance Vector | Hop count | Bellman-Ford | Slow | Small |
| OSPF | Link State | Cost | Dijkstra | Fast | Large |
| EIGRP | Advanced DV | Composite | DUAL | Fast | Large |
| BGP | Path Vector | Path attributes | — | Slow | Very large |
5.8. Internet Control Message Protocol (ICMP)
ICMP Message Types:
| Type | Message | Purpose |
|---|---|---|
| 0 | Echo Reply | Ping response |
| 3 | Destination Unreachable | Network/host unreachable |
| 8 | Echo Request | Ping request |
| 11 | Time Exceeded | TTL expired (traceroute) |
5.9. Network Address Translation (NAT)
NAT Types:
| Type | Description |
|---|---|
| Static NAT | One-to-one mapping (public to private) |
| Dynamic NAT | Pool of public addresses |
| PAT (Port Address Translation) | Many-to-one using ports |
6. Transport Layer
6.1. Functions of Transport Layer
| Function | Description |
|---|---|
| Segmentation | Breaking data into segments |
| Port Addressing | Identifying applications |
| Connection Control | Connection-oriented vs connectionless |
| Flow Control | Preventing sender overload |
| Error Control | Reliability, retransmission |
6.2. TCP (Transmission Control Protocol)
TCP Characteristics:
-
Connection-oriented
-
Reliable (acknowledgments, retransmission)
-
Flow control (sliding window)
-
Congestion control
-
Ordered delivery
-
Error checking
TCP Header Format:
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options (if any) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Field | Description |
|---|---|
| Source/Dest Port | 16-bit port numbers |
| Sequence Number | Byte number of first data byte |
| Acknowledgment Number | Next expected byte (if ACK flag set) |
| Data Offset | TCP header length |
| Flags | URG, ACK, PSH, RST, SYN, FIN |
| Window | Flow control window size |
| Checksum | Error detection |
| Urgent Pointer | Offset to urgent data |
TCP Flags:
| Flag | Name | Purpose |
|---|---|---|
| SYN | Synchronize | Connection establishment |
| ACK | Acknowledgment | Acknowledging data |
| FIN | Finish | Connection termination |
| RST | Reset | Abort connection |
| PSH | Push | Deliver data immediately |
| URG | Urgent | Urgent data |
TCP Three-Way Handshake:
Client Server | | |------ SYN (seq=x) ----->| | | |<--- SYN-ACK (seq=y, ack=x+1)| | | |------ ACK (ack=y+1) --->| | |
TCP Connection Termination (Four-way handshake):
Client Server | | |------ FIN (seq=x) ----->| | | |<--- ACK (ack=x+1) ------| | | |<--- FIN (seq=y) --------| | | |------ ACK (ack=y+1) --->| | |
TCP Flow Control (Sliding Window):
-
Advertised window (rwnd) from receiver
-
Sender cannot exceed window size
TCP Congestion Control:
-
Congestion window (cwnd) at sender
-
Slow Start (exponential growth until threshold)
-
Congestion Avoidance (linear growth)
-
Fast Retransmit (triple duplicate ACK)
-
Fast Recovery
6.3. UDP (User Datagram Protocol)
UDP Characteristics:
-
Connectionless
-
Unreliable (no ACK, no retransmission)
-
No flow control
-
No congestion control
-
No ordering
-
Low overhead
UDP Header Format:
0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Length | Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
6.4. TCP vs. UDP Comparison
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Reliable (ACKs) | Unreliable |
| Flow Control | Yes | No |
| Congestion Control | Yes | No |
| Ordering | Yes | No |
| Error Checking | Yes | Yes (optional) |
| Header Size | 20-60 bytes | 8 bytes |
| Speed | Slower | Faster |
| Applications | HTTP, FTP, SMTP, SSH | DNS, VoIP, streaming, gaming |
6.5. Port Numbers
Well-Known Ports (0-1023):
| Port | Protocol | Service |
|---|---|---|
| 20,21 | TCP | FTP |
| 22 | TCP | SSH |
| 23 | TCP | Telnet |
| 25 | TCP | SMTP |
| 53 | TCP/UDP | DNS |
| 67,68 | UDP | DHCP |
| 80 | TCP | HTTP |
| 110 | TCP | POP3 |
| 143 | TCP | IMAP |
| 443 | TCP | HTTPS |
| 161 | UDP | SNMP |
Registered Ports (1024-49151): Assigned to user processes
Dynamic Ports (49152-65535): Temporary (client-side)
7. Application Layer
7.1. Common Application Layer Protocols
| Protocol | Port | Transport | Purpose |
|---|---|---|---|
| HTTP | 80 | TCP | Web browsing |
| HTTPS | 443 | TCP | Secure web |
| FTP | 20,21 | TCP | File transfer |
| SMTP | 25 | TCP | Email sending |
| POP3 | 110 | TCP | Email retrieval |
| IMAP | 143 | TCP | Email retrieval (server-side) |
| DNS | 53 | UDP/TCP | Domain name resolution |
| DHCP | 67,68 | UDP | IP address assignment |
| Telnet | 23 | TCP | Remote terminal |
| SSH | 22 | TCP | Secure remote access |
| SNMP | 161 | UDP | Network management |
7.2. DNS (Domain Name System)
DNS Hierarchy:
Root (.) ├── com │ ├── google.com │ └── example.com ├── org ├── net ├── edu └── country domains (pk, uk, jp, etc.)
DNS Record Types:
| Type | Description | Example |
|---|---|---|
| A | IPv4 address | 192.168.1.1 |
| AAAA | IPv6 address | 2001:db8::1 |
| CNAME | Canonical name (alias) | www → @ |
| MX | Mail exchange | mail.example.com |
| NS | Name server | ns1.example.com |
| PTR | Reverse lookup | 1.1.168.192.in-addr.arpa |
| TXT | Text information | SPF records |
DNS Resolution Process:
Client → Local DNS Server → Root DNS → TLD DNS → Authoritative DNS → Response
7.3. HTTP (Hypertext Transfer Protocol)
HTTP Methods:
| Method | Description |
|---|---|
| GET | Retrieve resource |
| POST | Submit data to server |
| PUT | Upload resource |
| DELETE | Delete resource |
| HEAD | Get headers only |
| OPTIONS | Get supported methods |
HTTP Status Codes:
| Code Range | Category | Example |
|---|---|---|
| 1xx | Informational | 100 Continue |
| 2xx | Success | 200 OK, 201 Created |
| 3xx | Redirection | 301 Moved Permanently, 304 Not Modified |
| 4xx | Client Error | 400 Bad Request, 401 Unauthorized, 404 Not Found |
| 5xx | Server Error | 500 Internal Server Error, 503 Service Unavailable |
HTTP Versions:
| Version | Features |
|---|---|
| HTTP/1.0 | Basic, one request per connection |
| HTTP/1.1 | Persistent connections, pipelining |
| HTTP/2 | Multiplexing, server push, header compression |
| HTTP/3 | Uses QUIC (UDP-based) |
7.4. Email Protocols
SMTP (Simple Mail Transfer Protocol):
-
Used for sending email between servers
-
Port 25 (plain), 587 (submission)
-
Commands: HELO, MAIL FROM, RCPT TO, DATA, QUIT
POP3 (Post Office Protocol version 3):
-
Download emails from server
-
Emails deleted from server after download (typically)
-
Port 110 (plain), 995 (SSL)
IMAP (Internet Message Access Protocol):
-
Emails remain on server
-
Server-side folder management
-
Port 143 (plain), 993 (SSL)
8. Network Security
8.1. Security Threats
| Threat | Description |
|---|---|
| Sniffing | Capturing network traffic |
| Spoofing | Faking source address |
| Man-in-the-Middle | Intercepting communications |
| Denial of Service (DoS) | Overwhelming resources |
| Session Hijacking | Taking over authenticated session |
| Replay Attack | Retransmitting captured data |
8.2. Network Security Protocols
| Protocol | Layer | Purpose |
|---|---|---|
| IPsec | Network | IP packet encryption/authentication |
| SSL/TLS | Transport | Secure socket layer (HTTPS) |
| SSH | Application | Secure remote access |
| HTTPS | Application | HTTP over TLS |
| DNSSEC | Application | Secure DNS |
8.3. Firewalls
| Type | Layer | Inspection |
|---|---|---|
| Packet Filtering | Network | Headers only |
| Stateful Inspection | Network/Transport | Connection state |
| Application Gateway | Application | Full application data |
| Next-Gen Firewall (NGFW) | Multi-layer | Deep packet inspection |
9. Network Performance Metrics
| Metric | Definition |
|---|---|
| Bandwidth | Maximum data rate (bits per second) |
| Throughput | Actual data transfer rate |
| Latency (Delay) | Time for packet to travel from source to destination |
| Jitter | Variation in latency |
| Packet Loss | Percentage of packets lost |
| RTT (Round Trip Time) | Time for packet to go and return |
CSE-3206: Software Engineering
1. Introduction to Software Engineering
1.1. What is Software Engineering?
Software Engineering is the systematic application of engineering principles to the development, operation, and maintenance of software. It encompasses methodologies, tools, and processes to produce high-quality software within time and budget constraints.
The Core Question: How do we develop high-quality software systematically, predictably, and efficiently while meeting user requirements and managing complexity?
1.2. Software Crisis
| Problem | Description |
|---|---|
| Cost overruns | Projects exceeding budget |
| Schedule overruns | Late delivery |
| Poor quality | Bugs, reliability issues |
| Hard to maintain | Difficult to modify |
| User dissatisfaction | Doesn’t meet needs |
1.3. Software Engineering vs. Programming
| Aspect | Programming | Software Engineering |
|---|---|---|
| Focus | Code writing | Entire development process |
| Scale | Individual/small team | Large team |
| Timeframe | Short-term | Long-term lifecycle |
| Documentation | Minimal | Extensive |
| Process | Ad-hoc | Systematic |
2. Software Development Life Cycle (SDLC)
2.1. SDLC Phases
Requirements → Design → Implementation → Testing → Deployment → Maintenance
| Phase | Activities | Outputs |
|---|---|---|
| Requirements | Gather, analyze, document | SRS (Software Requirements Specification) |
| Design | Architecture, detailed design | Design documents, diagrams |
| Implementation | Coding, unit testing | Source code |
| Testing | Integration, system, acceptance testing | Test reports, bug reports |
| Deployment | Installation, data migration, training | Deployed system |
| Maintenance | Bug fixes, enhancements, updates | Updated versions |
2.2. Software Development Models
Waterfall Model:
Requirements → Design → Implementation → Testing → Deployment → Maintenance
(complete each phase before moving to next)
| Advantages | Disadvantages |
|---|---|
| Simple, easy to understand | No feedback between phases |
| Disciplined, milestones | Late testing (bugs found late) |
| Good for stable requirements | Not suitable for changing requirements |
V-Model (Verification & Validation):
Requirements → System Design → Architecture Design → Module Design → Implementation
↑ ↑ ↑ ↑ ↓
Acceptance Test ← System Test ← Integration Test ← Unit Test ← Implementation
Prototyping Model:
-
Build prototype → User evaluation → Refine → Repeat → Final product
Spiral Model:
-
Risk-driven iterative model
-
Quadrants: Determine objectives → Identify risks → Development → Plan next iteration
Iterative and Incremental Model:
-
Build system in increments (small releases)
-
Each increment adds functionality
Agile Model:
-
Iterative, incremental, adaptive
-
Customer collaboration
-
Responding to change
2.3. Agile Methodologies
Agile Manifesto (4 values):
-
Individuals and interactions over processes and tools
-
Working software over comprehensive documentation
-
Customer collaboration over contract negotiation
-
Responding to change over following a plan
CSE-4208 Computer Network Security – Detailed Study Notes
These notes cover the fundamental principles of network security, cryptographic techniques, security protocols, network attacks, and defense mechanisms.
1. Introduction to Network Security
1.1 What is Network Security?
| Aspect | Detail |
|---|---|
| Definition | Network security is the practice of protecting computer networks and their data from unauthorized access, misuse, modification, or denial of service. |
| Goals (CIA Triad) | Confidentiality (data privacy), Integrity (data accuracy), Availability (data accessible when needed) |
| Additional Goals | Authentication (verify identity), Authorization (access control), Non-repudiation (proof of origin) |
1.2 Types of Security Threats
| Threat Type | Description | Examples |
|---|---|---|
| Passive attacks | Eavesdropping, monitoring | Traffic analysis, packet sniffing |
| Active attacks | Modification, disruption | Masquerade, replay, DoS |
| Insider threats | Internal malicious actors | Disgruntled employees |
| Malware | Malicious software | Viruses, worms, Trojans, ransomware |
2. Cryptographic Fundamentals
2.1 Symmetric Key Cryptography
| Aspect | Detail |
|---|---|
| Principle | Same key for encryption and decryption |
| Advantages | Fast, efficient for bulk data |
| Disadvantages | Key distribution problem |
| Algorithms | DES, 3DES, AES, RC4, Blowfish |
AES (Advanced Encryption Standard):
-
Block size: 128 bits
-
Key sizes: 128, 192, 256 bits
-
Rounds: 10 (128-bit key), 12 (192-bit), 14 (256-bit)
DES (Data Encryption Standard):
-
Block size: 64 bits
-
Key size: 56 bits (effective)
-
Rounds: 16
2.2 Asymmetric (Public Key) Cryptography
| Aspect | Detail |
|---|---|
| Principle | Two keys: public (encryption), private (decryption) |
| Advantages | Solves key distribution; provides digital signatures |
| Disadvantages | Slower than symmetric |
| Algorithms | RSA, ECC, Diffie-Hellman, DSA |
RSA Algorithm:
1. Choose two large primes p and q 2. Compute n = p × q, φ(n) = (p-1)(q-1) 3. Choose e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1 4. Compute d such that d × e ≡ 1 mod φ(n) 5. Public key: (e, n); Private key: (d, n) 6. Encryption: C = M^e mod n 7. Decryption: M = C^d mod n
Diffie-Hellman Key Exchange:
1. Agree on prime p and primitive root g
2. Alice: chooses private a, sends A = g^a mod p
3. Bob: chooses private b, sends B = g^b mod p
4. Shared secret: K = B^a mod p = A^b mod p = g^{ab} mod p
2.3 Hash Functions
| Aspect | Detail |
|---|---|
| Definition | One-way function producing fixed-size output (digest) |
| Properties | Preimage resistance, second preimage resistance, collision resistance |
| Algorithms | MD5 (broken), SHA-1 (weak), SHA-256, SHA-3 |
2.4 Digital Signatures
| Aspect | Detail |
|---|---|
| Purpose | Authentication, integrity, non-repudiation |
| Process | Sign: hash → encrypt with private key → signature Verify: hash → decrypt signature with public key → compare |
3. Network Security Protocols
3.1 SSL/TLS (Secure Sockets Layer / Transport Layer Security)
| Aspect | Detail |
|---|---|
| Purpose | Secure communication over TCP (HTTPS) |
| Layers | Record protocol (encryption), Handshake protocol (authentication, key exchange) |
| TLS versions | TLS 1.2 (widely used), TLS 1.3 (faster, more secure) |
TLS Handshake Summary:
Client → Server: ClientHello (supported ciphers) Server → Client: ServerHello (chosen cipher, certificate) Client → Server: Pre-master secret (encrypted with server's public key) Both: Generate session keys Client → Server: Finished (encrypted) Server → Client: Finished
3.2 IPSec (Internet Protocol Security)
| Aspect | Detail |
|---|---|
| Purpose | Secure IP communications (network layer) |
| Modes | Transport mode (end-to-end), Tunnel mode (gateway-to-gateway) |
| Protocols | AH (Authentication Header) – integrity, authentication ESP (Encapsulating Security Payload) – confidentiality, integrity, authentication |
3.3 SSH (Secure Shell)
| Aspect | Detail |
|---|---|
| Purpose | Secure remote login and command execution |
| Port | 22 |
| Features | Secure file transfer (SFTP), port forwarding, X11 forwarding |
3.4 VPN (Virtual Private Network)
| Aspect | Detail |
|---|---|
| Purpose | Extend private network over public internet |
| Types | Site-to-site, remote access, SSL VPN |
| Protocols | IPSec, OpenVPN, WireGuard, PPTP (obsolete) |
4. Network Attacks and Defenses
4.1 Common Network Attacks
| Attack | Description | Mitigation |
|---|---|---|
| Packet sniffing | Capturing network traffic | Encryption (TLS, IPSec) |
| Man-in-the-middle (MITM) | Intercepting and modifying communications | Authentication, PKI |
| ARP spoofing | Associating attacker’s MAC with legitimate IP | Static ARP, DAI |
| DNS spoofing | Poisoning DNS cache | DNSSEC |
| Replay attack | Resending captured legitimate messages | Timestamps, nonces |
| DoS/DDoS | Overwhelming resources | Rate limiting, filtering, CDN |
| Session hijacking | Stealing session tokens | Secure cookies, HTTPS |
| Phishing | Deceptive messages to steal credentials | User education, 2FA |
4.2 Firewalls
| Type | Layer | Description | Examples |
|---|---|---|---|
| Packet filtering | 3-4 | Examines headers (IP, port) | iptables, ACLs |
| Stateful inspection | 3-4 | Tracks connection state | Cisco ASA |
| Application gateway | 7 | Proxies specific applications | Web proxy, FW |
| Next-gen firewall (NGFW) | 3-7 | Deep packet inspection, IPS | Palo Alto, Fortinet |
4.3 Intrusion Detection/Prevention Systems (IDS/IPS)
| Type | Location | Action | Examples |
|---|---|---|---|
| NIDS | Network segment | Alert only | Snort, Suricata |
| NIPS | Inline | Block traffic | Snort inline, Suricata |
| HIDS | Host | Monitor host activity | OSSEC, Tripwire |
Detection Methods:
-
Signature-based: Matches known attack patterns (fast, misses zero-day)
-
Anomaly-based: Baseline normal behavior (detects zero-day, higher false positives)
5. Wireless Network Security
5.1 Wi-Fi Security Protocols
| Protocol | Encryption | Authentication | Status |
|---|---|---|---|
| WEP | RC4 | Pre-shared key | Broken (do not use) |
| WPA | TKIP (RC4) | PSK or 802.1X | Deprecated |
| WPA2 | CCMP (AES) | PSK or 802.1X | Current (but has KRACK vulnerability) |
| WPA3 | GCMP-256 | SAE (Simultaneous Authentication of Equals) | Latest (most secure) |
5.2 802.1X (Port-Based Authentication)
Components:
-
Supplicant: Client device
-
Authenticator: Switch/AP
-
Authentication server: RADIUS
6. Sample Exam Questions
Short Answer (5 marks each)
-
Distinguish between symmetric and asymmetric encryption. Give one example of each.
-
What is the difference between a virus and a worm?
-
Explain the purpose of a digital signature. How does it provide non-repudiation?
-
What is the difference between IDS and IPS?
-
List the four goals of network security (CIA triad + one more).
Numerical/Conceptual Problem
RSA Calculation:
Given p = 11, q = 13, e = 7. Compute n, φ(n), d, and encrypt M = 5.
Solution:
n = p × q = 11 × 13 = 143 φ(n) = (p-1)(q-1) = 10 × 12 = 120 d = e⁻¹ mod φ(n) = 7⁻¹ mod 120 7 × 103 = 721 ≡ 1 mod 120 (since 120×6=720) d = 103 Encryption: C = M^e mod n = 5⁷ mod 143 5²=25, 5⁴=25²=625≡625-4×143=625-572=53, 5⁷=5⁴×5²×5=53×25×5=53×125=6625 6625 ÷ 143 = 46 remainder: 143×46=6578, 6625-6578=47 C = 47
CSE-4209 Artificial Intelligence – Detailed Study Notes
These notes cover the fundamental principles of AI, search algorithms, knowledge representation, reasoning under uncertainty, machine learning, and AI applications.
1. Introduction to Artificial Intelligence
1.1 What is AI?
| Aspect | Detail |
|---|---|
| Definition (Turing) | Can machines think? |
| Definition (Russell & Norvig) | Study of agents that perceive their environment and take actions to maximize success |
| Four Approaches | Acting humanly (Turing Test), Thinking humanly (cognitive modeling), Thinking rationally (logic), Acting rationally (rational agent) |
1.2 History of AI
| Era | Milestone | Significance |
|---|---|---|
| 1950 | Turing Test | Proposed test for machine intelligence |
| 1956 | Dartmouth Conference | “Artificial Intelligence” coined |
| 1960s-70s | Early AI (Logic Theorist, GPS) | Problem-solving, theorem proving |
| 1970s-80s | Expert systems (MYCIN, DENDRAL) | Rule-based reasoning |
| 1980s-90s | AI Winter | Reduced funding |
| 1997 | Deep Blue beats Kasparov | Chess AI milestone |
| 2012 | ImageNet (AlexNet) | Deep learning revolution |
| 2016 | AlphaGo beats Lee Sedol | Go AI milestone |
| 2020s | Large language models (GPT, BERT) | Generative AI |
1.3 AI Applications
| Domain | Applications |
|---|---|
| Healthcare | Diagnosis, drug discovery, medical imaging |
| Finance | Fraud detection, algorithmic trading |
| Transportation | Self-driving cars, route optimization |
| NLP | Chatbots, translation, summarization |
| Computer vision | Face recognition, object detection |
| Robotics | Autonomous navigation, manipulation |
2. Intelligent Agents
2.1 Agent Definition
| Term | Definition |
|---|---|
| Agent | Anything that perceives its environment through sensors and acts through actuators |
| Rational agent | Chooses actions to maximize performance measure |
| PEAS | Performance measure, Environment, Actuators, Sensors |
2.2 Environment Properties
| Property | Types |
|---|---|
| Observability | Fully vs. Partially observable |
| Agent count | Single vs. Multi-agent |
| Determinism | Deterministic vs. Stochastic |
| Episodicity | Episodic vs. Sequential |
| Dynamics | Static vs. Dynamic |
| Continuity | Discrete vs. Continuous |
3. Problem Solving and Search
3.1 Uninformed Search
| Algorithm | Strategy | Time | Space | Optimal? |
|---|---|---|---|---|
| BFS | Expand shallowest | O(bᵈ) | O(bᵈ) | Yes |
| DFS | Expand deepest | O(bᵐ) | O(bm) | No |
| IDS | Iterative deepening | O(bᵈ) | O(bd) | Yes |
| UCS | Expand lowest cost | O(b^(C*/ε)) | O(b^(C*/ε)) | Yes |
where b = branching factor, d = depth, m = max depth
3.2 Informed Search (Heuristics)
| Algorithm | Strategy | Optimal? | Condition |
|---|---|---|---|
| Greedy best-first | Expand node with lowest h(n) | No | – |
| A* | Expand node with lowest f(n) = g(n) + h(n) | Yes | Admissible heuristic |
Admissible heuristic: Never overestimates cost to goal
3.3 Local Search
| Algorithm | Description |
|---|---|
| Hill climbing | Move to neighbor with higher value (greedy) |
| Simulated annealing | Accept worse moves with probability |
| Genetic algorithm | Evolutionary (selection, crossover, mutation) |
4. Adversarial Search (Game Playing)
4.1 Minimax Algorithm
Principle: MAX aims to maximize outcome; MIN aims to minimize outcome
Value(s) = max_{a∈Actions(s)} Value(Result(s,a)) for MAX
Value(s) = min_{a∈Actions(s)} Value(Result(s,a)) for MIN
4.2 Alpha-Beta Pruning
Principle: Prune branches that cannot influence final decision
Efficiency: Reduces nodes from O(bᵈ) to O(bᵈ/²) with perfect ordering
5. Knowledge Representation and Reasoning
5.1 Propositional Logic
| Connectives | Meaning |
|---|---|
| ¬P | Not P |
| P ∧ Q | P and Q |
| P ∨ Q | P or Q |
| P → Q | If P then Q |
| P ↔ Q | P if and only if Q |
5.2 First-Order Logic (FOL)
| Element | Syntax | Example |
|---|---|---|
| Constants | a, b, c | John, 5 |
| Variables | x, y, z | person, number |
| Predicates | P(x), Q(x,y) | Student(x), Likes(x,y) |
| Quantifiers | ∀ (for all), ∃ (exists) | ∀x Student(x) → Person(x) |
5.3 Inference Methods
| Method | Description |
|---|---|
| Forward chaining | Data-driven; apply rules to known facts |
| Backward chaining | Goal-driven; work backward from goal |
| Resolution | Refutation proof (unification) |
6. Reasoning Under Uncertainty
6.1 Probability Basics
| Term | Definition | ||
|---|---|---|---|
| P(A) | Probability of event A | ||
| **P(A | B)** | Conditional probability: P(A∩B)/P(B) | |
| Bayes’ theorem | P(A | B) = P(B | A)P(A)/P(B) |
6.2 Bayesian Networks
Definition: Directed acyclic graph where nodes represent variables, edges represent conditional dependencies
6.3 Naïve Bayes Classifier
Assumption: Features are conditionally independent given class
P(C|X) ∝ P(C) ∏ P(x_i|C)
7. Machine Learning
7.1 Types of Learning
| Type | Description | Examples |
|---|---|---|
| Supervised | Labeled training data | Classification, regression |
| Unsupervised | No labels | Clustering, PCA |
| Reinforcement | Rewards/punishments | Game playing, robotics |
7.2 Supervised Learning Algorithms
| Algorithm | Type | Characteristics | |
|---|---|---|---|
| Linear regression | Regression | y = wx + b | |
| Logistic regression | Classification | P(y=1 | x) = 1/(1+e^{-wx}) |
| k-NN | Both | Lazy learner, distance-based | |
| Decision tree | Both | Hierarchical, interpretable | |
| SVM | Classification | Maximum margin hyperplane | |
| Neural network | Both | Deep learning, flexible |
7.3 Model Evaluation
| Metric | Formula | Use |
|---|---|---|
| Accuracy | (TP+TN)/(TP+TN+FP+FN) | Balanced classes |
| Precision | TP/(TP+FP) | FP costly |
| Recall | TP/(TP+FN) | FN costly |
| F1 | 2×P×R/(P+R) | Imbalanced classes |
| AUC-ROC | Area under ROC curve | Threshold-independent |
8. Neural Networks and Deep Learning
8.1 Perceptron
y = f(Σ w_i x_i + b)
Activation functions: Sigmoid, Tanh, ReLU, Softmax
8.2 Multi-Layer Perceptron (MLP)
Backpropagation: Chain rule to compute gradients, update weights via gradient descent
8.3 Deep Learning Architectures
| Architecture | Use | Key feature |
|---|---|---|
| CNN | Images | Convolution, pooling |
| RNN/LSTM | Sequences | Hidden state, gates |
| Transformer | NLP | Self-attention |
| GAN | Generation | Generator + discriminator |
9. Natural Language Processing (NLP)
9.1 NLP Tasks
| Task | Description |
|---|---|
| Tokenization | Split text into tokens |
| POS tagging | Label parts of speech |
| NER | Identify named entities |
| Sentiment analysis | Determine sentiment |
| Machine translation | Translate between languages |
| Question answering | Answer questions from text |
9.2 Language Models
| Model | Description |
|---|---|
| Bag of words | Word counts (ignores order) |
| Word2Vec | Dense vector embeddings |
| BERT | Bidirectional transformer |
| GPT | Autoregressive transformer |
10. Sample Exam Questions
Short Answer (5 marks each)
-
Distinguish between supervised and unsupervised learning. Give an example of each.
-
What is an admissible heuristic? Why is it important for A* search?
-
Explain the minimax algorithm for game playing.
-
What is the difference between precision and recall?
-
State Bayes’ theorem and explain its importance in AI.
Problem-Based Questions
1. A Search:*
Consider a grid with start S(0,0) and goal G(2,2). Heuristic = Manhattan distance. Moves: up, down, left, right (cost 1 each). Trace A* search.
Solution:
f(n) = g(n) + h(n) where h = |x_G - x_n| + |y_G - y_n| S: g=0, h=4, f=4 Expand S → neighbors: (0,1) g=1, h=3, f=4; (1,0) g=1, h=3, f=4 Continue until goal reached...
2. Naïve Bayes:
Given: P(spam)=0.4, P(“free”|spam)=0.8, P(“free”|ham)=0.1. Calculate P(spam|”free”).
Solution:
P("free") = P(spam)P(free|spam) + P(ham)P(free|ham)
= 0.4×0.8 + 0.6×0.1 = 0.32 + 0.06 = 0.38
P(spam|free) = (0.4×0.8)/0.38 = 0.32/0.38 = 0.842
Quick Revision Table – AI Search Algorithms
| Algorithm | Complete | Optimal | Time | Space |
|---|---|---|---|---|
| BFS | Yes | Yes | O(bᵈ) | O(bᵈ) |
| DFS | No | No | O(bᵐ) | O(bm) |
| IDS | Yes | Yes | O(bᵈ) | O(bd) |
| UCS | Yes | Yes | O(b^(C*/ε)) | O(b^(C*/ε)) |
| A* | Yes | Yes (with admissible h) | O(bᵈ) | O(bᵈ) |