Program Control & Functions
Definition: Program control refers to the order in which instructions are
executed. In imperative languages (like C++ and Java), this flow is manipulated
using loops (iteration), function calls, and recursion.
1. Iteration vs. Recursion
A. Iteration (Looping)
The process of executing a set of instructions repeatedly until a condition
becomes false.
● Types:
○ Entry Controlled: Condition checked before execution (e.g., for,
while).
○ Exit Controlled: Body executes at least once before checking
condition (e.g., do-while).
● State: Maintained by a control variable (e.g., i = 0).
● Memory: Very efficient. Uses constant stack space O(1).
B. Recursion
A function calls itself to solve a smaller instance of the problem.
● Anatomy of Recursion:
1. Base Case: The condition that stops the recursion (prevents infinite
loops).
2. Recursive Step: The logic where the function calls itself with
modified parameters.
How Recursion Works in Memory (The Call Stack)
Every time a function is called, an Activation Record (Stack Frame) is pushed
onto the system stack.
● It holds: Local variables, Parameters, Return Address.
● When the Base Case is hit, the stack begins to "unwind" (pop frames off).
Types of Recursion (Exam Important)
1. Direct Recursion: Function A calls Function A.
2. Indirect Recursion: Function A calls B, and B calls A.
3. Tail Recursion: The recursive call is the very last action in the function.
○ Significance: Compilers can optimize this into a loop (Tail Call
Optimization), saving stack space. Java does not currently support
this optimization standardly; C++ compilers often do.
Comparison Table:
Feature Iteration Recursion
Complexity Lower overhead Higher overhead (context switching).
(faster).
Memory Constant space. Linear space O(N) (risk of
StackOverflow).
Readability Better for linear Better for Trees/Graphs/Divide &
tasks. Conquer.
2. Functions and Scope of Variables
A. Scope Rules
Scope defines the "visibility" of a variable—where in the code it can be
accessed.
1. Lexical Scope (Static Scope)
● Used by: C, C++, Java, Python.
● Rule: The scope is determined by the structure of the text at compile
time.
● Mechanism: If a variable isn't found in the current function, the compiler
looks in the parent block where the function was defined.
2. Dynamic Scope
● Used by: Lisp (early versions), Perl (optional), Bash.
● Rule: The scope is determined by the execution flow at runtime.
● Mechanism: If a variable isn't found, the program looks in the function
that called the current function.
Example Scenario:
C++
int x = 10;
void printX() { cout << x; }
void runner()
{
int x = 20;
printX();
}
● Lexical Scope (C++/Java): Prints 10. (Matches x where printX
was written).
● Dynamic Scope: Prints 20. (Matches x where printX was called).
3. Parameter Passing Mechanisms
This is the method by which data is transferred from the "caller" function to the
"callee" function.
A. Pass by Value (Call by Value)
● Concept: The function receives a copy of the actual data.
● Implication: Modifications inside the function do not affect the original
variable.
● Language Support: C, C++, Java (Always).
B. Pass by Reference (Call by Reference)
● Concept: The function receives an alias (reference) to the actual variable.
No copy is made.
● Implication: Modifications inside the function directly change the
original variable.
● Language Support: C++ (using &), C# (using ref). Java does NOT
support this.
C. Pass by Address (Call by Pointer)
● Concept: The memory address of the variable is passed explicitly.
● Implication: You can dereference the pointer to modify the original
value.
● Language Support: C, C++.
The "Java Trap" :
Candidates often think Java passes objects by reference. It does not.
● Java passes the value of the reference.
● If you pass an object Student s to a function:
○ You can change the student's name (because you have a copy of
the key to their house).
○ You cannot make s point to a completely different student object in
the caller's scope.
Code Illustration:
Java
// Java Code
void change(Dog d)
{
[Link] = "Max"; // WORKS: Changes the object's internal data.
d = new Dog("Fido"); // USELESS: Changes only the local copy of the pointer.
}
4. Binding of Variables & Functions
Binding is the connection between a "name" (like a function call) and the "code"
(memory address) that executes.
A. Static Binding (Early Binding)
● When: Occurs at Compile Time.
● Speed: Fast execution.
● What uses it?
○ C++: Non-virtual functions.
○ Java: static, private, and final methods.
○ Function Overloading (choosing the right method based on
arguments).
B. Dynamic Binding (Late Binding)
● When: Occurs at Runtime.
● Speed: Slower (requires lookup).
● What uses it?
○ Polymorphism (Overriding).
○ C++: Virtual functions (virtual void display()).
○ Java: All non-static/non-final methods.
Concept Check:
Parent p = new Child();
[Link]();
● If show() is static, the compiler looks at the type of the
reference (Parent) -> Static Binding.
● If show() is not static, the JVM looks at the actual object
(Child) -> Dynamic Binding.
5. Summary Table for Revision
Concept C++ Implementation Java Implementation
Scope Lexical (Block Scope). Lexical (Block Scope).
Global Vars Supported. Not supported (must be inside a
Class).
Pass by Value Yes (Default). Yes (Always).
Pass by Ref Yes (using &). No.
Recursion Supported (Tail recursion Supported (No standard tail
optimized). optimization).
Binding Static (default), Dynamic (via Dynamic (default), Static (via
virtual). static/final).
6. Functional vs. Logic Programming
A. Functional Programming (FP)
● Core Concept: Treats computation as the evaluation of mathematical
functions. It avoids "changing state" and "mutable data."
● Key Characteristics:
1. Immutability: Once a variable is defined, it cannot be changed
(e.g., x = x + 1 is illegal).
2. Pure Functions: The output depends only on the input. No "side
effects" (like printing to a console or changing a global variable).
3. First-Class Functions: Functions can be passed as arguments to
other functions (like variables).
4. Recursion over Loops: FP languages rarely use for or while loops;
they use recursion for iteration.
● Languages: Haskell, Scala, Lisp. (Java supports this via Lambda
Expressions & Streams).
B. Logic Programming (LP)
● Core Concept: Computation is based on formal logic. You define "what is
true" (Facts) and "how things relate" (Rules), and the computer figures out
the solution.
● Key Characteristics:
1. Declarative: You tell the computer what to do, not how to do it.
2. Facts & Rules:
■ Fact: Parent(John, Bob) (John is the parent of Bob).
■ Rule: Grandparent(X, Y) :- Parent(X, Z), Parent(Z, Y).
3. Backtracking: The system tries to solve a query; if it hits a dead
end, it goes back to the last decision point and tries a different
path.
● Languages: Prolog, Datalog.
Comparison Table for Exam:
Feature Functional Programming Logic Programming
Building Block Functions. Facts & Rules.
Execution Reduction (evaluating Unification & Backtracking
Model expressions). (searching for proofs).
State Immutable (cannot N/A (Relationships are defined, not
change). "variables").
Example Code f(x) = x * x mother(X, Y) :- parent(X, Y),
female(X).
7. Exception Handling as Control Flow
A. The Control Flow Change
When an exception is thrown:
1. The normal flow stops immediately.
2. The runtime unwinds the stack (pops stack frames) looking for a
matching catch block.
3. If found, control jumps directly to that catch block.
4. If not found, the program terminates (crashes).
B. The finally Block Trap
● Rule: The finally block ALWAYS executes, regardless of whether an
exception happened or not.
The "Return" Override Trap:
If a try block returns a value, but the finally block also returns a value, the
finally block's return wins.
Java
// Java Example
int test()
{
try { return 10; }
finally { return 20; }
}
// Output: 20 (The 10 is discarded!)
8. Advanced Binding:
A. Variable Binding Times
When is a variable actually connected to a memory address?
1. Compile Time: (Static variables in C/C++).
2. Load Time: Global variables (bound when the program starts loading into
memory).
3. Run Time: Local variables (bound when the function is called/pushed to
stack).
B. Static vs. Dynamic Type Checking
● Statically Typed (C++, Java): Types are checked during compilation. int x
= "Hello" throws an error before you run the code.
● Dynamically Typed (Python, JavaScript): Types are checked during
execution. You won't know there is an error until the line actually runs.
Variables, Scope & Storage Classes
1. Variable Basics: Declaration vs. Definition
In casual coding, we use these terms interchangeably. In exam theory
(especially C++), they are distinct.
● Declaration: Tells the compiler, "A variable of this name and type exists
somewhere." No memory is allocated yet.
○ Example (C++): extern int a;
● Definition: Tells the compiler, "Create this variable now." Memory is
allocated.
○ Example: int a; or int a = 10;
● Initialization: Assigning the first value to a variable at the moment of
definition.
Note: In Java, a declaration of a class variable int a; automatically
defines it with a default value (0). In C++, a local declaration int a;
defines it but leaves it with garbage value until initialized.
2. Scope of Variables (The "Where")
Scope determines the region of the code where a variable is visible and
accessible.
A. Block Scope (Local Scope)
● Definition: Variables declared inside curly braces { ... } are only visible
inside those braces.
● Context: Loops (for, while), if statements, and function bodies.
● C++ vs. Java Difference:
○ C++: You can declare a variable inside a block that has the same
name as a variable in the outer block (Shadowing).
○ Java: You cannot declare a variable inside an inner block if a
variable with the same name exists in the immediate outer local
block.
Java
void test()
{
int x = 10;
if (true) {
int x = 20; // COMPILER ERROR in Java! (Variable 'x' is already defined in
scope)
// VALID in C++ (Inner 'x' hides outer 'x')
}
}
B. Method/Function Scope
● Variables declared as parameters or inside a function are local to that
function.
● They die (are removed from the Stack) when the function returns.
C. Class Scope (Instance Variables)
● Variables declared inside a class but outside any method.
● Visibility: Accessible by all methods within the class.
● Lifetime: They exist as long as the Object exists on the Heap.
D. Global Scope (File Scope)
● C++: Variables declared outside all functions. Visible to the entire file (and
other files if extern is used).
● Java: No true Global Scope. Everything must be inside a class. The
closest equivalent is public static variables, which are accessible globally
via the Class Name.
3. Lifetime & Storage Classes
Storage Classes (C/C++ vs. Java): A Storage Class defines four properties of a
variable:
1. Scope: Where the variable is available.
2. Lifetime: How long the variable exists in memory.
3. Linkage: Visibility across different files.
4. Storage Location: Where it is stored (Stack, RAM/Data Segment, or CPU
Register).
Storage Keyword Storage Default Scope Lifetime
Class Location Value
Automatic auto Stack Garbage Local End of
(Block) Block
Register register CPU Garbage Local End of
Register (Block) Block
Static static Data Zero (0) Local or End of
Segment File* Program
External extern Data Zero (0) Global (All End of
Segment files) Program
I. Register Variables
● Keyword: register int count;
● Concept: Requests the compiler to store the variable in a CPU Register
instead of RAM (Main Memory) for faster access.
● Key Restrictions :
1. No Address Access: You cannot use the address-of operator (&) on
a register variable because registers do not have a memory
address like RAM does.
2. Size Limit: Usually limited to the size of a register (e.g., 1 word /
32-bit / 64-bit). You cannot store large arrays/structures here.
3. It is a Request, not a Command: If the CPU registers are full, the
compiler automatically converts it to a standard auto variable.
4. Scope: strictly local (Block scope). You cannot have a global
register variable (registers are too valuable to hold a value for the
whole program duration).
II. Static Variables
This is the most versatile storage class.
A. Internal Static (Local Static)
Defined inside a function.
● Persistence: It is initialized only once (first time the function is called). It
retains its value between function calls.
● Visibility: Only visible inside that function.
Code Example:
C
void func()
{
static int x = 0; // Initialized once.
x++;
printf("%d ", x);
}
// Calling func() three times prints: 1 2 3
// (If 'x' was 'auto', it would print: 1 1 1)
B. External Static (Global Static / File Scope)
Defined outside functions but with the static keyword.
● The "Linkage" Trap:
○ A normal global variable (int x;) can be accessed by other files
using extern.
○ A static global variable (static int x;) is private to the file. Other
files cannot see it.
● Use Case: Encapsulation in C. Hiding variables from other parts of the
program.
C. Static Functions
● Functions are extern (global) by default.
● Declaring static void helper() makes the function accessible only within
the file it is defined. It prevents naming conflicts with functions in other
files.
D. External Variables (extern)
● Concept: Declaring a variable without defining it. It tells the compiler "Go
look for this variable in another file."
● Declaration vs. Definition:
○ int x = 10; (Definition: Allocates memory).
○ extern int x; (Declaration: No memory allocated, just points to the
definition).
C/C++ vs. Java Differences
Feature C / C++ Java
auto Local variable Not used for storage. (Used for type
(default). inference in Java 10+ var).
register Supported. Not Supported. JVM handles optimization
automatically.
extern Used for global Not Supported. Java uses public
variables. classes/packages.
static Retains value in Not Supported. You cannot have static
(Local) function. variables inside a method.
static File scope or Class Class Member Only. Belongs to the Class,
(Class) member. shared by objects.
Scope is spatial (where code is). Lifetime is temporal (when memory exists). The
Storage Class determines the lifetime.
Storage Class Memory Lifetime Default Value
Area
Automatic Stack Created when block starts, Garbage (C++) /
(Local) destroyed when block ends. Error (Java)*
Static Data Created once at program start, Zero (0/null).
Segment lives until program ends.
Dynamic Heap Created via new/malloc. Lives until Garbage (C++) /
deleted (C++) or Garbage Collected Default (Java).
(Java).
*Note: Java local variables must be initialized before use, or the compiler throws
an error.
The static Keyword
This is a high-frequency exam topic.
1. Static Local Variable (C++ Only):
○ A variable inside a function that remembers its value between
function calls.
○ Example: Counting how many times a function was called.
○ Java does NOT support static local variables.
2. Static Member Variable (C++ & Java):
○ Belongs to the Class, not the Object.
○ Shared among all instances of the class.
○ Access: [Link].
4. Variable Shadowing (Hiding)
Shadowing occurs when a variable in an inner scope has the same name as a
variable in an outer scope.
The "This" Keyword Solution
When a local parameter shadows a class member variable, this is used to refer
to the class member.
Java
class Student
{
int marks; // Class/Instance scope
void setMarks(int marks)
{ // Local parameter scope
// marks = marks; // WRONG: Assigns local to local (Self-assignment)
[Link] = marks; // CORRECT: '[Link]' refers to the instance variable
}
}
5. Binding of Variables (Linking Name to Value)
This connects the "Scope" topic to the "Program Control" topic.
● Static Binding (Early Binding):
○ The variable name is connected to a memory offset at Compile
Time.
○ Used for standard variables, overloaded methods, and
private/static methods.
● Dynamic Binding (Late Binding):
○ The variable/method is connected to code at Runtime.
○ Used for Polymorphism (referring to an object via a Parent
reference).
Note: In Java, member variables are always Statically Bound, while
methods are Dynamically Bound.
● If Parent p = new Child();
● p.x refers to Parent's x (Reference type determines variable).
● [Link]() executes Child's show (Actual Object determines
method).
6. Access Modifiers (Visibility Controls)
This defines scope across different classes and packages.
Modifier Class Package (Same Subclass (Child) World
Folder) (Global)
public Yes Yes Yes Yes
protected Yes Yes Yes (Even if diff No
package)
default (No Yes Yes No (Strictly Package No
keyword) Private)
private Yes No No No
C++ Note: C++ does not have "default/package" access. It has public,
private, and protected. In C++, protected is strictly for inheritance, not for
package/file sharing.
7. Special Variable Modifiers (Keywords)
These keywords change how and where variables are stored or accessed.
Keyword Language Function & Exam Relevance
volatile C++ / Java Prevents Optimization. Tells the compiler, "Do not
cache this variable; always read it from main
memory."
• Use: In multithreading (Java) or hardware
access (C++).
mutable C++ Only Breaks const. Allows a class member variable to
be modified even inside a const function.
• Use: For internal counters or caches that don't
change the "logical" state of the object.
transient Java Only Serialization Control. Tells the JVM, "Do not save
this variable when writing the object to a file."
• Use: Security (passwords) or temporary derived
data.
register C / C++ Hint to Compiler. Requests to store the variable
in a CPU Register instead of RAM for speed.
• Note: Modern compilers often ignore this, but
you cannot use the & (address-of) operator on a
register variable.
Parameter Passing Mechanisms
Parameter passing refers to how arguments are supplied to
functions/methods when a function is invoked.
It determines:
● How data moves into a function
● Whether modifications inside a function reflect outside
● Whether values or references are duplicated
● Behavior in memory (stack / heap)
● Performance implications
Parameter passing is the mechanism used to transfer data from a calling
function (Caller) to a called function (Callee).
Key Terminology:
1. Actual Parameters (Arguments): The values passed in the function call.
○ Example: func(10, 20); (10 and 20 are Actual).
2. Formal Parameters: The variables defined in the function header to
receive values.
○ Example: void func(int a, int b) (a and b are Formal).
WHY PARAMETER PASSING IS IMPORTANT?
● Supports modularity and reuse
● Controls data sharing vs data protection
● Determines cost (memory, CPU time)
● Enables recursion
● Influences language semantics (C vs C++ vs Java)
● Helps in object-oriented programming & functional programming
CLASSIFICATION OF PARAMETER PASSING TECHNIQUES
Parameter passing methods fall into three broad categories:
A. Call-by-Value
B. Call-by-Reference
C. Call-by-Address (Pointers)
Additional conceptual models (in academic theory):
D. Call-by-Name
E. Call-by-Result
F. Call-by-Value-Result
G. Call-by-Need (Lazy Evaluation)
(Used in functional/logical languages)
1. Pass by Value (Call by Value)
● Language Support: C, C++, Java (Always), Python (Primitives).
● Mechanism:
○ The value of the Actual Parameter is copied into the Formal
Parameter.
○ Separate memory is allocated for the Formal parameters on the
Stack.
● Implication: Changes made to the variable inside the function do NOT
affect the original variable in the caller.
● Pros: Data safety (Original data cannot be corrupted).
● Cons: Memory wastage (redundant copying) and performance overhead
for large structures/objects.
Code Example (C++/Java):
C++
void change(int x)
{
x = 100; // Changes only the local copy
}
// Main:
int a = 10;
change(a);
print(a); // Output: 10 (Unchanged)
2. Pass by Address (Call by Pointer)
● Language Support: C, C++. (Not available in Java).
● Mechanism:
○ The memory address (pointer) of the Actual Parameter is passed
to the function.
○ The Formal Parameter is a pointer variables (e.g., int *ptr).
● Implication: By dereferencing the pointer (*ptr), the function accesses
and modifies the original memory location.
● Pros: Memory efficient (no copying of large data).
● Cons: Unsafe (Original data can be modified unintentionally); Null pointer
risks.
Code Example (C/C++):
C++
void change(int *ptr)
{
*ptr = 100; // Goes to the address and changes value
}
// Main:
int a = 10;
change(&a); // Pass the address
print(a); // Output: 100 (Modified)
3. Pass by Reference (Call by Reference)
● Language Support: C++, C#, PHP. (NOT supported in C or Java).
● Mechanism:
○ The Formal Parameter becomes an Alias (a nickname) for the
Actual Parameter.
○ No new memory is allocated for the data; the Formal parameter
shares the same memory address as the Actual parameter.
● Syntax: Uses the ampersand & in the function signature.
● Difference from Pointers:
○ A reference cannot be NULL.
○ A reference cannot be "re-seated" (made to refer to a different
variable later).
Code Example (C++):
C++
void change(int &ref)
{
ref = 100; // 'ref' is just an alias for 'a'
}
// Main:
int a = 10;
change(a); // Syntax looks like Pass by Value
print(a); // Output: 100 (Modified)
4. The "Java" Parameter Passing Model
This is the most frequent source of confusion.
Golden Rule: Java is strictly Pass by Value.
Case A: Passing Primitives (int, float, boolean)
● Works exactly like standard "Pass by Value."
● A copy is made. Original is untouched.
Case B: Passing Objects (Arrays, Strings, Custom Classes)
● Mechanism: Java passes the Value of the Reference.
● It copies the "remote control" (address/handle), not the "TV" (Object).
● Effect:
1. You CAN modify the internals of the object (because you have a
copy of the key to the house).
2. You CANNOT swap the object or make the original reference point
to a new object (because you only have a copy of the reference
variable).
Java Exam Example:
Java
class Test
{
int x;
}
void modify(Test t)
{
t.x = 100; // VALID: Modifies the object on Heap.
t = new Test(); // INVALID: Changes only the local 't', not the caller's
reference.
t.x = 500; // Modifies the NEW object, original is untouched.
}
5. Advanced/Theoretical Mechanisms
These concepts are rare in modern coding but appear in "Concepts" syllabus
questions.
A. Pass by Value-Result (Copy-Restore)
● Used in: Ada, Fortran.
● Mechanism:
1. Copy In: Value is copied to the function (like Pass by Value).
2. Execute: Function runs locally.
3. Copy Out: On return, the final value is copied back to the original
variable.
● Difference from Reference: If the function crashes halfway, the original
variable is never updated. In Pass by Reference, updates happen
immediately in memory.
B. Pass by Name (Lazy Evaluation)
● Used in: Algol 60 (Historical).
● Mechanism: The argument is not evaluated until it is actually used inside
the function.
● Concept: Similar to Macros in C (#define). The code is textually
substituted.
6. Summary Comparison Table
Feature Pass by Value Pass by Address Pass by Reference
(Pointer)
Copying Copies actual Copies the address. No copying (Alias).
data.
Memory Distinct memory Pointer variable takes Shared memory
locations. stack space. location.
Side Effects No side effects. Modification affects Modification affects
original. original.
Syntax (C++) void f(int x) void f(int *x) void f(int &x)
Java Support Yes (Standard) No No
Null Safety Safe. Risk of Null Pointer Safe (Cannot be
Exception. Null).
Object-Oriented Programming (OOP) Concepts
Object-Oriented Programming (OOP) is a programming paradigm that
organizes software design around data (objects) rather than functions and
logic. It focuses on objects, which are instances of classes. C++ supports both
procedure-oriented and object-oriented programming.
Key Features of OOP
1. Encapsulation
● Wrapping of data and functions into a single unit (class).
● Ensures data hiding — private data cannot be accessed directly from
outside the class.
● Achieved through access specifiers (private, public, protected).
Example:
2. Data Abstraction
● Showing only essential details and hiding the background
implementation.
● Achieved using classes, abstract classes, or interfaces.
Example:
3. Inheritance
● Mechanism by which one class acquires properties of another.
● Promotes code reusability and establishes a class hierarchy.
● Types: Single, Multiple, Multilevel, Hierarchical, Hybrid.
Example:
4. Polymorphism
● Means many forms — same function behaves differently depending on
the object type.
● Types:
○ Compile-time → Function & Operator Overloading
○ Runtime → Virtual Functions
Example:
5. Dynamic Binding (Late Binding)
● Linking of a function call with its actual function definition happens at
runtime.
● Enables runtime polymorphism via virtual functions.
6. Message Passing
● Objects communicate by sending and receiving messages (function
calls).
● Example: [Link](); → message display() is sent to obj.
Advantages / Benefits of OOP
● Reusability: Classes can be reused in multiple programs.
● Modularity: Code is divided into independent objects.
● Security: Data hiding prevents unauthorized access.
● Extensibility: Easy to add new features via inheritance.
● Maintainability: Changes in one class don’t affect others.
● Real-world modeling: Objects represent real entities.
Functions, Classes & Objects
1. Introduction to a Class
A class is a user-defined data type that binds data (variables) and functions
(methods) together into a single logical unit. It models a real-world entity and
serves as a blueprint for creating objects.
Syntax:
Example:
2. Class Definition
Defines the data and behavior of objects. Includes:
● Data members
● Member functions
● Access specifiers
● Constructors/Destructors (optional)
Example:
3. Defining Members
● Member functions can be defined inside (inline) or outside the class using
the scope resolution operator (::).
Example:
4. Objects
An object is an instance of a class. Each object holds its own copy of data
members but shares member functions.
Example:
5. Access Control
C++ uses access specifiers to control visibility of class members:
● private: Accessible only within the class.
● protected: Accessible within the class and derived classes.
● public: Accessible anywhere in the program.
Default: private (for class), public (for struct).
6. Class Scope
Members of a class are recognized only within the class scope. They can be
accessed using an object and the dot operator (.):
[Link]();
7. Scope Resolution Operator (::)
Used for:
1. Defining functions outside a class.
2. Accessing global variables when local names shadow them.
3. Accessing static members.
Example:
8. Inline Functions
● Functions defined inside a class are automatically inline.
● inline suggests the compiler expand code instead of calling function.
Example:
Use: Small, frequently called functions. Compiler may ignore inline requests.
9. Memory Allocation for Objects
● Data members: Each object has its own copy.
● Member functions: Shared among all objects.
● Static members: One copy shared by all objects.
Memory created when: Object is instantiated.
10. Static Data Members
● Belong to the class, not any object.
● Only one copy exists for the entire class.
Declaration: Inside class with static keyword.
Definition: Outside class.
11. Static Member Functions
● Declared with static keyword.
● Can access only static data members.
● Called using class name without object.
Example: Counter::show();
12. Arrays of Objects
Used to store multiple objects of the same class.
Student s[5];
s[0].getData();
Each object has its own copy of class variables.
13. Objects as Function Arguments
Objects can be:
1. Passed by value: Copy created; original remains unchanged.
2. Passed by reference: No copy; changes affect original.
3. Returned by function: Entire object returned.
Example:
14. Friend Functions
A friend function can access private and protected members of a class though
it is not a member itself.
Syntax:
Key Points:
● Declared inside class with friend keyword.
● Defined outside the class.
● Not affected by access specifiers.
● Friendship is not mutual or inherited.
15. Advantages of Using Classes and Objects
● Data hiding and encapsulation.
● Code reusability through member functions.
● Abstraction of implementation details.
● Easier maintenance and debugging.
● Promotes modular, object-based design.
Constructors, Destructors, and Inheritance
1. Introduction to Constructors
A constructor is a special member function of a class that is automatically
called when an object is created. Its primary purpose is to initialize objects.
Characteristics:
● Name of constructor = class name.
● No return type (not even void).
● Invoked automatically during object creation.
● Can be overloaded (multiple constructors allowed).
Syntax:
Example:
2. Default Constructors
● A default constructor is a constructor with no parameters.
● Automatically called when an object is created without arguments.
● If no constructor is defined, the compiler provides a default one.
Example:
Note: Once a user-defined constructor exists, the compiler no longer provides
the implicit default constructor.
3. Parameterized Constructors
Used to initialize objects with specific values at creation
Example:
Can be overloaded:
● You can define multiple constructors with different parameter lists.
4. Copy Constructor
● A copy constructor initializes a new object as a copy of an existing
object.
● Syntax: ClassName(const ClassName &obj)
● Called in three cases:
1. When an object is initialized with another object.
2. When passed by value.
3. When returned by value.
Example:
Note: If you don’t define one, the compiler provides a shallow copy constructor.
5. Multiple Constructors in a Class
● Also called constructor overloading.
● A class can have several constructors with different parameter lists.
● Compiler chooses the right one based on arguments.
Example:
6. Destructors
● A destructor is a special member function used to clean up when an
object goes out of scope.
● Same name as class, preceded by a ~ (tilde).
● No arguments, no return type, cannot be overloaded.
Syntax:
~ClassName();
Example:
Automatic invocation:
● Called automatically when object is destroyed or goes out of scope.
Use: Free dynamic memory or release resources.
INHERITANCE
Inheritance is a mechanism by which one class (derived) acquires the
properties and behaviors of another class (base).
Benefits:
● Code reusability
● Extensibility
● Reduced redundancy
Syntax:
Access specifiers: public, protected, private — determine visibility of base class
members in derived class.
Base Public Protected Private
Member Inheritance Inheritance Inheritance
public public protected private
protected protected protected private
private not inherited not inherited not inherited
2. Defining Derived Classes
Example:
Here, Derived inherits members of Base.
Types of Inheritance:
Single Inheritance
● One base class → one derived class.
Advantage: Simplest form; supports code reuse.
Multiple Inheritance
● Derived class inherits from two or more base classes.
Problem: Ambiguity when same member name appears in multiple bases —
solved using scope resolution operator.
Multilevel Inheritance
● Derivation occurs across multiple levels.
Advantage: Gradual specialization of base classes.
Hierarchical Inheritance
● Several derived classes inherit from one base class.
Advantage: Same base functionality reused by multiple derived classes.
Hybrid Inheritance
● Combination of multiple and multilevel inheritance.
● May cause ambiguity (diamond problem).
● Solved using virtual base classes.
Example:
Virtual base classes ensure only one copy of base class members is inherited.
Constructor and Destructor Execution in Inheritance
● Constructors are called from base to derived.
● Destructors are called in reverse order (derived to base).
Example:
Output:
Advantages of Inheritance
● Code reusability.
● Reduces redundancy.
● Easier maintenance and extension.
● Promotes logical hierarchy and modularity.
Pointers, Virtual Functions, and Polymorphism
1. Introduction to Memory Management
Memory management refers to the efficient handling of memory during
program execution. In C++, memory can be allocated statically, automatically,
or dynamically.
Types of Memory:
1. Static Memory Allocation –
○ Performed by the compiler at compile-time.
○ Used for global variables and static local variables.
○ Lifetime: Entire duration of the program.
2. Automatic (Stack) Memory Allocation –
○ Created when the function is called.
○ Released automatically when the function exits.
○ Example: Local variables.
3. Dynamic Memory Allocation –
○ Managed manually by the programmer using new and delete
operators.
○ Lifetime: Until explicitly released.
Need for Dynamic Memory:
● When the size of data is not known in advance.
● To allocate memory based on user input or runtime conditions.
● Provides flexibility and efficient memory utilization.
2. The new and delete Operators
new Operator
● Allocates memory for variables or objects at runtime.
● Returns a pointer to the allocated memory.
● Automatically calls the constructor (if used for objects).
Syntax:
Example:
delete Operator
● Used to free memory allocated by new.
● Automatically calls the destructor when deleting objects.
Syntax:
Example:
Allocating and Deallocating Arrays:
Important Points:
● Failure to free memory causes memory leaks.
● Always pair new with delete and new[] with delete[].
● Avoid dangling pointers (accessing freed memory).
3. Pointers to Objects
A pointer to an object is used to access class members indirectly using the ->
operator.
Example:
Advantages of Pointers to Objects:
● Support dynamic polymorphism.
● Enable runtime allocation of objects.
● Facilitate arrays of objects with variable size.
● Allow passing objects to functions by reference.
4. Pointers to Derived Classes
Pointers of the base class can point to derived class objects. This enables
polymorphism when virtual functions are used.
Example:
Key Point:
● When a function in the base class is declared as virtual, the derived class
version is executed.
Example with Virtual:
Applications:
● Achieving runtime polymorphism.
● Designing flexible APIs for inheritance hierarchies.
5. Polymorphism
Polymorphism means many forms — the same function behaves differently
depending on the object or context.
Types:
1. Compile-time Polymorphism → resolved at compile time.
2. Runtime Polymorphism → resolved at runtime.
Purpose:
● Increase code flexibility.
● Support extensibility via inheritance.
● Enable function reusability.
6. Compile-time Polymorphism (Static Binding)
Achieved by:
1. Function Overloading
2. Operator Overloading
Function Overloading:
Same function name, different parameters.
Rules:
● Functions must differ by parameter type or number.
● Cannot overload by return type alone.
Operator Overloading:
Allows operators to be redefined for user-defined data types.
Benefits:
● Enhances code readability.
● Enables intuitive usage of objects.
7. Runtime Polymorphism (Dynamic Binding)
● Achieved using pointers and virtual functions.
● Function call is resolved at runtime.
● Enables overriding behavior dynamically.
Example:
Advantages:
● Achieves abstraction and flexibility.
● Promotes interface-based programming.
8. Virtual Functions
Virtual functions enable runtime polymorphism by allowing derived classes to
override base class methods.
Key Characteristics:
● Declared in the base class using the virtual keyword.
● Accessed using base class pointers/references.
● Decided at runtime, not compile time.
● Not inherited by constructors but destructors can and should be virtual.
● Cannot be static or friend.
Example:
Virtual Table (vtable):
● A table created internally by the compiler containing addresses of virtual
functions.
● Each object of a class with virtual functions has a vptr (virtual pointer) to
the vtable.
● Ensures correct function call during runtime.
9. Pure Virtual Functions and Abstract Classes
Pure Virtual Function:
● Declared using = 0 inside a class.
● Must be defined in derived classes.
● Makes the class abstract (cannot instantiate).
Example:
Abstract Class:
● Contains at least one pure virtual function.
● Used as a base class to enforce method implementation in derived
classes.
Example:
10. Advantages of Polymorphism and Virtual Functions
● Promotes code reusability and scalability.
● Enables dynamic behavior during runtime.
● Simplifies complex hierarchies using abstraction.
● Allows generic programming using base class interfaces
Constructors & Exception Handling.
Constructors: A Constructor is a special member function used to initialize
objects. It is automatically called when an instance of a class is created.
Universal Rules (C++ & Java):
1. Name: Must be exactly the same as the Class name.
2. Return Type: None. Not even void.
3. Invocation: Implicitly called upon object creation (new keyword).
[Link] of Constructors
Definition: A constructor is a special method used to initialize objects. It creates
the memory environment for an object to exist.
I. Default Constructor (No-Argument Constructor)
Definition: A constructor that accepts absolutely zero parameters.
The "Implicit" Rule (Compiler Magic):
● If a class has no constructors defined by the programmer, the compiler
automatically inserts a hidden, empty Default Constructor.
● Purpose: To ensure every object is created validly, even if the
programmer forgets to write initialization code.
The "Withdrawal" Rule:
● If the programmer defines ANY constructor (even a parameterized one),
the compiler stops providing the automatic Default Constructor.
● Implication: If you write a constructor taking arguments, you cannot
create an empty object (e.g., new Student()) unless you manually write
a no-argument constructor yourself.
C++ vs. Java Behavior:
● Java: The default constructor initializes numeric variables to 0, booleans
to false, and objects to null.
● C++: The default constructor leaves primitive variables (int, float) with
Garbage Values (random memory data) unless explicitly initialized.
Code Example: The "Compiler Rule"
C++ Implementation
class Student
{
public:
int id;
// Compiler inserts: Student() { } implicitly here.
};
int main() {
Student s1; // VALID: Uses the implicit default constructor.
cout << [Link]; // WARNING: In C++, this contains GARBAGE value.
return 0;
}
Java Implementation
class Student
{
int id;
// Compiler inserts: Student() { super(); } implicitly here.
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // VALID
[Link]([Link]); // SAFE: Java initializes this to 0.
}
}
II. Parameterized Constructor
Definition: A constructor that accepts one or more arguments (parameters).
Purpose: It allows the creation of objects with specific, unique data at the very
moment of birth (e.g., creating a Student with name "Ram" and ID "101").
Constructor Overloading:
● You can have multiple constructors in a single class (Default +
Parameterized).
● The compiler decides which one to call based on the number and type of
arguments passed (Polymorphism).
Code Example: Initialization Difference
C++ Implementation
class Box
{
int width, height;
public:
// Preferred C++ Syntax: Member Initializer List
// More efficient than assignment inside {}
Box(int w, int h) : width(w), height(h) {
// Body can be empty
}
};
int main() {
Box b(10, 20); // Object created with width=10, height=20
return 0;
}
Java Implementation
class Box
{
int width, height;
// Standard Java Syntax
Box(int width, int height) {
[Link] = width; // 'this' resolves the naming conflict
[Link] = height;
}
}
public class Main {
public static void main(String[] args) {
Box b = new Box(10, 20);
}
}
III. Copy Constructor (The "Cloning" Mechanism)
Definition: A constructor used to create a new object as an exact copy of an
existing object.
C++ Specifics:
● Syntax: Takes a reference to an object of the same class (e.g.,
Class(const Class &obj)).
● Trigger Points: It is called automatically when:
○ An object is initialized from another (Obj A = B;).
○ An object is passed by value to a function.
○ An object is returned by value from a function.
● Shallow vs. Deep Copy:
○ Shallow Copy (Default): Copies member values directly. If the
object contains a Pointer, it copies the address, not the data. This
leads to two objects pointing to the same memory (Dangerous).
○ Deep Copy: You must write a custom Copy Constructor to allocate
new memory and copy the actual data, ensuring the two objects
are independent.
Java Specifics:
● Java does not have a built-in "Copy Constructor" mechanism like C++.
● Arguments are passed by value (reference value), so copying is usually
done via a .clone() method or a manually created constructor that
takes an object as an argument.
Code Example: Deep vs. Shallow Copy
C++ Implementation (Deep Copy Logic)
#include <iostream>
using namespace std;
class Buffer
{
int* ptr;
public:
Buffer(int val) {
ptr = new int(val); // Allocation on Heap
}
// Custom Copy Constructor (Deep Copy)
Buffer(const Buffer &obj) {
// Allocate NEW memory, then copy the VALUE
ptr = new int(*([Link]));
}
~Buffer() { delete ptr; } // Destructor cleans up
};
int main() {
Buffer b1(10);
Buffer b2 = b1; // Calls Copy Constructor
// Both b1 and b2 have their OWN memory. Safe.
}
Java Implementation (Manual Copy)
class Buffer
{
int val;
Buffer(int val) { [Link] = val; }
// Manual Copy Constructor
Buffer(Buffer obj)
{
[Link] = [Link]; // Copies the value
}
}
public class Main {
public static void main(String[] args) {
Buffer b1 = new Buffer(10);
// Creates a new object b2 with b1's data
Buffer b2 = new Buffer(b1);
}
}
2. Constructor Chaining & Inheritance
2.1 The this Keyword (Chaining)
● Purpose: Calling one constructor from another within the same class to
avoid code duplication.
● Rule: The call to this() must be the first statement in the constructor.
Java Example:
class Box
{
Box() { this(10); } // Calls the parameterized version
Box(int x) { ... }
}
2.2 The super Keyword (Inheritance)
● Purpose: Calling the Parent Class constructor from the Child Class.
● The Rule of Life: When a Child object is created, the Parent constructor
MUST execute first.
● Implicit Call: If you don't write super(), the compiler inserts a call to the
Parent's no-arg constructor automatically.
● Trap: If the Parent has only a parameterized constructor, the Child must
explicitly call super(args), otherwise it’s a Compile Time Error.
3. C++ Specific: Initialization Lists
● Syntax: Constructor() : var1(val), var2(val) { }
● Why use it?
1. Performance: It initializes variables directly rather than creating
them and then assigning values (Assigning = 2 steps).
2. Mandatory For:
■ const member variables.
■ Reference (&) member variables.
■ Objects that do not have a default constructor.
Exception Handling
Definition: A mechanism to handle runtime errors (abnormal conditions) so the
normal flow of the application can be maintained.
1. The Core Keywords
Keyword Usage
try The block of code to monitor for errors.
catch The block that executes if an exception occurs in
the try block.
finally (Java) A block that ALWAYS executes (cleanup
code).
throw Used to manually trigger an exception.
throws (Java) Declares that a method might throw an
exception.
i. Keywords: try and catch
try
● Used to wrap code that may cause an exception.
● Marks the beginning of exception-handling logic.
catch
● Used to handle the exception thrown in the try block.
● Can have multiple catch blocks for different exception types
public class TryCatchExample
{
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
// Accessing index 5 (which does not exist)
[Link](numbers[5]);
}
catch (ArrayIndexOutOfBoundsException e) {
// This block runs because the error occurred above
[Link]("Error: Index is out of bounds!");
}
}
}
Output: Error: Index is out of bounds!
ii. Keyword: finally
● Optional block.
● Executes always, whether exception occurs or not.
Used for:
● Closing files
● Releasing resources
● Closing DB connections
public class FinallyExample {
public static int testMethod() {
try
{
[Link]("Inside Try Block");
return 1; // Returning early
}
finally
{
// This runs even though we returned above
[Link]("Inside Finally Block");
}
}
public static void main(String[] args)
{
testMethod();
}
}
Output:
Inside Try Block
Inside Finally Block
iii. Keyword: throw
● Used to explicitly throw an exception inside a method or block.
● Used for user-defined or manual exception generation.
public class ThrowExample {
static void setBalance(int balance) {
if (balance < 0)
{
// Manually triggering an exception for invalid logic
throw new IllegalArgumentException("Balance cannot be negative");
}
[Link]("Balance set to: " + balance);
}
public static void main(String[] args)
{
setBalance(-100); // This line crashes the program
}
}
Output:
Exception in thread "main" [Link]: Balance cannot
be negative
iv. Keyword: throws
● Used in method signature to declare exceptions that the method may
throw.
● Delegates exception handling to the caller function.
import [Link];
class Server
{
// 'throws' warns the compiler that this method is risky
void connect() throws IOException
{
throw new IOException("Connection Failed");
}
}
public class ThrowsExample {
public static void main(String[] args) {
Server s = new Server();
try {
[Link](); // We MUST handle the exception here because of 'throws'
}
catch (IOException e) {
[Link]("Handled: " + [Link]());
}
}
}
Output:
Handled: Connection Failed
2. The Java Exception Hierarchy
In Java, everything is an Object. The root of errors is the Throwable class.
2.1 Error vs. Exception
1. Error: Serious problems that a reasonable application should not try to
catch. Usually irrecoverable.
○ Examples: StackOverflowError, OutOfMemoryError,
VirtualMachineError.
2. Exception: Conditions that a reasonable application might want to catch.
2.2 Checked vs. Unchecked Exceptions (Crucial)
This distinction exists only in Java, not C++.
Feature Checked Exceptions Unchecked Exceptions
Class Exception (but not RuntimeException.
Parent RuntimeException).
Compiler Enforced. Compiler forces you Ignored. Compiler does not
Check to try-catch or throws. force handling.
Nature External failures beyond Logic errors / Programming
program control. bugs.
Examples IOException, SQLException, NullPointerException,
FileNotFoundException. ArithmeticException,
IndexOutOfBounds.
3. Control Flow: Stack Unwinding
When an exception is thrown:
1. The runtime stops execution of the current method.
2. It checks if the current method has a catch block.
3. If No: It pops the current stack frame (method returns abnormally) and
checks the caller method.
4. If Yes: It executes the catch block.
5. Unwinding: This process of popping stack frames continues until a
handler is found or the main() method is reached (causing a crash).
4. The finally Block (Java)
● Purpose: Cleanup (Closing files, database connections, sockets).
● The Guarantee: The finally block runs whether an exception is handled,
unhandled, or if the code runs normally.
The "Return" Override Trap:
int test() {
try { return 1; }
finally { return 2; }
}
// Returns 2. The finally block overrides the try return.
● The "Death" Exception: The only time finally does NOT run is if you call
[Link](0) (kills the JVM).
5. C++ Exception Handling Differences
1. No finally: C++ does not have a finally keyword.
○ Solution: It uses RAII (Resource Acquisition Is Initialization).
Objects created on the stack (like smart pointers) have their
Destructors called automatically when the scope is exited (stack
unwinding), ensuring cleanup.
2. Catch All: C++ uses catch(...) to catch any type of exception.
Throw Anything: In Java, you can only throw objects of Throwable. In C++, you
can throw anything (int, char*, class).
throw 404; // Valid in C++, Invalid in Jav
6. Exam Traps
Trap 1: Order of Catch Blocks
● Rule: Specific exceptions must come before general exceptions.
● Scenario: If you catch Exception (Parent) before FileNotFoundException
(Child), the Child block is unreachable.
● Result: Compile Time Error in Java.
Trap 2: Method Overriding with Exceptions
If a Parent class method declares it throws IOException:
1. The Child class override can throw IOException.
2. The Child class override can throw a Subclass (FileNotFoundException).
3. The Child class override can throw Nothing.
4. BUT: The Child CANNOT throw a broader exception (Exception) or a new
checked exception.
Trap 3: Throw vs. Throws
● throw: Action. Used inside a method. Followed by an instance (throw new
Exception()).
● throws: Declaration. Used in method signature. Followed by class names
(void func() throws IOException).
Summary Cheat Sheet
Concept C++ Java
Destructor Yes (~Class()). Used for No. Uses Garbage Collection &
cleanup. finalize() (deprecated).
Copy Yes. Vital for pointers. No. Uses clone().
Constructor
Throw Types Any primitive or object. Only Throwable objects.
Checked No. All are unchecked. Yes. Distinguishes
Exceptions Checked/Unchecked.
Finally Block No. (Uses Yes.
Destructors/RAII).
Functional & Logic Programming
Definition: Functional Programming is a declarative programming paradigm
where programs are constructed by applying and composing functions.
● Root Foundation: It is based on Lambda Calculus (a formal system in
mathematical logic for expressing computation).
● The Core Philosophy: "Move data through functions, rather than
mutating the data itself."
1. The 5 Pillars of Functional Programming
A. Immutability (The Golden Rule)
● Concept: Data cannot be modified after it is created.
● Mechanism: If you need to change an object (e.g., change a User's
name), you do not modify the existing object. Instead, you create a new
copy of the object with the updated value.
● Why? (Exam Importance):
1. Thread Safety: Since data never changes, multiple threads can
access it simultaneously without "Race Conditions" or the need for
complex locks/synchronization.
2. Predictability: You don't have to worry that Function A secretly
changed the data used by Function B.
B. Pure Functions
A function is "Pure" if it meets two strict criteria:
1. Deterministic: For the exact same input, it always produces the exact
same output.
○ Impure: random(), [Link]() (Result changes every time).
○ Pure: add(2, 3) (Always returns 5).
2. No Side Effects: The function does not modify anything outside its scope.
○ It does not change global variables.
○ It does not print to the console (I/O).
○ It does not write to a database.
C. Referential Transparency
● Definition: Because pure functions are deterministic, you can replace a
function call with its resulting value without breaking the program.
● Example:
○ If x = add(2, 3) and y = add(2, 3) * 5.
○ You can optimize y to 5 * 5 directly. This allows compilers to perform
massive optimizations (Memoization).
D. Higher-Order Functions (HOF)
In FP, functions are "First-Class Citizens." This means a function is treated just
like a variable (integer, string).
A Higher-Order Function is a function that either:
1. Takes a function as an argument. (e.g., "Do this logic on every item in
the list").
2. Returns a function as a result.
E. Recursion & Tail Call Optimization (TCO)
● The Problem: FP avoids loops (for, while) because loop counters (i++)
require mutation.
● The Solution: Recursion.
● The Risk: Standard recursion fills up the Stack memory, causing
StackOverflowError.
● The Optimization (TCO): Many FP languages (and modern C++
compilers) optimize "Tail Recursion" (where the recursive call is the last
thing the function does). They convert the recursion into a loop internally,
using constant O(1) stack space.
○ Note: Java does not currently support TCO at the compiler level.
2. Common Functional Operations
These are the standard tools used in FP to process collections of data.
Operation Description Example
Map Transforms every element in a collection using a Output: [2, 4, 6]
function.
Input: [1, 2, 3] Function: x * 2
Filter Selects elements that satisfy a condition Output: [3, 4]
(Predicate).
Input: [1, 2, 3, 4] Condition: x > 2
Reduce Combines all elements into a single value Output: 6
(Accumulator).
Input: [1, 2, 3] Logic: Sum
3. Functional Programming in Java
Java 8 introduced FP features to the language. You must know these interfaces.
A. Functional Interfaces
An interface with exactly one abstract method.
Interface Method Concept Example Use
Signature
Predicate<T> boolean test(T t) Takes a value, returns Filter logic (e.g., check
True/False. if age > 18).
Function<T, R> R apply(T t) Takes type T, Map logic (e.g., convert
transforms it, returns String to Integer).
type R.
Consumer<T> void accept(T t) Takes a value, does forEach (e.g., print to
something, returns console).
nothing.
Supplier<T> T get() Takes nothing, Lazy initialization /
produces a value. Factory methods.
B. Lambda Expressions
A short way to write anonymous functions.
Old Java (Anonymous Class):
// Verbose
Predicate<Integer> isEven = new Predicate<Integer>() {
public boolean test(Integer n) { return n % 2 == 0; }
};
New Java (Lambda):
// Concise
Predicate<Integer> isEven = n -> n % 2 == 0;
C. Method References (::)
A shorthand syntax for a lambda that calls an existing method.
● Lambda: s -> [Link](s)
● Method Ref: [Link]::println
4. Comparison: Imperative vs. Functional
Feature Imperative (Legacy Functional (Modern
Java/C) Java/Haskell)
Focus How to do it (Steps). What to do (Declarative).
State Mutable (Changeable Immutable (Final variables).
variables).
Iteration Loops (for, while). Recursion / Streams API.
Order Execution order matters. Order often irrelevant
(Parallelizable).
Debugging Harder (Side effects hide Easier (Pure functions are isolated).
bugs).
5. Pros & Cons
Advantages
1. Bug Reduction: No side effects means functions don't break each other.
2. Concurrency: Immutable data is inherently thread-safe. Perfect for
Cloud/Distributed systems.
3. Testing: Pure functions are incredibly easy to unit test (Input $\to$
Output).
Disadvantages
1. Memory Usage: Creating new objects instead of modifying existing ones
(Immutability) consumes more RAM.
2. Performance: Recursion is generally slower than native CPU loops.
3. Learning Curve: Requires a shift in thinking (unlearning loops)
Logic Programming (LP)
Definition: A paradigm based on Formal Logic. The program is a collection of
sentences in logical form, expressing facts and rules about a problem domain.
Primary Language: Prolog (Programming in Logic).
1. Core Components
A. Facts (The Data)
● Unconditional truths about the world.
● Syntax (Prolog): parent(john, bob).
● Meaning: "It is a fact that John is the parent of Bob."
B. Rules (The Logic)
● Conditional truths. New information is inferred from existing facts.
● Syntax: grandparent(X, Y) :- parent(X, Z), parent(Z, Y).
● Meaning: X is the grandparent of Y IF X is the parent of Z AND Z is the
parent of Y.
C. Queries (The Questions)
● The user asks the system a question (Goal).
● Input: ?- grandparent(john, alice).
● Output: True or False.
2. The Execution Engine (How it works)
Logic programming does not follow "Step 1, Step 2, Step 3." It uses an
Inference Engine.
A. Unification (Pattern Matching)
● The process of matching a Query with Facts/Rules in the database.
● If you ask parent(john, X), the system searches for facts starting with
parent and binds john to the first argument, revealing X to be bob.
B. Backtracking (Exam Key Term)
● Definition: The engine searches for a solution. If it reaches a dead end (a
rule fails), it goes back to the previous decision point and tries a different
path.
● Analogy: Solving a maze. If you hit a wall, you retrace your steps to the
last junction and turn right instead of left.
C. Closed World Assumption
● Concept: If the system cannot prove something is true, it assumes it is
False.
● Example: If the database doesn't list "Mars" as a planet, the system
believes "Mars is not a planet."
Summary Comparison Table
Feature Imperative Functional Logic (Prolog)
(C/Java) (Haskell/Scala)
Focus How to solve What is the value What is true
(Algorithms). (Expressions). (Relationships).
State Mutable Immutable (Constant). N/A (Facts).
(Changeable).
Control Loops, Conditionals. Recursion, Function Unification,
Flow Calls. Backtracking.
Primary Procedure / Object. Function. Clause (Fact/Rule).
Unit
Execution Explicit steps. Evaluation of math. Search for proof.