Comprehensive University Study Notes on Object-Oriented Programming and Data Structures in C++

Fundamental Principles of Programming and Problem Solving

  • Problem Solving Fundamentals:

    • Problem solving is an organized approach to identifying a problem and determining the optimal, most efficient, reliable, and cost-effective solution.
    • Different problems require distinct analytical approaches; computer programs serve as essential tools to execute step-by-step instructions designed to transform raw input data into meaningful information.
    • Foundational problem-solving tools in software engineering include algorithms, flowcharts, and structured computer programs.
  • Computer Programs and Software Development:

    • A computer program is a structured set of instructions instructing a computer hardware architecture on how to perform specific computations or data processing tasks.
    • Key advantages of computer programs include rapid and automated execution of repetitive operations, error-free processing of massive datasets, dynamic formatting of output results, and efficient resource consumption.
    • The individual authoring these instructions using specialized syntactical rules is designated as a programmer.
  • Algorithms and Pseudo Code Design:

    • An algorithm is a finite, step-by-step procedure formulated to solve a specified problem before actual code implementation.
    • Essential properties of a robust algorithm:
    • Complex problems must be broken down into discrete, manageable, and logically sound operational steps.
    • Steps must be numbered strictly in sequential order.
    • Steps must be descriptive, unambiguous, and written in clear, simple language independent of any target machine architecture.
    • Pseudo code serves as an informal high-level description of program logic that closely mirrors natural language (such as English). It eliminates syntactical rigidity and separates problem-solving into two phases:
    • Logic Design: Outlining the operational procedures and sequencing required to resolve the computational task.
    • Coding: Translating planned algorithmic steps into target programming language statements.
    • Core algorithmic examples:
    • Summation of Two Integers:
      • Step 1: Start
      • Step 2: Input AA
      • Step 3: Input BB
      • Step 4: Total = A+BA + B
      • Step 5: Display Total
      • Step 6: Exit
    • Circle Area Computation (Area=3.14×r2\text{Area} = 3.14 \times r^2):
      • Step 1: Start
      • Step 2: Input radius in rr
      • Step 3: area=3.14×r×r\text{area} = 3.14 \times r \times r
      • Step 4: Print area
      • Step 5: End
    • Kinematic Distance Traveled (s=v×ts = v \times t):
      • Step 1: Start
      • Step 2: Input average speed in vv
      • Step 3: Input time in tt
      • Step 4: s=v×ts = v \times t
      • Step 5: Print ss
      • Step 6: End
    • Sum of First 50 Natural Numbers:
      • Step 1: Start
      • Step 2: Set sum=0\text{sum} = 0
      • Step 3: Set N=0N = 0
      • Step 4: Repeat Steps 5 and 6 while (N≤50N \le 50)
      • Step 5: sum=sum+N\text{sum} = \text{sum} + N
      • Step 6: N=N+1N = N + 1
      • Step 7: Print sum
      • Step 8: End
    • Major advantages of algorithms:
    • Reduced Complexity: Decouples logical reasoning from syntactical constraints.
    • Increased Flexibility: The identical algorithm can be translated interchangeably into C++, Java, Visual Basic, or Python.
    • Ease of Understanding: Enables non-technical domain experts to inspect computational logic without knowing machine-level nuances.
  • Flowcharts and Visual Representation:

    • A flowchart is a graphical representation of the logical steps, data flows, and decision paths of an algorithm, functioning analogously to an architectural blueprint.
    • Standard geometric flowchart symbols:
    • Parallelogram: Input or Output operations (e.g., reading values, printing calculated metrics).
    • Rectangle: Computational processing, data transformations, or variable assignments (e.g., Sum=A+B\text{Sum} = A + B).
    • Diamond: Selection, evaluation, or branching based on a boolean condition (has one entry path and two exit paths: True/False or Yes/No).
    • Oval: Terminal delimiter representing the starting or ending point of a program sequence.
    • Flow Lines (Arrows): Indicate the exact operational sequence and direction of data processing (typically top-to-bottom or left-to-right).
    • Circle (Connector): Merges multiple intersecting flow lines into a single path to eliminate visual congestion across complex diagrams.
    • Double-lined Rectangle: Subroutine or function call containing isolated sub-logic.
    • Preparation (Hexagon): Used specifically with loop control constructs to establish initial values, step conditions, and terminating boundaries.
    • Flowchart construction guidelines:
    • Requirements must be ordered with strict logical consistency.
    • Ensure diagrams remain clean, clear, and unambiguous.
    • Only one flow line should emerge from an operational process rectangle.
    • Exactly one flow line must enter a decision diamond, and exactly two flow lines must emerge corresponding to evaluated conditions.
    • Ensure the terminal start and end markers are unique and logical.
    • Complex, messy crossover paths must be mitigated using connector symbols.
    • Logic validity should be verified using dry-run desk checks with trace tables.
    • Key differences between flowcharts and algorithms:
    • Flowcharts use geometric symbols; algorithms use plain, structured text.
    • Flowcharts are graphically complex and time-consuming to create or modify; algorithms are fast and simple to adjust.
    • Flowcharts highlight visual branching and control paths; algorithms emphasize discrete step-by-step procedures.
  • Stages of the Software Development Life Cycle (SDLC):

    • 1. Defining and Analyzing the Problem: Identifying user requirements, determining mandatory inputs, required processing, target hardware/software environment, and formatted output expectations.
    • 2. Designing the Algorithm and Flowchart: Structuring the underlying logical architecture and visualizing alternative procedural paths.
    • 3. Coding or Writing the Program: Translating the validated algorithm into concrete instructions using a chosen programming language syntax.
    • 4. Program Testing and Debugging: Verifying operational correctness by executing the code across boundary, valid, and invalid datasets, identifying and eliminating bugs.
    • 5. Final Documentation: Creating user operating manuals and technical developer documentation detailing installation steps, hardware requisites, and internal architecture for maintenance.
  • Taxonomy of Programming Languages:

    • Low-Level Languages:
    • Machine Language (1GL): Primitive binary code (00s and 11s). Executed natively and instantly by the CPU without translation; strictly machine-dependent, difficult to learn, and prone to human error.
    • Assembly Language (2GL): Symbolic language replacing raw binary instructions with mnemonics (e.g., SUB, ADD, MOV). Requires an assembler to produce machine code; predominantly utilized for system software and direct device control.
    • High-Level Languages:
    • Languages designed with English-like keywords, abstractions, and standardized syntax that are machine-independent and accessible to human developers.
    • Procedural Languages (3GL): Step-by-step instruction sequences instructing the computer what to do and how to execute it (e.g., FORTRAN [Formula Translation, engineered for science and engineering], BASIC [Beginner's All-purpose Symbolic Instruction Code, developed in the late 1960s for education], COBOL [Common Business Oriented Language, early 1960s, verbose and optimized for commercial data], Pascal [named for Blaise Pascal, structured for business and science], C [developed by Dennis Ritchie at Bell Labs in 1972 for UNIX]).
    • Non-Procedural Languages (4GL): Declarative environments where the user defines what outcome is required rather than specifying algorithmic steps on how to achieve it (e.g., SQL [Structured Query Language, IBM-originated ANSI standard], RPG [Report Program Generator, early 1960s for IBM business machines]). Greatly reduces human coding error and accelerates reporting.
    • Natural Programming Languages (5GL): Artificial intelligence-oriented languages that accept human conversational input; highly resource-intensive and historically experimental.
  • Source Code vs. Object Code:

    • Source Code: Program instructions authored by humans in a high-level or assembly language. It is human-readable, easily modified, and cannot be directly executed by the processor hardware.
    • Object Code: Machine code produced after translation by a compiler or assembler. It contains binary instructions directly understood by the CPU, contains more individual instruction statements than the source code, and is difficult for humans to inspect or modify.
  • Language Processors (Translators):

    • Compiler: Scans and translates an entire high-level source code module into machine language all at once, producing a permanent, reusable object file (.obj). Displays a comprehensive list of all detected syntax errors upon completing compilation.
    • Interpreter: Translates and immediately executes a high-level program line by line. Halts execution instantly when a syntax error is discovered, facilitating real-time debugging. Does not generate a standalone object code file; source instructions must be re-translated on every execution pass.
    • Assembler: Translates symbolic low-level assembly language mnemonics into machine code.
  • Programming Paradigms and Structured Control Structures:

    • Structured Programming: Decomposes a monolithic software problem into smaller sub-programs or modules. Improves reusability, simplifies testing, and accelerates maintenance.
    • Core building blocks of structured code:
    • Sequential Execution: Statements execute strictly in the sequential order they appear, exactly once without deviation.
    • Selection (Branching): Directs execution down alternate logical paths evaluated by a condition (e.g., if, if-else, switch).
    • Repetition (Iteration/Looping): Repeats a block of statements based on a loop control condition (e.g., while, do-while, for).
    • Subroutine / Function Calls: Temporarily diverts control to a named modular block, executing its enclosed instructions before returning control to the statement directly following the invocation point.
    • Limitation of Structured Systems: Functions and data lack natural binding; data cannot easily be protected against unintended external modification across large procedural systems.
    • Object-Oriented Programming (OOP): Treats software design around autonomous, real-world models termed "objects" combining internal state (data members) and behavioral logic (member functions).
    • Event-Driven Programming: Execution flow is determined by external system or user interactions called events (e.g., mouse clicks, key presses, window resizing). Commonly paired with visual environments.
    • Visual Programming: Graphical development environments (e.g., Visual Basic, PowerBuilder) offering drag-and-drop UI component palettes (buttons, textboxes, lists) with attached event-handler code stubs, requiring higher memory and fast modern graphics interfaces.

C++ Language Foundations, Structure, and Development Environment

  • Historical Evolution of C++:

    • Lineage of Development: ALGOL 60 led to CPL (Combined Programming Language, 1963), simplified by Martin Richards into BCPL (Basic Combined Programming Language, 1967). Ken Thompson developed B language in 1970 at Bell Laboratories as a foundation for operating system development.
    • Birth of C: Dennis Ritchie derived C from B language in 1972 at AT&T Bell Laboratories to develop the UNIX operating system. Early C was standardized as K&R (Kernighan & Ritchie) C, subsequently formalized as ANSI C.
    • Origin of C++: Bjarne Stroustrup began creating C++ in 1980 at Bell Labs, originally designated "C with Classes" to combine the raw efficiency of C with Simula-like object abstraction mechanisms. Renamed C++ in 1983; commercial release occurred in October 1985. Formalized by ANSI/ISO committee X3J16 in mid-1998.
  • Distinguishing Architectural Features of C++:

    • Convenience and Structure: Provides high-level object-oriented abstractions while maintaining low-level access to system memory.
    • Case Sensitivity: Uppercase and lowercase alphabetic letters are treated as completely distinct identifiers (Total is distinct from total). All standard keywords are written strictly in lowercase.
    • Portability and Machine Independence: Code written to standard specifications can run across distinct CPU architectures (e.g., Intel, Motorola) with minimal recompilation.
    • Direct Hardware Manipulation: Retains direct memory addressing via pointers, enabling efficient system-level, embedded, and driver software development.
    • Brevity and Speed: Compilers produce highly optimized machine code that rivals low-level assembly in execution speed.
    • Backward Compatibility: Seamlessly integrates legacy standard C code without architectural redesign.
  • Basic Structure of a C++ Source Program:

    • Every valid C++ executable source program consists of three fundamental tiers:
    • Preprocessor Directives: Instructions executed by the preprocessor before compilation begins.
    • The main() Function: The entry point where CPU program execution strictly originates.
    • Program Statements (Body): Instructions enclosed within structural delimiters (curly braces { }), with each individual statement terminated by a semicolon (;).
  • Preprocessor Directives and Header Files:

    • Preprocessor directives start with a hash symbol (#) in the first column, contain no trailing semicolon, and instruct the preprocessor to alter the source code text prior to compiling.
    • The #include directive instructs the preprocessor to parse and insert the entire contents of a specified header file into the source file.
    • Header files (ending with .h in traditional C++) contain declarations, standard library function definitions, macros, and global constants.
    • Inclusion Syntax: #include <iostream.h> searches system default directories (typically the INCLUDE subdirectory); #include "myheader.h" searches the current local working directory first before checking system paths.
    • iostream.h provides definitions for fundamental stream objects: cout (console output) and cin (console input).
  • The main() Function and Statement Terminology:

    • Execution of every standard C++ application begins at the first statement inside main() and terminates at its conclusion.
    • Syntax structure: cpp void main() { // statements composing the function body } &nbsp;&nbsp;&nbsp;&nbsp;
    • Omitting the main() function allows compilation into an object module (.obj), but linker operations fail to generate an executable (.exe).
    • Curly braces ({ and }) act as compound statement delimiters defining block scope.
    • Semicolons (;) act as explicit statement terminators; missing terminators yield syntax errors.
  • Lexical Tokens in C++:

    • A token is the smallest individual syntactical element recognized by the compiler. C++ statements are composed of six token categories:
    • Keywords: 63 predefined, reserved words with fixed linguistic meaning (e.g., int, float, for, class, public, virtual).
    • Identifiers: User-defined symbolic labels assigned to variables, functions, structures, and arrays.
    • Constants (Literals): Fixed, unalterable numerical, character, or boolean values directly embedded in source statements.
    • String Literals: Sequences of characters enclosed within double quotation marks (e.g., "System Boot Complete").
    • Operators: Specific operational symbols triggering evaluations or manipulations on data operands (e.g., +, -, *, &&).
    • Punctuators (Separators): Syntactical delimiters that structure code and separate tokens (e.g., [ ], ( ), { }, ,, ;, :).
    • White Spaces: Spaces, tabs, carriage returns, and newlines inserted to enhance human readability. Compilers ignore white spaces except when encountered within literal string constants.
  • Turbo C++ Integrated Development Environment (IDE):

    • An integrated software environment created by Borland International providing an editor, compiler, linker, and interactive debugger.
    • Directory Hierarchy: TC\BIN holds binaries and IDE executables (TC.EXE); TC\INCLUDE contains standard library header files; TC\LIB stores precompiled runtime library routines.
    • Key Menu Commands & Shortcuts:
    • F1: Context-sensitive help.
    • F2: Save the active source file.
    • F3: Open an existing file.
    • F7: Trace Into (Single-step execution down into function bodies).
    • F8: Step Over (Single-step execution bypassing function internals).
    • F10: Activate the top menu bar.
    • Alt + F9: Compile source program into an object file (.obj).
    • Ctrl + F9: Link and run executable code directly from the IDE.
    • Alt + F5: Switch to User Screen to inspect program runtime output.
    • Ctrl + F7: Add a watch variable expression.
    • Ctrl + F8: Toggle a breakpoint on the current source code line.
    • Alt + X: Exit Turbo C++ IDE.
    • Program Construction Lifecycle: Editing (.cpp) →\rightarrow Saving →\rightarrow Compiling (.obj) →\rightarrow Linking (.exe) →\rightarrow Loading (Loader places binary in memory) →\rightarrow Executing.
  • Taxonomy of Programming Errors:

    • Syntax Errors: Occur when source code violates grammatical rules of C++ (e.g., omitting statement terminators ;, missing closing delimiters }, misspelling keywords like doubel). Detected and listed completely by the compiler; object code generation is aborted.
    • Logical Errors: Occur when flawed algorithm design causes incorrect behavior or inaccurate mathematical calculations (e.g., coding Average = Total * 5 instead of Total / 5, using a < b instead of a > b). Compilers cannot detect logical errors; program compiles and runs smoothly but yields wrong results.
    • Run-Time Errors: Arise when instructions demand illegal operations during execution (e.g., dividing by zero x / 0, attempting to access an invalid memory address, opening a non-existent file). Causes immediate operating system termination or program crashes.
  • Turbo C++ Interactive Debugging Tools:

    • Single Stepping: Executing source instructions sequentially, one discrete line per keystroke (F7), enabling programmers to observe variables and identify the exact line triggering failure.
    • Watches: Dynamic monitoring panels that track and evaluate changing variable contents in real-time as execution steps through code.
    • Breakpoints: Programmatically inserted flags halting program execution at a predetermined code line (Ctrl + F8), allowing developers to inspect variable states prior to executing the rest of the file.
    • Evaluate/Modify Window: Diagnostic dialog allowing users to view an active variable's contents and inject new test values on the fly during an paused debugging session.

Data Representation, Variables, Constants, and Operators

  • Fundamental C++ Primitive Data Types and Storage Requirements:

    • Integer Data Types (Fixed-Point Whole Numbers):
    • int (Signed Integer): Uses 2 bytes (in 16-bit systems/MS-DOS); numerical range from −32,768-32,768 to +32,767+32,767.
    • short int: Allocates 2 bytes; range identical to 16-bit int (−32,768-32,768 to +32,767+32,767).
    • unsigned int: Allocates 2 bytes; ignores sign bit; range from 00 to 65,53565,535.
    • long int: Allocates 4 bytes; range from −2,147,483,648-2,147,483,648 to +2,147,483,647+2,147,483,647.
    • unsigned long int: Allocates 4 bytes; range from 00 to 4,294,967,2954,294,967,295.
    • Symbolic range limits defined in <limits.h>: INT_MIN, INT_MAX, SHRT_MIN, SHRT_MAX, UINT_MAX, LONG_MIN, LONG_MAX, ULONG_MAX.
    • Real / Floating-Point Data Types (Fractional Real Values):
    • float: Uses 4 bytes; numerical range from ±3.4×10−38\pm 3.4 \times 10^{-38} to ±3.4×10+38\pm 3.4 \times 10^{+38}; provides 6 to 7 decimal places of precision.
    • double: Uses 8 bytes; range from ±1.7×10−308\pm 1.7 \times 10^{-308} to ±1.7×10+308\pm 1.7 \times 10^{+308}; provides 15 decimal digits of precision.
    • long double: Uses 10 bytes; range from ±1.7×10−4932\pm 1.7 \times 10^{-4932} to ±1.7×10+4932\pm 1.7 \times 10^{+4932}; provides 19 decimal digits of precision.
    • Precision and limit constants defined in <float.h>: FLT_MIN, FLT_MAX, DBL_MIN, DBL_MAX, LDBL_MIN, LDBL_MAX.
    • Character Data Type:
    • char: Uses 1 byte of memory; stores integer ASCII character encodings ranging from −128-128 to +127+127 (signed) or 00 to 255255 (unsigned). Enclosed in single apostrophes (e.g., 'A', '7', ' '). Limits in <limits.h>: CHAR_MIN, CHAR_MAX.
  • Signed vs. Unsigned Integers and Two's Complement Mechanics:

    • In signed integers, the most significant bit (MSB) functions as the sign flag (00 for positive, 11 for negative).
    • Unsigned integers treat the MSB as part of the numerical magnitude, doubling the positive range.
    • Negative integers are represented internally using two's complement notation:
    • Take the absolute value in binary.
    • Invert all bits (one's complement: 0→10 \rightarrow 1, 1→01 \rightarrow 0).
    • Add binary 11 to the least significant bit (LSB).
    • This scheme eliminates positive/negative zero ambiguity and allows subtraction using regular binary addition circuits.
  • Integer Overflow and Underflow:

    • Overflow occurs when an assigned value or calculation result exceeds the maximum upper limit of an integer type. Underflow occurs when a value drops below the absolute minimum limit.
    • In signed integer representations, binary overflow rolls over into the sign bit: adding 11 to a 16-bit signed integer holding 3276732767 (01111111 11111111) yields −32768-32768 (10000000 00000000).
    • Compilers do not issue syntax or runtime warnings for integer overflow; calculations silently produce wildly inaccurate outputs.
  • Floating-Point Precision Loss and Scientific Notation:

    • Real numbers can be specified in scientific exponential notation: ±me±n\pm m\text{e}\pm n (e.g., 4.694×10−3=4.694e-34.694 \times 10^{-3} = 4.694\text{e-}3), where mm is the mantissa (1≤∣m∣<101 \le |m| < 10) and nn is an integer exponent.
    • Under IEEE 754 floating-point standards, computers store fractional numbers using sums of negative powers of two (2−1=0.52^{-1} = 0.5, 2−2=0.252^{-2} = 0.25, 2−3=0.1252^{-3} = 0.125, etc.).
    • Decimal fractions such as 0.10.1 and 0.20.2 cannot be represented cleanly as finite sums of binary fractions, forming repeating binary expansions analogous to 13\frac{1}{3} in base 10. Consequently, operations such as 0.1+0.20.1 + 0.2 evaluate to approximate values (e.g., 0.300000000000000040.30000000000000004).
    • double is preferred for scientific computing because its 53-bit significand provides 15–17 decimal digits of precision, significantly reducing accumulated rounding error compared to float's 24-bit significand (6–7 decimal places).
  • Bitwise Operations at the Binary Level:

    • Bitwise operators manipulate individual binary bits within integral operands:
    • Bitwise AND (&): Yields 11 if and only if both bits are 11; otherwise 00.
    • Bitwise OR (|): Yields 11 if either or both bits are 11; yields 00 only when both bits are 00.
    • Bitwise XOR (^): Yields 11 if the bits are different (00 and 11); yields 00 if the bits are identical (00 and 00, or 11 and 11).
    • Step-by-Step Computational Trace for Integers 5 and 3:
    • Representation: 510=010125_{10} = 0101_2; 310=001123_{10} = 0011_2
    • Bitwise AND (5 & 35 \,\&\, 3):       0101&00110001  ⟹  110\begin{array}{ccccc} & 0 & 1 & 0 & 1 \\ \& & 0 & 0 & 1 & 1 \\ \hline & 0 & 0 & 0 & 1 \end{array} \implies 1_{10}
    • Bitwise OR (5∣35 \mid 3):       0101∣00110111  ⟹  710\begin{array}{ccccc} & 0 & 1 & 0 & 1 \\ \mid & 0 & 0 & 1 & 1 \\ \hline & 0 & 1 & 1 & 1 \end{array} \implies 7_{10}
    • Bitwise XOR (5∧35 \wedge 3):       0101∧00110110  ⟹  610\begin{array}{ccccc} & 0 & 1 & 0 & 1 \\ \wedge & 0 & 0 & 1 & 1 \\ \hline & 0 & 1 & 1 & 0 \end{array} \implies 6_{10}
  • Variable Declaration, Allocation, and Initialization:

    • A variable represents a named temporary memory cell mapped to a RAM address. Its name remains permanent, while its stored value can change during execution.
    • Three core attributes established upon declaration: variable name, variable data type, and physical memory address.
    • Declaration Syntax: data_type variable_name; (e.g., int marks; float average; char grade;).
    • Memory allocation occurs immediately upon declaration; variables left uninitialized contain random binary noise known as garbage values.
    • Initialization Syntax: Assigns an explicit starting value during declaration: int testVar = 100;.
    • Rules for Valid Variable Identifiers:
    • Must contain only alphanumeric characters (A-Z, a-z, 0-9) and underscores (_).
    • First character must strictly be an alphabetic letter or underscore (starting with numbers like 9minute is invalid).
    • Whitespace characters and special symbols (#, $, @, -, .) are strictly prohibited.
    • Cannot collide with any of the 63 reserved keywords.
    • Identifiers are evaluated up to 31 characters on standard compilers; excess characters are ignored.
  • Literal vs. Symbolic Constants:

    • Literal Constants: Raw values typed directly into expressions:
    • Integer Literals: 87, -10, 65000L (L denotes long).
    • Floating-Point Literals: 50.75F (F denotes float), 15.32 (defaults to double), 52000.33L (denotes long double).
    • Character Literals: Enclosed in single quotes: 'A', ' ', '$'.
    • String Literals: Enclosed in double quotes: "Pakistan Zindabad".
    • Symbolic Constants: Named memory locations holding unalterable values, defined using two methods:
    • Preprocessor #define Directive: #define PI 3.141593 performs text replacement before compilation. It lacks data type validation, does not allocate typed storage, and is invisible in the debugger symbol table.
    • The const Qualifier: const float PI = 3.141593; creates a strongly-typed constant. Enforces compiler type safety, respects normal block scoping rules, and integrates with interactive debuggers, making it safer and preferred in modern C++.
  • Expressions, Assignment Statements, and Memory Mechanics:

    • An expression is any sequence of operators and operands that evaluates to a single scalar value (e.g., A + B, x + 100).
    • Assignment Statement: variable = expression; evaluates the right-hand expression first, storing the resulting value into the left-hand variable.
    • Lvalue and Rvalue:
    • An lvalue (locator value) represents an identifiable memory address that can persist across expressions. It must appear on the left side of an assignment operator (e.g., a variable x).
    • An rvalue represents a temporary data value produced by an expression or literal (e.g., the number 5 or x + 2).
    • All lvalues can legally serve as rvalues, but pure rvalues cannot serve as lvalues (x = 5; is legal; 5 = x; triggers a compile-time error).
    • Compound Assignment Operators: Combines an arithmetic operator with an assignment: x += 10; is equivalent to x = x + 10;. Supported variants include +=, -=, *=, /=, %=.
  • Arithmetic Operators and Division Truncation:

    • Five basic arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
    • Integer Division Truncation: If both operands in a division expression are integers, C++ performs integer division, discarding any fractional remainder (e.g., 7 / 2 evaluates to 3, not 3.5). To retain fractional values, at least one operand must be a floating-point type (7.0 / 2 yields 3.5).
    • Modulus Operator (%): Calculates the integer remainder of division; works strictly with integer data types (using % with float or double causes a compile error). Examples: 10 % 3 yields 1, 3 % 5 yields 3, 0 % 4 yields 0.
  • Increment (++) and Decrement (--) Operators:

    • Unary operators incrementing or decrementing a variable's value by 11. Can only be applied to modifiable lvalues (variables), not literal constants or composite expressions (10++ or (a+b)++ are invalid).
    • Prefix Form (++x, --x): Increments or decrements the operand first, then returns the updated value to the enclosing expression.
    • Postfix Form (x++, x--): Evaluates the current value within the enclosing expression first, then applies the increment or decrement afterward.
    • Undefined Behavior with Multiple Increments: Expressions referencing and modifying the same scalar variable multiple times without an intervening sequence point (e.g., x = ++a + a++;) produce undefined behavior. Compilers are free to reorder sub-expression evaluations, leading to inconsistent and unpredictable results across different optimization levels and platforms.
  • Operator Precedence and Associativity:

    • Precedence: Determines which operations are evaluated first in a complex expression.
    • Associativity: Dictates the direction of evaluation (Left-to-Right or Right-to-Left) for operators sharing the identical precedence rank.
    • Summary of Operator Hierarchy (Highest to Lowest):
    • Parentheses: ( ) (Highest precedence, evaluated from innermost to outermost)
    • Postfix Unary: ++, -- (Left-to-Right)
    • Prefix Unary: ++, --, +, -, !, sizeof, cast (type) (Right-to-Left)
    • Multiplicative: *, /, % (Left-to-Right)
    • Additive: +, - (Left-to-Right)
    • Relational: <, <=, >, >= (Left-to-Right)
    • Equality: ==, != (Left-to-Right)
    • Logical AND: && (Left-to-Right)
    • Logical OR: || (Left-to-Right)
    • Conditional (Ternary): ?: (Right-to-Left)
    • Assignment: =, +=, -=, *=, /=, %= (Right-to-Left, Lowest precedence)
    • Evaluation Trace Example: Solving r=a×b/(−c×31%13)×dr = a \times b / (-c \times 31 \% 13) \times d with a=10a = 10, b=20b = 20, c=15c = 15, d=8d = 8:
    • Sub-expression −c-c evaluates to −15-15.
    • Inside parentheses: −15×31=−465-15 \times 31 = -465.
    • Remainder: −465%13=−10-465 \% 13 = -10.
    • Parenthesized expression resolves to −10-10.
    • Main expression becomes: 10×20/(−10)×810 \times 20 / (-10) \times 8.
    • Left-to-right evaluation: 10×20=20010 \times 20 = 200.
    • Division: 200/(−10)=−20200 / (-10) = -20.
    • Multiplication: −20×8=−160-20 \times 8 = -160.
  • Type Casting Mechanisms:

    • Implicit Type Conversion (Type Promotion / Coercion): Handled automatically by the compiler in mixed-type expressions. Operands with lower memory rank are widened to match the highest-ranking operand to prevent precision loss without altering the underlying variable definition.
    • Promotion Order: char →\rightarrow int →\rightarrow long →\rightarrow float →\rightarrow double →\rightarrow long double.
    • Explicit Type Casting: Manual conversion instructed directly by the programmer using the cast operator: (desired_type) expression.
    • Scenario Demanding Explicit Cast: Calculating the real-number average of two integer test scores: cpp int score1 = 15, score2 = 16; float average = (float)(score1 + score2) / 2; // Produces 15.5 instead of truncated 15 &nbsp;&nbsp;&nbsp;&nbsp;
  • The sizeof Operator and Program Comments:

    • sizeof is a compile-time unary operator returning the memory footprint in bytes for a given data type, variable, or literal value (e.g., sizeof(char) returns 1, sizeof(int) returns 2 or 4, sizeof(double) returns 8).
    • Comments provide explanatory text documenting code behavior and are stripped out by the preprocessor, adding zero overhead to the final binary:
    • Single-Line Comments: Prefixed by double forward slashes: // Documenting logic here.
    • Multi-Line Comments: Enclosed between block delimiters: /* Multi-line explanation */.

Input and Output Streams, Escape Sequences, and Format Manipulators

  • Standard Input and Output Stream Architecture:

    • I/O operations in C++ are handled via byte streams—sequences of bytes flowing between physical devices and the program.
    • Stream mechanisms are defined within <iostream.h>, which provides fundamental abstractions:
    • cout: Standard console output stream connected to the display monitor.
    • cin: Standard console input stream connected to the keyboard buffer.
    • Insertion Operator (<<): Puts formatted data into the output stream on its left.
    • Extraction Operator (>>): Extracts formatted characters from the input stream on its left and assigns them to the storage variable on its right.
  • Output Stream Behavior and Concatenation:

    • Multiple insertion operations can be chained together in a single statement: cpp cout << "Value of A: " << a << " and B: " << b; &nbsp;&nbsp;&nbsp;&nbsp;
    • Quotation marks distinguish string literals from variable names (cout << "a"; displays the letter a, whereas cout << a; prints the value stored in variable a).
  • Control Characters (Escape Sequences):

    • Formatted non-printing characters prefixed with a backslash (\):
    • \a: Alert / Bell (triggers an audible system beep).
    • \b: Backspace (moves cursor back one space, deleting the previous character on subsequent output).
    • \f: Form feed (ejects paper on a printer or clears older terminals).
    • : Newline (moves the active cursor to the beginning of the next line).
    • \r: Carriage return (returns the cursor to the first column of the active line, overwriting existing characters).
    • \t: Horizontal tab (advances cursor to the next tab stop, typically multiples of 8 columns).
    • \': Prints an escaped single quotation mark.
    • \": Prints an escaped double quotation mark.
    • \\: Prints a literal backslash character.
  • Standard I/O Formatting Manipulators:

    • Manipulators modify how input and output streams format and display values:
    • endl: Inserts a newline character into the stream and flushes the output buffer immediately (found in <iostream.h>).
    • setw(n): Sets the field width for the immediately following output item to n columns. Output is right-justified by default. If the value exceeds n characters, C++ expands the field rather than truncating (defined in <iomanip.h>).
    • setprecision(n): Configures the total number of digits displayed for floating-point values, or sets fixed decimal places when combined with fixed. Rounds trailing digits (defined in <iomanip.h>).
    • fixed: Forces floating-point numbers to display in standard decimal format rather than scientific notation.
    • showpoint: Forces trailing zeros and a decimal point to display for floating-point values even if the fractional part is zero.
    • setfill(ch): Replaces unused leading whitespace in a setw formatted column with the fill character ch (e.g., cout << setw(10) << setfill('*') << 25; displays ********25).
  • Keyboard Input Mechanics with cin:

    • The extraction operator (>>) automatically skips all leading whitespace (spaces, tabs, newlines). It reads characters matching the target variable's type and stops reading as soon as it hits trailing whitespace.
    • Chained inputs allow reading multiple variables in a single statement: cin >> a >> b >> c;.
  • Buffer Mechanics and Mixing cin >> with getline():

    • When reading data using cin >>, non-whitespace characters are parsed and extracted, but trailing delimiters (like the newline character generated by pressing Enter) remain in the input buffer.
  • cin.getline(str, len) reads all characters up to the next newline , stores them in str, and removes the from the buffer.

  • When cin >> variable; is immediately followed by cin.getline(str, len);, the getline() call reads the leftover from the previous input and immediately returns an empty string without waiting for user input.

  • Resolution via cin.ignore(): Calling cin.ignore() discards the leftover newline character from the buffer before invoking getline(): cpp #include <iostream.h> void main() { int age; char fullName[50]; cout << "Enter age: "; cin >> age; cin.ignore(); // Clears leftover ' ' from the input stream buffer cout << "Enter full name: "; cin.getline(fullName, 50); cout << "Age: " << age << ", Name: " << fullName; } &nbsp;&nbsp;&nbsp;&nbsp;

Control Structures: Conditional Execution and Branching

  • Classification of Program Control Structures:

    • Program execution follows three basic structural patterns:
    • Sequential Structure: Operations execute one after another in written order.
    • Selection (Conditional) Structure: Selects among alternative execution paths based on boolean conditions.
    • Repetition (Iterative) Structure: Executes a block of instructions repeatedly while a condition remains true.
  • Relational Operators and Expressions:

    • Relational operators compare two values and evaluate to a boolean result: true (11) or false (00):
    • Greater than (>)
    • Less than (<)
    • Equal to (==)
    • Greater than or equal to (>=)
    • Less than or equal to (<=)
    • Not equal to (!=)
    • Any non-zero numeric value is treated as logical true in conditional contexts, while zero (0) evaluates to false.
  • The Simple if Statement and Compound Blocks:

    • Executes an attached statement only if its relational condition evaluates to true; otherwise, the statement is skipped.
    • Syntax:cpp if (condition) single_statement; &nbsp;&nbsp;&nbsp;&nbsp;
    • To execute multiple statements conditionally, enclose them in curly braces to form a compound block ({ statement1; statement2; }). Placing a semicolon directly after the condition (if (x > y);) creates an empty statement, breaking the intended logic.
    • Limitation: The simple if handles actions when a condition is true, but cannot directly specify an alternative path when the condition evaluates to false.
  • The Two-Way if-else Construct:

    • Guarantees that exactly one of two alternate statement blocks will execute while the other is skipped: cpp if (condition) { // statements executed when condition is true } else { // statements executed when condition is false } &nbsp;&nbsp;&nbsp;&nbsp;
  • Multi-Way if-else-if Ladders:

    • Evaluates a series of conditions sequentially until the first true condition is found. The matching block executes, and all remaining branches are skipped. If no conditions evaluate to true, the trailing else block executes as a fallback.
  • Nested if Statements and the Dangling else Ambiguity:

    • An if statement placed inside another if or else block creates a nested selection structure.
    • The Dangling Else Problem: When an else clause follows nested if statements without explicit curly braces, it pairs with the closest preceding if that lacks an else: cpp if (x > 0) if (y > 0) cout << "Both positive"; else cout << "Matches inner if (y <= 0)!"; &nbsp;&nbsp;&nbsp;&nbsp;
  • To bind the else to the outer if, enclose the inner construct in curly braces: cpp if (x > 0) { if (y > 0) cout << "Both positive"; } else { cout << "Matches outer if (x <= 0)!"; } &nbsp;&nbsp;&nbsp;&nbsp;

  • Logical Operators and Compound Conditions:

    • Combine two or more relational tests into a single boolean condition:
    • Logical AND (&&): Evaluates to true only if both conditions are true. Employs short-circuit evaluation: if the left operand is false, the right operand is never evaluated.
    • Logical OR (||): Evaluates to true if either condition is true. Employs short-circuit evaluation: if the left operand is true, the right operand is skipped.
    • Logical NOT (!): Unary operator that inverts the truth value of a condition (!true is false, !false is true).
  • The Multi-Branch switch Selection Structure:

    • Compares an integer or character expression against multiple constant values (case labels): cpp switch (expression) // Must evaluate to int or char { case constant1: statements; break; // Exits the switch construct case constant2: statements; break; default: // Optional fallback executed when no cases match statements; } &nbsp;&nbsp;&nbsp;&nbsp;
    • Role of the break Statement: Terminates execution of the switch block. If break is omitted, execution falls through to subsequent case labels, executing their statements regardless of whether their constants match.
    • Comparison: switch vs. Nested if-else:
    • switch only evaluates discrete integer or character equality; it cannot directly test floating-point numbers or logical ranges (e.g., x >= 10 && x <= 20).
    • if-else can evaluate complex conditions, logical operators, floating-point numbers, and variable-to-variable comparisons.
  • The Conditional (Ternary) Operator (?:):

    • A compact three-operand alternative to simple if-else expressions: (condition) ? true_expression : false_expression;.
    • Evaluates the condition first. If true, it returns true_expression; if false, it returns false_expression (e.g., max = (a > b) ? a : b;).
  • Unconditional Branching with goto:

    • Directly transfers control to a labeled line in the same function: goto label_name;.
    • Labels are declared using an identifier followed by a colon (label_name:). Unchecked use of goto creates hard-to-maintain, unstructured code ("spaghetti code") and should generally be avoided.

Iterative Structures: Loops and Nested Repetition

  • Loop Classifications:

    • Counter-Controlled Loops: Execute for a predetermined number of iterations using a dedicated counter variable that tracks steps up to a limit.
    • Sentinel-Controlled Loops: Iterate indefinitely until a specific sentinel value is encountered (e.g., reading inputs until the user enters -1).
    • Pretest vs. Posttest Loops:
    • Pretest Loops (while, for): The loop condition is evaluated before executing the body. If the condition is false initially, the body does not execute at all.
    • Posttest Loops (do-while): The condition is evaluated after executing the body. The body is guaranteed to execute at least once regardless of the condition.
  • The while Loop:

    • Executes a block of statements repeatedly as long as its condition evaluates to true: cpp while (condition) { // loop body } &nbsp;&nbsp;&nbsp;&nbsp;
    • If the condition never becomes false, the loop runs indefinitely, creating an infinite loop.
  • The do-while Loop:

    • A posttest loop construct that always executes its body at least once: cpp do { // loop body } while (condition); // Notice the mandatory trailing semicolon &nbsp;&nbsp;&nbsp;&nbsp;
  • The for Loop:

    • A compact loop structure combining initialization, loop condition, and increment/decrement expressions in a single line: cpp for (initialization; condition; update) { // loop body } &nbsp;&nbsp;&nbsp;&nbsp;
    • Execution Sequence:
    • 1. Execute initialization once upon entering the loop.
    • 2. Evaluate condition. If false, terminate the loop.
    • 3. Execute the statements within the loop body.
    • 4. Execute the update expression.
    • 5. Return to Step 2.
    • Loop expressions can use comma operators to initialize or update multiple variables: for(i = 0, j = 10; i < j; i++, j--).
  • Jump Statements: break and continue:

    • break: Immediately exits the innermost loop or switch statement, transferring control to the line directly following the block.
    • continue: Skips the remaining statements in the current iteration of the loop, jumping straight to the next iteration (in a for loop, control moves directly to the update expression).
  • Nested Loops:

    • Placing one loop inside another creates a nested loop construct. For every single iteration of the outer loop, the inner loop runs through its complete lifecycle.
    • If an outer loop runs MM times and its inner loop runs NN times, the inner loop body executes a total of M×NM \times N times.

Linear and Multidimensional Arrays, Searching, and Sorting Algorithms

  • Array Fundamentals and Memory Architecture:

    • An array is a collection of contiguous, identically-typed memory locations referenced by a single common name.
    • Individual elements are accessed using a zero-based integer index or subscript enclosed in square brackets ([ ]).
    • For an array of size NN, legal indices range from 00 to N−1N - 1.
    • Declaring an array reserves a fixed, continuous block of memory: int marks[5]; allocates 5 consecutive integer cells (10 bytes on 16-bit systems).
  • Array Initialization:

    • Elements can be initialized using a comma-separated list enclosed in curly braces: cpp int marks[5] = {70, 54, 82, 96, 49}; &nbsp;&nbsp;&nbsp;&nbsp;
    • If the initialization list contains fewer values than the declared array size, remaining elements are automatically zeroed out.
    • If the size is omitted, the compiler sizes the array based on the number of provided initializers: int age[] = {23, 56, 87}; creates an array of size 3.
    • Initializing more values than the declared size causes a compile-time error.
  • Two-Dimensional and Multidimensional Arrays:

    • A two-dimensional array represents data structured into rows and columns: cpp int matrix[4][3]; // Declares an array with 4 rows and 3 columns (12 total elements) &nbsp;&nbsp;&nbsp;&nbsp;
  • Elements are accessed using two indices: matrix[row][col].

  • Two-dimensional arrays can be initialized using nested inner braces: cpp int arr[2][3] = { {15, 21, 9}, {84, 33, 72} }; &nbsp;&nbsp;&nbsp;&nbsp;

    • Higher-dimensional arrays (e.g., 3D arrays like int cube[3][7][4];) represent data across multiple dimensions, with total memory size scaling as the product of all dimension bounds.
  • Searching Algorithms:

    • Sequential (Linear) Search:
    • Sequentially steps through the array from index 00 to N−1N-1, comparing each element to the target value until a match is found or the end is reached.
    • Works on unsorted arrays, but searches take longer on large datasets (O(N)O(N) time complexity).
    • Binary Search:
    • Requires the array to be sorted beforehand. Compares the target value to the middle element of the array:
      • If the target matches the middle element, the search succeeds.
      • If the target is smaller, the search continues in the left half.
      • If the target is larger, the search continues in the right half.
    • Halves the remaining search space with each comparison (O(log⁡N)O(\log N) time complexity), making it vastly faster than linear search on large datasets.
  • Sorting Algorithms:

    • Selection Sort:
    • Divides the array into sorted and unsorted segments. Repeatedly finds the minimum element in the unsorted segment and swaps it with the first element of that segment.
    • Dry Run Trace on {56, 78, 33, 81, 12}:
      • Pass 1: Identifies minimum value 12 at index 4; swaps with index 0: {12, 78, 33, 81, 56}.
      • Pass 2: Scans indices 1–4; finds minimum 33 at index 2; swaps with index 1: {12, 33, 78, 81, 56}.
      • Pass 3: Scans indices 2–4; finds minimum 56 at index 4; swaps with index 2: {12, 33, 56, 81, 78}.
      • Pass 4: Scans indices 3–4; finds minimum 78 at index 4; swaps with index 3: {12, 33, 56, 78, 81}. Array is now sorted.
    • Bubble Sort (Exchange Sort):
    • Steps through the array repeatedly, comparing adjacent elements and swapping them if they are out of order. Larger elements "bubble up" to the end of the array with each pass.
    • Dry Run Trace on {10, 30, 15, 25, 5}:
      • Pass 1:
      • Compare 10 & 30: No swap →\rightarrow {10, 30, 15, 25, 5}
      • Compare 30 & 15: Swap →\rightarrow {10, 15, 30, 25, 5}
      • Compare 30 & 25: Swap →\rightarrow {10, 15, 25, 30, 5}
      • Compare 30 & 5: Swap →\rightarrow {10, 15, 25, 5, 30} (Largest value 30 bubbles to the end)
      • Pass 2:
      • Compare 10 & 15: No swap →\rightarrow {10, 15, 25, 5, 30}
      • Compare 15 & 25: No swap →\rightarrow {10, 15, 25, 5, 30}
      • Compare 25 & 5: Swap →\rightarrow {10, 15, 5, 25, 30}
      • Pass 3:
      • Compare 10 & 15: No swap →\rightarrow {10, 15, 5, 25, 30}
      • Compare 15 & 5: Swap →\rightarrow {10, 5, 15, 25, 30}
      • Pass 4:
      • Compare 10 & 5: Swap →\rightarrow {5, 10, 15, 25, 30}. Array is fully sorted.

User-Defined Data Types: Structures, Unions, and Enumerations

  • Structures (struct):

    • A user-defined aggregate data type that groups variables of different types under a single identifier.
    • Declaration Syntax:cpp struct Student { int rollNo; // 2 bytes int marks; // 2 bytes float average; // 4 bytes char grade; // 1 byte }; // Notice the mandatory closing semicolon &nbsp;&nbsp;&nbsp;&nbsp;
    • The structure declaration establishes a new type blueprint but does not allocate memory on its own. Memory is only allocated when a structure variable is defined: Student s1; (allocates 2+2+4+1=92 + 2 + 4 + 1 = 9 contiguous bytes).
    • Members are accessed using the dot member access operator: s1.rollNo = 101;.
    • Structure variables can be initialized using braced lists: Student s1 = {101, 850, 85.0, 'A'};.
    • Two structure variables of the identical type can be directly assigned using =: s2 = s1; performs a shallow byte-by-byte copy of all member fields.
  • Arrays of Structures and Structures with Arrays:

    • A structure can contain array members (e.g., int marks[5];), with elements accessed via combined syntax: s1.marks[2] = 95;.
    • An array of structures stores collections of structured records: Student classList[50]; creates 50 distinct Student instances, accessed via classList[i].rollNo.
  • Nested Structures:

    • A structure can include an instance of another structure as a member: cpp struct Date { int day, month, year; }; struct Employee { int id; Date birthDay; // Nested structure member }; &nbsp;&nbsp;&nbsp;&nbsp;
    • Nested members are accessed by chaining dot operators: emp.birthDay.year = 1995;.
  • Unions (union):

    • Similar to a structure, but all members share the exact same memory space. The total memory allocated for a union equals the size of its largest member.
    • Only one member can hold a valid value at any given time; writing to a new member overwrites existing data across all other members.
    • Syntax:cpp union Data { char ch; // 1 byte int n; // 2 bytes float f; // 4 bytes }; // Total size is 4 bytes (the size of float) &nbsp;&nbsp;&nbsp;&nbsp;
  • Enumerations (enum):

    • A user-defined type composed of named integer constants: cpp enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; &nbsp;&nbsp;&nbsp;&nbsp;
  • By default, the first enumerator is assigned 0, and each subsequent item increments by 1 (Sunday = 0, Monday = 1, etc.).

  • Values can be customized explicitly: enum Week { Sat = 1, Sun, Mon }; assigns Sat = 1, Sun = 2, Mon = 3.

Procedural Modularization: Functions, Scope, and Storage Classes

  • Function Architecture and Syntax:

    • A function is a named, reusable subprogram designed to execute a specific task.
    • Function Prototype (Declaration): Informs the compiler of the function's name, return type, and parameter types before its definition: int calculateSum(int, int);.
    • Function Definition: Contains the actual implementation code: cpp int calculateSum(int a, int b) // Function header { return a + b; // Function body } &nbsp;&nbsp;&nbsp;&nbsp;
    • Function Call: Statement that invokes the function: int res = calculateSum(5, 10);.
  • Parameter Passing Mechanisms:

    • Pass-by-Value: The default mechanism. Copies the value of the actual argument into the function's local parameter. Modifications inside the function alter the local copy only and have no effect on the original argument in the calling environment.
    • Pass-by-Reference: Passes the actual memory address of the argument using reference declarators (&). The parameter becomes an alias for the original argument, so any modifications inside the function directly alter the original variable in the caller: cpp void swap(int &x, int &y) { int temp = x; x = y; y = temp; } &nbsp;&nbsp;&nbsp;&nbsp;
  • Return Statement:

    • Returns execution control back to the caller, optionally returning a single computed value: return expression;. A function returning void exits using return; without an expression.
  • Scope and Lifetime of Variables:

    • Local (Automatic) Variables: Declared inside a function or block. Visible only within that block; created upon entry and destroyed immediately upon exiting the block.
    • Global Variables: Declared outside all function blocks. Visible to all functions throughout the file; allocated in global data space upon program start and persist until program termination.
    • Static Local Variables: Declared inside a function using the static keyword. Retains its local function scope, but persists across multiple function calls without being destroyed, retaining its value between invocations. Initialized exactly once on the first function call.
    • Register Variables: Declared using the register keyword. Suggests that the compiler store the variable in a high-speed CPU register rather than RAM to accelerate loop counters; compilers can override this request if registers are unavailable.
  • Functions with Arrays and Structures:

    • Passing an array to a function automatically passes the memory address of its first element by reference; the array is not duplicated in memory: void printArray(int arr[], int size);.
    • Multi-dimensional array parameters must explicitly declare all dimension bounds except the first: void processMatrix(int matrix[][4], int rows);.
    • Structures can be passed by value (copying all fields) or by reference (void update(Student &s);), and can also be returned from functions.
  • Advanced Function Techniques:

    • Default Arguments: Default parameter values declared in the function prototype: void show(int n = 100);. All default parameters must be positioned to the right of non-default parameters.
    • Inline Functions: Functions prefixed with the inline keyword. Suggests to the compiler that it replace the function call directly with the function's body code during compilation, eliminating the runtime overhead of a function call. Best reserved for short, frequently executed functions.
    • Function Overloading: Declaring multiple functions sharing the same name but with different parameter signatures (different number, types, or order of parameters). The return type alone cannot be used to distinguish overloaded functions.
    • Recursion: A programming technique where a function calls itself directly or indirectly. Must include a clear base case to terminate execution; otherwise, endless recursive calls trigger a stack overflow error.
  • Standard Library Functions Across Headers:

    • <conio.h>: Console I/O helpers:
    • clrscr(): Clears the console text screen.
    • clreol(): Clears from the current cursor position to the end of the line.
    • getch(): Reads a single character from the keyboard without echoing it to the screen; does not wait for Enter.
    • getche(): Reads a single character from the keyboard and echoes it to the screen.
    • kbhit(): Checks whether a keyboard key has been pressed (returns non-zero if a key was pressed; otherwise 0).
    • gotoxy(x, y): Moves the console cursor to horizontal column x (0–790–79) and vertical row y (0–240–24).
    • <stdio.h>: Standard C I/O utilities: getchar(), putchar(), gets(), puts().
    • <math.h>: Common mathematical operations: abs(int), fabs(double) (absolute value), ceil(x) (rounds up), floor(x) (rounds down), sin(rad), cos(rad), tan(rad), log(x) (natural logarithm), log10(x), pow(base, exp), sqrt(x), fmod(x, y) (floating-point remainder).
    • <ctype.h>: Character classification and transformation: isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), isprint(), ispunct(), tolower(), toupper().

Memory Management and Pointer Manipulation

  • Pointers and Memory Addressing:

    • Computer memory consists of sequential, byte-level memory locations, each assigned a unique hexadecimal address.
    • The address-of operator (&) returns the memory address of an operand variable: cout << &x;.
    • A pointer is a variable specifically designed to hold the memory address of another variable.
    • Declaration Syntax: int *ptr; (declares a pointer targeting an integer).
    • The dereference (indirection) operator (*) accesses or updates the data stored at the address held by the pointer: *ptr = 25;.
  • The void* (Generic) Pointer:

    • A pointer declared as void *ptr; can hold the memory address of any data type (int, float, char).
    • A void* pointer cannot be dereferenced directly without first explicitly casting it to the target concrete pointer type.
  • Pointer Arithmetic:

    • Only addition and subtraction operations are legal on pointers.
    • When an integer nn is added to or subtracted from a pointer, the address advances or retreats by n×sizeof(base_type)n \times \text{sizeof}(\text{base\_type}) bytes:
    • If int *p = 1000;, executing p++; advances the address to 1002 (on a 2-byte integer platform) or 1004 (on a 4-byte system).
    • char *cp = 1000; cp++; advances to 1001.
  • Pointers and Array Navigation:

    • An array's name acts as a constant pointer to its first element: int arr[5]; means arr equals &arr[0].
    • Array elements can be traversed using pointer arithmetic: *(arr + i) is functionally identical to arr[i].
  • Pointers to Structures and Arrow (->) Operator:

    • When referencing a structure through a pointer, structure members are accessed using the arrow operator (->) rather than the dot operator: ptr->rollNo = 10; is shorthand for (*ptr).rollNo = 10;.
  • Dynamic Memory Allocation (new and delete):

    • System memory is divided into five logical segments:
    • Global Namespace: Stores global and static variables.
    • Registers: Fast storage located directly within the CPU.
    • Code Space: Holds compiled binary instructions.
    • Stack: Automatically manages local variables, parameters, and function call frames.
    • Free Store (Heap): Memory pool available for dynamic runtime allocation.
    • The new Operator: Allocates memory from the heap dynamically during execution and returns its address: int *ptr = new int; or int *arr = new int[50];.
    • The delete Operator: Releases dynamically allocated heap memory back to the system: delete ptr; or delete[] arr; for dynamically created arrays.
    • Memory Leaks: Occur when dynamically allocated heap memory loses all pointer references without first being freed via delete. The orphaned memory remains locked and unusable until the entire program terminates.

Character Array Manipulation and String Handling Library Functions

  • C-Style Strings:

    • In C++, a string is represented as a one-dimensional array of char elements ending with an explicit null terminator character ('\0', ASCII value 0).
    • Array sizing must account for the null terminator: storing the 5-letter word "HELLO" requires an array of at least 6 characters (char str[6];).
  • Standard <string.h> Library Functions:

    • strlen(s): Returns the number of characters in string s, excluding the null terminator.
    • strcpy(dest, src): Copies the null-terminated string src into buffer dest.
    • strncpy(dest, src, n): Copies up to n characters from src to dest.
    • strcat(dest, src): Appends a copy of src to the end of dest.
    • strncat(dest, src, n): Appends up to n characters from src to dest.
    • strcmp(s1, s2): Performs case-sensitive lexicographical comparison. Returns 0 if strings are identical, a negative value if s1 < s2, and a positive value if s1 > s2.
    • stricmp(s1, s2): Performs case-insensitive string comparison.
    • strncmp(s1, s2, n): Compares up to n characters of two strings with case-sensitivity.
    • strchr(s, c): Returns a pointer to the first occurrence of character c in string s, or NULL if not found.
    • strrchr(s, c): Returns a pointer to the last occurrence of character c in string s.
    • strstr(s1, s2): Locates the first occurrence of substring s2 within string s1.
    • strlwr(s): Converts all alphabetical characters in s to lowercase.
    • strupr(s): Converts all alphabetical characters in s to uppercase.
    • strrev(s): Reverses the characters within string s in-place.
    • memset(buf, ch, n): Fills the first n bytes of memory area buf with character ch.
    • memcpy(dest, src, n): Copies n bytes from src directly to dest (faster than memmove, but does not handle overlapping regions safely).
    • memmove(dest, src, n): Copies n bytes from src to dest, correctly handling overlapping memory regions.
    • memcmp(b1, b2, n): Compares the first n bytes of memory buffers b1 and b2.
    • memchr(buf, ch, n): Searches the first n bytes of buf for the first occurrence of ch.
    • strtok(str, delim): Breaks string str into a series of tokens delimited by characters in delim.
    • strspn(s1, s2): Returns the length of the initial segment of s1 consisting entirely of characters present in s2.
    • strcspn(s1, s2): Returns the length of the initial segment of s1 consisting entirely of characters not present in s2.

Object-Oriented Programming: Classes, Objects, and Encapsulation

  • Core OOP Paradigms:

    • Encapsulation: Packaging data members and their manipulating member functions within a unified class boundary, hiding internal state details.
    • Information Hiding: Restricting direct external access to internal object state using access specifiers.
    • Abstraction: Exposing an object's essential interface while concealing the complex underlying implementation mechanics.
  • Class Specifications and Access Control:

    • A class serves as an abstract blueprint or user-defined type used to instantiate objects.
    • Class Declaration:cpp class ClassName { private: // Accessible only to member functions and friend entities (default) int data; public: // Accessible anywhere the object is visible void setData(int d) { data = d; } int getData() { return data; } }; // Notice the mandatory closing semicolon &nbsp;&nbsp;&nbsp;&nbsp;
  • Constructors and Destructors:

    • Constructors: Special member functions invoked automatically whenever an object of that class is created. They have no return type (not even void) and share the identical name as the class:
    • Default Constructor: Takes no parameters.
    • Parameterized Constructor: Accepts arguments to initialize data members to specified values.
    • Overloaded Constructors: Multiple constructors defined with distinct parameter lists.
    • Copy Constructor: Initializes a new object as a copy of an existing object of the same class: ClassName(const ClassName &obj);.
    • Destructors: Special member functions invoked automatically when an object goes out of scope or is deleted from memory. Named using a tilde (~) prefix followed by the class name. Takes no parameters, has no return type, and cannot be overloaded (each class can have at most one destructor).
  • Static Members in Classes:

    • Static Data Members: Declared using the static keyword. A single variable is shared among all instantiated objects of the class rather than being duplicated per object. Must be explicitly defined in global file scope using the scope resolution operator: int ClassName::count = 0;.
    • Static Member Functions: Member functions that can be invoked without referencing an object instance: ClassName::displayCount();. Can only access static data members or other static member functions within the class.
  • Friend Functions and Friend Classes:

    • Friend Function: A non-member function granted explicit access to a class's private and protected members via a friend declaration inside the class body.
    • Friend Class: Declaring friend class B; inside class A grants all member functions of class B direct access to A's private and protected members.

Operator Overloading: Customizing Operators for User-Defined Types

  • Principles of Operator Overloading:

    • Extends C++ built-in operators (+, -, *, ==, ++) to work seamlessly with user-defined class objects.
    • Overloaded operators are implemented by writing functions named with the operator keyword followed by the target operator symbol.
    • Cannot create new operator symbols, alter operator precedence, change associativity rules, or modify how operators act on built-in types.
  • Overloading Unary Operators:

    • Member functions overloading unary operators take no arguments because the single operand is the calling object instance (this): cpp class Counter { private: int count; public: Counter() : count(0) {} // Overloading Prefix Increment (++c) Counter operator++() { Counter temp; temp.count = ++count; return temp; } // Overloading Postfix Increment (c++) Counter operator++(int) // Dummy int parameter distinguishes postfix { Counter temp; temp.count = count++; return temp; } }; &nbsp;&nbsp;&nbsp;&nbsp;
  • Overloading Binary Operators:

    • When a binary operator is overloaded as a member function, the left operand acts as the calling object, while the right operand is passed as an explicit argument: cpp class Complex { private: float real, imag; public: Complex(float r = 0, float i = 0) : real(r), imag(i) {} Complex operator+(const Complex &other) { return Complex(real + other.real, imag + other.imag); } bool operator==(const Complex &other) { return (real == other.real && imag == other.imag); } }; &nbsp;&nbsp;&nbsp;&nbsp;

Class Hierarchies, Inheritance, and Containership

  • Inheritance Paradigms and Benefits:

    • A mechanism allowing a new derived class (child/subclass) to inherit members from an existing base class (parent/superclass).
    • Enhances software modularity, minimizes duplicate code, and facilitates clear hierarchical data modeling.
    • Syntax:cpp class Derived : access_specifier Base { // derived class additions }; &nbsp;&nbsp;&nbsp;&nbsp;
  • The protected Access Specifier:

    • Members marked protected remain inaccessible to outside client code (like private members), but can be freely accessed by member functions of derived classes.
  • Inheritance Access Modes:

    • Public Inheritance: Public members of the base class remain public in the derived class; protected members remain protected.
    • Protected Inheritance: Both public and protected members of the base class become protected members within the derived class.
    • Private Inheritance (Default): Public and protected members of the base class become private members within the derived class, preventing further downstream inheritance.
    • Note: Private members of a base class are never directly accessible to derived classes under any inheritance mode.
  • Constructors and Destructors in Class Hierarchies:

    • When an object of a derived class is created, base class constructors execute first, followed by derived class constructors.
    • When the derived object is destroyed, destructors execute in reverse order: the derived class destructor runs first, followed by the base class destructor.
    • Arguments can be passed to base class constructors using constructor initialization lists: cpp Derived(int x, int y) : Base(x) { // initialize derived members with y } &nbsp;&nbsp;&nbsp;&nbsp;
  • Member Function Overriding:

    • Occurs when a derived class defines a member function with the exact same name and parameter signature as a function in its base class.
    • The derived class's implementation hides the base version. To invoke the hidden base function explicitly, use the scope resolution operator: Base::display();.
  • Multiple Inheritance, Ambiguities, and Virtual Base Classes:

    • Multiple inheritance occurs when a derived class inherits directly from two or more base classes: class C : public A, public B { };.
    • Ambiguity Errors: Occur when multiple base classes share a function with the same name. Resolved by qualifying calls with the intended class name (obj.A::show();) or overriding the function inside the derived class.
    • The Diamond Problem: Arises when two derived classes share a common base, and a fourth class inherits from both derived classes, causing duplicate base class subobjects to be included. Solved using virtual base classes: cpp class Base { public: int val; }; class Child1 : virtual public Base { }; class Child2 : virtual public Base { }; class GrandChild : public Child1, public Child2 { }; // Only ONE copy of Base is inherited &nbsp;&nbsp;&nbsp;&nbsp;
  • Containership (Composition / Aggregation):

    • An alternative design pattern where a class includes an instance of another class as a member field (modeling a "has-a" relationship, as opposed to inheritance's "is-a" relationship).

Polymorphism, Virtual Functions, and Dynamic Binding

  • Polymorphism and Method Binding:

    • Polymorphism ("many forms") enables objects of different derived types to respond uniquely to identical function calls.
    • Early (Static) Binding: Function calls are resolved at compile time based on the static pointer or reference type.
    • Late (Dynamic) Binding: Function calls are resolved at runtime based on the actual type of object being pointed to. Implemented via virtual functions.
  • Virtual Functions:

    • Declared in a base class using the virtual keyword: virtual void draw();.
    • When a base class pointer points to a derived class object, calling a virtual function executes the derived class's overridden version rather than the base version.
  • Pure Virtual Functions and Abstract Base Classes:

    • A pure virtual function is declared with an assignment to zero (= 0) and contains no body in the base class: cpp virtual void render() = 0; // Pure virtual function &nbsp;&nbsp;&nbsp;&nbsp;
  • An abstract class is any class that contains at least one pure virtual function. It cannot be directly instantiated to create objects; it exists solely to define an interface for derived classes to implement.

Generic Programming: Function and Class Templates

  • Concept of Templates:

    • Enables developers to write generic, type-independent blueprints for functions and classes, with concrete data types specified later upon instantiation.
  • Function Templates:

    • Declaration Syntax:cpp template <class T> T findMax(T a, T b) { return (a > b) ? a : b; } &nbsp;&nbsp;&nbsp;&nbsp;
    • The compiler inspects the arguments provided in calls (e.g., findMax(5, 10) vs. findMax(3.5, 1.2)) and generates concrete, type-specific function definitions behind the scenes.
  • Class Templates:

    • Creates generic classes capable of storing and processing arbitrary data types: cpp template <class T> class Container { private: T element; public: Container(T arg) : element(arg) {} T getElement() { return element; } }; &nbsp;&nbsp;&nbsp;&nbsp;
  • Instantiation: Must explicitly specify concrete types inside angle brackets: Container<int> intObj(100); Container<float> floatObj(25.5);.

File Streams and Persistent Storage Operations

  • C++ File Stream Class Hierarchy (<fstream.h>):

    • ios: Base class for stream handling; tracks error and status flags.
    • istream: Handles input operations; provides cin.
    • ostream: Handles output operations; provides cout, cerr (unbuffered error), clog (buffered error).
    • ifstream: Derived from istream; dedicated to file input (reading).
    • ofstream: Derived from ostream; dedicated to file output (writing).
    • fstream: Derived from iostream; supports simultaneous file reading and writing.
  • File Opening Modes and Operations:

    • Files can be opened using open() or via constructor invocation: ofstream outFile("data.txt", ios::out | ios::app);.
    • Common Mode Flags:
    • ios::in: Open for reading.
    • ios::out: Open for writing (truncates existing files by default).
    • ios::app: Append output to the end of the file.
    • ios::ate: Open and seek to the end of the file immediately.
    • ios::trunc: Discard existing file contents upon opening.
    • ios::binary: Process data in raw binary mode rather than formatted text.
    • ios::nocreate: Fails to open if the file does not already exist.
    • ios::noreplace: Fails to open if the target file already exists.
  • Checking File State and Closing Streams:

    • Check whether a file opened successfully using boolean stream evaluation: if (!outFile) { /* handle error */ } or outFile.is_open().
    • Always release file handles when finished: outFile.close();.
  • Text vs. Binary File Processing:

    • Text (Formatted) I/O: Uses stream operators << and >>, or line-by-line reading with file.getline(buffer, size). Stores numbers as human-readable character strings.
    • Binary I/O: Stores raw memory bytes directly to disk, preserving exact binary representations and saving storage space:
    • Writing Binary Records: file.write((char*)&object, sizeof(object));
    • Reading Binary Records: file.read((char*)&object, sizeof(object));
    • Detecting End-of-File: The member function file.eof() returns true (11) as soon as a read operation attempts to read past the end of the file.
  • Random Access and File Pointers:

    • File streams maintain internal position indicators:
    • Get Pointer: Tracks the next position to read from (manipulated via seekg()).
    • Put Pointer: Tracks the next position to write to (manipulated via seekp()).
    • Seek Syntax: file.seekg(offset, origin);
    • offset: Byte offset distance (positive to move forward, negative to move backward).
    • origin: Seek reference base point:
      • ios::beg: Beginning of the file.
      • ios::cur: Current file pointer position.
      • ios::end: End of the file.

Fundamental and Advanced Data Structures

  • Data Structure Classifications:

    • Linear Data Structures: Elements form a sequential chain where each element has distinct predecessors and successors (e.g., Arrays, Stacks, Queues, Linked Lists).
    • Non-Linear Data Structures: Elements exhibit hierarchical or interconnected relationships (e.g., Trees, Graphs).
  • Linked Lists:

    • Dynamic data structures made of self-referential nodes linked via pointers.
    • Singly-Linked List: Each node stores data and a single pointer pointing to the next node in the sequence. The final node's pointer is set to NULL.
    • Doubly-Linked List: Nodes maintain two pointers: previous and next, enabling bidirectional traversal.
    • Circularly-Linked List: The final node links back to the first node instead of holding NULL, forming a continuous loop.
  • Stack Data Structure (LIFO):

    • Follows a Last-In, First-Out (LIFO) access pattern. Insertion and deletion occur strictly at a single end termed the top of the stack.
    • Core Operations:
    • push(val): Places a new item onto the top of the stack. Fails with a stack overflow error if the stack is full.
    • pop(): Removes and returns the item currently at the top of the stack. Fails with a stack underflow error if the stack is empty.
  • Queue Data Structure (FIFO):

    • Follows a First-In, First-Out (FIFO) access pattern.
    • Elements are inserted at the rear (enqueue) and removed from the front (dequeue).
  • Tree Concepts and Binary Trees:

    • Tree Terminology:
    • Root: Topmost node in the tree hierarchy with no incoming parent edges.
    • Edge: Directed connection link from a parent node to a child node.
    • Leaf (Terminal Node): A node with no children.
    • Subtree: Any node below the root viewed as the root of its own sub-hierarchy.
    • Height / Depth: The length of the longest path from the root down to a leaf.
    • Binary Tree: A tree where every node has at most two children, designated the left child and right child.
    • Binary Search Tree (BST): A binary tree structured such that for any node NN:
    • All values in NN's left subtree are strictly less than NN's value.
    • All values in NN's right subtree are strictly greater than NN's value.
    • Tree Traversal Algorithms:
    • Preorder: Visit Root →\rightarrow Traverse Left Subtree →\rightarrow Traverse Right Subtree.
    • Inorder: Traverse Left Subtree →\rightarrow Visit Root →\rightarrow Traverse Right Subtree (processes BST nodes in ascending sorted order).
    • Postorder: Traverse Left Subtree →\rightarrow Traverse Right Subtree →\rightarrow Visit Root.
    • BST Node Deletion Cases:
    • Case 1 (Leaf Node): Delete the node and set the parent's pointer to NULL.
    • Case 2 (Single Child): Bypass the node by linking its parent directly to its child.
    • Case 3 (Two Children): Locate the node's inorder successor (the smallest value in its right subtree), copy the successor's value into the target node, and recursively delete the successor node.
  • Graph Theory Fundamentals:

    • A graph consists of a set of vertices (nodes) connected by edges (arcs).
    • Directed Graph (Digraph): Edges have direction, represented by arrows indicating one-way paths from a source vertex to a target vertex.
    • Undirected Graph: Edges are bidirectional connections between vertex pairs.
    • Paths and Cycles: An acyclic path visits no vertex more than once; a cyclic path contains a loop that starts and ends at the identical vertex.

Review Exercises, Comprehensive Analyses, and Diagnostic Questions

  • Sequential 4-Digit Integer Decomposition Without Branching or Loops:

    • Problem Statement: Read a 4-digit positive integer (e.g., 45674567), separate its digits using division (/) and modulus (%), and compute both the sum of its digits (4+5+6+7=224+5+6+7 = 22) and the reversed number (76547654).
    • Step-by-Step Mathematical Derivation:
    • Let N=4567N = 4567.
    • Digit 4 (d4d_4): Extract using integer division: d4=N/1000=4567/1000=4d_4 = N / 1000 = 4567 / 1000 = 4.
    • Reduce remainder: R1=N%1000=567R_1 = N \% 1000 = 567.
    • Digit 3 (d3d_3): Extract: d3=R1/100=567/100=5d_3 = R_1 / 100 = 567 / 100 = 5.
    • Reduce remainder: R2=R1%100=67R_2 = R_1 \% 100 = 67.
    • Digit 2 (d2d_2): Extract: d2=R2/10=67/10=6d_2 = R_2 / 10 = 67 / 10 = 6.
    • Digit 1 (d1d_1): Extract final digit: d1=R2%10=67%10=7d_1 = R_2 \% 10 = 67 \% 10 = 7.
    • Sum of Digits: Sum=d1+d2+d3+d4=7+6+5+4=22\text{Sum} = d_1 + d_2 + d_3 + d_4 = 7 + 6 + 5 + 4 = 22.
    • Reversed Number: Reverse=(d1×1000)+(d2×100)+(d3×10)+d4=7000+600+50+4=7654\text{Reverse} = (d_1 \times 1000) + (d_2 \times 100) + (d_3 \times 10) + d_4 = 7000 + 600 + 50 + 4 = 7654.
    • Implementation Program: ```cpp

    include

    include

    void main() { clrscr(); int num, d1, d2, d3, d4, rem, sum, rev; cout << "Enter a 4-digit positive integer: "; cin >> num; d4 = num / 1000; rem = num % 1000; d3 = rem / 100; rem = rem % 100; d2 = rem / 10; d1 = rem % 10; sum = d1 + d2 + d3 + d4; rev = (d1 * 1000) + (d2 * 100) + (d3 * 10) + d4; cout << "Sum of digits: " << sum << endl; cout << "Reversed number: " << rev << endl; getch(); }     ```

  • Detailed Code Analysis and Output Traces:

    • Relational and Arithmetic Expression Evaluation:
    • If int i = 1, j = 2, k = 3; double x = 1.0, y = 2.0, z = 3.0;:
      • Expression: i + j == k evaluates to (1 + 2 == 3) →\rightarrow 3 == 3 →\rightarrow 1 (True).
      • Expression: k - i < y > x evaluates as ((3 - 1) < 2.0) > 1.0 →\rightarrow (2 < 2.0) > 1.0 →\rightarrow 0 > 1.0 →\rightarrow 0 (False).
      • Expression: z - x + 1 != j + k - 2 * i evaluates as ((3.0 - 1.0) + 1) != ((2 + 3) - (2 * 1)) →\rightarrow 3.0 != 3 →\rightarrow 0 (False).
    • Loop Output Tracing:
    • Trace of postfix and prefix interaction: cpp int a = 10; cout << a++ << endl; // Prints 10, then increments a to 11 cout << ++a << endl; // Increments a to 12, then prints 12 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  • Trace of pointer arithmetic on arrays: cpp int num[5] = {3, 4, 6, 2, 1}; int *p = num; cout << *p << " " << *(p + 1); // Prints "3 4" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Compile-Time vs. Runtime vs. Logical Errors (Diagnostic Guide):

    • Multiplying two numbers when the user intended to add them: Logical Error (program compiles and runs, but calculates the wrong result).
    • Dividing by zero during execution: Run-time Error (violates mathematical processor rules, terminating the program immediately).
    • Forgetting a closing delimiter } or statement terminator ;: Compile-time (Syntax) Error (violates grammar, preventing object code generation).
    • Spelling a word wrong in an output string literal: Logical Error (runs smoothly, but displays an incorrect message).
    • Accessing an out-of-bounds array index (arr[10] in an array of size 5): Run-time Error or Undefined Memory Behavior (reads unallocated memory without a compiler warning).