0% found this document useful (0 votes)
28 views149 pages

Computer Science - Unit 1 Mod 2

The document outlines a curriculum for a computer science course focused on problem-solving and programming in C. It details the internal assessment project where candidates must select a real-world problem, create an algorithm, implement it in C, and document their process. The assessment includes specific criteria for evaluation, including problem definition, analysis, and solution selection, with a structured timeline for submission.

Uploaded by

brandon.johnson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views149 pages

Computer Science - Unit 1 Mod 2

The document outlines a curriculum for a computer science course focused on problem-solving and programming in C. It details the internal assessment project where candidates must select a real-world problem, create an algorithm, implement it in C, and document their process. The assessment includes specific criteria for evaluation, including problem definition, analysis, and solution selection, with a structured timeline for submission.

Uploaded by

brandon.johnson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 149

1 Computer Science

Problem Solving with Computers


Module 2 – Problem Solving
with Computers

2 Unit 1 – Module 3 – Programming (C)


Fundamentals
of Computer
Science
Module 1 – Computer
Architecture and Organization
Candidates are expected to choose a problem for
which a software solution is appropriate
(something that exists as a paper-based
process) and create an algorithm for the
solution using sequencing, selection,
assignments, iteration (bounded and
unbounded).
They should represent their algorithms using any
combination of narrative, flow charts and
3 Internal pseudocode. Candidates are expected to
implement the algorithm in C using arrays with
Assessme no less than five functions and create a test plan.
nt
The Internal Assessment is worth 20% of the
final grade. The length of the report of the
project should not exceed 1500 words excluding
diagrams, graphs, tables and bibliography.
The following aspects of the project will be assessed:
 Definition of Problem (1mark) Sept 13th
 Background

4 Internal 

Problem Context
Problem Description

Assessment  Problem Analysis Sept 27th


 Identification of Specification(4marks)
Timeline  Functional Specification
*Dates are all subject to  Non-Functional Specifications
change at a moments  Program Design (21 marks) Oct 28th
notice;
 Narrative
 Flow charts or Pseudocode
 Use of Files
 Description of File Inputs and Outputs
 Use of appropriate data structures
 Demonstration of structured programming concepts
 Coding of program (19 marks) Jan 31
 Draft Due Dec 31st
 Testing and presentation (11marks) Feb 28
 Documentation
 Communication of Information. (1mark)

 The following are problems that are existing and needs a
solution. Select one of the following or see me to make a case
for an alternative:
 Reservation and Booking: Hotel, excursions, airports,
5 Internal salon.
 Inventory Management and Sales System: Bakery,
Assessment dressmaker, product creator and seller.
 Education: Reports, club management, attendance,
Project student registration system to keep track of student
information.
Options  Library: Rental books management.
 Services: Mechanic, barber shop, space rentals,
contractors, nail tech, etc.
 Hospital Industry: Clinic, hospital, health centers.
 Police: Accident reporting, traffic tickets, etc.
 Food/Restaurant Ordering.
 Property Management: Tenant management, rent
collection, maintenance scheduling.
 Event Management: Event planning, attendee tracking,
ticket sales.
 Human Resources: Employee onboarding, performance
tracking, payroll management.
6
Problem Solving
understand the problem-solving process;
“Before writing a program to solve a particular problem, it’s essential
to have a thorough understanding of the problem and a carefully
planned approach to solving the problem” – How To C.
Problem-solving is a fundamental skill in computer science and
everyday life. It involves identifying a challenge or issue and
developing a systematic approach to overcome it.

What is a Problem?

A problem is a question or situation that requires a solution. In


computer science, problems can range from simple calculations to
complex data processing tasks.

7 Explain A problem can be defined as a difference between the actual


situation and the desired situation.
the
concept of The discrepancy between the way things are and the way we
want them to be.
Problem-
Solving Problem-Solving is the process of finding a structured solution to a
problem.

A solution is a method or approach that resolves the problem at


hand.
8 What is a Problem?

 A problem can be defined as a situation that presents a challenge or an


obstacle that needs to be addressed. It can vary in complexity and can
arise in different forms. Problems can be simple, like deciding what to
wear to school, or complex, such as determining how to reduce pollution
in a city.
Top-down – Looking at the BIG picture problem and try to solve the
Problem whole issue. Also known as decomposition, involves breaking a large
problem into smaller, more manageable parts. Continue breaking
9
Solving down each component into smaller sub-components until you reach a
level where each part can be easily implemented or understood.

Methods
Bottom-up starts with the most basic components and builds up to
the overall system. Begin by identifying and implementing the
fundamental components or modules. Once the basic components
are developed, start combining them to form higher-level systems or
modules.

Step-wise refinement, also known as iterative refinement, is an


approach where the problem is solved progressively through a series
of refinements. It combines elements of both top-down and bottom-
up approaches. It involves starting with a broad outline of the
solution and gradually adding more detail in successive steps.
 Problem Definition
 Problem Analysis
 Solution Analysis - identify and evaluate possible
solutions
10 5 Steps to  Selection of Solution - select and justify the optimal
Problem solutions

Solving  Implementation and Review


11 Problem Definition
 The first step in solving any problem is to clearly define what the issue is.
This might seem obvious, but many people rush into trying to solve a
problem without fully understanding its nature.
 Defining the problem the user wants to solve and deciding what the user
wants to achieve and writing it down.
 Identify the Problem. Is there a Problem?
 A problem can be a task or something to be done.
 The Problem is to be examined at different angles and the problem definition
clarifies the points of focus.
Problem Definition
12
 Identify the organization/institution/industry. Who or what is affected by this
problem?
 Identify the problem
 What is the background of the problem?
 What is the system currently like?
 Why is this system NOT working? What are the visible signs that there's an issue?
 Objective is to eliminate unimportant aspects and zero in on the root problem.
 Be concise – keep it short, keep it clear. an you summarize the issue in one or
two sentences? Keep it cutesy!
 At this stage, focus on describing the problem, not solving it.
 Write the problem for non-techy people to understand. Try to keep the terms
simple.
 For example, instead of saying, "We need a new computer system," a
better problem definition might be, "Our current computer system is slow
and crashes frequently, causing delays in customer service and
frustrating our staff."
 First Section of the IA is the Definition of problem;
 What is due NOW(Sept 13th)?
 Cover Page (Relevant to the Problem)
 Table of Content (auto generated)
 Definition Of Problem
 Background.
13 IA Alert!  Problem Context.
 Problem Description.

 20 marks Graded
14 IA: Definition Of Problem
 The Cover Image should be a real place that has a real problem.
 The Background should have the name of the organization, name of owner
and address of business.
 History and specifics of the organization: Who owns the place/who works there?
What do they do? When did it start? Why was it needed in the community? Where
is it located?
 Description of Context should come from an interview that describes how
exactly the business is operated on a day-to-day basis, focus on the
papers(forms, receipts, invoice, records, attendance, etc.) in the system.
Describe how the current system works without critique, NO NEGATIVE
STATEMENTS.
 Description of the Problem should outline all the issues in the system and
what is wrong that can be solved in programming. Critique in Point format,
minimum of 6 points.
 Problem Definition
 Problem Analysis
 Solution Analysis - identify and evaluate possible
solutions
15 5 Steps to  Selection of Solution - select and justify the optimal
Problem solutions

Solving  Implementation and Review


16 Problem Analysis
 This stage involves breaking down the problem into its component
parts and understanding the underlying causes.
 To conduct a thorough problem analysis:
 Gather data: Collect relevant information about the problem
from various sources.
 Identify stakeholders: Determine who is affected by the
problem and who needs to be involved in the solution.
 Analyze root causes: Use defining diagrams to dig deeper into
the underlying causes of the problem.
 Document requirements: Clearly list both functional and non-
functional requirements based on your analysis.
17 Functional Analysis

 This focuses on what a system must do—the core features and tasks it
performs.
 Ensures the system performs its intended functions correctly.
 Answers the who, what, where
 Eg:
 The system must be able to store username, date of birth and email addresses.
 The system should require users to log in with a username and password to access
the system.
 Users should be able to input, edit, or delete data within specific fields or forms. (be
specific)
 The system should enable users to search and retrieve information from a database
or repository.
18 Non-Functional Analysis

 This focuses on how well a system performs its functions—quality


attributes such as performance, security, and usability.
 Defines constraints and expectations for system operation.
 E.g.
 The system must be able to store a maximum of 25 users.
 The system should be accessible 24/7 with no more than 5 hours of
downtime per year.
 The system should have an intuitive interface that allows new users to
complete basic tasks with explicit instructions.
19 Problem Analysis
 This is the process of determining
 What inputs are needed for the system
 What process is involved in solving the problem
 What outputs are needed from the system
 In this phase we check what the current system is like and identify the
root causes to the problems.
 Having Properly identified the root cause of the problem, further fact
finding is carried out to assess the full effect of the problem on the
organization(long- and short-term effects). We use interviews and
questionnaires to aid in the data collection process. Not required for
this IA but in UNIT 2.
20 Problem Analysis
21 Di Ship a Sink! – This is a Problem
 Problem Analysis--------------------
 Note the problem definition.
 There’s a lateral displacement of
the craft that is resulting in a
decline of said craft into the liquid
abys that it should remain buoyant
atop.
22 Three components of every Problem
Analysis
 The Customer Requirements are then translated into Technical System
Requirements.
 The Technical requirements - Sub-divide the problem into
 Inputs – a list of source data provided to the problem
 Outputs – a list of data generated by the solution to the problem
 The processing steps/list of actions to produce the required outputs
 May use a defining diagram.
23 Defining Diagram
 The defining diagram is created using the details of the problem
statement.
 It uses the explicit and implied details of the problem statement.
 The defining diagram presents the input, output and processing for the
problem in a tabular format.
 At this point you don’t care HOW the process is done, you just need to
have a place holder for the action. Eg Calculate Sum, Calculate Product
etc.
 Descriptive words/nouns usually become inputs/outputs
 Verbs/actions usually become the process
24 The Defining Diagram
25 Problem Specifications
 Identification of Specification: Stating the root problems and what is
needed.
 Functional Requirement:
 List of WHAT the System Needs to do. Can be thought of in terms of how
the system responds to inputs.
 E.g. Problem: Attendance registers are often misplaced.
 Functional Requirement: The system needs to store the attendance of
students.
 Non-Functional Requirement
 non-functional requirements specify the constraints of the system.
 Speed, efficiency, Scale of the system, user friendliness
 E.g. Problem: Attendance registers are often misplaced.
 Non-Functional Requirement: The system must be available 99.9% of the time.
 What is Due NOW(Sept 28th)?
 The Objective of the System
 Identification of Specification
26 IA Alert!  Functional Specification
 Non-Functional Specifications
 Problem Definition
 Problem Analysis
 Solution Analysis - identify and evaluate
possible solutions
27 Steps to  Selection of Solution - select and justify the optimal
Problem solutions

Solving  Implementation and Review


28
Solution Analysis
 A solution is a method or approach that resolves the problem. In
computer science, solutions often take the form of algorithms or programs.
 A good solution should be:
 Efficient
 Accurate
 Scalable
 Easy to understand and maintain
 There is no one way that will solve all problems.
29 Solution Analysis
With a clear understanding of the problem and its
requirements, it's time to generate potential solutions.
This stage involves creative thinking and considering a
wide range of possibilities.
1. Brainstorm: Generate as many ideas as possible
without judgment. Encourage wild ideas, as they
can lead to innovative solutions.
2. Research: Look for existing solutions to similar
problems. What have others done in comparable
situations?
3. Consult experts: Seek input from people with
relevant expertise or experience.
4. Consider constraints: Keep in mind any limitations
such as budget, time, or resources that might affect
the feasibility of solutions.
 Problem Definition
 Problem Analysis
 Solution Analysis - identify and evaluate possible
solutions
30 Steps to  Selection of Solution - select and justify the
Problem optimal solutions

Solving  Implementation and Review


Solution Selection
 At this stage, the Pros and Cons of each solution is
weighed and evaluated, and a choice is made based on
certain criteria.
 Rank solutions: Based on your evaluation, rank the
solutions from most to least promising.
 Choose the best option: Select the solution that best
meets your criteria and addresses the problem most
effectively.
 Develop a list of criteria for acceptable solutions.
 Cost
 Response Time
 Man-power
 Client Satisfaction
 After identifying appropriate solution, plans for
Implementation and evaluation is done.
 Select appropriate solution based on the assessment of
31
acceptable solutions.
 Problem Definition
 Problem Analysis
 Solution Analysis - identify and evaluate possible
solutions
32 Steps to  Selection of Solution - select and justify the optimal
Problem solutions

Solving  Implementation and Review


33 Implementation and Review

 Design, Develop and implement the selected solution.


 Solution Design consists of writing an algorithm to outline the solution.
This algorithm will go through desk checking to ‘test’ if it works.
 Solution Development takes the algorithm and converts it to a computer
system by programming. For your IA you will be using C – Code.
 After development there is a testing and review that takes place.
 Review or assess the program. Assess the Data. Determine Additional
needs.
 Creating a test plan, executing the tests for performance.
 Review may lead to another problem-solving cycle.
34 Extra: How to Solve a Problem in Four
Steps
 https://www.youtube.com/watch?v=QOjTJAFyNrU
35 Extra: The Psychology of Problem-
Solving
 https://www.youtube.com/watch?v=vg936IW9i7Q
36 Problem Solving Example 1
Describe the steps you will take to produce a solution.
Do not attempt to solve the problem, merely describe what you would do to
solve it.
37 Answer
 Talk to the shopkeeper and try to understand the problem. Replay the
Problem
definition problem statement to the shopkeeper outlining what you understand the
problem to be.
 Collect some data about the ordering and selling transactions that are done
Problem daily or weekly.
Analysis  Analyze all the data that you collect.

Solution  Think of two or three possible ways of helping the shopkeeper keep track of
analysis the orders and sales.

Select  Weigh the pros and cons of each solution and decide on which is best.
solution  Choose a solution.
 Create a plan to get the solution into action.
Implemen
tation and  Implement the plan.
review  Review the results and correct any errors where necessary.
38 Problem Solving Example 2
39 Answer
Problem  Talk to the treasurer and try to understand the problem. Validate/Verify the
definition problem by making a problem statement to the treasurer.
Problem  Collect some data about the membership and required dues.
Analysis  Analyze the data collected.
Solution  Think of two or three possible ways of helping to track membership and
analysis subscriptions.
 Weigh the pros and cons of each solution and decide which is best to solve the
Select problem.
solution  Choose a solution.
 Create a plan to get the solution into action.
Implemen
tation and  Implement the plan.
review  Review the results and Correct any errors where necessary.
Program
Design
Develop a detailed logical plan to
solve the problem. 40
41 Program Design

 Break down the solution into small manageable pieces


 Use pseudocode or flowcharts or other appropriate tools to represent
your design.
 Check your design using appropriate input data to make sure the design
will give the correct output.
 A Program Design is in the form of an Algorithm.
42 The Algorithm

 Algorithms are step-by-step procedures designed to solve specific


problems or perform tasks.
 To be considered effective and reliable, algorithms must possess certain
essential properties. What are the properties of a good algorithm?
 A list of steps involved in accomplishing a task.
 Detailed precise ordered instructions describing the process necessary
to produce the desired output from the given input.
 A logical plan for a solution to a given problem.
 An algorithm as a problem-solving strategy; What is its role and
importance in the problem-solving process?
43 The Algorithm
 An algorithm must provide a general solution to the problem
 This means that it should be able to handle various inputs within the problem
domain and produce correct outputs consistently.
 Clearly Defined and Unambiguous Steps
 This means that anyone following the algorithm should be able to understand
and execute each step without confusion or misinterpretation. An algorithm
provides a clear sequence of instructions, reducing ambiguity in problem-
solving.
 Finite Number of Steps
 An algorithm must have a finite number of steps, meaning it should
eventually terminate and produce a result.
 Flow of control from one process to another.
 The algorithm should have a well-defined flow of control, indicating how it
moves from one step or process to another. It ensures that problems are
solved in an optimal way, minimizing time and resource usage.
44
45 The Algorithm

 An algorithm can be compared to a recipe, as it outlines the specific


steps required to accomplish a task.
 It is characterized by being clear, precise, and unambiguous, ensuring
that it provides correct solutions in all cases and ultimately has a
definite end.
 When used as a problem-solving strategy, an algorithm plays a crucial
role in guiding the process, ensuring that each step is followed
systematically to achieve the desired outcome.
 Its importance lies in its ability to break down complex problems into
manageable steps, leading to efficient and reliable solutions.
Narrative

Pseudocode
46 Ways to
represent
an
algorithm
Flowcharts
47 Narrative

 Developed in the Solution Selection Process. The resulting narrative is


the English, steps on what the program is to accomplish.
 EG
 The program will show a menu, and the user has the option 1 to 5 to select.
 If option 1 is selected the user will be taken to the Information entering screen
where they will be required to enter their name, telephone number and grade.
 Once the user completes the form the information is stored in the User Info
File.
48 Flowchart
 Flowcharts are visual representations of algorithms using standardized
symbols and shapes connected by arrows to show the flow of control.
 They provide a clear, graphical representation of the algorithm's steps
and decision points.
 Flowcharts are particularly useful for visualizing complex processes and
identifying potential issues in the algorithm's logic.
 Key elements of a flowchart include:
 Oval: Start/End
 Rectangle: Process or Action
 Diamond: Decision
 Parallelogram: Input/Output
 Arrows: Flow of Control
49 Pseudocode

 Structured English formalized to look like high level computer languages


 Statements are written in simple English
 Each instruction is written in a separate line
 Keywords and indentation are used to signify a particular structure
 Each set of instructions are written from top to bottom, with one entry
and one exit point
 Groups of statements can be formed into modules and that module
given a name.
 KEYWORDS are Capital for aesthetics.
50 Program Data

 Before we can develop the Algorithm, we must understand the data the
algorithm will be manipulating.
 Variables – The name given to a collection of memory cells, designed
to store a particular data item.
 Constants – a data item with a name and value that remains the same
throughout the execution of the program
 Literals – a constant whose name is the written representation of its
value. Eg 2, True, “Jack”
51 Naming Variables

 All variable names must be meaningful, adequately describe the


variable
 Try to stick to short single word variable names – BUT if you must, use
underscores or camel case.
52
53 Data Types
 The form/Type of data to be collected
 A Data Type can be an elementary data item or a data structure.
 Elementary Data Item – A single variable that is always treated as a unit.
(usually built into the programming language)
 Real
 Integer
 Character
 Boolean
 Advanced Data Types/Data Structure – A combination of built in data items
 Arrays
 Lists
 Stacks
 Queue
54 Declaring Variables
 Declaring a variable refers to creation of said variable in memory.
Variables must be created before they can be used. ( Tip: Data can not be
stored in a memory location that hasn’t been created, so therefore
doesn’t exist. ) Declare your variable and constants at the beginning of
your program/algorithm.
55 Constructs used in Structured
Programming
 Input Statements: READ num1
 Output Statements: PRINT “The boy is “, boyname
 Assignment Statements:
 sum  num1 + num2
 Control Structures
 Structural Statements come in pairs
 For every BEGIN there is an END
 For every IF there is an ENDIF
56 Assignment Statements

 Variable name is always on the LHS of the assignment.


 LHS = RHS

 Num 2
 Num  “Jack”

 2 = num
 “Jack” = num
57 Control Structures

 The Structure Theorem states that is possible to write any computer


program by using only 4 basic control structures that are easily
represented in pseudocode:
 Sequence
 Selection
 Repetition
 Recursion (to be discussed later)
58 Sequence
 Selection Control Structures are used to choose an
alternate course based on a stated criteria.
 KEYWORDS: IF THEN, ELSE, ENDIF

 IF (condition) THEN
 Statement
Selection/  ENDIF
59
Decision/
Condition  IF (condition) THEN
 Statement1
 ELSE
 Statement 2
 ENDIF
60 Nested Ifs
 There are times when multiple checks need to be made before a decision is
arrived at. This is where we place an IF inside another IF…….a nested IF.
 IF (condition) THEN
 Statement
 ELSE
 IF (Condition) THEN
 Statement
 ELSE
 IF (Condition) THEN
 Statement

 ELSE
 ….

 ENDIF
 ENDIF Write a pseudocode algorithm to calculate the discount on an Item. If
the price is between 1 and 100 dollars the discount is 5% if the price
 ENDIF is between 100 and 1000 the discount is 7% and all prices over 1000
receives a discount of 10%.
61 Selection conditions

 True or False statements are generated by comparison. Mathematical symbols are


used for comparing values.
62 Math Operators
63 Comparison Operators

Algebraic equality Visual Basic equality Example of Meaning of


or relational or relational Visual Basic Visual Basic
operators operators condition condition
Relational operators
> > x > y x is greater than y

< < x < y X is less than y

≥ >= x >= y X is greater than or equal to y

≤ <= x <= y X is less than or equal to y

Equality operators

= = x = y X is equal to y

 <> x <> y x is not equal to y


64 Logical Operators

 AND
 OR
 NOT

 They operate on Boolean values


65 Selection
CASE
66
67 Repetition/Iteration/Loops
 A repetition statement allows you to specify that an
action is to be repeated while some condition remains
true. There are 2 basic categories of repetitive
statement/loop.
 Counter Controlled repetition/Finite/Bounded Loops
 Sentinel Controlled repetition/Infinite/Unbounded
Loops
 Other Types of Loops include
 Pre-test Loop
 Post-test Loop
 Bounded Loop
 KEYWORDS: WHILE – DO – ENDWHILE, REAPEAT- UNTIL,
FOR – ENDFOR
 Iteration (looping) is the ability of the computer to
repeat a block of instructions until some condition is
fulfilled.
68 Counter Controlled LoOPs
 For counter-controlled loops there has to be a variable that keep track of
the number of times the loop was repeated.
 The COUNTER is a special variable that keeps track to the number of loops
done. Counters increment by 1. cc+1
 The ACCUMULATOR is a special variable that keeps adding values onto
previously added values. Accumulators increase by any amount of values.
sumsum + num

 All counters and accumulators must be initialized. Usually initialized to 0


but can be any starting amount.
 c0
 sum0
69 Pre-Test LoOP
 WHILE (condition) DO
 Statement
 ENDWHILE

 The condition must be true BEFORE the program enters the loop and does
the statements inside the loop.
 Initializations must happen before the loop
 When do we initialize?
 When the variable is on both sides of the equation ( sum  sum + num)
 When a variable is used in a comparison in an IF statement. (IF num > max THEN)
 The statements to be repeated must be placed in the TRUE path of the loop
test.
 The loop exits on the condition being False and it SKIPS all the statements
inside the loop.
 Write a pseudocode algorithm to accept 6 numbers from the user and print
the sum.
70 Post Test LoOP

 REPEAT
 Statements
 UNTIL (condition)
 DO
 Statements
 WHILE (condition)

 In this iteration the loop terminating condition is not made until the body
of the loop is executed at least once.
 Write a pseudocode algorithm to accept 6 numbers from the user and print
the sum.
71 Bounded/Indexed LoOP

 FOR counter  starting_Value TO ending_Value STEP incremental_value


DO
 Statement
 ENDFOR (the FOR loop comes with a build in counter that increments/increases the counter by 1)

 Bounded loops allow you to execute a set of statements a number of


times which is known before entering the loop.
 It is sometimes referred to as definite repetition.
 Write a pseudocode algorithm to accept 6 numbers from the user and
print the sum.
 The range limits are inclusive.
72 Sentinel Controlled LoOPs

 Sentinel-controlled repetition is sometimes called indefinite repetition


because it is not known in advance how many times the loop will be
executed.
 The loop ends if the user enters a particular value.
 The loop keeps going until it reaches a particular value based on
calculations.

 NB Indefinite is different than infinite. Infinite means never ending.


Indefinite means it will end at some point but we cannot say when.
73
74 Flowchart Symbols
75 General Rules for flowcharting
 All boxes of the flowchart are connected with Arrows. (Not lines)
 Flowchart symbols have an entry point on the top of the symbol with no
other entry points. The exit point for all flowchart symbols is on the
bottom except for the Decision symbol.
 The Decision symbol has two exit points; these can be on the sides or the
bottom and one side. Generally a flowchart will flow from top to bottom.
However, an upward flow can be shown as long as it does not exceed 3
symbols.
 Connectors are used to connect breaks in the flowchart. Examples are:
 From one page to another page. Off Page Connector.
 From the bottom of the page to the top of the same page. Off Page Connector.
 Subroutines and Interrupt programs have their own and independent
flowcharts. *more on this at a later date*
76 Selection
77 Selection/Condition Flowchart
78 Iteration/Repetition
 Iteration (looping) is the ability
of the computer to repeat a
block of instructions until some
condition is fulfilled.
 There are different types of
Loops
 Pre-test Loop
 Post-test Loop
 Indexed Loop
 Counter- Controlled Loops
 Sentinel Control Loops
 Bounded
 Unbounded
79 Pre-Test Loop
 In this type of iteration, the loop’s exit condition (what makes it stop looping) is
tested BEFORE the performance of the body of the loop.

 This is where we start to use accumulators and counters.


 Sum is often used as an accumulator, it keeps adding/accumulating, a particular value
in each time the loop goes around.
 Count is often used as a counter which adds/accumulates by a constant amount,
usually 1, It is used to keep track of how many times we have gone around in the loop.
80 Pre-Test Loop
81 E.g. Add 6 numbers
82 Post-test Loop

 In this iteration the loop terminating condition is not made until the body
of the loop is executed at least once.
83 E.g. Add 6 numbers
84 Bounded/Indexed Loop

 This type of loop does counting and is used when the exact number of
repetitions is known in advance. It is sometimes referred to as definite
repetition.
85 E.g. Add 6 numbers
86

 Write a pseudocode algorithm to print the table of squares from 1 to 10.


Each line should consist of the number and the square of that number.
87

 Write a Pseudocode algorithm to read the names and ages of ten (10)
people and print the name of the oldest person. Assume that there are
no persons of the same age. Data is supplied in the following form:
name, age, name, age etc.
88

 Write an algorithm to read ELEVEN numbers find their average and print
it. The algorithm should also print the number of times 6 occurs in the
data.
89
Data Structures
A data structure is a particular way of organizing data in a computer so
that it can be used effectively. Often speaks to a logical grouping of sets of
data.
90 Data Structures

 A structure is a collection of one or more variables grouped under a


single name for easy manipulation.
 Each variable within a structure is called a member of the structure.
 An instance is the actual declaration of a structure so it can also be
used later in a program.
 Structure elements can be accessed through a structure variable using
a dot (.) operator.
91 Record

 A record is a programmer-defined data type.


 If you want to hold related data of different data types it is practical to
use a record type.
92 Record
93
Arrays
An aggregate of homogenous data items.
94
What is an array?
 A variable is a memory location that can store a value. But each variable can
only hold one item of data.
 An array is a series of memory locations, each of which holds a single item of
data, but with each box sharing the same name. All data in an array must be
of the same data type.
 That means that, for example, we can store 6 values of type integer in an
array without having to declare 6 different variables, each one with a
different identifier. Instead of that, using an array we can store 6 different
values of the same type, integer for example, with a unique identifier.
 score_1, score_2, score_3, score_4, score_5, score_6
 Array score[6]
 Any facility that holds more than one item of data is known as a data
structure. Therefore, an array is a data structure.
95 Structure of an Array
 An array consists of two main parts:
 The content of the array typically called the element of the array.
 The address of the element of the array typically called the index.

 We can think of a one-dimensional array as a table with one row. Indices


usually start at 0.

0 1 2 3 4
5
96 Array Structure
 Arrays are named like variables. The number in brackets determines how
many data items the array can hold. The array score[9] would allow ten data
items to be stored.
 Arrays have a fixed predetermined size. An array cannot hold more items than
its capacity.

 Declare
 Array array_name[max_index] as datatype
 Eg Array score[6] as integer NB the index for this array will end at 5, because it starts at 0

 Assign values to array


 array_name[index] <- literal
 Eg score[0] <- 45
97 Accessing Elements

 To access an element in the array we must use the array name and the index surrounded by square
brackets:
 array_name[index]
 To place the score of 15 at position 4 in the score array it would read:
 score[3] = 15
 NB position 4 is index number 3.

 We can read directly into arrays.


 READ score[4] would see position 5 being filled with whatever number the user enters.
 We can use variables for indices
 Eg c = 3

15
PRINT score[c]
98
Using a loop to fill the array -1

□ Write an algorithm to place three numbers entered


by the user into the array.

numbers
0 1 2 3 4 i
numbers[5]
Indicating the size
For i = 0 To 3 Do of the array

Read numbers[i]
Endfor
99
Using a loop to fill the array - 2

□ Write an algorithm to place three numbers entered by


the user into the array.

numbers 0
0 1 2 3 i
4
numbers[5] Initialise i to 0 then check
if the value of i equals 3
For i = 0 To 3 Do if not then it will proceed
into the loop or other
Read numbers[i] wise stop.

Endfor
100
Using a loop to fill the array - 3

□ Write an algorithm to place three numbers entered by


the user into the array. 9

numbers 9 0
0 1 2 3 i
4
numbers[5] At the start of the loop i is
0 and therefore the value
For i = 0 To 3 Do read will be placed into
location 0. The user
Read numbers[i] entered
. 9
Endfor
101
Using a loop to fill the array - 4

□ Write an algorithm to place three numbers entered by


the user into the array.

numbers 9 1
0 1 2 3 i
4
numbers[5] When the Endfor
statement is reached i is
For i = 0 To 3 Do incremented by 1.
Read numbers[i]
Endfor
102
Using a loop to fill the array - 5

□ Write an algorithm to place three numbers entered by


the user into the array.

numbers 9 1
0 1 2 3 i
4
numbers[5] Check if the value of i
equals 3 if not then it will
For i = 0 To 3 Do continue the loop or
other
. wise stop
Read numbers[i]
Endfor
103
Using a loop to fill the array - 6

□ Write an algorithm to place three numbers entered by


the user into the array. 23

numbers 9 23 1
0 1 2 3 i
4
numbers[5] i is now 1 and therefore
the value read will be
For i = 0 To 3 Do placed into index 1. The
user
. entered 23
Read numbers[i]
Endfor
104
Using a loop to fill the array - 7

□ Write an algorithm to place three numbers entered by


the user into the array.

numbers 9 23 2
0 1 2 3 4
i
numbers[5] When the Endfor
statement is reached i is
For i = 0 To 3 Do incremented by 1.
Read numbers[i]
Endfor
105
Using a loop to fill the array - 8

□ Write an algorithm to place three numbers entered by


the user into the array.

numbers 9 23 2
0 1 2 3 i
4
numbers[5] Check if the value of i
equals 4 if not then it will
For i = 0 To 3 Do continue the loop or
otherwise stop.
Read numbers[i]
Endfor
106
Using a loop to fill the array - 9

□ Write an algorithm to place three numbers entered by


the user into the array. 11

numbers 9 23 11 2
0 1 2 3 i
4
numbers[5] i is now 2 and therefore
the value read will be
For i = 0 To 3 Do placed into index 2. The
user entered 11.
Read numbers[i]
Endfor
107 Using a loop to fill the array - 10

□ Write an algorithm to place three numbers entered by


the user into the array.

numbers 9 23 11 3
0 1 2 3 i
4
numbers[5] When the Endfor
statement is reached i is
For i = 0 To 3 Do incremented by 1.
Read numbers[i]
Endfor
108 Using a loop to fill the array - 11

□ Write an algorithm to place three numbers entered by


the user into the array.

numbers 9 23 11 3
0 1 2 3 i
4
numbers[5] Check if the value of i
equals 3, if not then it will
For i = 0 To 3 Do continue the loop or
otherwise stop. Since i
Read numbers[i] equals 3 the loop stops.

Endfor
109
Using a loop to display the array -
1
□ Write an algorithm to show the first three numbers in
the array. Assume that the array already have the data
loaded.
numbers 9 23 11 0
0 1 2 3 4 i

9
For i = 0 To 3 Do
Print numbers[i]
Endfor
110
Using a loop to display the array -
2
□ Write an algorithm to show the first three numbers in
the array. Assume that the array already have the data
loaded.
numbers 9 23 11 1
0 1 2 3 4 i

9 23
For i = 0 To 3 Do
Print numbers[i]
Endfor
111
Using a loop to display the array -
3
□ Write an algorithm to show the first three numbers in
the array. Assume that the array already have the data
loaded.
numbers 9 23 11 2
0 1 2 3 4 i

For i = 0 To 3 Do 9 23 11

Print numbers[i]
Endfor
112 Things to remember about
Arrays
□ Never try to access an index outside the array range.
□ The index of the last element in the array is always SIZE -1
□ When the array starts at 0 the index of an element is
always position -1
113 Try this!
114  BEGIN
 DECLARE c AS Integer
 RECORD STUDENT
 DECLARE
 name as STRING
 Age as INTEGER

 END STUDENT
 DECLARE ARRAY stud[20] AS STUDENT
 FOR c0 TO 20 DO
 PRINT “PLEASE Enter your name and age”
 READ stud[c].name, stud[c].age

 ENDFOR
 END
115 Classwork

 A book record has the following data:


title, author, price, and # of pages.
 Prompt the user for and read the data for 10 books using an array.
 For each book with the number of pages greater than 300, increase its cost by
20%.
 AFTER all the books have been updated, display the title and price for all
books. The title and price must be displayed in one uninterrupted list.
116
Modularization Process
breaks down complex systems into small and solvable parts
117 Modularization
Modularization is a fundamental concept in programming that
promotes the division of a program into smaller, manageable, and
reusable parts called modules.
The division of a problem into smaller subtasks, or modules each
with a single purpose.

Identify major tasks to be performed then divide the problem into


sections that represent those tasks. Look at each sub task to see if
it can be divided even further.
This is called the Top-Down Design or Functional Decomposition.

By using the top-down design methodology, the programmer is


adopting a modular approach to program design.
118 The Modularization Process

 A module is defined as a section of an algorithm that is dedicated to a


single function. A Module has to PRODUCE some value or outcome.
 Modules should have a single entry, and a single exit with a top-to-
bottom sequence of instructions.
 The name of the module should describe the work to be done as a
single specific function. Names should begin with a verb followed by
a two-word object. E.g. PrintPageHeader, CalculateSalesTax,
VaildateInputDate, AddNewUser, UpdateUser.
Benefits of Modular Design
119
Ease of Understanding – each module should perform just one function. When code
is organized into modules, it becomes easier to understand. Each module typically has
a specific purpose, making it simpler for programmers to follow the logic of the
program.

Reusable code and Elimination of Redundancy – modules used in one algorithm


can also be used in other algorithms. Modules can be reused across different projects.
This reduces redundancy in code and saves time, as developers can implement existing
modules rather than writing new code from scratch.

Efficiency of Maintenance and Testing – each module should be self contained and
have little or no effect on other modules within the algorithm. This modular approach
simplifies debugging and allows developers to focus on specific areas of the code. Each
module can be validated for correctness through unit testing.

Collaboration: In team environments, modularization allows multiple developers to


work on different modules simultaneously. This parallel development can accelerate
project timelines and improve productivity
Hierarchy/
Structured Charts
Structure charts are a visual
representation of a system's modules 12
0
121 Structure Charts

 Structure charts are a visual representation of a system's modules,


illustrating how they interact and relate to one another. These charts help
developers and stakeholders understand the architecture of a system,
providing clarity regarding the hierarchy and flow of control among modules.
 Components of a Structure Chart
1. Modules: Each module is represented by a box, labeled with its name. The
box may also include a brief description of the module's purpose.
2. Connections: Lines connecting the boxes indicate the relationships between
modules. Solid lines typically represent a direct call or use of one module by
another, while dashed lines may indicate less direct relationships or data flow.
3. Hierarchical Levels: Structure charts often use different levels to show the
relationship between higher-level modules (parent modules) and their
submodules (child modules). This hierarchy helps in understanding how
complex systems are organized.
122 Hierarchy/Structured Charts
 Uses a tree-like diagram of boxes; each box represents a module in
the program and the lines connecting the boxes represent the relationship
of the modules to other in the program hierarchy.
 Does not show the sequences of execution but the modules themselves in
the order they appear in the algorithm.
 Shows the names of all modules in the program and their hierarchical
relationship to each other.
 The controlling module or mainline is at the top. On the next line
are the modules that are called directly from the mainline. On the next
line are the modules that are called directly from the mainline’s
submodules and so on.
 The controlling module is referred to as the Calling Module and
subordinate module the Called Module.
123 Hierarchy/Structured Charts
 https://www.youtube.com/watch?v=QN2bjNplGlQ
124
AmongUS

Imposter Crew

Call Repair Find Report Call


KillCrew Sabotage
Meeting Ship Locations Murder Meeting
125 Module Structure
 A function/module is a block of code designed to perform a specific task.
 ReturnDatatype FUNCTION moduleName(datatype parameter(s))
 Statements
 END moduleName

 FUNCTION moduleName (datatype parameters)


 Statements
 END moduleName

 FUNCTION moduleName ()
 Statements
 END moduleName
126
127 FUNCTION Main()
DECLARE sq, val AS Integer

END Main
128
Variables in Modules
Local and Global Variables
129 Scope of a Variable
 The scope of a variable is the portion of a program in which that variable
has been defined and to which it can be referred.
 If a list is created of all the modules in which a variables can be referenced
that list defines the scope of the variable.
 Variables can be global or local.
 Global Data is data that can be used by all the modules in a program. The
scope of a global variable is the whole program, because every module in
the program can access the data. The lifetime of the global variable spans
the execution of the whole program.
 Local Data – variables that are defined within subordinate modules are
called local variables. These local variables are not known to the calling
module, or to any other module. The scope of a local variable is simply the
module in which it was created or defined. The lifetime of a local variable is
limited to the execution of the single subroutine in which it is defined.
Using local variables can reduce what is known as program side effects.
130 Side Effects
 When variables are global, any part of the program can change them, which
makes it harder to figure out where things go wrong if a bug occurs.
 Global variables stay in memory for the entire duration of the program. This
can lead to inefficient memory use, especially when large data structures are
used globally but are only needed in specific parts of the code.
 In contrast, local variables are removed from memory once the function they
are declared in finishes executing.
 In programs with multiple threads (like parallel processing or multithreading),
global variables can cause race conditions where different threads modify the
same variable simultaneously, causing inconsistent results.
 Local variables prevent such conflicts because they are specific to each
thread or function.
 If multiple functions or parts of the code use the same global variable, they
might unintentionally overwrite each other's changes, leading to hard-to-find
bugs.
131 Passing Parameters
 An efficient way of inter-module communication is the passing of
parameters or arguments between modules.
 Parameters are simply data items that are transferred from a calling
module to its subordinate module at the time of calling.
 When the calling module calls a subordinate module in pseudocode, it
must consist of the name of the called module with a list of the
parameters to be passed to the called module enclosed in parentheses
- for example:
 CalculateSalesTax (salesAmount, taxRate)
Called
Parameters
Module

 The names that the respective modules give to their parameters need not be
the same but their number, type and order must be identical.
 Parameter names that appear when a submodule
is defined are known as formal parameters.
Variables and expressions that are passed to a
submodule in a particular call are called actual
parameters. A call to a submodule will include an
Formal and actual parameter list, one variable for each formal
parameter name.
13
2 Actual  There is a one-to-one correspondence between
Parameters formal and actual parameters, which is determined
by the relative position in each parameter list.
Also, the actual parameter corresponding to a
formal parameter must have the same data type
as that specified in the declaration of the formal
parameter.
133 Formal and Actual Parameters
 For example, a mainline may call a module with an actual parameter list, as
follows:
 Print_page_headings (page_count, line_count)
 while the module may have been declared with the following formal parameter
list:
 Print_page_headings (page_counter, line_counter)
 Although the parameter names are different, the actual and formal parameters
will correspond.
134 Value and Reference Parameters
 Parameters may have one of three functions:
 To pass information from a calling module to a subordinate
module. The subordinate module would then use that information in
its processing, but would not need to communicate any information
back to the calling module.
 To pass information from a subordinate module to its calling
module. The calling module would then use that parameter in
subsequent processing.
 To fulfil a two-way communication role. The calling module may
pass information to a subordinate module, where it is amended in
some fashion, then passed back to the calling module.
135 Module Structure
 ReturnDatatype FUNCTION moduleName(datatype parameter(s))
 Statements
 END moduleName

 FUNCTION moduleName (datatype parameters)


 Statements
 END moduleName

 FUNCTION moduleName ()
 Statements
 END moduleName
136 Value parameters
 Value parameters only pass data one way - that is, the value of the
parameter is passed to the called module. When a submodule is called,
each actual parameter is assigned into the corresponding formal
parameter, and from then on, the two parameters are independent. The
called module may not modify the value of the parameter in any way,
and, when the submodule has finished processing, the value of the
parameter returns to its original value.

Called/Submodule Formal
MAIN MODULE/Calling Parameters
module
calcAvg(grade1,grade2,grade3){
g1=45
g2=66
Actual average<(grade1+grade2+grade3)/
g3=89
Parameters 3
Print “the average is”, average
Call calcAvg(g1,g2,g3)
}
137 Modularization Classwork - Pairs
 You will write a pseudocode algorithm that does the following:
 Take 3 numbers from the user.
 Pass these 3 numbers to three different functions (listed below).
 Print results using the values returned from each function.
 Functions:
 EvenOdd: This function checks if a number is odd or even. It accepts 1
number and returns "Even" or "Odd".
 SqSum: This function adds up the squares of the 3 numbers. It accepts 3
numbers, squares them, adds them up, and returns the sum.
 Highest: This function finds the highest number of the 3. It accepts 3 numbers
and returns the largest number.
 Each function should accept parameters and return a value.
 The main program should call these functions and use the returned
values in print statements.
138
Pause
IA Alert!

 What's Due Now?


 Identification of Specification
 Functional Requirements
 Non-Functional Requirements
 Structure Chart
 The Algorithm
 The flow chart/Pseudocode should be logical, easy to follow and is an accurate
description of the solution - outlined in the narrative - using the applicable symbols
or algorithmic structures. The flow chart/ Pseudocode should also show extensive
use of structured programming concepts such as input statements, outputs
statements, assignment statements, control structures.
 Must have Functions: Menu, accepting Data, Reading and Writing to a File,
Array/Data manipulations, Data Structures.
139
Program Development
Translate your design into a programming language – C! See
Module 3 slides
140
Program Testing
Input real life data and look at the resulting output
141
Desk Check
Testing out the pseudocode
142 Desk checking

 Desk checking is a manual (non computerized) technique for checking


the logic of an algorithm. The person performing the desk check
effectively acts as the computer, using pen and paper to record results.
The desk checker carefully follows the algorithm being careful to rigidly
adhere to the logic specified. The desk check can expose problems with
the algorithm.
 Desk checks are useful to check an algorithm (before coding) thereby
confirming that the algorithm works as expected and saves time
possibly writing a program that doesn't do what was intended. Another
benefit of a desk check is that it confirms to the programmer/designer
that the algorithm performs as intended.
143 It’s the same thing as a trace table
 A desk check is normally done as a table with columns for:
 Pseudo code line number column (Pseudo code doesn't normally have lines
numbers, but these are necessary in a desk check to specify the line(s) being
executed)
 One column per variable used. The columns should be in alphabetical order
on variable name with the variable name at the top of the column. As the
algorithm is executed, the new values of the variables are put in the
appropriate column.
 A condition column. The result of the condition will be true (T) or false (F). As
the algorithm is executed, conditions are evaluated and the details are
recorded in the column. Show working when evaluating the conditions. This is
used whenever a condition is evaluated - IF WHILE or FOR statements all have
explicit or implicit conditions.
 An Input/Output column is used to show what is input by the user and
displayed by the program. Show inputs with: the variable name, a "?" and the
value input e.g. price ? 200. Show outputs with the variable name, an =, and
the value displayed (or just the value displayed) e.g. discountPrice= 180 .
144 Desk Checks vs Test Plans
 A Desk Check concentrates on the value of variables and the logic i.e.
what is the value of variable x after statement n; what is the next
statement to be executed?
 A Test Plan focuses on the values of inputs and outputs required to test
a program without concern for the internal workings i.e. are the results
(outputs) correct for the inputs?.
145 Test Plan: Functional Specifications
146
147
148
Module 2 Complete!
149 References

 Janse, B. (2018). Problem Definition Process. Retrieved 9/13/2020 from


ToolsHero:
https://www.toolshero.com/problem-solving/problem-definition-process/
 Campion College. Problem solving Process. Retrieved 9/13/2020 from
Campion’s Google Drive:
https://drive.google.com/file/d/0B2foYiM-VdRFWF9HaXVweFNuY28/view
 Brown, D & Kusiak, J (2002-2007).Problem Analysis Techniques.
Retrieved 9/13/2020 from
https://www.miun.se/siteassets/fakulteter/nmt/summer-university/proble
manalysispdf
 https://www.bbc.co.uk/bitesize/guides/zy9thyc/revision/1
 Array Slides – Lavare Henry

You might also like