Module Notes
Module Notes
Definitions
• User Requirements: Statements that describe what a user needs or wants a system to
do in order to achieve their goals. They are written in plain language that the target
users can understand.
• System Requirements: Detailed specifications for how the system will be built to meet
the user requirements. These requirements are typically written for developers and
engineers and use technical language.
Explanation
User requirements focus on the "what" - what the user wants the system to accomplish. They
describe the features and functionalities that will be valuable to the user. System requirements,
on the other hand, focus on the "how" - how the system will be built to deliver the
functionalities outlined in the user requirements. They delve into the technical aspects like
programming languages, hardware specifications, and security measures.
Example:
• User Requirement: A library user wants to be able to search for books by title, author, or
keyword.
• System Requirement: The library search system shall be able to query a database of
books based on user-provided keywords, titles, or authors and return a list of relevant
books within 2 seconds.
Differences
Here's a table summarizing the key differences between user requirements and system
requirements:
Level of
High level overview Specific and measurable
Detail
"The system shall support image uploads in JPEG
"The system should allow
Example and PNG formats, with a maximum file size of 10
users to upload photos."
MB."
FACT-FINDING METHODS
Fact-finding methods are essentially tools used to gather information and data in a structured
way. This information is then used to understand a situation, identify problems, and develop
solutions. They are widely used in various fields, including business analysis, system
development, research, and more. Here's a breakdown of some common fact-finding methods:
1. Examining Documentation:
o Advantages:
o Disadvantages:
2. Interviewing:
o Advantages:
o Disadvantages:
3. Observation:
o Advantages:
o Disadvantages:
4. Questionnaires:
o Definition: Standardized surveys with predetermined questions used to gather
information from a large group of people.
o Advantages:
o Disadvantages:
5. Research:
o Definition: Reviewing existing studies, reports, and data related to the topic to
gain background knowledge and industry trends.
o Advantages:
o Disadvantages:
1. Inputs:
o Definition: Inputs are the data or instructions that a program receives from the
user or another source. They are the starting point for the program's execution.
o Types/Examples:
▪ User input: Data entered by the user through keyboard, mouse, touch
screen, etc. (e.g., name, age, product selection)
2. Processes:
o Definition: Processes are the steps or instructions that the program follows to
transform the input data into the desired output. They represent the core logic
and functionality of the program.
o Types/Examples:
3. Outputs:
o Definition: Outputs are the results generated by the program after processing
the inputs. They are the information presented to the user or another system.
o Types/Examples:
▪ Saved data: Information written to a file or database for future use. (e.g.,
user preferences, transaction history)
Here's a breakdown of three popular solutions for business software needs, along with their
advantages and disadvantages to help you decide which might be the most suitable alternative:
o Definition: This involves buying pre-built software that caters to general business
needs or specific industry functions. It's a readily available solution requiring
minimal customization.
o Advantages:
▪ Vendor support: Benefit from ongoing support and updates from the
software vendor.
o Disadvantages:
▪ Limited customization: May not perfectly fit your specific business needs.
o Advantages:
o Disadvantages:
▪ Hidden costs: Project scope creep and additional expenses can occur.
3. In-House Development:
o Definition: Building the software within your organization using your own
employees or a dedicated in-house development team.
o Advantages:
▪ Alignment with business goals: Ensures the software directly aligns with
your business objectives.
o Disadvantages:
▪ Longer development time: Building from scratch takes longer than using
existing solutions.
WALKTHROUGHS
• Improved quality: Through collaborative review, walkthroughs can help identify and
address inconsistencies, errors, or inefficiencies in design, functionality, or user
experience.
• User perspective: Users can provide valuable insights into how they actually use or
experience a process, highlighting areas that may not be readily apparent to the
development team.
• Improved solutions: User input helps ensure the solutions developed truly address their
needs and pain points, leading to more user-friendly and effective outcomes.
• Increased user satisfaction: By involving users in the problem-solving process, you can
ensure solutions resonate with real-world needs, leading to higher user satisfaction.
These three concepts are fundamental tools for planning and designing programs before diving
into actual coding. Here's a breakdown of each:
1. Flowcharts:
• How to Create:
1. Define the Start and End: Start with a "Start" symbol and an "End" symbol to
mark the program's beginning and conclusion.
2. Identify Steps: Break down the program's logic into individual steps represented
by rectangular boxes.
3. Decision Points: Use diamond shapes for decision points where the program
needs to make a choice based on a condition. Connect outgoing arrows labeled
with "Yes" and "No" (or true/false) based on the condition's outcome.
4. Connect the Steps: Connect the boxes and diamonds with arrows to show the
flow of execution. Arrows typically flow from top to bottom, but conditional
branches can deviate based on user input or calculations.
Example: Here's a flowchart for a simple program that checks if a number is even or odd:
2. Algorithms:
• How to Create:
1. Identify the Problem: Clearly define the problem you are trying to solve with
your program.
2. Break Down the Steps: List the steps involved in solving the problem in a clear
and concise manner.
Start
Enter a number
Is number Even?
Even?
Even?
End
Print Even Print Odd
No
Even?
Yes
Even?
13
• Use Precise Language: While not formal code, the instructions should be unambiguous
and leave no room for misinterpretation.
Pseudocode
• Definition: Pseudocode is a way of writing an algorithm using keywords and phrases that
resemble a programming language, but without the strict syntax rules of a specific
language. It's more detailed than an algorithm but less formal than actual code.
How to Create:
1. Use Keywords: Use keywords like "if," "else," "while," "for," etc., to represent control
flow and logic.
2. Mimic Programming Language: Structure the pseudocode in a way that resembles the
programming language you plan to use, making the transition to actual coding smoother.
3. Focus on Readability: Maintain clarity and readability, ensuring anyone can understand
the overall logic.
Example:
An algorithm is the foundation of any computer program. It's essentially a set of well-defined
instructions that, when followed step-by-step, solves a specific problem or accomplishes a
particular task. Here's a breakdown of its definition and key characteristics:
Definition
An algorithm is a finite sequence of precise instructions that provide a clear and unambiguous
solution to a specific problem. It acts as a roadmap, guiding the computer through the
necessary steps to achieve the desired outcome.
• Finitude: The algorithm must have a finite number of steps. It should eventually
terminate and not run indefinitely.
• Unambiguity: Each step in the algorithm should be clear and have a single
interpretation. This ensures consistency and avoids confusion during execution.
• Definiteness: The steps involved in the algorithm must be definite and leave no room for
improvisation.
• Input: The algorithm should clearly define the type of data it expects as input.
• Output: The algorithm should produce a well-defined output that satisfies the intended
purpose.
• Effectiveness: The algorithm should be efficient and solve the problem in a reasonable
amount of time and with appropriate resource usage.
• Generality: Ideally, the algorithm can be applied to a range of similar problems with
minor modifications.
Examples of Algorithms
• Sorting Algorithms: These algorithms arrange data in a specific order (e.g., alphabetical,
numerical).
• Decision-Making Algorithms: These algorithms analyze data and make choices based on
predefined conditions.
Transforming program designs like algorithms and pseudocode into actual C++ code involves
translating the high-level steps into the specific syntax and functionalities of the C++
programming language. Here's a breakdown of the process with examples:
1. C++ Code:
#include
int main() {
int n, factorial = 1;
if (n < 0) {
cout << "Error: Factorial is not defined for negative numbers." <<
endl;
factorial *= i;
cout << "The factorial of " << n << " is: " << factorial << endl;
return 0;
Explanation
• The C++ code translates each step of the algorithm into corresponding programming
constructs.
• Variables (n and factorial) are declared to store the input number and the calculated
result.
• Error handling is added to check for negative input as factorial is not defined for negative
numbers.
1. Example: Describe the step-by-step process of calculating the factorial of a given non-
negative integer.
2. Pseudocode:
1. C++ Code
#include
int main() {
cout << number1 << " is greater than " << number2 << endl;
} else {
cout << number2 << " is greater than " << number1 << endl;
return 0;
}
Explanation
• Similar to the algorithm example, the pseudocode is translated into C++ syntax.
• User prompts and input reading are achieved with cout and cin.
• An if-else statement implements the conditional logic for determining the larger number.
FLOWCHART SYMBOLS
Here's how relevant flowchart symbols are applied for the three programming constructs:
1. Sequence:
1. Selection:
o Example:
1. Iteration:
o Example:
Converting Flowchart Logic to C++ Code
Here's how you can convert flowchart logic into C++ code:
o Identify the different symbols and their meanings (input, processing, decision,
output, etc.).
o Trace the flow of execution through the flowchart, following the arrows.
Consider the flowchart from the previous example that checks if a number is even or odd.
#include
int main() {
int number;
if (number % 2 == 0) {
} else {
}
return 0;
Explanation:
• The if statement checks if the remainder of dividing number by 2 is 0 (even) or not (odd).
• Break down complex flowcharts into smaller sub-functions for better organization.
• Use comments in your code to explain what each section does, improving readability.
• Test your code thoroughly with different input values to ensure it works correctly.
o Visit the official Dev-C++ website (a search for "Dev-C++ download" should lead
you there).
o Locate the download section and download the latest stable version of the
installer for your operating system (typically a Windows executable file).
o Follow the on-screen instructions during the installation process. You may
encounter options like:
o Once the installation progress bar reaches 100%, the installer may prompt you to
create a desktop shortcut or launch Dev-C++ immediately.
4. Verification:
o You should see the Dev-C++ IDE window with its menus and workspace.
o Try creating a simple C++ program (e.g., "Hello, World!") to verify that the
compiler is working correctly.
PSEUDOCODE
Pseudocode Definition:
• Informality: Unlike actual code, pseudocode doesn't adhere to the strict syntax rules of
a programming language. It allows for more natural language elements to improve
readability.
FEATURES OF OOP
Object-Oriented Programming (OOP) is a programming paradigm that focuses on creating
"objects" to model real-world entities. These objects encapsulate data (attributes) and related
operations (methods) that manipulate that data.
1. Encapsulation:
o Encapsulation refers to bundling data (attributes) and the methods that operate
on that data together within a single unit called a class.
o This concept promotes data hiding by restricting direct access to the data.
Instead, methods within the class are responsible for accessing and modifying
the data, ensuring data integrity and consistency.
2. Inheritance:
o Inheritance allows you to create new classes (subclasses) that inherit properties
and behaviors from existing classes (parent classes).
o This promotes code reusability and reduces redundancy. Subclasses can inherit
the general functionality of the parent class and add specific details or
modifications as needed.
o Inheritance helps create a hierarchy of classes, where more general classes serve
as parents and more specific classes inherit from them.
3. Polymorphism:
o Polymorphism allows for flexible code that can handle objects of different types
without modifying the core functionality.
4. Abstraction:
• Data hiding is a specific aspect of encapsulation that focuses on restricting direct access
to an object's data.
• Abstraction is a broader concept that encompasses not only data hiding but also the
idea of simplifying the user's view of an object's functionalities.
SOFTWARE ARCHITECTURE
Software architecture refers to the high-level structure of a software system. It defines the
overall organization of the system, including:
• Components: The building blocks of the system, often represented as modules, services,
or subsystems.
• Relationships: How components are connected and how they depend on each other.
• Constraints: Rules and guidelines that govern the design and development of the
system, such as performance requirements, security considerations, and scalability
needs.
• Provides a Roadmap: It acts as a blueprint for the development team, guiding them in
building a system that meets the requirements and objectives.
• Reduces Risks: By identifying potential issues early in the development process, a good
architecture can help mitigate risks associated with complexity and integration
challenges.
Common Software Architecture Styles:
• Layered Architecture: Organizes the system into horizontal layers, each with a specific
responsibility (e.g., presentation, business logic, data access). Layers interact with each
other in a well-defined manner.
• Client-Server Architecture: Separates the user interface (client) from the core
functionality (server). This allows for easier maintenance and scalability.
PROGRAMMING PARADIGMS
1. Imperative Programming:
o Advantages:
o Disadvantages:
2. Procedural Programming:
o Advantages:
o Disadvantages:
▪ Complexity Can Creep In: Even with procedures, programs can still
become complex with intricate dependencies between functions. Imagine
a cake recipe with many sub-recipes – it can get hard to keep track of the
flow of data and control.
o Example: In our cake recipe analogy, procedures could represent functions like
mixDryIngredients and mixWetIngredients. These functions would be called from
the main recipe (program) to achieve the overall goal of baking a cake.
o Core Idea: OOP takes a different approach by organizing code around objects.
Objects encapsulate data (attributes) and related operations (methods) that
manipulate that data. It's like creating a "cake object" that holds all the
information and actions related to baking a cake.
o Advantages:
o Disadvantages:
4. Functional Programming:
o Advantages:
o Disadvantages:
5. Logic Programming:
o Advantages:
o Disadvantages:
While all programming paradigms have their strengths and weaknesses, OOP (Object-Oriented
Programming) offers several advantages that can make it a compelling choice for many projects,
especially those involving complex systems and data modelling.
o OOP promotes modularity by organizing code into classes that encapsulate data
(attributes) and related operations (methods). This modular structure improves
code maintainability and reusability. You can create reusable components
(classes) that can be easily integrated into different parts of your program or
even used in other projects.
o Objects naturally model real-world entities like users, products, bank accounts,
etc. This makes OOP code more intuitive and easier to reason about for problems
that involve such entities. Compared to functional programming or logic
programming, which might require a more abstract approach, OOP's object-
centric view can make the code more closely resemble the problem domain.
o OOP allows creating new classes (subclasses) that inherit properties and
behaviors from existing classes (parent classes). This promotes code reuse and
reduces redundancy. Additionally, polymorphism allows objects of different
classes to respond to the same method call in different ways. This flexibility
enhances code maintainability and can simplify complex interactions between
objects.
• Steeper Learning Curve: OOP concepts like classes, inheritance, and polymorphism can
have a steeper learning curve compared to simpler paradigms.
• Over-Engineering: For smaller projects, OOP can sometimes lead to overly complex class
hierarchies. It's essential to strike a balance between reusability and simplicity.
METHODOLOGIES:
Methodologies define a set of best practices, processes, and tools used to manage projects
from inception to completion. They provide a framework for:
• Planning and Requirement Gathering: Defining project goals, scope, and user needs.
• Task Management: Breaking down work into manageable tasks and assigning them to
team members.
• Collaboration: Facilitating communication and collaboration among team members.
• Quality Assurance: Ensuring the project meets quality standards and user requirements.
• Delivery and Feedback: Delivering project outcomes and incorporating feedback for
improvement.
• Enhanced Efficiency: They help streamline processes, avoid unnecessary work, and
optimize workflows.
• Reduced Risks: Proactive risk management helps identify and address potential issues
early on, mitigating their impact.
• Better Quality Outcomes: By following best practices and quality checks, methodologies
help deliver high-quality results.
There are various software development methodologies, each with its own strengths and focus
areas. Here are some widely used examples:
• Scrum: A popular Agile framework that uses sprints, backlog management, and daily
stand-up meetings for team synchronization.
• Kanban: A visual approach that uses boards and cards to represent workflow stages,
promoting continuous flow and visualization of tasks.
CATEGORIZING METHODOLOGIES
Methodologies can be categorized in several ways, depending on the specific aspect you're
interested in. Here are some common classification schemes:
1. By Development Lifecycle:
3. By Level of Formality:
4. By Project Type:
A well-structured C++ program is organized into logical components that enhance readability,
maintainability, and modularity. Here's a breakdown of the essential elements:
• Provide instructions to the preprocessor, which is a separate program that runs before
the actual compilation.
2. Global Declarations:
• Use global declarations sparingly to avoid naming conflicts and promote encapsulation
(explained later).
3. Functions:
• Encapsulate a specific task or set of instructions that can be reused throughout the code.
• Structure:
o { function body }: The code that executes when the function is called.
• Types of functions:
o Main function: The entry point of the program (usually named main).
4. Local Declarations:
• Variables and functions declared within the body of a function or block (e.g., within an if
statement).
• Examples:
6. Comments:
• Used to explain the purpose of code sections, improve readability, and document your
code.
• Types:
o Single-line comments: Start with //.
Example:
#include
library elements
int main() {
int number;
Key Points:
• Consider using header files to organize declarations and improve code reusability.
• Strive for a balance between global and local declarations for proper encapsulation and
modularity.
• The building blocks of programs, representing different kinds of data a program can
store and manipulate.
o Integers (whole numbers): int, short, long (depending on the size and range)
o Arrays: Collections of elements of the same data type, accessed using an index.
Variables:
• Must be declared with a data type and a name before being used.
• Naming Rules:
o Cannot be a keyword (reserved word) in the programming language (e.g., int, if,
for are keywords in C++)
• Can be assigned values using the assignment operator (=) and updated throughout the
program.
Operators:
o Comparison operators: ==, !=, <, >, <=, >= (for comparing values)
Expressions:
o Conditional statements: if, else if, else (execute code based on conditions)
o Looping statements: for, while, do-while (repeat code blocks a certain number of
times or until a condition is met)
Functions:
Comments:
• Lines of text that are ignored by the compiler but provide explanations for human
readers.
• Common functions for input: cin (C++), input() (Python), scanf (C)
• Common functions for output: cout (C++), print() (Python), printf (C)
Memory Management:
• The process of allocating and deallocating memory for variables and data structures.
• Some languages (like C) require manual memory management, while others (like
Python) handle it automatically.
PROGRAMMING ERRORS
1. Syntax Errors:
• These are the most basic errors and often the easiest to identify.
• They occur when the code violates the grammatical rules of the programming language.
• Examples:
2. Runtime Errors:
• These errors occur during the program's execution, not during compilation or
interpretation.
• Examples:
o Division by zero
o Dereferencing a null pointer (using a pointer that doesn't point to valid memory)
o Trying to open a non-existent file
• Symptoms: The program might crash abruptly, display error messages, or produce
unexpected results.
3. Logical Errors:
• These are the trickiest errors to catch as they might not prevent the program from
running but produce incorrect or unintended results.
• They stem from flaws in the program's logic or the programmer's understanding of the
problem.
• Examples:
o Infinite loops
• Symptoms: The program might run successfully but produce the wrong output or exhibit
unexpected behavior. Debugging logical errors often involves analyzing the program's
logic step-by-step and comparing its behavior to the intended outcome.
4. Linker Errors:
• These errors occur during the linking stage, where separate object files (compiled code
modules) are combined to create an executable program.
• They happen when the linker cannot find necessary functions, libraries, or symbols
referenced in the code.
• Examples:
o Circular dependencies between object files (where one file needs a function from
another, and vice versa)
• Symptoms: The linker throws an error message indicating that it cannot resolve symbol
references or complete the linking process.
5. Semantic Errors:
• These errors violate the programming language's rules or conventions but might not be
caught by the compiler or interpreter.
• They often involve using code that is technically valid but doesn't make sense
semantically (meaning-wise).
• Examples:
• Symptoms: These errors can be difficult to detect and might lead to unexpected
behavior or incorrect results at runtime. Often, careful code review and analysis are
required to catch semantic errors.
IDENTIFIER:
• It acts as a label that uniquely identifies that element throughout the program.
Types of Identifiers:
1. Predefined Identifiers:
o They represent keywords like int, float, if, else, for, while, etc., or standard library
functions like printf, cin (C++), print, input (Python).
o You cannot use predefined identifiers as your own variable or function names
because they have special meanings in the language.
2. User-Defined Identifiers:
o They allow you to create meaningful names that reflect the element's purpose.
• Case-sensitive: Uppercase and lowercase letters are considered different (e.g., age and
Age are distinct identifiers).
• Reserved words: Cannot use keywords (predefined identifiers) as your own identifiers.
• Meaningful names: Choose names that clearly indicate what the identifier represents
(e.g., customerName, productPrice, isRegistered).
• Avoid overly generic names: Don't use overly short or generic names like x, y, temp
unless their purpose is very clear within a small code block.
• Variable Identifiers: Names given to variables that can store and change their values
during program execution. (e.g., total, average, userChoice)
• Constant Identifiers: Names given to constants that hold fixed values that cannot be
changed during program execution. These are often declared using the const keyword or
uppercase letters by convention (e.g., PI, MAX_VALUE, GRAVITATIONAL_CONSTANT).
#include
int main() {
int age;
double accountBalance;
cout << "You are " << age << " years old." << endl;
return 0;
DATA TYPES
Define the kind of values a variable can hold and the operations that can be performed on
them.
C++ provides a variety of built-in data types for storing different kinds of data:
o int: Most common integer type, size varies depending on the system (typically 4
bytes).
o short: Smaller integer type, often used for memory optimization (usually 2
bytes).
o long: Larger integer type for bigger numbers (size varies, usually 4 or 8 bytes).
o long long: Even larger integer type for very big numbers (usually 8 bytes).
While standard data types are fundamental, C++ allows you to create your own complex data
structures:
• Arrays: Collections of elements of the same data type, accessed using an index. (e.g., int
numbers[10];)
o Example:
• struct Person {
• string name;
• int age;
};
OPERATORS
Operators are symbols that perform specific operations on data (operands) in C++ expressions.
Understanding operators is essential for manipulating data, making decisions, and controlling
program flow. Here's a breakdown of some common operators:
1. Arithmetic Operators:
o Examples:
▪ + (addition)
▪ - (subtraction)
▪ * (multiplication)
▪ / (division)
▪ % (modulo - remainder after division)
o Examples:
▪ x += 3: Equivalent to x = x + 3 (increases x by 3)
▪ y -= 2: Equivalent to y = y - 2 (decreases y by 2)
3. Relational Operators:
o Examples:
▪ == (equal to)
4. Logical Operators:
o Examples:
▪ && (AND): Both conditions must be true for the expression to be true.
▪ || (OR): At least one condition must be true for the expression to be true.
o Example:
age >= 18 ? cout << "You are eligible to vote." << endl; : cout << "You are not eligible to vote." <<
endl;
o Evaluates multiple expressions from left to right, returning the value of the
rightmost expression.
o Example:
o Syntax: object_name.member_name
FUNCTIONS
What is a Function?
A function is a reusable block of code that performs a specific task. It encapsulates a set of
instructions that can be called from different parts of your program, promoting modularity and
code organization.
1. Code Reusability: The same function can be called multiple times within your program
or even in different programs, avoiding code duplication and saving time.
2. Modularity: Functions break down complex programs into smaller, manageable units,
making the code easier to understand, maintain, and modify.
6. Information Hiding: Functions can hide implementation details, exposing only necessary
functionality through their interfaces (parameters and return type). This promotes
encapsulation and reduces coupling between program parts.
1. Predefined Functions:
o These functions are already defined by the C++ standard library and available for
use in your programs.
o Examples:
o They are typically declared in header files like <iostream>, <cmath>, <cstring>,
etc.
2. User-Defined Functions:
o Structure:
▪ return_type: The data type of the value the function returns (or
void if it doesn't return anything).
#include
int main() {
return 0;
By understanding and utilizing both predefined and user-defined functions, you can write
efficient, modular, and reusable C++ programs.
Return
void Any data type (or void)
Type
Returns a
No Yes
Value
void printMessage() { cout << "Hello!" << int addNumbers(int x, int y) { return
Example
endl; } x + y; }
Parameter passing refers to the mechanism by which arguments (values or variables) are passed
to functions when they are called. C++ uses pass-by-value for parameter passing. This means
that a copy of the argument's value is passed to the function, not the original variable itself.
Example:
• Function Definition
• Function Call
int main() {
int x = 5;
modifyValue(x);
However, for arrays and objects (complex data structures), passing a copy of the entire structure
might be inefficient.
In these cases, C++ provides references, which allow you to pass a reference to the original
memory location of the variable.
Variable scope refers to the part of the program where a variable is accessible and usable.
Understanding scope is crucial for avoiding naming conflicts and ensuring proper data access.
Types of Scope:
1. Block Scope: Variables declared within a code block (e.g., if statement, loop) are only
accessible within that block.
2. Function Scope: Variables declared within a function are only accessible within that
function and any nested functions within it.
3. File Scope (Global Scope): Variables declared outside any function but within the same
source file are accessible throughout the file. Use global variables sparingly as they can
lead to naming conflicts and make code harder to maintain.
Scope Rules:
1. A variable can't have the same name as a predefined identifier (keyword) in C++.
2. A variable can't be declared twice within the same scope (block or function).
3. A variable declared within an inner scope (e.g., nested function) takes precedence over a
variable with the same name in an outer scope.
Example:
void outerFunction() {
if (true) {
// cout << blockVar << endl; // Error: blockVar not accessible here
(out of scope)
int main() {
// cout << localVar << endl; // Error: localVar not accessible here
(out of scope)
outerFunction();
return 0;
}
FUNCTION PROTOTYPE VS. FUNCTION DEFINITION
Placed before the function's first call or at Placed after all other code in the
Location
the beginning of the source file source file
Specifies parameter list (data types and Must specify parameter list and match
Parameters
names) the prototype
Semicolon Ends with a semicolon (;) Does not end with a semicolon (;)
FUNCTION OVERLOADING
Function overloading refers to the ability to define multiple functions with the same name but
different parameter lists. This allows you to create functions that perform similar tasks but can
accept different types or numbers of arguments.
• Improved Readability: Function names can reflect their purpose more clearly, especially
for functions with similar functionalities.
• Flexibility: You can choose the appropriate function based on the type and number of
arguments you want to pass.
• Type Safety: The compiler can check for type mismatches between arguments and
function parameters, preventing errors.
Example
int main() {
return 0;
Function Overloading
In this example, we have two calculateArea functions with different parameter lists. The
compiler can identify which function to call based on the arguments provided in the main
function.
Note: Function overloading works based on the combination of function name and parameter
list. You cannot overload functions based solely on the return type.
C++ CONTROL STRUCTURES
They dictate the flow of execution in your program. They allow you to control which parts of
your code run and when, making your programs more dynamic and interactive. Here's a
breakdown of the three fundamental control structures:
1. Sequence:
• The most basic structure, where statements are executed one after the other in the
order they appear in the code.
Example:
C++
int x = 5;
double y = 3.14;
2. Selection:
• Also known as branching, allows you to choose between alternative code blocks based
on a condition.
o if-else statement: Executes one code block if the condition is true, another if it's
false.
Example:
C++
int grade = 85;
} else {
3. Iteration (Looping):
• Allows you to repeat a block of code a specific number of times or until a certain
condition is met.
o do-while loop: Executes a code block at least once, then continues to repeat it as
long as a condition is true.
Example:
C++
int count = 0;
1. Sequence:
Example:
#include
int main() {
cout << "The sum of " << num1 << " and " << num2 << " is " << sum
<< endl;
return 0;
Exam Question:
Write a C++ program that prompts the user to enter two numbers, calculates their sum, and
displays the result.
Selection (if-else):
Example:
C++
#include <iostream>
int main() {
int age;
} else {
return 0;
Exam Question:
Write a C++ program that asks the user for their age and determines if they are eligible to vote
(voting age is 18 or older). Print a message indicating their eligibility.
Example:
C++
#include <iostream>
int main() {
int num_students;
return 0;
DATA STRUCTURE
Data Structure:
• A data structure is a specialized format for organizing, processing, retrieving, and storing
data efficiently.
o Arrays
o Linked lists
o Stacks
o Queues
o Trees
o Graphs
ARRAYS
• Arrays are a fundamental data structure that store a collection of elements of the same
data type under a single name.
• They are efficient for random access (accessing any element directly using its index).
• Arrays are versatile and can be used for various problem-solving tasks, such as:
o Storing lists of items (e.g., student names, grades)
Array Implementation:
1. Define Array:
2. C++
3. data_type array_name[size];
5. C++
▪ During declaration:
▪ C++
▪ C++
▪ int scores[3];
▪ scores[0] = 85;
▪ scores[1] = 90;
8. Two-Dimensional Arrays:
o Two-dimensional arrays represent a grid or table-like structure.
o C++
o data_type array_name[rows][columns];
o Example:
o C++
o Example:
o C++
o cout << matrix[1][0] << endl; // Prints the element at row 1, column 0
Additional Notes:
• Be cautious of out-of-bounds access (trying to access elements outside the array's size),
as this can lead to program crashes.
Suppose you have an array to store the scores of 5 students. Write a C++ program to calculate
the average score:
C++
#include <iostream>
int main() {
int scores[5];
double average;
int sum = 0;
cout << "Enter score for student " << i + 1 << ": ";
// Calculate sum
sum += scores[i];
// Calculate average
cout << "The average score is: " << average << endl;
return 0;
This program demonstrates how to declare, initialize, access, and manipulate elements in a one-
dimensional array to solve a simple problem. You can extend this concept to more complex
scenarios using arrays effectively.
A structure (struct) is a user-defined data type that groups variables of potentially different data
types under a single name. This allows you to create composite data types that represent real-
world entities with various attributes.
2. Create Structure:
3. C++
4. struct structure_name {
};
Example:
C++
struct Person {
string name;
int age;
double height;
};
6. Instantiate Structure:
C++
Person person1;
o Access and modify member variables using the dot (.) operator:
8. C++
9. [Link] = "Alice";
[Link] = 1.75;
Structures are versatile and can be used for various problem-solving tasks:
o Representing Complex Objects: Define a structure to group related data for tasks
like storing student information (name, ID, grades), product information (name,
price, quantity), or employee data (name, position, department).
o Organizing Data: Structures help maintain data integrity and make code more
readable.
Imagine a library system where you need to store information about books. You can create a
Book structure to represent each book:
C++
struct Book {
string title;
string author;
int year_published;
bool is_available;
};
This structure defines four member variables to hold the book's title, author, publication year,
and availability status. You can then declare an array of Book structures to manage a collection
of books in the library.
o Data Organization: Organize related data into a single unit, making code more
readable and maintainable.
o Data Integrity: Ensures that data elements are always grouped together,
reducing errors.
o Efficiency: Can be more efficient than using separate variables for each data
element, especially when passing data to functions.
CLASSES
1. Class:
A class is a user-defined blueprint or template that represents real-world entities with their
attributes (data members or variables) and behaviors (methods or functions). Classes provide a
powerful way to encapsulate data and functionality, promoting modularity and code reusability.
2. Creating a Class:
3. C++
4. class class_name {
5. private:
7. public:
};
o protected: Members are accessible within the class and derived classes
(inheritance).
10. C++
class_name object_name;
o Define multiple methods with the same name but different parameter lists.
o The compiler selects the appropriate method based on the arguments provided
at the call.
13. C++
14. #include
16.
18. private:
19. string name;
21. public:
26. }
30. }
35. } else {
37. }
38. }
41. }
44. cout << depositor_name << " deposited $" << amount << endl;
45. deposit(amount); // Call internal deposit method
46. }
47. };
48.
51. [Link](100.0);
52. if ([Link](50.0)) {
53. cout << "Withdrawal successful. New balance: $" << [Link]() << endl;
54. } else {
56. }
58. return 0;
FILES
File streams provide a mechanism for your C++ programs to interact with files, allowing you to
read data from or write data to external storage.
• Text Files:
o Ideal for storing human-readable information like configuration settings, log files,
or source code.
• Binary Files:
o Used for storing machine-readable data like images, audio, compressed files, or
compiled program code.
FILE STREAMS
C++ provides file streams for working with files. Here are the main classes:
• fstream: Can be used for both reading and writing to a text file.
• ios (base class): Provides basic file operations used by the other stream classes.
• Opening a File:
▪ mode: Specifies how to open the file (e.g., ios::in for reading, ios::out for
writing, ios::app for appending to an existing file).
o Example:
Use member function is_open(): Returns true if the file is open successfully, false otherwise.
• Reading/Writing Data:
o Text Files: Use >> for reading and << for writing, similar to console input/output.
o Binary Files: Use member functions like read() and write() to handle raw bytes.
• Closing a File:
Use member function close(): Releases resources associated with the file. It's crucial to close
files when done to avoid data loss or resource leaks.
#include
#include
int main() {
ifstream inputFile("[Link]");
if (inputFile.is_open()) {
string line;
[Link]();
} else {
return 0;
Important Note:
• File operations can fail due to various reasons like file not found, permission issues, or
disk errors. Always handle potential errors using is_open() checks and appropriate error
handling mechanisms.
• Example:
C++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
if (outputFile.is_open()) {
[Link]();
} else {
return 0;
• C++ offers different modes for opening files, allowing you to control how the file is
handled:
o ios::app: Appends data to the end of an existing file (doesn't create a new file if it
doesn't exist).
o ios::in (for reading): Opens an existing file for reading. If the file doesn't exist, an
error occurs.
o ios::binary: Enables binary mode for reading or writing raw binary data (not
recommended for text files).
WRITE OPERATIONS:
• Use the insertion operator (<<) to write data to an open text file.
• Example (appending):
C++
if (outputFile.is_open()) {
[Link]();
READ OPERATIONS:
• Use the extraction operator (>>) to read data from an open text file.
• Text files usually contain lines of text that can be read using getline().
• Example:
C++
ifstream inputFile("[Link]");
if (inputFile.is_open()) {
string line;
[Link]();
} else {
cerr << "Error: Could not open file for reading." << endl;
Example Program:
Here's a C++ program that demonstrates reading a text file, counting the number of lines, and
displaying the result:
C++
#include <iostream>
#include <fstream>
int main() {
string filename;
int lineCount = 0;
getline(cin, filename);
ifstream inputFile(filename);
if (inputFile.is_open()) {
string line;
lineCount++;
[Link]();
cout << "The file '" << filename << "' has " << lineCount << " lines." << endl;
} else {
cerr << "Error: Could not open file '" << filename << "'." << endl;
return 0;
Explanation:
1. Include headers:
o <iostream> for input/output operations (cout, cin)
2. Declare variables:
3. Get filename:
o Prompt the user to enter the file name and store it in the filename variable using
getline (to handle spaces).
o Create an ifstream object named inputFile and pass the filename as an argument.
o Create a string variable line to store each line read from the file.
o Use a while loop with getline(inputFile, line) to read each line until the end of file
is reached.
o Inside the loop, increment the lineCount for each line read.
7. Display results:
o If the file was opened successfully, print a message with the file name, line count,
and a newline character (endl).
o If there was an error opening the file, print an error message with the file name.
8. Return 0: