lOMoARcPSD|53287610
CSC 509 - Lecture 4 - Compiled by Dr Salaamudeen
Alhassan
Object Oriented Programming with C++ (University for Development Studies)
Scan to open on Studocu
Studocu is not sponsored or endorsed by any college or university
Downloaded by Idris Olalekan (
[email protected])
lOMoARcPSD|53287610
Code: CSC 409
Title: Object Oriented Programming with C++
Lecture 4
▪ Functions
A function is a block of code that performs a specific task when called.
• Why use functions?
1 Code Reusability
2 Easier to maintain
3 Improved readability and modularity
• Types of Functions
1 Built-in Functions: Predefined in C++ libraries (e.g., sqrt(), cout, cin,
printf()).
2 User-defined Functions: Custom functions created by the programmer.
• Syntax of a Function
returnType functionName([parameters]) {
// body of the function
return value; // optional
}
1 returnType: Type of value returned by the function (e.g., int, void, float).
2 functionName: Identifier for the function.
3 parameters: Inputs (optional).
4 return: Ends the function and returns a value.
• Example of a Simple Function
#include <iostream>
using namespace std;
int addNumbers(int a, int b) {
return a + b;
}
int main() {
int result = addNumbers(5, 10);
cout << "Sum is: " << result << endl;
return 0;
}
1 addNumbers(int a, int b) is a user-defined function that adds two
integers.
2 main() calls the addNumbers function and prints the result.
• Function Declaration vs. Definition
Page 1 of 10
lOMoARcPSD|53287610
1 Declaration (Prototype): Informs the compiler about a function before it is
defined.
int multiply(int, int); // Declaration
2 Definition: Contains the actual code.
int multiply(int x, int y) {
return x * y;
}
• Calling a Function
1 Syntax:
functionName([arguments]);
2 Example
int result = multiply(4, 5); // Calls multiply
function
• Types of User-defined Functions
1 Void Functions (no return value)
void greet() {
cout << "Hello, World!" << endl;
}
2 Value-returning Functions (returns a value)
int square(int num) {
return num * num;
}
• Function Parameters
1 Pass by Value: Copies values to parameters.
void display(int x) {
cout << x << endl;
}
2 Pass by Reference: Uses references to modify the original variable.
int a = 5;
int b = 3;
swap(a, b);
cout>>a>>b;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
• Arguments
Page 2 of 10
lOMoARcPSD|53287610
1 Allows default values for parameters.
int add(int x, int y = 10) {
return x + y;
}
▪ Example: add(5) will return 15.
• Function Overloading
1 Multiple functions with the same name but different parameters.
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
• Inline Functions
1 Inline keyword suggests the compiler to insert function code directly into the
calling location for performance.
inline int cube(int x) {
return x * x * x;
}
• Recursion
1 A function calling itself.
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
• Scope and Lifetime of Variables
1 Local Variables: Declared inside a function, accessible only within it.
2 Global Variables: Declared outside all functions, accessible throughout the
program.
• Function Pointers
1 A function pointer is a pointer that points to the address of a function.
2 Syntax:
returnType (*pointerName)(parameterTypes);
3 Example:
#include <iostream>
using namespace std;
int add(int a, int b) {
Page 3 of 10
lOMoARcPSD|53287610
return a + b;
}
int main() {
int (*funcPtr)(int, int) = &add; // Function
pointer declaration
cout << "Sum: " << funcPtr(5, 10) << endl; //
Calls add function
return 0;
}
• Lambda Functions (C++11 and above)
1 Anonymous functions that can be defined inline without a name.
2 Syntax:
[ captureList ] ( parameterList ) -> returnType {
functionBody;
};
3 Example:
#include <iostream>
using namespace std;
int main() {
auto multiply = [](int a, int b) -> int {
return a * b;
};
cout << "Product: " << multiply(5, 4) << endl;
return 0;
}
4 Capture List: Specifies which variables are accessible from the enclosing
scope.
• Const Functions
1 A const member function does not modify the object.
2 Syntax:
class Rectangle {
int width, height;
public:
int getArea() const {
return width * height;
}
};
• Static Functions
1 A static function belongs to the class rather than an object.
2 Usage: Shared by all objects of the class.
class Math {
Page 4 of 10
lOMoARcPSD|53287610
public:
static int cube(int x) {
return x * x * x;
}
};
int main() {
cout << "Cube: " << Math::cube(3) << endl; //
Access without object
return 0;
}
• Function Templates
1 Allows defining functions that operate on different types.
2 Syntax:
template <typename T>
T getMax(T a, T b) {
return (a > b) ? a : b;
}
3 Example:
int main() {
cout << "Max of 10 and 20: " << getMax(10, 20)
<< endl;
cout << "Max of 5.5 and 2.2: " << getMax(5.5,
2.2) << endl;
return 0;
}
• Recursive Function vs. Iteration
Feature Recursion Iteration
Definition Function calls itself Looping construct (for, while)
Complexity More memory usage (stack frames) Less memory overhead
Example factorial(n) for(int i=1; i<=n; i++)
• Function Overloading vs. Function Templates
Page 5 of 10
lOMoARcPSD|53287610
Feature Function Overloading Function Templates
Definition Multiple functions with same One template for all data
name but different parameters types
Code Duplication Possible Avoided
Example int sum(int a, int b) and template <typename T> T
double sum(double a, double sum(T a, T b)
b)
• Common Errors in Functions
1 Forgetting to return a value: When a non-void function does not return a
result.
2 Mismatched parameters: Calling a function with incorrect arguments.
3 Infinite recursion: Forgetting the base case in recursive functions.
• Performance Considerations
1 Use inline functions to avoid overhead for small functions.
2 Avoid deep recursion for large datasets to prevent stack overflow.
3 Prefer passing by reference over value for large data structures.
• Practical Applications
1 Functions are used in sorting algorithms, searching, and data manipulation.
2 Key to modular programming in real-world projects like banking systems,
gaming, and scientific computation.
• Best Practices
1 Keep functions short and focused on a single task.
2 Use descriptive names for functions and parameters.
3 Avoid global variables when possible.
4 Use comments to explain complex logic.
• Arrays
o An array is a collection of variables of the same type stored in contiguous
memory locations.
o Why use arrays?
▪ Store multiple values in a single variable.
▪ Simplify the management of related data.
o Array Declaration
▪ Syntax:
dataType arrayName[size];
Page 6 of 10
lOMoARcPSD|53287610
▪ Example:
int numbers[5]; // Declares an array to store
5 integers
▪ Array Initialization
▪ During declaration
int numbers[5] = {1, 2, 3, 4, 5};
▪ Partial initialization (remaining values set to 0)
int numbers[5] = {1, 2};
▪ Without specifying size:
int numbers[] = {1, 2, 3};
▪ Accessing Array Elements
▪ Elements are accessed using indices.
▪ Example:
cout << "First element: " << numbers[0]; // Access first
element
▪ Traversing an Array
▪ Use a loop to access all elements:
for(int i = 0; i < 5; i++) {
cout << "Element " << i << ": " <<
numbers[i] << endl;
}
▪ Types of Arrays
▪ One-Dimensional Array:
▪ Example: int arr[5];
▪ Two-Dimensional Array:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
▪ Multi-Dimensional Arrays (more than 2 dimensions).
▪ Example of 2D array
#include <iostream>
Page 7 of 10
lOMoARcPSD|53287610
using namespace std;
int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
▪ Character Arrays (Strings)
▪ Example:
char name[6] = "Alice"; // Null-
terminated string
▪ Use cin, cout to handle strings:
char input[20];
cin >> input; // Takes a single word
▪ Common Operations on Arrays
▪ Finding the sum of array elements:
int sum = 0;
for(int i = 0; i < n; i++) {
sum += arr[i];
}
▪ Finding the maximum element:
int max = arr[0];
for(int i = 1; i < n; i++) {
if(arr[i] > max) {
max = arr[i];
}
}
▪ Passing Arrays to Functions
▪ Example of pass-by-reference:
void printArray(int arr[], int size) {
Page 8 of 10
lOMoARcPSD|53287610
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
▪ Call
printArray(numbers, 5);
▪ Limitations of Arrays
▪ Fixed size (static memory allocation).
▪ Lack of bounds checking (accessing arr[10] in a size-5 array is
undefined behavior).
▪ Inflexibility compared to modern data structures like vectors.
▪ Dynamic Arrays
▪ Use new to allocate memory dynamically.
int* dynArray = new int[size];
▪ Free the memory:
delete[] dynArray;
• Multi-dimensional Array Example
int matrix[2][2] = {
{1, 2},
{3, 4}
};
cout << matrix[1][0]; // Outputs 3
▪ Best Practices for Arrays
▪ Use descriptive names for array variables.
▪ Initialize arrays before use.
▪ Avoid magic numbers – use constants for array size.
▪ Prefer vectors for dynamic size requirements.
▪ Practical Applications of Arrays
▪ Storing and manipulating lists of data (e.g., student grades,
temperature readings).
▪ Use in sorting algorithms (bubble sort, merge sort).
▪ Matrix operations in scientific computing.
Page 9 of 10
lOMoARcPSD|53287610
• Assignment
Design a C++ program to manage student records using functions. Your program
should perform the following tasks:
1 Input Student Details:
Create a function named inputStudentDetails that accepts student data from
the user. Each student should have the following attributes:
▪ Name (string)
▪ Sudent Id(int)
▪ Marks in three courses (float)
2 Calculate Average Marks:
Create a function calculateAverage that takes the marks of a student as
arguments and returns the average.
3 Display Student Information:
Create a function displayStudentDetails that displays the student’s name, roll
number, marks in each subject, and the calculated average marks.
4 Find and Display the Topper:
Use a function findTopper to determine which student has the highest average
marks and display their details.
5 Additional Requirements:
▪ Use an array of structures to store the data for multiple students.
▪ Use function prototypes and appropriate return types.
▪ Use pass-by-reference where applicable to update student
information.
6 Constraints
▪ Assume a maximum of 5 students for this exercise.
▪ Handle invalid input gracefully (e.g., negative marks).
Page 10 of 10