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
- Step 3: Input
- Step 4: Total =
- Step 5: Display Total
- Step 6: Exit
- Circle Area Computation ():
- Step 1: Start
- Step 2: Input radius in
- Step 3:
- Step 4: Print area
- Step 5: End
- Kinematic Distance Traveled ():
- Step 1: Start
- Step 2: Input average speed in
- Step 3: Input time in
- Step 4:
- Step 5: Print
- Step 6: End
- Sum of First 50 Natural Numbers:
- Step 1: Start
- Step 2: Set
- Step 3: Set
- Step 4: Repeat Steps 5 and 6 while ()
- Step 5:
- Step 6:
- 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., ).
- 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 (s and s). 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.
- Compiler: Scans and translates an entire high-level source code module into machine language all at once, producing a permanent, reusable object file (
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 (
Totalis distinct fromtotal). 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
#includedirective instructs the preprocessor to parse and insert the entire contents of a specified header file into the source file. - Header files (ending with
.hin traditional C++) contain declarations, standard library function definitions, macros, and global constants. - Inclusion Syntax:
#include <iostream.h>searches system default directories (typically theINCLUDEsubdirectory);#include "myheader.h"searches the current local working directory first before checking system paths. iostream.hprovides definitions for fundamental stream objects:cout(console output) andcin(console input).
- Preprocessor directives start with a hash symbol (
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 } - 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.
- Execution of every standard C++ application begins at the first statement inside
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\BINholds binaries and IDE executables (TC.EXE);TC\INCLUDEcontains standard library header files;TC\LIBstores 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) Saving Compiling (.obj) Linking (.exe) Loading (Loader places binary in memory) 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 likedoubel). 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 * 5instead ofTotal / 5, usinga < binstead ofa > 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.
- Syntax Errors: Occur when source code violates grammatical rules of C++ (e.g., omitting statement terminators
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.
- Single Stepping: Executing source instructions sequentially, one discrete line per keystroke (
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 to .short int: Allocates 2 bytes; range identical to 16-bitint( to ).unsigned int: Allocates 2 bytes; ignores sign bit; range from to .long int: Allocates 4 bytes; range from to .unsigned long int: Allocates 4 bytes; range from to .- 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 to ; provides 6 to 7 decimal places of precision.double: Uses 8 bytes; range from to ; provides 15 decimal digits of precision.long double: Uses 10 bytes; range from to ; 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 to (signed) or to (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 ( for positive, 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: , ).
- Add binary 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 to a 16-bit signed integer holding (
01111111 11111111) yields (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: (e.g., ), where is the mantissa () and is an integer exponent.
- Under IEEE 754 floating-point standards, computers store fractional numbers using sums of negative powers of two (, , , etc.).
- Decimal fractions such as and cannot be represented cleanly as finite sums of binary fractions, forming repeating binary expansions analogous to in base 10. Consequently, operations such as evaluate to approximate values (e.g., ).
doubleis preferred for scientific computing because its 53-bit significand provides 15–17 decimal digits of precision, significantly reducing accumulated rounding error compared tofloat'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 if and only if both bits are ; otherwise . - Bitwise OR (
|): Yields if either or both bits are ; yields only when both bits are . - Bitwise XOR (
^): Yields if the bits are different ( and ); yields if the bits are identical ( and , or and ). - Step-by-Step Computational Trace for Integers 5 and 3:
- Representation: ;
- Bitwise AND ():
- Bitwise OR ():
- Bitwise XOR ():
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
9minuteis 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(Ldenoteslong). - Floating-Point Literals:
50.75F(Fdenotesfloat),15.32(defaults todouble),52000.33L(denoteslong 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
#defineDirective:#define PI 3.141593performs text replacement before compilation. It lacks data type validation, does not allocate typed storage, and is invisible in the debugger symbol table. - The
constQualifier: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
5orx + 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 tox = x + 10;. Supported variants include+=,-=,*=,/=,%=.
- An expression is any sequence of operators and operands that evaluates to a single scalar value (e.g.,
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 / 2evaluates to3, not3.5). To retain fractional values, at least one operand must be a floating-point type (7.0 / 2yields3.5). - Modulus Operator (
%): Calculates the integer remainder of division; works strictly with integer data types (using%withfloatordoublecauses a compile error). Examples:10 % 3yields1,3 % 5yields3,0 % 4yields0.
- Five basic arithmetic operators: addition (
Increment (
++) and Decrement (--) Operators:- Unary operators incrementing or decrementing a variable's value by . 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.
- Unary operators incrementing or decrementing a variable's value by . Can only be applied to modifiable lvalues (variables), not literal constants or composite expressions (
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 with , , , :
- Sub-expression evaluates to .
- Inside parentheses: .
- Remainder: .
- Parenthesized expression resolves to .
- Main expression becomes: .
- Left-to-right evaluation: .
- Division: .
- Multiplication: .
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:
charintlongfloatdoublelong 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
The
sizeofOperator and Program Comments:sizeofis a compile-time unary operator returning the memory footprint in bytes for a given data type, variable, or literal value (e.g.,sizeof(char)returns1,sizeof(int)returns2or4,sizeof(double)returns8).- 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; - Quotation marks distinguish string literals from variable names (
cout << "a";displays the lettera, whereascout << a;prints the value stored in variablea).
- Multiple insertion operations can be chained together in a single statement:
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.
- Formatted non-printing characters prefixed with a backslash (
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 toncolumns. Output is right-justified by default. If the value exceedsncharacters, 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 withfixed. 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 asetwformatted column with the fill characterch(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;.
- The extraction operator (
Buffer Mechanics and Mixing
cin >>withgetline():- When reading data using
cin >>, non-whitespace characters are parsed and extracted, but trailing delimiters (like the newline charactergenerated by pressing Enter) remain in the input buffer.
- When reading data using
cin.getline(str, len)reads all characters up to the next newline, stores them instr, and removes thefrom the buffer.When
cin >> variable;is immediately followed bycin.getline(str, len);, thegetline()call reads the leftoverfrom the previous input and immediately returns an empty string without waiting for user input.Resolution via
cin.ignore(): Callingcin.ignore()discards the leftover newline character from the buffer before invokinggetline():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; }
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() orfalse(): - 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
truein conditional contexts, while zero (0) evaluates tofalse.
- Relational operators compare two values and evaluate to a boolean result:
The Simple
ifStatement 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; - 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
ifhandles actions when a condition is true, but cannot directly specify an alternative path when the condition evaluates to false.
The Two-Way
if-elseConstruct:- 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 }
- Guarantees that exactly one of two alternate statement blocks will execute while the other is skipped:
Multi-Way
if-else-ifLadders:- 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
elseblock executes as a fallback.
- 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
Nested
ifStatements and the DanglingelseAmbiguity:- An
ifstatement placed inside anotheriforelseblock creates a nested selection structure. - The Dangling Else Problem: When an
elseclause follows nestedifstatements without explicit curly braces, it pairs with the closest precedingifthat lacks anelse:cpp if (x > 0) if (y > 0) cout << "Both positive"; else cout << "Matches inner if (y <= 0)!";
- An
To bind the
elseto the outerif, enclose the inner construct in curly braces:cpp if (x > 0) { if (y > 0) cout << "Both positive"; } else { cout << "Matches outer if (x <= 0)!"; } 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 (!trueis false,!falseis true).
The Multi-Branch
switchSelection Structure:- Compares an integer or character expression against multiple constant values (
caselabels):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; } - Role of the
breakStatement: Terminates execution of theswitchblock. Ifbreakis omitted, execution falls through to subsequent case labels, executing their statements regardless of whether their constants match. - Comparison:
switchvs. Nestedif-else: switchonly evaluates discrete integer or character equality; it cannot directly test floating-point numbers or logical ranges (e.g.,x >= 10 && x <= 20).if-elsecan evaluate complex conditions, logical operators, floating-point numbers, and variable-to-variable comparisons.
- Compares an integer or character expression against multiple constant values (
The Conditional (Ternary) Operator (
?:):- A compact three-operand alternative to simple
if-elseexpressions:(condition) ? true_expression : false_expression;. - Evaluates the condition first. If true, it returns
true_expression; if false, it returnsfalse_expression(e.g.,max = (a > b) ? a : b;).
- A compact three-operand alternative to simple
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 ofgotocreates hard-to-maintain, unstructured code ("spaghetti code") and should generally be avoided.
- Directly transfers control to a labeled line in the same function:
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
whileLoop:- Executes a block of statements repeatedly as long as its condition evaluates to true:
cpp while (condition) { // loop body } - If the condition never becomes false, the loop runs indefinitely, creating an infinite loop.
- Executes a block of statements repeatedly as long as its condition evaluates to true:
The
do-whileLoop:- A posttest loop construct that always executes its body at least once:
cpp do { // loop body } while (condition); // Notice the mandatory trailing semicolon
- A posttest loop construct that always executes its body at least once:
The
forLoop:- A compact loop structure combining initialization, loop condition, and increment/decrement expressions in a single line:
cpp for (initialization; condition; update) { // loop body } - Execution Sequence:
- 1. Execute
initializationonce upon entering the loop. - 2. Evaluate
condition. If false, terminate the loop. - 3. Execute the statements within the loop body.
- 4. Execute the
updateexpression. - 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--).
- A compact loop structure combining initialization, loop condition, and increment/decrement expressions in a single line:
Jump Statements:
breakandcontinue: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 aforloop, 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 times and its inner loop runs times, the inner loop body executes a total of 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 , legal indices range from to .
- 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}; - 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.
- Elements can be initialized using a comma-separated list enclosed in curly braces:
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)
- A two-dimensional array represents data structured into rows and columns:
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} }; - 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.
- Higher-dimensional arrays (e.g., 3D arrays like
Searching Algorithms:
- Sequential (Linear) Search:
- Sequentially steps through the array from index to , 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 ( 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 ( 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
12at index 4; swaps with index 0:{12, 78, 33, 81, 56}. - Pass 2: Scans indices 1–4; finds minimum
33at index 2; swaps with index 1:{12, 33, 78, 81, 56}. - Pass 3: Scans indices 2–4; finds minimum
56at index 4; swaps with index 2:{12, 33, 56, 81, 78}. - Pass 4: Scans indices 3–4; finds minimum
78at index 4; swaps with index 3:{12, 33, 56, 78, 81}. Array is now sorted.
- Pass 1: Identifies minimum value
- 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
{10, 30, 15, 25, 5} - Compare 30 & 15: Swap
{10, 15, 30, 25, 5} - Compare 30 & 25: Swap
{10, 15, 25, 30, 5} - Compare 30 & 5: Swap
{10, 15, 25, 5, 30}(Largest value 30 bubbles to the end) - Pass 2:
- Compare 10 & 15: No swap
{10, 15, 25, 5, 30} - Compare 15 & 25: No swap
{10, 15, 25, 5, 30} - Compare 25 & 5: Swap
{10, 15, 5, 25, 30} - Pass 3:
- Compare 10 & 15: No swap
{10, 15, 5, 25, 30} - Compare 15 & 5: Swap
{10, 5, 15, 25, 30} - Pass 4:
- Compare 10 & 5: Swap
{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 - 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 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 distinctStudentinstances, accessed viaclassList[i].rollNo.
- A structure can contain array members (e.g.,
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 }; - Nested members are accessed by chaining dot operators:
emp.birthDay.year = 1995;.
- A structure can include an instance of another structure as a member:
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)
Enumerations (
enum):- A user-defined type composed of named integer constants:
cpp enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
- A user-defined type composed of named integer constants:
By default, the first enumerator is assigned
0, and each subsequent item increments by1(Sunday = 0,Monday = 1, etc.).Values can be customized explicitly:
enum Week { Sat = 1, Sun, Mon };assignsSat = 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 } - 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; }
Return Statement:
- Returns execution control back to the caller, optionally returning a single computed value:
return expression;. A function returningvoidexits usingreturn;without an expression.
- Returns execution control back to the caller, optionally returning a single computed value:
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
statickeyword. 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
registerkeyword. 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.
- Passing an array to a function automatically passes the memory address of its first element by reference; the array is not duplicated in memory:
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
inlinekeyword. 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.
- Default Arguments: Default parameter values declared in the function prototype:
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 columnx() and vertical rowy().<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.
- A pointer declared as
Pointer Arithmetic:
- Only addition and subtraction operations are legal on pointers.
- When an integer is added to or subtracted from a pointer, the address advances or retreats by bytes:
- If
int *p = 1000;, executingp++;advances the address to1002(on a 2-byte integer platform) or1004(on a 4-byte system). char *cp = 1000; cp++;advances to1001.
Pointers and Array Navigation:
- An array's name acts as a constant pointer to its first element:
int arr[5];meansarrequals&arr[0]. - Array elements can be traversed using pointer arithmetic:
*(arr + i)is functionally identical toarr[i].
- An array's name acts as a constant pointer to its first element:
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;.
- When referencing a structure through a pointer, structure members are accessed using the arrow operator (
Dynamic Memory Allocation (
newanddelete):- 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
newOperator: Allocates memory from the heap dynamically during execution and returns its address:int *ptr = new int;orint *arr = new int[50];. - The
deleteOperator: Releases dynamically allocated heap memory back to the system:delete ptr;ordelete[] 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
charelements 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];).
- In C++, a string is represented as a one-dimensional array of
Standard
<string.h>Library Functions:strlen(s): Returns the number of characters in strings, excluding the null terminator.strcpy(dest, src): Copies the null-terminated stringsrcinto bufferdest.strncpy(dest, src, n): Copies up toncharacters fromsrctodest.strcat(dest, src): Appends a copy ofsrcto the end ofdest.strncat(dest, src, n): Appends up toncharacters fromsrctodest.strcmp(s1, s2): Performs case-sensitive lexicographical comparison. Returns0if strings are identical, a negative value ifs1 < s2, and a positive value ifs1 > s2.stricmp(s1, s2): Performs case-insensitive string comparison.strncmp(s1, s2, n): Compares up toncharacters of two strings with case-sensitivity.strchr(s, c): Returns a pointer to the first occurrence of charactercin strings, orNULLif not found.strrchr(s, c): Returns a pointer to the last occurrence of charactercin strings.strstr(s1, s2): Locates the first occurrence of substrings2within strings1.strlwr(s): Converts all alphabetical characters insto lowercase.strupr(s): Converts all alphabetical characters insto uppercase.strrev(s): Reverses the characters within stringsin-place.memset(buf, ch, n): Fills the firstnbytes of memory areabufwith characterch.memcpy(dest, src, n): Copiesnbytes fromsrcdirectly todest(faster thanmemmove, but does not handle overlapping regions safely).memmove(dest, src, n): Copiesnbytes fromsrctodest, correctly handling overlapping memory regions.memcmp(b1, b2, n): Compares the firstnbytes of memory buffersb1andb2.memchr(buf, ch, n): Searches the firstnbytes ofbuffor the first occurrence ofch.strtok(str, delim): Breaks stringstrinto a series of tokens delimited by characters indelim.strspn(s1, s2): Returns the length of the initial segment ofs1consisting entirely of characters present ins2.strcspn(s1, s2): Returns the length of the initial segment ofs1consisting entirely of characters not present ins2.
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
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).
- Constructors: Special member functions invoked automatically whenever an object of that class is created. They have no return type (not even
Static Members in Classes:
- Static Data Members: Declared using the
statickeyword. 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.
- Static Data Members: Declared using the
Friend Functions and Friend Classes:
- Friend Function: A non-member function granted explicit access to a class's
privateandprotectedmembers via afrienddeclaration inside the class body. - Friend Class: Declaring
friend class B;inside classAgrants all member functions of classBdirect access toA's private and protected members.
- Friend Function: A non-member function granted explicit access to a class's
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
operatorkeyword 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.
- Extends C++ built-in operators (
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; } };
- Member functions overloading unary operators take no arguments because the single operand is the calling object instance (
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); } };
- 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:
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 };
The
protectedAccess Specifier:- Members marked
protectedremain inaccessible to outside client code (likeprivatemembers), but can be freely accessed by member functions of derived classes.
- Members marked
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 }
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
- Multiple inheritance occurs when a derived class inherits directly from two or more base classes:
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
virtualkeyword: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.
- Declared in a base class using the
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
- A pure virtual function is declared with an assignment to zero (
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; } - 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.
- Declaration Syntax:
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; } };
- Creates generic classes capable of storing and processing arbitrary data types:
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; providescin.ostream: Handles output operations; providescout,cerr(unbuffered error),clog(buffered error).ifstream: Derived fromistream; dedicated to file input (reading).ofstream: Derived fromostream; dedicated to file output (writing).fstream: Derived fromiostream; 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.
- Files can be opened using
Checking File State and Closing Streams:
- Check whether a file opened successfully using boolean stream evaluation:
if (!outFile) { /* handle error */ }oroutFile.is_open(). - Always release file handles when finished:
outFile.close();.
- Check whether a file opened successfully using boolean stream evaluation:
Text vs. Binary File Processing:
- Text (Formatted) I/O: Uses stream operators
<<and>>, or line-by-line reading withfile.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 () as soon as a read operation attempts to read past the end of the file.
- Text (Formatted) I/O: Uses stream operators
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:
previousandnext, 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 :
- All values in 's left subtree are strictly less than 's value.
- All values in 's right subtree are strictly greater than 's value.
- Tree Traversal Algorithms:
- Preorder: Visit Root Traverse Left Subtree Traverse Right Subtree.
- Inorder: Traverse Left Subtree Visit Root Traverse Right Subtree (processes BST nodes in ascending sorted order).
- Postorder: Traverse Left Subtree Traverse Right Subtree 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., ), separate its digits using division (
/) and modulus (%), and compute both the sum of its digits () and the reversed number (). - Step-by-Step Mathematical Derivation:
- Let .
- Digit 4 (): Extract using integer division: .
- Reduce remainder: .
- Digit 3 (): Extract: .
- Reduce remainder: .
- Digit 2 (): Extract: .
- Digit 1 (): Extract final digit: .
- Sum of Digits: .
- Reversed Number: .
- 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(); } ```
- Problem Statement: Read a 4-digit positive integer (e.g., ), separate its digits using division (
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 == kevaluates to(1 + 2 == 3)3 == 31(True). - Expression:
k - i < y > xevaluates as((3 - 1) < 2.0) > 1.0(2 < 2.0) > 1.00 > 1.00(False). - Expression:
z - x + 1 != j + k - 2 * ievaluates as((3.0 - 1.0) + 1) != ((2 + 3) - (2 * 1))3.0 != 30(False).
- Expression:
- 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
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" 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).