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

Control Structures and Data Structures I

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

Control Structures and Data Structures I

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

Module 3.

Control Structures and Data Structures -


Part 1
In this module, you will advance your programming skills by learning how to create
paths in your programs based on your data. For example, you may want your
program to add two variables together with the addition operator if some data is a
certain value, but if that data is not that value you may instead want to multiply those
two variables together.

The process of creating paths that your program can follow is achieved with
conditional statements. This is the basis of AI (Artificial Intelligence) as your program
is now able to make decisions for itself based on the data you provide it!

During the lectures, you will learn about the many conditional statements that C++
provides, such as the If condition statement that lets your program execute
instructions only if some data is a specific value. If it is not that specific value you can
instruct your program to execute other instructions using an else conditional
statement.

Data structures are fundamental to computer science and programming, providing a


means of organising and storing data in a computer so that it can be accessed and
modified efficiently. Understanding how to work with different types of data
structures, such as lists, arrays, and linked lists, is vital for any software developer or
computer scientist.

In this module, you will:

● Explore solutions for handling conditional and repetitive statements and


how they are used in real-world applications.
● Learn about conditional statements, including how to write programs that
demonstrate this essential concept.
● Discover the methods for handling repetitive statements in projects,
promoting efficient looping constructs.
● Learn what data structures are, their importance, and their application in
programming.
● Investigate the process of creating applications, focusing on the
application of data structures.

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

● Write a program to find the minimum of three numbers


● Write a program to display a multiplication table
● Create an array and loop through it.
Subject Learning Outcomes

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

​ SLO 2: Gain the ability to create and modify basic data structures such as
arrays and linked lists, along with performing operations like insertion,
deletion, and traversal.

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 1. Conditional Statements

Key takeaways from this topic...


1. The if statement in C++ executes a block of code if a specified condition is
true, allowing for basic decision-making.
2. else and else-if provide additional pathways for code execution when the
initial if condition is false, enabling multiple conditions to be tested
sequentially.
3. The switch statement offers a way to select and execute code from multiple
potential branches based on the value of a variable, simplifying complex
conditional logic.

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: Conditional Statements

This module introduces you to the conditional statements that C++ provides—if, if
else, if … else, switch, ?:, and also how to nest these conditions amongst each other.
To use these statements you will need to use relational operators which you learnt
about in the previous module, and we will recap again.

By combining both relational operators and conditional statements you can make
your programs make decisions! To understand the decisions that the program makes
you will learn about flowcharts which will provide a visual way of representing the
decisions and the outcomes.

if statement

Programs often take actions based on conditions, only executing particular


statements when some condition is true. The if statement selects and executes one
or more statements based on some condition. If the condition is true, then the
statements in the if block are executed. If the condition evaluates to false then the
statements are skipped and the program control passes to the statement following
the if statement.

Example:

if (age >= 18)

{
cout << “You may enter!\n”;
}

if...else statement

Depending on the outcome of the condition, the if...else statement causes one of the
two possible statement(s) to execute.

An if statement can be followed by an optional else statement, which executes when


the condition is false. If the condition evaluates to true, the statement(s) inside the
body of if is executed. If the condition evaluates to false, the statement(s) inside the
body of else is executed.
Example:

if (age >= 18)

{
cout << “You may enter!\n”;
}

else

{
cout << “You aren't old enough.\n”;
}

Switch case statement

A switch case statement is used when we have multiple conditions that lead to
different outcomes. We can use lengthy if...else if...else, but it gets messy with more
than a few possible outcomes.

The switch case is a clean and efficient method of handling multiple conditions.

Example:

switch (age)

case 16:

cout << “Sweet sixteen!\n”;

break;
case 18:

cout << “Welcome to adulthood!\n”;

break;

case 50:

cout << “The good stuff starts now!\n”;

break;

default:

cout << “This is a great age!\n

break;

Topic 2. Loops

Key takeaways from this topic...

1. The for loop in C++ is used for iterating over a sequence of values with a
known number of iterations, defined by initialisation, condition, and increment
expressions.
2. The while loop repeatedly executes a block of code as long as a specified
condition remains true, suitable for scenarios where the number of iterations
is not known in advance.
3. The do-while loop guarantees that the block of code will run at least once
before checking the condition, making it useful for cases where an initial
execution is necessary.
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: Loops

In this topic, you'll catapult the effectiveness


of your programs by adding loops. Up until now, your instructions will have been
executed once by the computer, but using loops you will be able to instruct the
computer to execute instructions as many times as you wish. 1 time, 10 times,
infinite times!

This topic introduces you to the three types of loop statements that C++
provides—for, while, do while. Like conditional statements, you need to use relational
operators. By combining both relational operators and loop statements you can
instruct your programs to execute a set of instructions as many times as you like.
You can also instruct the program to stop a loop by using special keywords in C++,
which we will soon cover.

Imagine a game that runs until the player closes it, to achieve this you will tell the
computer to run a sequence of instructions over and over again, using a loop, until
the player presses the quit button. Loop statements allow you to specify how many
times you want the computer to run a specific set of instructions. Flowcharts will
again be demonstrated to visualise how the computer will loop over your instructions.

What are loops?

So far, we have been writing statements that get executed sequentially, one
statement followed by another. Loops allow a programmer to repeatedly execute a
block of statements until a condition is satisfied.

Let’s say we want to print “Hello, world!” 5 times. We could do it sequentially, like
this:

cout << "Hello, world!" << endl;


cout << "Hello, world!" << endl;
cout << "Hello, world!" << endl;
cout << "Hello, world!" << endl;
cout << "Hello, world!" << endl;

Or we can use loops to make our code leaner, more efficient and DRY.

DRY: Don’t Repeat Yourself


A key programming principle that you should aspire to is DRY code, meaning that
when possible, avoid repeating lines of code. This is important because it makes our
code easier to read and maintain. If we repeat code, and that code requires a
change, we have to remember to make the change in multiple places if the code is
repeated.

Loops are one tool you can use to keep code DRY.

Loop types

C++ programming language provides the following types of loops:

for loop

for (init; condition; expression)


{
statement(s);
}

Example:

int main()
{

for (int i = 0; i < 10; ++i)


{
cout << "hello, world!" << endl;
}

return 0;
}
while loop

while (condition)
{
statement(s);
}

Example:

int main()
{

int m = 1;

while (m <= 10)


{
cout << "hello, world!" << endl;
m++;
}

return 0;

do...while loop

Syntax:

do
{
statement(s);
} while (condition);
Example:

int main()
{

int m = 1;

do
{
cout << "Value of m: " << m << endl;
m++;
} while (m <= 6);

return 0;
}

Nested loops

The body of a loop can contain another loop known as a nested loop. The inner loop
must be completed each time through the outer loop.

In the following example, the ‘row’ loop starts first, then enters the ‘column’ loop and
executes the statements inside the column loop until it reaches 5 loops or iterations.
Then, it exits out of the column loop and goes through the row loop again as the
steps are repeated until the number of iterations through the ‘row’ loop reaches 5.

for (int row = 1; row <= 5; row++)


{

for (int col = 1; col <= 5; col++)


{
cout << "row " << row << ", col " << col;
cout << "\t";
}
cout << endl;
}

Loop control statements

Sometimes, you might want to skip the execution of a loop for a certain condition or
terminate it immediately without checking the condition. In C++ there are two
statements to specifically alter the normal flow of a loop. They are:

● break
● continue

For example, we want to loop through the data of all aged people except those aged
55. Or if we want to find the first person aged 20. In these scenarios, break and
continue statements can be used.

Topic 3. Introduction to Data Structures

Key takeaways from this topic...

1. The foundational understanding of data structures allows for more efficient


data management and manipulation in software development.
2. Data structures are not one-size-fits-all; different types serve different
purposes, be it stacks, queues, arrays, or linked lists.
3. Data structures play a critical role in the efficiency of algorithms, directly
affecting computational complexity and runtime.
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 Data Structures

source: Geeks for Geeks

Data structures serve as the backbone for organising information in the realm of
programming. Much like how a library arranges books on shelves, data structures
help you organise and store data in your programs. Understanding how to properly
utilise these structures will set you on a path towards becoming a proficient
programmer.

Types of Data Structures

Different tasks call for different types of organisation. In the world of data structures,
you have several options to fit your specific needs:

Linear Structures

● Arrays: Fixed in size, arrays offer quick access but fall short when it
comes to dynamic resizing. They’re best for situations where you know the
size of the data set in advance.

● Linked Lists: Comprising nodes connected by pointers, linked lists are


dynamic, making it easier to insert and delete elements. However, this
flexibility comes at the cost of slower data retrieval compared to arrays.

Hierarchical Structures

● Trees: Imagine a tree with a trunk, branches, and leaves. A tree structure
starts with a root node, which branches off into several sub-nodes, and so
on. Trees are commonly used in databases to facilitate quick data
retrieval.

● Graphs: Unlike trees, graphs can have nodes that are interconnected in
complex ways, allowing for a more flexible representation of relationships
between elements. They’re commonly used in network routing and social
networking applications.

Tabular Structures
● Hash Tables: These are akin to a magical library where you whisper the
name of a book and it appears before you. Hash tables use a unique key
to store data, offering almost instantaneous data lookup.

● Dictionaries: Similar to hash tables but often with a focus on key-value


pairs, dictionaries are utilised when you need to associate specific values
with unique keys.

Further Reading

Introduction to Data Structures

Links to an external site.

The choice of a good data structure makes it possible to perform a variety of critical
operations effectively. A data structure is not only used for organising data but also
for processing, retrieving, and storing data. Explore further the different categories of
data structures and the most commonly used types.

Reference: Geeks for Geeks n.d., Introduction to Data Structures, Geeks for Geeks, accessed 30
January 2024, <https://www.geeksforgeeks.org/introduction-to-data-structures/>

Section 2: The Importance of Data Structures


source: freepik

Links to an external site.

Why Data Structures Matter

● Efficiency
The right data structure optimises both time and memory. In turn, this
makes your program run more swiftly, making tasks like data retrieval and
storage more effective.

● Ease of Operations
Data structures make it simpler to add, remove, or modify data. As your
programs grow more complex, this flexibility becomes increasingly
important.

● Data Organisation
When data is well-organised, your algorithms run more smoothly, making
your programs more reliable and user-friendly.
Section 3: QuickShop Case Study

source: freepik

Links to an external site.

Background

QuickShop, a fast-growing supermarket chain, identified that its current inventory


management system was becoming a bottleneck in its operations.

As the inventory grew, the existing system struggled to maintain performance levels,
causing delays in various processes including stock checks and billing. Realising the
critical role of data structures in efficient data management, QuickShop decided to
revamp its inventory system.

The Challenge
The central challenge was to design a system that could handle a vast and dynamic
range of products while ensuring quick and accurate data retrieval. The system
needed to facilitate seamless additions and removals of items, track inventory levels
in real-time, and offer rapid search capabilities to enhance the customer experience
at the checkout points.

The Strategy

QuickShop’s IT team proposed leveraging different data structures to build a


versatile and efficient inventory management system. The strategy involved the
integration of arrays, linked lists, and hash tables in various components of the
system. Here’s how they planned to do it:

● Arrays for Fixed Categories


Arrays were implemented to categorise items into fixed groups like
perishables, non-perishables, etc., allowing for quick and easy sorting and
filtering of products based on their categories.

● Linked Lists for Dynamic Inventory


Understanding that the inventory was dynamic and constantly changing,
linked lists were employed to manage the list of products within each
category, facilitating efficient additions and removals of items.

● Hash Tables for Quick Item Lookup


To revolutionise the checkout process, hash tables were introduced. Each
product was associated with a unique barcode as a hash key, enabling
instant retrieval of product details during billing, thereby reducing the
checkout time significantly.

Implementation

A cross-functional team involving IT specialists and operations managers worked


hand-in-hand to execute the plan. After weeks of development and testing, the new
system was launched. The team conducted extensive training to familiarise the staff
with the new system and ensure a smooth transition.
Outcome

With the new system in place, QuickShop witnessed a remarkable improvement in


their operations:

● Increased Efficiency
The system allowed for quicker data access and manipulation,
considerably reducing the time taken for inventory management and billing
processes.

● Improved Customer Experience


Customers enjoyed a quicker checkout process, enhancing their overall
shopping experience at QuickShop.

● Ease of Scalability
As QuickShop expanded, adding new products and categories to the
inventory became a seamless process, enabling the supermarket to grow
without being hindered by its systems.

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

Expand All
Panels
Collapse All
Panels
Reading: C++ Decision-Making with if, if...else
This article explains in detail, with examples, how to effectively use the if, if...else
and Nested if...else decision-making statements in C++.

C++ if, if...else and Nested if...else

Reference: Programiz, 2024, 'C++ if, if...else and Nested if...else', Programiz (online), accessed 16
Sept 2024, <https://www.programiz.com/cpp-programming/if-else>

Reading: C++ switch..case


The switch statement allows us to execute a block of code among many alternatives.
This article explains in detail, with examples, how to effectively use switch cases.

C++ switch..case Statement

Reference: Programiz, 2024, 'C++ switch..case Statement', Programiz, accessed 16 Sept 2024,
<https://www.programiz.com/cpp-programming/switch-case>

Reading: C++ Loops


The following tutorial articles from Programiz explain in detail, with examples, how to
effectively use various types and elements of loops.

● C++ for Loop


● C++ while and do...while Loop
● Links to an external site.

● C++ break Statement
● Links to an external site.

● C++ continue Statement
● Links to an external site.

Reference: Programiz, 2024, 'Flow Control', C++ Programming, Programiz, accessed 16 Sept. 2024,
<https://www.programiz.com/cpp-programming/>

Reading: Introduction to Data Structures


Data structures are methods for organising data to optimise efficiency in terms of
space and time, crucial for effective software development. This article explains the
various types of data structures, including linear structures like arrays and linked
lists, as well as non-linear ones like trees and graphs, each serving distinct purposes
for managing and processing data. Understanding these structures is essential for
developers to handle data effectively across diverse applications in programming
and system design.

Introduction to Data Structures

Reference: Geeks4Geeks, 2024, 'Introduction to Data Structures', Geeks4Geeks, accessed 16 Sept.


2024, <https://www.geeksforgeeks.org/introduction-to-data-structures/>

Video: Data Structures Explained


This video is an introduction to the concept of data structures, and its purpose is to
explain the idea behind them, in under 5 minutes, using understandable and
relatable examples.

Data Structures Explained (04:44)

See also CodeBeauty's playlist "C++ for Beginners

Links to an external site.

" that covers all of the concepts from this and previous modules.

Reference: CodeBeauty, 2021, 'Data Structures Explained', YouTube, accessed 16 Sept. 2024,
<https://www.youtube.com/watch?v=_T42E9RkWVQ>

You might also like