0% found this document useful (0 votes)
27 views

Modular Programming and Algorithms II

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Modular Programming and Algorithms II

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Module 6. Modular Programming and Algorithms Pt.

2
In the previous module, we discussed the practice of modular programming and
standard algorithms being central to efficient coding and software development. This
module introduces more principles of modular programming.

You've learned that functions let you reuse blocks of code numerous times, saving
you from having to repeat lots of code. This module looks at Header files that work
similarly, allowing you to reuse entire files that include any number of functions. They
let you separate programs into several files and allow you to use the code of one file
in another file.

You will also learn about a fundamental data type of C++, the string. You previously
learned how to store your name and other words in arrays of characters. This is
done so frequently that C++ has a data type that will handle all the complexity for
you, and allow operations of words such as adding (concatenating) words together to
form a sentence.

In this module, you will explore:

● Learn further about the modular programming approach, breaking down


complex programs into manageable and reusable modules or functions.
● Gain insights into pass-by-reference parameter passing, and how it affects
the calling variables.
● Gain insights about C++ header files and its usage
● Gain insights about C++ strings and its usage

To enhance your understanding, we have tailored specific learning activities:

● Write a function that uses pass-by-value and demonstrates its effect on


the caller's variables.
● Write a program to calculate the area of a triangle, using Header Files and
Built-in Libraries.
● Write a program to implement an algorithm that reads in a sentence and
search string. Then count the occurrences of the search string within the
sentence.

Subject Learning Outcomes


The material in this module relates to the following subject learning outcomes:

​ SLO 3: Learn to implement complex data structures like stacks, queues,


trees, and graphs, as well as algorithms for sorting and searching.

Student Expectations

During this module, you are expected to spend time working through the prescribed
material prior to attending class. This will enable a more valuable discussion to take
place in online tutorials or conferences, where you will be able to discuss concepts,
present ideas and explore information collaboratively in greater depth.

Accordingly, it is suggested that you allow:

4 hours for facilitated study. This includes guided facilitated study, watching or
attending course lectures (live or pre-recorded), responding to facilitator feedback.

8 hours for personal study. This includes reading through course material,
undertaking learning activities and exploring additional related resources.

Topic 3. Pass-by-Reference Parameter Passing

Key takeaways from this topic...


1. Pass-by-reference allows a function to modify the caller's variables directly,
facilitating data manipulation without creating a copy.
2. Using pass-by-reference can save memory, as it avoids creating copies of
large data structures.
3. While pass-by-reference is powerful, it can also introduce errors if not used
carefully, as changes to the variable within the function affect its original value.

Learner Guide

The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All

Panels

Collapse All

Panels

Section 1: Understanding Pass-By-Reference and Its Comparison with


Pass-By-Value

In programming, particularly in languages such as C++, parameter passing is a


technique where you provide inputs to functions. There are several methods to pass
parameters, and one of the most commonly used methods is "pass-by-reference".
This method not only facilitates the efficient use of memory but also allows the
function to modify the original data.

Understanding Pass-By-Reference
Pass-by-reference is a parameter passing method where a function receives the
reference or memory address of the arguments, rather than their values. This
approach allows the function to access and modify the original variables, which can
enhance the functionality and efficiency of programs. Key features of this method
include:

● Memory Efficiency: Since only the memory address is passed, it prevents


duplication and saves memory space.
● Data Modification: Functions can alter the original data as they have
access to the memory address where the data is stored.
● Complex Data Handling: It is beneficial when working with complex data
structures, as it avoids the overhead of copying large amounts of data.

Comparison with Pass-By-Value

Understanding pass-by-reference becomes clearer when compared with


pass-by-value, another prevalent parameter passing method. In the pass-by-value
approach, a copy of the data is passed to the function, and any modifications made
inside the function do not affect the original data. The comparison between the two
methods can be summarised as follows:

● Memory Usage: Pass-by-reference is more memory-efficient as it avoids


data duplication, unlike pass-by-value where a copy of data is created.
● Data Alteration: In pass-by-value, the original data remains unaffected by
the function's operations, whereas pass-by-reference allows for direct
modification of the original data.
● Use Cases: Pass-by-value is suitable for smaller data sets or when you
want to ensure the original data is not modified. On the other hand,
pass-by-reference is ideal for larger data sets and when modification of
the original data is necessary.

Further Reading

Parameter Passing in C++


Links to an external site.

Explore these methods of parameter passing with code examples.

Reference: Geeks for Geeks 2023, 'Parameter Passing in C++', Geeks for Geeks, accessed 31
January 2024, <https://www.geeksforgeeks.org/parameter-passing-techniques-in-cpp/>

Section 2: Real-World Applications of Pass-By-Reference

Real-world scenarios witness a significant application of pass-by-reference


parameter passing, showcasing its efficiency and utility. Here are some of the
applications where this concept is predominantly applied:

● Database Management: In systems where large databases are handled,


pass-by-reference assists in efficient memory management, facilitating
quicker data retrieval and modification.
● Gaming Industry: Game developers use this method to efficiently manage
and modify game states without incurring the overhead of copying large
data sets.
● Simulation Software: In simulations where real-time data modification is
essential, pass-by-reference enables seamless data updates, providing
accurate and timely results.

Section 3: Case Study: Enhancing Performance in a Financial Analytics Tool


Background

In the competitive financial sector, analytics tools play a pivotal role in facilitating
data-driven decisions. A leading financial analytics firm was grappling with
performance bottlenecks in their flagship tool, which was primarily attributed to the
existing method of pass-by-value parameter passing. This method was causing
delays, particularly during real-time data analysis phases, leading to high memory
consumption and consequently, slower processing times.

Objective

The primary objective was to augment the tool's performance by reducing memory
consumption, thus facilitating more efficient real-time data modification capabilities.
The aim was to revamp the system's core functionalities to streamline processes,
reduce latency, and offer more accurate and timely insights to their clients.

Implementation

To address the issue, the firm initiated a comprehensive analysis to pinpoint the
exact causes of the delays. It was decided to shift from the current pass-by-value
parameter passing method to a more efficient pass-by-reference parameter passing
technique. This shift involved significant changes in the coding structure and data
handling processes within the tool. Key strategies implemented included:

● Algorithm Optimisation: The development team worked meticulously to


optimize the existing algorithms, enhancing their performance and
reducing computational complexity.
● Memory Management: The new method facilitated better memory
management by eliminating the need to create multiple data copies,
thereby saving considerable memory space.
● Real-Time Data Modification: With the shift to pass-by-reference
parameter passing, the tool was now capable of conducting real-time data
modifications, which enhanced the accuracy and speed of financial
analyses.
● Testing and Deployment: Before fully integrating the changes, extensive
testing was conducted to ensure the stability and reliability of the updated
tool.

Outcome

Post-implementation, the tool demonstrated a significant improvement in


performance. It could now offer quicker data analyses and facilitate real-time
modifications. Clients noted a marked improvement in the speed and accuracy of the
analytics provided, fulfilling their needs for more precise and timely financial insights.

Furthermore, the transition led to an increase in client satisfaction levels, as they


could now make data-driven decisions faster, giving them a competitive edge in the
fast-paced financial sector.

Topic 2. Header Files and Built-in Libraries

Key takeaways from this topic...


1. Header files in C++ are used to declare functions, classes, and variables,
allowing code to be modular and reusable across different source files.
2. The #include directive is used to include header files in a C++ program,
enabling access to the declarations and definitions contained within them.
3. C++ provides standard header files (like <iostream> and <cmath>) for
built-in functionalities, while programmers can also create user-defined
header files to encapsulate their own functions and classes.

Learner Guide

The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All

Panels

Collapse All

Panels

Section 1: Header Files and Built-in Libraries

In this topic, you will learn how to create, modify, and use Header files. You will then
learn about libraries of functions that you can use within your program, by including a
header file, which lets you use decades of work by incredible programmers to help
you solve common problems in your own programs. You will learn about common
libraries such as the C math library and C type library.

What are header files?


Header files contain declarations, including function declarations, which can be used
in our main C++ program. For example, iostream is included in our main program to
use cout to print something to the console window.

Header files usually have a .h extension by convention. We can use as many header
files in our program as we like, and we can define our own.

Header files allow us to use existing functions already defined and tested by other
programmers. One programming principle is to avoid ‘recreating the wheel’. In other
words, if someone has already done it and it works well and is used by many, there
is no reason not to use it yourself.

They are necessary as our programs become larger.

Why the concern about large programs?

A large .cpp file increases the compile time. As our program gets bigger we will have
more lines of code, and if everything is in a single file, then everything must be
recompiled every time you make a change.

It keeps our code more organised. If you separate concepts into specific files, it is
easier to find the code you are looking for when you are making modifications. The
biggest source of bugs in code is caused by code that is hard to understand because
it is poorly organised.

Header files and libraries

Header files declare the functions implemented in a library.

○ Include in your program to use those functions.


○ Contents of header files are added to your source.cpp during
preprocessing.
Libraries contain the function implementations.

○ Separately compiled.
○ Automatically or manually linked by the compiler when your
source code is built.

Types of header files in C++

● Standard built-in header files


○ Provide basic function declarations.
○ Implemented with installed libraries.
○ Libraries are automatically linked by the compiler.
○ Examples, iostream, iomanip, etc...
● User header files
○ Functions that are not included in a built-in library.
○ Associated libraries must be manually linked during compilation.
○ Anyone can create and provide functions for others to use.

Standard built-in header files

Example

#include <iostream>

using namespace std;

int main()
{
cout << "hello, world!" << endl;
return 0;
}
This example program prints “Hello, world!” to the console window using cout. This
program does not have any definition or declaration about the cout, so how does the
compiler know about it?

The answer is, cout has been forward declared in the iostream header file.

When we use #include <iostream> we are requesting the preprocessor to copy all
the contents of iostream from the file named “iostream” into our source.cpp.

Topic 3. Strings

Key takeaways from this topic...

1. In C++, strings are represented as sequences of characters and can be


handled using the standard library's std::string class for easier
manipulation compared to character arrays.
2. C++ provides a variety of built-in functions for string manipulation, including
concatenation, substring extraction, and searching, making it simple to work
with text data.
3. While std::string is commonly used, strings can also be represented as
character arrays, which require careful management of memory and
null-terminators to indicate the end of the string.

Learner Guide

The Learner Guide provides the core knowledge for this topic. Work through the
materials and be prepared to discuss these in your forums, tutorials or classes.

Expand All
Panels

Collapse All

Panels

Section 1: Strings

Strings are handily provided to us in a library that we can include in our project via a
header file, another great example of a library we can use in our project that saves
us having to write our own functions!

During the lectures, you will learn about all the operations that we would want to
perform on a string, such as changing out letters in a string, comparing two strings to
see if they are the same, adding characters to the end of a string, and much more.

By using strings we can quickly change the data within a string, such as adding new
words to a string or replacing words in a string, for example, we could turn the string
from “Happy” to “Happy Birthday!” or “Happy Holidays!” by simply adding two words
to a string.

C-strings

C-strings, or character strings, are arrays of characters in C++ that end with a null
terminator (\0), which indicates the end of the string. Unlike the std::string
class, C-strings require manual memory management and careful handling to avoid
overflow and other issues. While they can be used for string manipulation, they often
involve more complex syntax and functions from the C standard library, such as
strlen() for length and strcpy() for copying.

Example:

char name[] = "Susan";


One dimensional array of characters which is terminated by a null character ‘\0'. C++
supports a wide range of functions that manipulate null-terminated strings.

Operations on character arrays <cstring>

Function Description

strcpy(s1, s2) Copies string s2 to s1.

strcat(s1, s2) Concatenates string s2 onto the end of


string s1.

strlen(s1) Returns the length of the string.

strcmp(s1, s2) ● Returns 0 if s1 and s2 are the


same;
● Less than 0 if s1 appears before
s2 in lexical order;
● Greater than 0 if s1 appears
after s2 in lexical order

https://docs.microsoft.com/en-us/cpp/standard-library/cstring
Links to an external site.

The String class

C++ Library - <cstring>

The standard C++ library provides a string class type that can be used for storing
text, such as “hello” or “My name is Tom!”.

String objects are dynamic, unlike character arrays, strings are not fixed.

The size of a string grows and shrinks when its contents change.

A string variable contains a collection of characters surrounded by double quotes.

https://en.cppreference.com/w/cpp/string/basic_string

Links to an external site.

Using the string class

To use strings, we must include an additional header file in the source code.

#include <cstring>

Create a variable of type string and assign the value enclosed in double quotes:
string message = "Hello";

We should also include using namespace std; to make the short name string visible
instead of std::string.

Further Resources
The resources in this section are for further exploration, providing additional
information for deeper insights.

Expand All
Panels
Collapse All
Panels
Reading: Pass-by-value vs Pass-by-reference — with C++ examples
This article explains how functions handle values when called in programming. When
calling a function, values can be passed either by value or by reference. The article
includes simple code examples for both pass-by-value and pass-by-reference,
clarifying the concepts with code and comments.

Pass-by-value vs Pass-by-reference — with C++ examples

Reference: Karimov I 2020, Pass-by-value vs Pass-by-reference — with C++ examples, Medium


(website), accessed 18 January 2024,
<https://medium.com/star-gazers/pass-by-value-vs-pass-by-reference-with-c-examples-911e7e81ae6
5>

Video: Header Files - C++ Tutorial For Beginners


The video explains the purpose and structure of header files in C++, emphasising
their role in organising code and separating function declarations from
implementations to enhance clarity and encapsulation. It demonstrates how to create
header files, include them in source files, and compile multiple files to maintain
modularity in larger applications.

Header Files - C++ Tutorial For Beginners

Links to an external site.

(09:39)
Reference: NeuralNine (2020) 'Header Files - C++ Tutorial For Beginners', YouTube [online video]
<https://www.youtube.com/watch?v=0TCh01BBlrM> Accessed 16 Sept. 2024

Video: Strings - C++ Tutorial For Beginners


This C++ programming tutorial provides an introduction to handling strings in C++,
differentiating between C-style strings and C++ string objects. It covers the creation
and manipulation of strings, including essential functions like strcpy, strcmp, and
strcat, while also discussing the security risks associated with using C strings, such
as buffer overflow vulnerabilities. The tutorial explains the advantages of using the
std::string class in C++, highlighting its ease of use, built-in methods for length and
comparison, and safer memory management.

Strings - C++ Tutorial For Beginners

Links to an external site.

(19:10)

Reference: NeuralNine, 2020, 'Strings - C++ Tutorial For Beginners', YouTube [online video]
<https://www.youtube.com/watch?v=zo6B_eJmeLo> Accessed 16 Sept. 2024

You might also like