Problem Solving with Programming - Comprehensive Study Notes
Foundations of Computing and Data Processing
Etymology and Evolution of the Term:
The word "computer" originates from the Latin verb computare, meaning "to compute" or "to calculate".
Early computers were conceived primarily as high-speed numerical calculators.
In modern applications, upwards of of computer tasks do not involve traditional mathematics or numerical calculations, making the term "data processor" a far more accurate descriptor.
Data versus Information:
Data: Unorganized, raw facts, figures, and symbols collected from various incoming sources. Examples include passenger booking records (name, age, sex), student grades, biodata, or scientific measurements.
Information: Data that has been captured, modified, processed, and organized into a meaningful, structured format that is useful to the recipient.
Data Processing Cycle: Comprises three fundamental sub-activities: capturing input data, manipulating/transforming the data, and managing and presenting the output outcomes.
Core Attributes and Operational Characteristics:
Automatic: Once initiated with a programmed set of instructions, computers execute tasks to completion without human intervention. They cannot initiate themselves, nor can they spontaneously diagnose or resolve problems outside their programmed scope.
Speed: Operates at rates far exceeding human capability, performing tasks in minutes that would take an individual an entire lifetime. Measured in microseconds (), nanoseconds (), and picoseconds (). Advanced computers execute tens of billions of elementary arithmetic calculations per second.
Accuracy: Calculations exhibit consistent precision determined strictly by machine design and circuit logic. System errors almost universally stem from human slip-ups—either flawed programming logic or inaccurate input values—a principle known as Garbage-In, Garbage-Out (GIGO).
Diligence: Computers are completely free from human psychological frailties such as fatigue, boredom, distraction, and loss of concentration. A machine executes the ten-millionth computation with the exact same speed and accuracy as the first.
Versatility: Capable of transitioning between completely disparate applications—such as compiling payroll, rendering graphics, managing inventory, or searching records—simply by loading a new set of instructions (program).
Memory Retention Power: Unlike the human brain, which selectively forgets non-essential details, a computer stores and recalls vast quantities of data indefinitely via secondary storage without degradation. Data is purged only upon explicit instruction.
Lack of Independent Intelligence (Zero IQ): A computer possesses no native intellect (). It is entirely reliant on human-authored machine instructions to determine what tasks to perform, the sequence of operations, and the decision pathways to follow.
Absence of Emotions and Sentiments: Machines lack feelings, instincts, personal tastes, knowledge born of lived experience, and moral compasses.
Historical Evolution of Computing Devices
Pioneering Mechanical and Electromechanical Devices:
Pascaline (1642): Blaise Pascal developed the first mechanical adding and subtracting machine utilizing geared wheels.
Leibniz Calculator (1671): German Baron Gottfried Wilhelm von Leibniz invented the first stepped-drum calculator capable of direct multiplication and division.
Key-Driven Calculators and Punched Cards (~1880s): Keyboard-based calculating machines emerged in the United States. Concurrently, Herman Hollerith developed punched cards for tabulating census data, establishing a data input and storage medium that persisted into the late 1970s.
Charles Babbage (The Father of Modern Digital Computing):
Difference Engine (1822): A specialized mechanical calculating machine designed to compute and tabulate polynomial functions without human error.
Analytical Engine (1842): A revolutionary conceptual design for a general-purpose, fully automatic, stored-program mechanical computer capable of executing sixty additions per minute. Although never constructed during his lifetime due to manufacturing limitations, its fundamental architecture anticipated modern digital computer organization.
Milestone Early Digital Computers:
Harvard Mark I (1937–1944): Built by Howard A. Aiken in collaboration with International Business Machines (IBM). Known formally as the Automatic Sequence Controlled Calculator. An electromechanical machine measuring approximately high and dozens of feet long, controlled by over electrical switches. Capable of handling numbers up to decimal digits; performed addition in approximately and multiplication in approximately .
Atanasoff-Berry Computer / ABC (1939–1942): Developed by Dr. John Vincent Atanasoff and Clifford Berry at Iowa State University. The first electronic digital calculating device dedicated to solving systems of linear equations, utilizing vacuum tubes for internal logic and regenerative capacitor drums for memory.
ENIAC (1943–1946): Electronic Numerical Integrator and Calculator, designed by J. Presper Eckert and John Mauchly at the University of Pennsylvania Moore School of Electrical Engineering for military ballistic trajectories. The first general-purpose, all-electronic digital computer. Occupied , incorporated over vacuum tubes, and completed an addition in and a multiplication in .
EDVAC (1946–1952): Electronic Discrete Variable Automatic Computer. Conceived to address ENIAC's rigid hardwired patch-panel programming. Incorporates Dr. John von Neumann's stored-program concept, storing program instructions and operational data together in binary notation (s and s) within internal memory.
EDSAC (1947–1949): Electronic Delay Storage Automatic Calculator, constructed by Maurice Wilkes at the Cambridge University Mathematical Laboratory. Ran its first program in May 1949. Required for addition and for multiplication, utilizing mercury acoustic delay lines for memory.
UNIVAC I (1951): Universal Automatic Computer, the first commercial, mass-produced digital computer. Delivered to the United States Census Bureau in 1951 and operated continuously for a decade. In 1954, General Electric Corporation became the first private enterprise to acquire a UNIVAC I for commercial payroll and data processing.
Early Commercial Expansion: IBM introduced the commercial IBM-701 in 1952, followed by the highly successful IBM-650 in 1953, which sold over units.
The Five Generations of Computers

First Generation (1942–1955):
Hardware Foundation: Thermionic vacuum tubes (valves) acting as electronic switches and amplifiers. Memory relied on electromagnetic relays, acoustic mercury delay lines, and electrostatic tubes.
Software and Programming: Machine language and early symbolic assembly languages. Input and output handled through physical punched cards and paper tapes.
Physical & Operational Traits: Huge physical footprint requiring entire dedicated rooms; high power consumption (each tube consumed approximately , with systems drawing tens of kilowatts); massive heat generation requiring heavy-duty air conditioning; short mean time between failures (MTBF) due to burned-out filaments.
Representative Machines: ENIAC, EDVAC, EDSAC, UNIVAC I, IBM-701.
Second Generation (1955–1964):
Hardware Foundation: Bipolar junction transistors, invented at Bell Telephone Laboratories in 1947 by John Bardeen, Walter Brattain, and William Shockley. Built from germanium and silicon semiconductors without filaments, rendering them roughly faster, vastly more durable, compact, and energy-efficient.
Primary and Secondary Storage: Magnetic core memory became standard for primary storage, supplemented by magnetic tape reels and early magnetic disks for high-capacity secondary storage.
Software Evolution: Introduction of high-level programming languages including FORTRAN (Formula Translation), COBOL (Common Business-Oriented Language), ALGOL (Algorithmic Language), and SNOBOL. Batch operating systems allowed automated sequencing of user workloads.
Application Domain: Expanded from purely military/scientific modeling into mainstream commercial data processing (banking, billing, payroll, inventory control).
Third Generation (1964–1975):
Hardware Foundation: Integrated Circuits (ICs), invented independently in 1958 by Jack St. Clair Kilby (Texas Instruments) and Robert Noyce (Fairchild Semiconductor). Circuit components (transistors, diodes, resistors, capacitors) were fabricated directly on a single silicon substrate.
Integration Scale:
Small-Scale Integration (SSI): Contained to components per chip.
Medium-Scale Integration (MSI): Contained up to several hundred transistors per chip.
Architectural Strides: Substantial drops in cost and footprint, paired with speeds reaching roughly one million instructions per second. Primary memory expanded up to a few megabytes ().
Operating Systems and Industry Paradigm:
Timesharing Systems: Developed by John Kemeny and Thomas Kurtz at Dartmouth College, enabling multiple remote interactive terminals to share CPU cycles concurrently.
Language Standardization: ANSI standardization of FORTRAN (1966) and COBOL (1968), alongside new languages such as BASIC and PASCAL.
Unbundling (1969): IBM ceased packaging hardware and software together at a single price point, fostering the modern independent commercial software industry.
Minicomputers: Introduction of compact, affordable departmental computers, epitomized by Digital Equipment Corporation's (DEC) PDP-8 in 1965.
Fourth Generation (1975–1989):
Hardware Foundation: Microprocessors containing complete central processing units on a single chip, driven by Large-Scale Integration (LSI) and Very Large-Scale Integration (VLSI, packing upwards of electronic components per silicon wafer).
Storage Technology: Semiconductor RAM (DRAM/SRAM) completely displaced magnetic core memory. Low-cost Winchester sealed hard drives and 5.25"/3.5" portable floppy diskettes became universal.
Microcomputer Revolution: Birthed affordable personal computers (PCs), desktop workstations, and portable systems from companies like Apple and IBM.
Software and Networking Paradigms: Spreadsheets (VisiCalc, Lotus 1-2-3), word processors, and graphical user interfaces (GUIs) featuring desktop icons, windows, and mouse input. Proliferation of the C language and UNIX operating systems. Emergence of Local Area Networks (LANs), Wide Area Networks (WANs), and early groupware (Computer Supported Cooperative Working - CSCW).
Fifth Generation (1989–Present):
Hardware Foundation: Ultra Large-Scale Integration (ULSI), integrating over components onto a single microprocessor chip, alongside multi-core and parallel processing architectures.
Capacity Growth: Memory and storage capacities grew exponentially (doubling or quadrupling every 18 months). Standardized high-density optical media (CD-ROM, DVD) and non-volatile flash memory.
System Reliability: Integration of hot-swappable ("hot-plug") hardware modules, enabling component replacement during live system execution without downtime.
Networking and Global Connectivity: Global expansion of the World Wide Web, high-speed fiber-optic telecommunications, digital multimedia processing, artificial intelligence frameworks, and cloud-distributed architectures.
Computer System Architecture and Block Diagram

Input Unit:
Translates external human-readable information (text, audio, video, tactile signals) into standard binary digital codes.
Routes the digitized data and instructions directly into the primary storage unit.
Storage / Memory Unit:
Primary Storage (Main Memory): Directly connected to and addressable by the CPU. Holds active program code, input data streams, and intermediate mathematical calculations. High speed, relatively expensive, restricted capacity, and strictly volatile (contents are lost immediately upon loss of power).
Secondary Storage (Auxiliary Memory): Serves as an archival, non-volatile repository for system software, installed applications, databases, and user files. Characterized by lower bit-cost, massive storage density, and slower access speeds compared to primary memory.
Central Processing Unit (CPU):
Acts as the computational brain of the entire hardware configuration.
Arithmetic Logic Unit (ALU): Executes all elementary arithmetic operations () and relational/logical evaluations (). Receives operands from storage, performs the calculation, and writes the output back to internal registers or main memory.
Control Unit (CU): Acts as the central nervous system. Coordinates instruction fetching, instruction decoding, execution sequencing, and the timing of data transfers among primary storage, the ALU, and external I/O peripherals.
Common Microprocessor Families: Intel 8088, 80286, 80386, 80486, Celeron, Pentium series (Pentium I, Pro, II, III, IV), Dual Core, and AMD processors.
Output Unit:
Accepts processed binary results from the storage unit.
Transposes the internal machine representations into user-interpretable external formats (human-readable text, visual displays, physical printouts, audio signals).
Data Representation and Number Systems
Fundamental Digital Data Units:
Bit (Binary Digit): The absolute smallest unit of digital storage, holding a state of either (low/off) or (high/on).
Byte: A grouping of precisely . Represents a single alphanumeric character or special symbol in memory.
Word/Multi-Byte Units: Digital computer architectures typically process data in groups of (), (), or ().
Memory Dumps: Direct hexadecimal or octal printouts of raw memory addresses and contents, used for low-level system debugging. Condensing binary into octal saves of display space; condensing into hexadecimal saves of display space.
Positional Number Systems:
Decimal System (Base 10): Utilizes unique digits (). Positional weights progress as powers of ten: .
Binary System (Base 2): Utilizes digits (). Positional weights progress as powers of two: . An -bit binary number represents decimal integers from to .
Octal System (Base 8): Utilizes distinct digits (). Positional weights progress as powers of eight: . Exactly () represent one octal digit.
Hexadecimal System (Base 16): Utilizes symbols: digits through , followed by letters through where , , , , , and . Positional weights progress as powers of sixteen: . Exactly () represent one hexadecimal digit.
Mathematical Number System Conversions:
Any Base to Base 10 Conversion: where is the digit at positional index (counted right-to-left starting at ) and is the source base.
Example 1 (): \begin{aligned}\n 11001_2 &= (1 \times 2^4) + (1 \times 2^3) + (0 \times 2^2) + (0 \times 2^1) + (1 \times 2^0) \\\n &= 16 + 8 + 0 + 0 + 1 = 25_{10}\n \end{aligned}
Example 2 (): \begin{aligned}\n 4706_8 &= (4 \times 8^3) + (7 \times 8^2) + (0 \times 8^1) + (6 \times 8^0) \\\n &= (4 \times 512) + (7 \times 64) + (0 \times 8) + (6 \times 1) \\\n &= 2048 + 448 + 0 + 6 = 2502_{10}\n \end{aligned}
Example 3 (): \begin{aligned}\n 1\text{AC}_{16} &= (1 \times 16^2) + (\text{A} \times 16^1) + (\text{C} \times 16^0) \\\n &= (1 \times 256) + (10 \times 16) + (12 \times 1) \\\n &= 256 + 160 + 12 = 428_{10}\n \end{aligned}
Example 4 (): \begin{aligned}\n 4052_7 &= (4 \times 7^3) + (0 \times 7^2) + (5 \times 7^1) + (2 \times 7^0) \\\n &= (4 \times 343) + (0 \times 49) + (5 \times 7) + (2 \times 1) \\\n &= 1372 + 0 + 35 + 2 = 1409_{10}\n \end{aligned}
Example 5 (): \begin{aligned}\n 4052_6 &= (4 \times 6^3) + (0 \times 6^2) + (5 \times 6^1) + (2 \times 6^0) \\\n &= (4 \times 216) + (0 \times 36) + (5 \times 6) + (2 \times 1) \\\n &= 864 + 0 + 30 + 2 = 896_{10}\n \end{aligned}
Base 10 to Any Base Conversion (Successive Division-Remainder Method): Divide the base 10 value successively by the target radix . Record remainders from right to left; the first remainder yields the Least Significant Digit (LSD), and the final non-zero remainder yields the Most Significant Digit (MSD).
Example (): \begin{aligned}\n 25 / 2 &= 12 \quad \text{remainder } 1 \quad (\text{LSD}) \\\n 12 / 2 &= 6 \quad \text{remainder } 0 \\\n 6 / 2 &= 3 \quad \text{remainder } 0 \\\n 3 / 2 &= 1 \quad \text{remainder } 1 \\\n 1 / 2 &= 0 \quad \text{remainder } 1 \quad (\text{MSD}) \\\n \text{Result} &= 11001_2\n \end{aligned}
Arbitrary Non-Decimal Base Conversions (Base Base via Base 10):
Example ():
Step 1: Base 6 to Base 10: \begin{aligned}\n 545_6 &= (5 \times 6^2) + (4 \times 6^1) + (5 \times 6^0) \\\n &= (5 \times 36) + (4 \times 6) + (5 \times 1) \\\n &= 180 + 24 + 5 = 209_{10}\n \end{aligned}
Step 2: Base 10 to Base 4: \begin{aligned}\n 209 / 4 &= 52 \quad \text{remainder } 1 \quad (\text{LSD}) \\\n 52 / 4 &= 13 \quad \text{remainder } 0 \\\n 13 / 4 &= 3 \quad \text{remainder } 1 \\\n 3 / 4 &= 0 \quad \text{remainder } 3 \quad (\text{MSD}) \\\n \text{Result} &= 3101_4\n \end{aligned}
Binary-Octal Shortcut Conversions:
Binary to Octal: Partition binary digits into groups of three starting from the right (LSD), padding the leftmost group with leading zeros if necessary. Convert each 3-bit grouping into its octal equivalent.
Octal to Binary: Transcribe each individual octal digit into its explicit 3-bit binary equivalent, then concatenate.
Binary-Hexadecimal Shortcut Conversions:
Binary to Hexadecimal: Partition binary digits into groups of four starting from the right (LSD). Convert each 4-bit nibble into its hexadecimal digit.
Hexadecimal to Binary: Transcribe each hexadecimal digit into its explicit 4-bit binary equivalent, then concatenate.
Semiconductor Memory and Storage Hierarchies
Memory Latency and the CPU Performance Mismatch:
A typical CPU processes register operations at approximately .
Secondary electromechanical disks read data at approximately (, or a performance gap).
Standard primary dynamic RAM responds at roughly a mismatch against processor cycles.
Standard Units of Digital Memory Measurement:
Kilobyte (KB): (; ).
Megabyte (MB): (; ).
Gigabyte (GB): (; ).
Terabyte (TB): (; ).
Petabyte (PB): (; ).
Exabyte (EB): (; ).
Zettabyte (ZB): (; ).
Yottabyte (YB): (; ).
Primary Memory Technologies:
Random Access Memory (RAM):
Volatile semiconductor integrated circuits mounted on circuit cards inserted into motherboard slots via Single In-line Memory Modules (SIMMs).
Read/write capability supporting random access; memory contents clear instantly when electrical current ceases.
Read-Only Memory (ROM):
Non-volatile semiconductor memory that cannot be rewritten during normal operation.
Programmed via irreversible internal microscopic fuse-links ("burned-in data"). Also historically designated field stores, permanent stores, or dead stores.
Houses permanent low-level firmware microprograms such as the system boot program (Basic Input/Output System - BIOS), which initializes hardware self-tests (POST) and loads the operating system kernel into volatile RAM.
Programmable Read-Only Memory (PROM):
Shipped unprogrammed from the manufacturer. End-users permanently burn proprietary firmware once using a dedicated hardware PROM programmer by selectively blowing internal fuse junctions. Once written, it functions irreversibly as standard ROM.
Erasable Programmable Read-Only Memory (EPROM):
UV-EPROM: Reusable chip featuring a transparent quartz crystal window. Exposing the internal silicon to high-intensity ultraviolet light over a specified duration discharges floating-gate charges, erasing the entire chip so it can be reprogrammed.
EEPROM (Electrically Erasable PROM): Data is modified or erased in place without physical removal by pulsing high-voltage electrical fields across floating gates. Forms the technical underpinning of modern solid-state flash memory.
Cache Memory:
Extremely fast, low-capacity static semiconductor buffer positioned directly between the central processor and dynamic main memory.
Pre-fetches and temporarily caches highly active instructions and operational data blocks, bridging the speed deficit between main memory and CPU internal clocks.
Secondary Storage Systems
Fundamental Access Methodologies:
Sequential-Access (Serial) Devices: Requires mechanically stepping through every preceding physical record to access a target position (analogous to magnetic audio tape cassettes). Highly efficient for batch applications requiring access to all records (such as utility billing or monthly payroll), but excessively slow for random lookups.
Direct-Access (Random-Access) Devices: Capable of directly accessing any target address block in constant or near-constant time without reading intermediate records (analogous to indexing tracks on an optical audio disc). Encompasses magnetic disks, optical discs, and flash memory drives.
Magnetic Hard Disk Technologies:
Constructed from rigid aluminum (or glass-ceramic) circular platters coated with magnetizable media, rotating at high constant angular velocity.
Zip / Bernoulli Disks: Removable single-platter magnetic media encased within a protective plastic shell, offering storage capacities of approximately .
Disk Packs: Multi-platter assemblies mounted on a single central spindle. Placed onto and removed from offline storage enclosures as needed, using dedicated multi-head read/write assemblies.
Winchester Hard Disks: Multiple platters, spindle motor, and aerodynamic flying heads permanently hermetically sealed inside an airtight, contamination-free metal casing. Eliminates atmospheric dust and smoke particles, allowing lower head fly-heights and greater track densities than open disk packs.
Solid-State Flash Storage:
Non-volatile solid-state drives and USB pen drives built on high-density EEPROM chips without moving parts. Retains data integrity for upwards of . Plugs directly into standard Universal Serial Bus (USB) ports; capacities scale across , , , , , , , , , and
Optical Disc Storage Mechanics:
Employs reflective circular polycarbonate substrates coated with microscopic pits and lands along a continuous single spiral track. Laser optical pickup assemblies read reflections without physical mechanical contact.
Rotational Dynamics: Constant Linear Velocity (CLV) requires dynamic rotational adjustments—spinning faster when reading innermost radii and slowing down toward outer edges to maintain a uniform linear speed beneath the laser.
Access Times: Typical optical access ranges from to , notably slower than floppy drives () and magnetic hard drives () due to drive tracking mechanics, non-hermetic construction, and extensive parity error-correction passes.
Optical Media Variations:
CD-ROM: Compact Disc Read-Only Memory. Diameter: (, often labeled ). Single-session pre-pressed data. Capacity: to .
WORM / CD-R: Write-Once, Read-Many. Photosensitive dye layer burned irreversibly by recording lasers. Supports Multi-Session Disks (MSD) where later sessions add data by writing an updated File Allocation Table (FAT), though existing burned sectors cannot be erased.
CD-RW: Phase-change recording using a metallic alloy layer. Reversible laser heating cycles shift material states between crystalline (reflective) and amorphous (light-scattering), supporting upwards of erase-rewrite cycles.
DVD (Digital Versatile / Video Disk): High-density optical storage utilizing shorter laser wavelengths and Eight-to-Fourteen Modulation Plus (EFM+) encoding. Single-layer discs hold ; dual-layer configurations hold . Incorporates Content Protection for Pre-recorded Media (CPPM) and geographic region-coding.
Comparative Evaluation of Optical Media:
Advantages: Extremely low cost-per-bit, high physical durability without head crashes, estimated archival lifespans exceeding , immunity to accidental magnetic erasure, lightweight and portable, and native support for multimedia audio playback.
Limitations: Significantly lower random access performance than magnetic hard disks, complex variable-speed laser pickup assemblies, permanent vulnerability to physical surface abrasions and fingerprint oils, and an inability to rewrite or recycle standard CD-ROM/WORM media.
Peripherals: Input and Output Engineering
Peripheral Interfacing Challenges:
Central processors and semiconductor memories operate millions of times faster than peripheral units. Input/output peripherals are fundamentally constrained by electromechanical components, creating a performance gap that demands dedicated hardware buffers, interrupt routines, and optimized controller buses.
Data Input Technologies:
Keyboards: The most prevalent text input device, dominated by the standardized QWERTY physical layout.
Point-and-Draw Graphical Devices:
Mouse: Handheld controller mapping planar translation across a surface to an on-screen graphical cursor. The cursor's specific single-pixel coordinate target is termed its hot-spot.
Alternative Pointing Devices: Trackballs, mechanical/optical joysticks, light pens, and capacitive/resistive touchscreens.
Direct Data Scanning Devices:
Flatbed Image Scanners: Operates like an optical photocopier. Documents are positioned facedown on a transparent glass platen while an internal linear light bar traverses beneath, line-by-line, capturing a document in approximately .
Hand-held Scanners: Compact array of light-emitting diodes (LEDs) swept manually across media; prone to spatial distortion if manual translation speed is inconsistent.
Optical Character Recognition (OCR):
Overcomes image scanner limitations where documents are saved as non-searchable, heavy raster bitmaps. A raw printed page containing consumes merely () in raw ASCII, compared to roughly as an uncompressed bitmap.
Analyzes scanned shapes against standardized optical typography fonts, primarily OCR-A (American standard) and OCR-B (European standard).
Magnetic Ink Character Recognition (MICR):
Financial banking standard used for high-speed automated check routing and clearance.
Bank codes, routing data, account numbers, and check numbers are pre-printed using an ink containing magnetizable iron oxide particles sculpted into the standardized E13B typeface ( decimal digits plus four control glyphs).
The MICR reader-sorter passes documents through a localized magnetic field to magnetize the particles, reads the analog waveforms emitted by each character contour, and physically sorts checks into receiving pockets.
Digitizers (Graphics Tablets):
Vector input device composed of a flat tablet embedded with an electrical grid of hundreds of fine copper wires and a handheld stylus or puck with crosshairs.
Translates analog planar coordinates () into precise digital vectors, enabling engineers and architects to draft blueprints in Computer-Aided Design (CAD) and digitize geographical survey maps in Geographical Information Systems (GIS).
Data Output Technologies:
Output Classifications:
Soft Copy: Ephemeral, non-tangible displays (CRT/LCD monitor screens, audio speaker prompts).
Hard Copy: Permanent physical output produced on tangible media (paper prints, microfilms, architectural plotter charts).
Display Monitors (Video Display Terminals - VDT):
Cathode Ray Tube (CRT): Bulky displays firing steered electron streams against interior phosphor coatings; typically weigh between and .
Liquid Crystal Display (LCD): Lightweight flat-panel displays (weighing under ) composed of a cold cathode backlight, polarizers, an alignment grid of transparent electrode coordinates (), a liquid crystal molecular solution, and a color filter mask. Electrostatic charges twist crystal molecules, turning sub-pixels on or off to meter light transmission.
Impact vs. Non-Impact Printing Hardware:
Dot-Matrix Printers (Impact Character): Uses an array of mechanical electromagnetic pins striking an inked ribbon against paper. Speeds range from to ; supports bidirectional passes; noisy; handles multi-part carbon-copy forms.
Drum Printers (Impact Line): A solid steel cylindrical drum embossed with full character bands along every printable column (e.g., ). Synchronized hammers strike from behind the paper as the drum rotates at high speeds. Prints to .
Chain/Band Printers (Impact Line): Characters are embossed along a rapidly cycling horizontal metal loop or chain with multiple repeated font sets (). Individual column hammers strike the ribbon as the matching character passes. Allows rapid interchanging of font bands; prints to .
Inkjet Printers (Non-Impact Character): Tiny micro-resistors heat up in microseconds, vaporizing microscopic ink pockets that spray ink droplets through up to per head across heights of roughly . Resolutions achieve up to ; speeds average . Utilizes black and CMY tricolor cartridges to blend photorealistic tones; quiet operation.
Laser Printers (Non-Impact Page): A revolving multi-faceted polygonal mirror sweeps a semiconductor laser beam across an electrostatically charged photoconductive selenium drum, creating a latent electrostatic charge image. Oppositely charged dry plastic toner powder adheres only to discharged laser targets, transfers to paper, and fuses permanently under heated pressure rollers. Yields razor-sharp output at , with speeds ranging from to dozens of ppm.
Plotters: Specialized vector drafting machines using physical ink pens driven along Cartesian axes () by stepper motors (or rotating drum feed mechanisms) to render continuous architectural and mechanical drafting diagrams without pixelation.
Telecommunications and the Internet
Origins and Genesis:
Conceived in 1969 by the United States Department of Defense through the Advanced Research Projects Agency Network (ARPANET) to establish an experimental, fault-tolerant packet-switched communication fabric between military research installations over leased telephone trunk circuits.
Universities and research laboratories integrated their computing systems into the ARPANET backbone, eventually evolving into an interconnected global network of networks.
The modern Internet operates without a single centralized corporate owner, governing body, or sovereign administrator; it is cooperatively supported by international standards bodies, telecommunication carriers, and end-users.
Internet Architecture and Web Foundations:
Internet Service Providers (ISPs):
Access ISPs: Connect end-users directly to regional routing centers via twisted-pair copper, high-frequency wireless, coaxial broadband cable, or fiber-optic lines.
Hosting ISPs: Provide co-location facilities, rack space, and high-availability servers for commercial internet platforms.
Transit ISPs: Run transcontinental fiber backbones that link regional access and hosting ISPs together.
Web Protocols and Formats:
World Wide Web (WWW): A hyperlinked information retrieval system layered on top of the physical Internet infrastructure.
Hypertext Transfer Protocol (HTTP): The fundamental client-server application layer protocol used by web browser clients to request and receive web resources from remote web servers.
HyperText Markup Language (HTML): The foundational markup standard for creating web documents. Utilizes hierarchical opening and closing structural tags (e.g.,
<h1>,</h1>). Allows authors to embed hyperlinked URLs, raster graphics, scripts, and semantic elements.Uniform Resource Locator (URL): The unique global addressing schema used to locate resources on the World Wide Web.
Web Page Rendering and Browsers:
Static Web Pages: Unchanging HTML/CSS files stored directly on a web server's storage system and delivered identically to all requesting clients.
Dynamic Web Pages: Pages assembled on the fly by server-side scripts and database queries, or manipulated dynamically in the browser via client-side scripting engines.
Web Browsers: Software tools that parse HTML, execute embedded scripts, and render visual/auditory web content. Includes modern GUI browsers (Microsoft Internet Explorer, Mozilla Firefox) and legacy text-mode terminals (Lynx, Links).
Web Accessibility: Standardized by the World Wide Web Consortium (W3C) and the Web Accessibility Initiative (WAI) to ensure pages can be consumed through screen readers, braille interfaces, high-contrast layouts, and customized user style sheets.
Fundamental C++ Programming Constructs
Source Code Compilation Paradigm:
Human-readable source code is written and saved as plain-text files using the
.cppfile extension.The language compiler parses, validates, and translates
.cpptext instructions into native binary object modules, which the linker binds into machine-executable binary files carrying the.exeextension.
Anatomy of a Minimalist C++ Program:
#include <iostream>
using namespace std;
int main()
{
cout << "Every age has a language of its own
";
return 0;
}
Structural Components:
Pre-processor Directives (
#include <iostream>):Lines beginning with a pound sign (
#) are instructions to the compiler's pre-processor rather than executable runtime statements. They never terminate with a semicolon.#includeinstructs the pre-processor to copy the declarations from the specified header file (such asiostream) directly into the current translation unit.Header files provide crucial declarations for input/output objects like
coutand operators like<<.Namespace Specification (
using namespace std;):Defines an explicit scope boundary for identifiers. Standard library routines are partitioned within the
stdnamespace. Without this statement, every standard library identifier must be qualified with the scope resolution operator (e.g.,std::cout).The Primary Function (
int main()):Every standard C++ program begins execution at the
main()function.The parentheses
()immediately following the identifier designatemainas a function capable of receiving parameters.The prefix keyword
intspecifies thatmainreturns an integer exit code to the host operating system upon termination.Block Delimiters (Braces
{}):Curly braces designate the structural beginning and conclusion of a statement block or function body, functionally equivalent to
BEGINandENDkeywords in other languages.Program Statements and Punctuation:
The program statement is the fundamental unit of procedural code. Every executable statement must conclude with a terminating semicolon (
;). Missing a semicolon is a common syntax error.Stream Output Statement:
cout(console output) is an object representing the standard output stream directed to the monitor.The insertion operator (
<<) routes the string literal to thecoutstream.Return Statement (
return 0;):Concludes execution of
main(), returning an integer value of to the host environment to signal error-free execution.
Code Commenting Styles:
Single-Line Comments: Introduced by a double forward-slash (
//). Causes the compiler to ignore all subsequent text on that physical line.Multi-Line (C-Style) Comments: Enclosed between
/*and*/. Spans multiple lines of text until the closing delimiter is encountered.
Data Types, Variables, and Expressions
Variables and Identifier Naming Rules:
Variables are named memory locations designated to hold runtime values of a specified type.
Identifier Rules: Names may contain uppercase letters (
A–Z), lowercase letters (a–z), digits (0–9), and underscores (_). The initial character must be a letter or an underscore. Identifiers are strictly case-sensitive (Var,var, andVARrepresent three distinct entities).
Comprehensive Primitive Data Types:
Type | Definition | Control Character | Value Range (Limits) |
|---|---|---|---|
| Integer | None | to |
| Short Integer | None | to |
| Long Integer |
| to |
| Floating Decimal Number |
| to |
| Double Decimal Number | None | to |
| Long Decimal Number | None | to |
| Character | None | to |
| Unsigned Integer | None | to |
| Unsigned Short Integer | None | to |
| Unsigned Long Integer | None | to |
| Unsigned Character | None | to |
| True or False | None | True = , False = |
Architectural Memory Sizing:
int: Takes () on standard modern 32-bit and 64-bit platforms. On legacy 16-bit systems (MS-DOS), anintoccupies with a range identical toshort.short: Universally occupies ().long: Guaranteed () across platforms.char: Occupies precisely (). Primarily used to store integer indices matching standard ASCII characters ( to ).float: Single-precision real number consuming .double: Double-precision real number consuming , offering roughly of precision.bool: Represents logical states. Compilers typically allocate a full of memory to allow rapid single-instruction memory addressing.
Character Escape Sequences:
Backslash characters (
\) cause subsequent characters to "escape" their literal interpretation.: Inserts a linefeed (newline), moving subsequent output to the beginning of the next display line.
\t: Inserts a horizontal tab, advancing output to the next tab stop (standard console tab stops are positioned every ).endl: Stream manipulator that inserts a newline and immediately flushes the output stream buffer.
Stream Input Processing with
cin:cinrepresents the standard console input stream (bound to the keyboard).The extraction operator (
>>) pulls formatted data from the input stream and assigns it to the target variable on the right:
#include <iostream>
using namespace std;
int main()
{
int ftemp;
cout << "Enter temperature in fahrenheit: ";
cin >> ftemp;
int ctemp = (ftemp - 32) * 5 / 9;
cout << "Equivalent in Celsius is: " << ctemp << '
';
return 0;
}
Constants:
#definevs.const:Legacy
#definedirectives perform blind pre-processor macro text replacements without data type safety (e.g.,#define PI 3.14159).Modern C++ strongly favors the
constqualifier, which enforces explicit data typing, memory allocation rules, and compiler type verification (e.g.,const float PI = 3.14159F;).
Type Casting:
Manual conversion of a value from one data type to another when automatic conversion does not apply.
Operators in C++
Standard Arithmetic Operators:
Addition (
+), Subtraction (-), Multiplication (*), Division (/).Integer division discards any fractional truncation remainder (e.g., ).
The Modulus / Remainder Operator (
%):Returns the integer remainder resulting from division. Operates strictly upon integer primitives (
char,short,int,long).
#include <iostream>
using namespace std;
int main()
{
cout << 6 % 8 << endl // Displays 6
<< 7 % 8 << endl // Displays 7
<< 8 % 8 << endl // Displays 0
<< 9 % 8 << endl // Displays 1
<< 10 % 8 << endl; // Displays 2
return 0;
}
Arithmetic Assignment Operators:
Syntactic shortcuts that perform an arithmetic operation on an existing variable and reassign the result to that same variable.
total += item;is mathematically identical tototal = total + item;.Supported operators include
+=,-=,*=,/=, and%=.
#include <iostream>
using namespace std;
int main()
{
int ans = 27;
ans += 10; // ans = 37
cout << ans << ", ";
ans -= 7; // ans = 30
cout << ans << ", ";
ans *= 2; // ans = 60
cout << ans << ", ";
ans /= 3; // ans = 20
cout << ans << ", ";
ans %= 3; // ans = 2
cout << ans << endl;
return 0;
}
Increment and Decrement Operators:
Prefix notation (
++count,--count): Increments or decrements the variable before its value is fetched for use in the surrounding expression.Postfix notation (
count++,count--): Evaluates the variable's current value in the surrounding expression before applying the increment or decrement.
#include <iostream>
using namespace std;
int main()
{
int count = 10;
cout << "count=" << count << endl; // Displays 10
cout << "count=" << ++count << endl; // Displays 11 (prefix: incremented first)
cout << "count=" << count << endl; // Displays 11
cout << "count=" << count++ << endl; // Displays 11 (postfix: incremented after evaluation)
cout << "count=" << count << endl; // Displays 12
return 0;
}
Standard Mathematical Library Functions:
Pre-compiled routines provided by the compiler (e.g.,
sqrt()from<cmath>), which accept arguments enclosed in parentheses and evaluate to a returned value.
Relational Comparison Operators:
Evaluate mathematical relationships between two operands, returning a boolean result (
trueorfalse).
Operator | Description | Left Operand () | Right Operand () | Expression Outcome |
|---|---|---|---|---|
| Equality test |
| ||
| Inequality test |
| ||
| Greater than |
| ||
| Less than |
| ||
| Greater than or equal to |
| ||
| Less than or equal to |
|
The Ternary Conditional Operator (
?:):C++'s only three-operand operator, offering a compact syntax for simple conditional choices:
Example:
min = (alpha < beta) ? alpha : beta;
Logical Operators:
Connect or invert Boolean expressions:
Operator | Description | Formal Evaluation Example (with , ) |
|---|---|---|
| Logical AND |
|
| Logical OR |
|
| Logical NOT |
|
Operator Precedence Hierarchy:
Highest to lowest precedence:
Unary operators (
!,++,--, unary-, address-of&, dereference*)Arithmetic operators (multiplicative
*,/,%evaluated before additive+,-)Relational operators (
<,<=,>,>=evaluated before==,!=)Logical operators (
&&evaluated before||)Conditional ternary operator (
?:)Assignment and compound assignment operators (
=,+=,-=, etc.)
Control and Branching Logic
Simple Decision Making (
ifStatement):Evaluates a test expression in parentheses. If true, it executes the immediately following statement or block; if false, it skips the block.
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter a number: ";
cin >> x;
if(x > 100)
{
cout << "The number " << x;
cout << " is greater than 100
";
}
return 0;
}
Two-Way Branching (
if...elseStatement):Executes one block when the test condition evaluates to true, and an alternate block when it evaluates to false.
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "
Enter a number: ";
cin >> x;
if(x > 100)
{
cout << "That number is greater than 100
";
}
else
{
cout << "That number is not greater than 100
";
}
return 0;
}
Nested and Multi-Tiered Selection Logic:
An
if...elsestructure nested within another conditional branch to evaluate complex conditions.
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter an integer: ";
cin >> num;
// Outer conditional check
if (num != 0)
{
// Inner nested conditional checks
if (num > 0)
{
cout << "The number is positive." << endl;
}
else
{
cout << "The number is negative." << endl;
}
}
else
{
cout << "The number is 0 and it is neither positive nor negative." << endl;
}
cout << "This line is always printed." << endl;
return 0;
}
Multi-Way Branching (
switchStatement):Selects execution pathways by comparing an integer or character control variable against discrete case constants.
The Role of the
breakStatement: Terminates theswitchblock, jumping execution to the first statement past the closing brace. Omitting abreakcauses execution to fall through into subsequent case statements regardless of whether they match.
#include <iostream>
using namespace std;
int main()
{
int speed; // Turntable rotational speed in RPM
cout << "
Enter 33, 45, or 78: ";
cin >> speed;
switch(speed)
{
case 33:
cout << "LP album
";
break;
case 45:
cout << "Single selection
";
break;
case 78:
cout << "Obsolete format
";
break;
default:
cout << "Invalid speed entered
";
}
return 0;
}
Iteration and Loop Structures
The
forLoop:Combines initialization, test condition, and loop variable update within a single header line:
for(initialization; test_expression; increment/decrement).Primarily utilized when the number of execution iterations is known in advance.
#include <iostream>
#include <iomanip> // Needed for setw manipulator
using namespace std;
int main()
{
int numb;
for(numb = 1; numb <= 10; numb++)
{
cout << setw(4) << numb; // Column 1: Base integer
int cube = numb * numb * numb;
cout << setw(6) << cube << endl; // Column 2: Calculated cube
}
return 0;
}
Decremental Iteration (Factorial Calculation):
#include <iostream>
using namespace std;
int main()
{
unsigned int numb;
unsigned long fact = 1;
cout << "Enter a number: ";
cin >> numb;
for(int j = numb; j > 0; j--)
{
fact *= j;
}
cout << "Factorial is " << fact << endl;
return 0;
}
The
whileLoop:A pre-tested loop that evaluates its condition before each iteration. The body executes zero or more times, continuing until the condition evaluates to false. Used when the iteration count depends on dynamic events (such as user input).
#include <iostream>
using namespace std;
int main()
{
int n = 99; // Initialized to a non-zero value
while(n != 0)
{
cin >> n;
}
cout << endl;
return 0;
}
Multi-Condition
whileLoop (Limiting Output Field Width):
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int pow = 1;
int numb = 1;
while(pow < 10000) // Loop terminates before power exceeds 4 digits
{
cout << setw(2) << numb;
cout << setw(5) << pow << endl;
++numb;
pow = numb * numb * numb * numb; // Calculate 4th power
}
cout << endl;
return 0;
}
The
do...whileLoop:A post-tested loop that evaluates its test expression at the bottom of the loop body. Guarantees that the loop statements execute at least once, regardless of the initial condition.
#include <iostream>
using namespace std;
int main()
{
long dividend, divisor;
char ch;
do
{
cout << "Enter dividend: "; cin >> dividend;
cout << "Enter divisor: "; cin >> divisor;
cout << "Quotient is " << dividend / divisor;
cout << ", remainder is " << dividend % divisor;
cout << "
Do another? (y/n): ";
cin >> ch;
} while(ch != 'n');
return 0;
}
Block Scope and Variable Visibility:
Variables declared inside braces
{}exist only within that local block. They are allocated when control reaches their declaration and are destroyed when execution exits the enclosing brace.
Arrays and String Manipulation
One-Dimensional Array Foundations:
An array is a fixed-size, contiguous sequence of elements sharing an identical data type.
Defined by specifying the base data type, array identifier, and size enclosed in square brackets:
int age[4];.Zero-Based Indexing: In an array of size , indices span from to . The fourth element of
age[4]is accessed viaage[3].
#include <iostream>
using namespace std;
int main()
{
int age[4];
for(int j = 0; j < 4; j++)
{
cout << "Enter an age: ";
cin >> age[j]; // Populate array elements
}
for(int j = 0; j < 4; j++)
{
cout << "You entered " << age[j] << endl; // Read array elements
}
return 0;
}
Array Initialization Lists:
Arrays can be initialized at definition using a comma-separated list enclosed in curly braces:
#include <iostream>
using namespace std;
int main()
{
int month, day, total_days;
int days_per_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
cout << "
Enter month (1 to 12): ";
cin >> month;
cout << "Enter day (1 to 31): ";
cin >> day;
total_days = day;
for(int j = 0; j < month - 1; j++)
{
total_days += days_per_month[j];
}
cout << "Total days from start of year is: " << total_days << endl;
return 0;
}
Multidimensional Arrays:
Arrays can have multiple dimensions, defined using consecutive bracketed sizes:
double sales[DISTRICTS][MONTHS];.Structured conceptually as a table of rows and columns (e.g., a 2D array is an array of 1D arrays).
#include <iostream>
#include <iomanip>
using namespace std;
const int DISTRICTS = 4;
const int MONTHS = 3;
int main()
{
int d, m;
double sales[DISTRICTS][MONTHS];
for(d = 0; d < DISTRICTS; d++)
{
for(m = 0; m < MONTHS; m++)
{
cout << "Enter sales for district " << d + 1 << ", month " << m + 1 << ": ";
cin >> sales[d][m];
}
}
cout << "
Month
";
cout << " 1 2 3";
for(d = 0; d < DISTRICTS; d++)
{
cout << "
District " << d + 1;
for(m = 0; m < MONTHS; m++)
{
cout << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint)
<< setprecision(2)
<< setw(10)
<< sales[d][m];
}
}
return 0;
}
C-String Architecture:
Strings in procedural C++ are null-terminated character arrays (
char str[MAX]).Every string literal must terminate with a null character (
' 0', integer value ) so stream operations and functions know where the string ends.
String Input Techniques:
Standard extraction (
cin >> str) stops reading at the first whitespace character (space, tab, newline).To read entire lines containing spaces, use the member function
cin.get(str, MAX, delimiter).The optional third parameter specifies a custom terminating character (defaults to newline
' 'if omitted):
#include <iostream>
using namespace std;
const int MAX = 2000;
char str[MAX];
int main()
{
cout << "
Enter a string:
";
cin.get(str, MAX, '$'); // Terminate reading only upon encountering $
cout << "You entered:
" << str << endl;
return 0;
}
C-String Library Operations (
<cstring>):Because C-strings are raw arrays, they cannot be copied or compared with standard operators (e.g.,
str2 = str1;is invalid).strlen(str): Returns the string length as an integer, excluding the null byte.strcpy(destination, source): Copies characters sequentially from the source string into the destination buffer, appending the terminating null character:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[] = "Tiger, tiger, burning bright
In the forests of the night";
const int MAX = 80;
char str2[MAX];
strcpy(str2, str1); // Copy contents of str1 into str2
cout << str2 << endl;
return 0;
}
Modular Programming: Functions and Recursion
Function Architecture and Syntax:
Functions modularize repetitive tasks into independent, reusable subprograms.
Function Declaration (Prototype): Informs the compiler about the function's name, return type, and parameter list before its first call:
void starline();.Function Call: Executes the function by name, transferring program control to its body:
starline();.Function Definition: Contains the actual declarator line and executable statement block:
#include <iostream>
using namespace std;
void starline(); // Prototype declaration
int main()
{
starline(); // Invocation call
cout << "Data type Range" << endl;
starline();
cout << "char -128 to 127" << endl;
starline();
return 0;
}
void starline() // Definition
{
for(int j = 0; j < 45; j++)
{
cout << '*';
}
cout << endl;
}
Passing Arguments to Functions:
Parameters act as local variables within the function, initialized with copies of the argument values passed by the caller:
#include <iostream>
using namespace std;
void repchar(char, int); // Prototype with types
int main()
{
repchar('-', 43);
cout << "Data type Range" << endl;
repchar('=', 23);
return 0;
}
void repchar(char ch, int n) // Definition
{
for(int j = 0; j < n; j++)
{
cout << ch;
}
cout << endl;
}
Returning Values via the
returnStatement:Functions compute a result and return it to the calling expression using the
returnkeyword:
#include <iostream>
using namespace std;
float lbstokg(float); // Prototype
int main()
{
float lbs, kgs;
cout << "
Enter your weight in pounds: ";
cin >> lbs;
kgs = lbstokg(lbs); // Function returns calculated weight
cout << "Your weight in kilograms is " << kgs << endl;
return 0;
}
float lbstokg(float pounds)
{
float kilograms = 0.453592 * pounds;
return kilograms;
}
Recursive Functions:
Recursion occurs when a function invokes itself directly or indirectly to solve smaller sub-problems.
Requires a well-defined base case to terminate execution; without one, the function recurses indefinitely until memory exhausts the stack.

Step-by-Step Recursive Factorial Evaluation:
To evaluate
factorial(3):
factorial(3)checks the base conditionif n == 1. This is false, so it callsfactorial(2)to compute3 * factorial(2).factorial(2)checksif n == 1. False, so it callsfactorial(1)to compute2 * factorial(1).factorial(1)checksif n == 1. True, so it hits the base case and returns .Unwinding:
factorial(2)evaluates2 * 1 = 2and returns it.Final calculation:
factorial(3)evaluates3 * 2 = 6and returns .
Memory Addressing, References, and Pointers
Addresses and the Address-Of Operator (
&):Every allocated byte in primary memory possesses a unique numerical address. Variable addresses are found using the unary address-of operator (
&var1):
0x8f4ffff4 <-- address of var1
0x8f4ffff2 <-- address of var2
0x8f4ffff0 <-- address of var3
Pointer Declarations and Syntax:
A pointer is a variable that stores the memory address of another variable.
Declared by placing an asterisk between the base type and the identifier:
int* ptr;.The pointer's data type dictates how the compiler interprets and manipulates the memory at that target address:
char* cptr;(pointer to a character)int* iptr;(pointer to an integer)float* fptr;(pointer to a floating-point number)
The Dereference (Indirection) Operator (
*):When applied to an initialized pointer, the asterisk (
*ptr) retrieves or modifies the actual value stored at the referenced memory address:
#include <iostream>
using namespace std;
int main()
{
int var1 = 11;
int var2 = 22;
int* ptr;
ptr = &var1; // Pointer stores the address of var1
cout << *ptr << endl; // Dereferencing outputs 11
ptr = &var2; // Pointer redirected to address of var2
cout << *ptr << endl; // Dereferencing outputs 22
return 0;
}
Passing Arguments: Reference vs. Pointer:
Passing by value copies the variable, preventing the function from modifying the original caller's data.
Pass by Reference (
double&): The function parameter acts as an alias directly bound to the caller's variable:
void centimize(double& v)
{
v *= 2.54;
}
Pass by Pointer (
double*): The function receives the memory address explicitly, modifying the caller's variable via pointer dereferencing:
void centimize(double* ptrd)
{
*ptrd *= 2.54;
}
Array Names as Pointer Constants:
An array's name evaluates directly to the memory address of its first element (
varray == &varray[0]).Functions accepting arrays can use pointer notation interchangeably:
void centimize(double* ptrd)is functionally equivalent tovoid centimize(double ptrd[]).
String Traversal via Pointer Arithmetic:
#include <iostream>
using namespace std;
void dispstr(char* ps)
{
while(*ps) // Loops until reading the null terminator ('\0', value 0)
{
cout << *ps++; // Prints character, then increments address pointer
}
cout << endl;
}
int main()
{
char str[] = "Idle people have the least leisure.";
dispstr(str);
return 0;
}
User-Defined Data Types: Structures

Structure Definition and Architecture:
A structure combines multiple related variables—potentially of differing data types—into a single user-defined composite type.
Introduced by the
structkeyword, followed by the structure name (tag), member declarations enclosed in braces, and a mandatory terminating semicolon:
struct part
{
int modelnumber; // ID number of widget
int partnumber; // ID number of widget part
float cost; // Cost of part
};
Memory Allocation:
Defining a structure tag serves purely as an architectural blueprint; it reserves no memory on its own.
Memory is allocated only when a concrete structure variable is instantiated:
part part1;.On a 32-bit architecture,
part1allocates ( each for the twointmembers, plus for thefloat).
Member Access via the Dot (
.) Operator:Individual members within a structure variable are accessed using the dot operator (
variable.member):
#include <iostream>
using namespace std;
struct part
{
int modelnumber;
int partnumber;
float cost;
};
int main()
{
part part1;
part1.modelnumber = 6244;
part1.partnumber = 373;
part1.cost = 217.55F;
cout << "Model " << part1.modelnumber;
cout << ", part " << part1.partnumber;
cout << ", costs $" << part1.cost << endl;
return 0;
}
Structure Initialization and Direct Assignment:
Structures can be initialized at definition using brace notation.
Structure variables of identical types can be assigned directly to one another using the assignment operator (
part2 = part1;), which performs a bitwise copy of all internal members:
#include <iostream>
using namespace std;
struct part
{
int modelnumber;
int partnumber;
float cost;
};
int main()
{
part part1 = { 6244, 373, 217.55F }; // Direct initialization
part part2;
part2 = part1; // Copies all member values from part1 into part2
cout << "Model " << part2.modelnumber;
cout << ", part " << part2.partnumber;
cout << ", costs $" << part2.cost << endl;
return 0;
}
Review Questions and Problem Exercises
Unit 1 Review Questions:
The third generation of computers ranges from: (a) 1955–1964, (b) 1964–1975, (c) 1942–1955, (d) 1975–1989. [Answer: (b) 1964–1975]
Created an electrical gadget that can solve mathematical equations: (a) Dr. John Atanasoff, (b) Herman Hollerith, (c) Professors J. Presper Eckert, (d) All of these. [Answer: (a) Dr. John Atanasoff]
Data handling is the action of utilising a computer to process data: (a) True, (b) False. [Answer: (a) True]
ULSI stands for: (a) Ultra Located Scale Integration, (b) Ultra Large-Scale Integration. [Answer: (b) Ultra Large-Scale Integration]
Portable computers are also known as: (a) Book computer, (b) Notebook computers. [Answer: (b) Notebook computers]
Computers of the second generation were made utilising: (a) Vacuum tubes, (b) Transistors, (c) IC Chip, (d) None of above. [Answer: (b) Transistors]
Unit 3 Exercises (Number System Conversions):
Find the decimal equivalent of the following binary numbers:
(a)
(b)
(c)
(d)
(e)
(f)
(g)
(h)
(i)
(j)
Find octal equivalents for selected binary values:
(a)
(b)
(j)
Convert the following numbers to decimal numbers:
(a)
(b)
(c)
(d)
Carry out the following base-to-base conversions:
(a) ;
(b) ;
(c)
Unit 4 Review Questions:
The extra RAM chips that connect into dedicated sockets on the motherboard are referred to as: (a) SIMMs, (b) SIMs, (c) PROM, (d) All of these. [Answer: (a) SIMMs]
Read-only memory (ROM) is divided into two types: factory-programmed and user-programmed: (a) True, (b) False. [Answer: (a) True]
Which memories are commonly used to store non-changing programs and data? (a) RAMs, (b) ROMs. [Answer: (b) ROMs]
Data is burned onto PROMs by the maker of the electronic device in which they are utilized: (a) True, (b) False. [Answer: (b) False — PROMs are user-programmed; factory-programmed ROMs are burned by manufacturers]
A megabyte (MB) is the same as (): (a) True, (b) False. [Answer: (a) True]
Unit 5 Self-Assessment Questions:
The act of retrieving data from a storage location is known as: (a) Memory write Operation, (b) Memory Read Operation. [Answer: (b) Memory Read Operation]
A storage system consisting of a rotating disc coated with a thin metal layer: (a) Memory disc, (b) Optical disk, (c) Hard disk, (d) None of these. [Answer: (b) Optical disk]
What does the LED indicator stand for? (a) Light-emitting diode, (b) Level-emitting diode, (c) Low-emitting diode, (d) None of these. [Answer: (a) Light-emitting diode]
A pointing device that looks like a roller-ball mouse: (a) Trackball, (b) All of the above, (c) Electronic pen, (d) None of the above. [Answer: (a) Trackball]
A colour inkjet printer has two ink cartridges: black and: (a) Tricolor, (b) Blue, green, white, (c) None of these. [Answer: (a) Tricolor]
CRT stands for: (a) Crystal ray tube, (b) Cathode ray tube. [Answer: (b) Cathode ray tube]
The patterns of standard UPC bar codes are decoded as: (a) 5 digits, (b) 10 digits, (c) 12 digits, (d) 2 digits. [Answer: (c) 12 digits]
Unit 9 Review Questions:
Arrange in order of precedence (highest first): logical, unary, arithmetic, assignment, relational, conditional. [Answer: Unary, Arithmetic, Relational, Logical, Conditional, Assignment]
The
&&and||operators: (a) compare two numeric values, (b) combine two numeric values, (c) compare two Boolean values, (d) combine two Boolean values. [Answer: (d) combine two Boolean values]
Unit 10 Review Questions:
A relational operator: (a) assigns one operand to another, (b) yields a Boolean result, (c) compares two operands, (d) logically combines two operands. [Answer: (c) compares two operands (yielding a Boolean result)]
Expression yielding true if variable
georgeis not equal tosally:george != sallyIs true or false in C++? [Answer: True — in C++, any non-zero numerical value evaluates to true]
If-then statement setting output to "Yes" if variable
age > 21, otherwise "No":cpp if(age > 21) cout << "Yes"; else cout << "No"; Statement using a logical operator evaluating to true if speed limit is 55 and speed is greater than 55:
(limit == 55) && (speed > 55)
Unit 11 Review Questions:
Three expressions in a for statement header: Initialization expression, test condition expression, and update/increment expression.
In a for loop with a multi-statement body, semicolons appear following: (a) the for statement itself, (b) the closing brace, (c) each statement within the loop body, (d) the test expression. [Answer: (c) each statement within the loop body]
True or False: The increment expression in a for loop can decrement the loop variable. [Answer: True]
For loop displaying numbers from 100 to 110:
cpp for(int i = 100; i <= 110; i++) cout << i << " ";
A block of code is delimited by: Curly braces
{}.A variable defined within a block is visible: (c) from the point of definition onward in the block.
While loop displaying numbers from 100 to 110:
cpp int i = 100; while(i <= 110) { cout << i << " "; i++; } Unit 12 Review Questions:
An array element is accessed using: (a) a first-in-first-out approach, (b) the dot operator, (c) a member name, (d) an index number. [Answer: (d) an index number]
All the elements in an array must be the: Identical (same) data type.
Statement defining a 1D array called
doubleArrayof type double holding 100 elements:double doubleArray[100];Elements of a 10-element array are numbered from: to .
Statement writing element
jof arraydoubleArraytocout:cout << doubleArray[j];Element
doubleArray[7]is which element of the array? (a) The sixth, (b) The seventh, (c) The eighth, (d) Impossible to tell. [Answer: (c) The eighth]
Unit 14 Review Questions:
Statement displaying the address of variable
testvar:cout << &testvar;The contents of two pointers pointing to adjacent variables of type float differ by: .
A pointer is: (c) a variable for storing addresses.
Expressions:
(a) Address of
var:&var(b) Contents of variable pointed to by
var:*var(c) Variable
varused as a reference argument:double& var(d) Data type pointer-to-char:
char*An address is a: numerical memory location, while a pointer is a: variable storing an address.
Definition for a variable of type pointer-to-float:
float* fptr;Asterisk placed after a data type means: Pointer definition (
float*), placed in front of a variable name means: Dereference operator (*ptr).The expression
*testcan be said to: (b) refer to the contents of test, (c) dereference test, (d) refer to the value of the variable pointed to by test. [Answer: All represent valid conceptual descriptions; formally (c) and (d)]Is the following code correct?
cpp int intvar = 333; int* intptr; cout << *intptr; [Answer: Incorrect —intptris an uninitialized wild pointer and contains an arbitrary garbage address; dereferencing it causes undefined behavior or a segmentation fault. It must first be assigned:intptr = &intvar;]
Unit 15 Review Questions:
A structure brings together a group of: (b) related data items.
True or False: A structure and a class use similar syntax: [Answer: True]
The closing brace of a structure is followed by a: Semicolon (
;).Structure specification called
timewith three int members (hrs,mins,secs):cpp struct time { int hrs; int mins; int secs; };
True or False: A structure definition creates space in memory for a variable: [Answer: False — memory is reserved only when a structure variable is defined/instantiated]
When accessing a structure member, the identifier to the left of the dot operator is the name of: (c) a structure variable.
Statement setting
hrsmember oftime2structure variable equal to 11:time2.hrs = 11;Memory used together by three variables of type
struct time(containing threeintmembers each on a 32-bit machine):