WELL SPRING UNIVERSITY, BENIN CITY,
EDOSTATE.
DEPARTMENT OF COMPUTING
CYBER SECURITY/COMP SC / SOFTW ENGR / INFOM SEC
PROGRAMME
SECOND SEMESTER 2023/2024
(3 UNITS)
Problem Solving (2 Units C: LH 30; PH 0)
COS 102
Course Contents
Introduction to the core concepts of computing. Problems and problem-solving. The
identification of problems and types of problems (routine problems and non-routine
problems). Method of solving computing problems (introduction to algorithms and
heuristics).
Solvable and unsolvable problems. Solution techniques of solving problems (abstraction,
analogy, brainstorming, trial and error, hypothesis testing, reduction, literal thinking, means
end analysis, method of focal object, morphological analysis, research, root cause analysis,
proof, divide and conquer). General Problem-solving process. Solution formulation and
design:
flowchart, pseudocode, decision table, decision tree. Implementation, evaluation and
refinement. Programming in C, Python etc.
Lab Work: Use of simple tools for algorithms and flowcharts; writing pseudocode; writing
assignment statements, input-output statements and condition statements; demonstrating
simple programs using any programming language (Visual Basic, Python, C)
Problem Solving in Computing
Problem solving in computing is the process of identifying, analyzing, and resolving
problems in a systematic and structured way, using computational thinking and
techniques.
Key Aspects of Problem Solving in Computing
1. Problem identification: Recognizing and defining the problem or challenge.
2. Analysis: Breaking down the problem into smaller, manageable parts, and
identifying key issues and constraints.
3. Design: Developing a plan or solution to address the problem, using computational
thinking and techniques.
4. Implementation: Building and testing the solution, using programming languages,
algorithms, and data structures.
5. Evaluation: Assessing the effectiveness of the solution, and identifying areas for
improvement.
Computational Thinking Skills
1. Algorithmic thinking: Developing step-by-step procedures to solve problems.
2. Abstraction: Focusing on essential features and ignoring irrelevant details.
3. Pattern recognition: Identifying patterns and relationships in data.
4. Decomposition: Breaking down complex problems into smaller, more manageable
parts.
Key Solution Techniques Of Solving Problems
Solving problems effectively requires structured techniques tailored to the nature of
the issue.
1. Define the Problem Clearly
i. Identify what the problem is and its root causes.
ii. Break it down into smaller, manageable parts.
2. Use Problem-Solving Frameworks
i. Trial and Error: Test different approaches until one works.
ii. Root Cause Analysis (RCA): Identify underlying causes rather than just
addressing symptoms.
iii. 5 Whys Technique: Ask "Why?" five times to drill down to the core issue.
iv. SWOT Analysis: Analyze strengths, weaknesses, opportunities, and threats to
determine the best course of action.
3. Generate Possible Solutions
i. Brainstorm multiple ideas without judgment.
ii. Think creatively and consider unconventional approaches.
4. Evaluate and Select the Best Solution
i. Compare pros and cons of each possible solution.
ii. Consider feasibility, risks, and potential consequences.
iii. Choose the most effective and practical solution.
5. Implement the Solution
i. Develop a clear action plan.
ii. Assign tasks and responsibilities.
iii. Execute the plan with monitoring mechanisms in place.
6. Reflect and Improve
i. Review the outcomes.
ii. Identify what worked and what didn’t.
iii. Adapt and refine the approach for future problems.
These techniques apply to different domains, whether in personal decision-making,
business strategies, or technical troubleshooting.
Applications of Problem Solving in Computing
1. Software development: Creating software applications to solve real-world
problems.
2. Data analysis: Analyzing and interpreting data to inform decision-making.
3. Artificial intelligence: Developing intelligent systems that can solve complex
problems.
4. Cybersecurity: Protecting computer systems and networks from cyber threats.
Benefits of Problem Solving in Computing
1. Improved critical thinking: Developing critical thinking skills through systematic
problem-solving.
2. Enhanced creativity: Encouraging creative solutions to complex problems.
3. Increased efficiency: Streamlining processes and improving productivity through
computational solutions.
4. Better decision-making: Informing decision-making through data analysis and
interpretation.
Algorithm in Problem Solving
An algorithm is a well-defined procedure or set of instructions in form logical steps,
to solve a specific problem or perform a particular task which takes some input and
produces a corresponding output.
Key Characteristics of an Algorithm
1. Input: An algorithm takes some input, which can be in the form of data, parameters,
or user input.
2. Processing: The algorithm performs some processing on the input, using a set of
instructions or rules.
3. Output: The algorithm produces some output, which can be in the form of data,
results, or solutions.
4. Finiteness: An algorithm must eventually terminate, producing a result or solution.
5. Correctness: An algorithm must produce the correct result or solution, given the
input and processing rules.
Types of Algorithms
1. Brute Force Algorithm: A straightforward approach that exhaustively tries all
possible solutions, suitable for small problem instances but may become
impractical for larger ones due to its high time complexity.
2. Recursive Algorithm: A method that breaks a problem into smaller, similar
subproblems and repeatedly applies itself to solve them until reaching a base case,
making it effective for tasks with recursive structures.
3. Encryption Algorithm: Utilized to transform data into a secure, unreadable form
using cryptographic techniques, ensuring confidentiality and privacy in digital
communications and transactions.
4. Backtracking Algorithm: A trial-and-error technique used to explore potential
solutions by undoing choices when they lead to an incorrect outcome, commonly
employed in puzzles and optimization problems.
5. Searching Algorithm: Designed to find a specific target within a dataset, enabling
efficient retrieval of information from sorted or unsorted collections.
6. Sorting Algorithm: Aimed at arranging elements in a specific order, like
numerical or alphabetical, to enhance data organization and retrieval.
7. Hashing Algorithm: Converts data into a fixed-size hash value, enabling rapid
data access and retrieval in hash tables, commonly used in databases and password
storage.
8. Divide and Conquer Algorithm: Breaks a complex problem into smaller
subproblems, solves them independently, and then combines their solutions to
address the original problem effectively.
9. Greedy Algorithm: Makes locally optimal choices at each step in the hope of
finding a global optimum, useful for optimization problems but may not always
lead to the best solution.
10. Dynamic Programming Algorithm: Stores and reuses intermediate results to
avoid redundant computations, enhancing the efficiency of solving complex
problems.Dynamic programming algorithms: Used to solve complex problems by
breaking them down into smaller sub-problems.
11. Randomized Algorithm: Utilizes randomness in its steps to achieve a solution,
often used in situations where an approximate or probabilistic answer suffices.
12. Graph algorithms: Used to solve problems related to graphs, such as finding the
shortest path between two nodes.
Algorithm Design Techniques
1. Divide and conquer: Breaking down complex problems into smaller sub-problems.
2. Dynamic programming: Solving complex problems by breaking them down into
smaller sub-problems and storing the solutions to sub-problems.
3. Greedy algorithms: Solving problems by making locally optimal choices, with the
hope that these choices will lead to a globally optimal solution.
4. Backtracking: Solving problems by recursively exploring all possible solutions, and
backtracking when a dead end is reached.
Algorithm Analysis
1. Time complexity: The amount of time an algorithm takes to complete, usually
measured in terms of the number of operations performed.
2. Space complexity: The amount of memory an algorithm uses, usually measured in
terms of the amount of data stored.
3. Efficiency: The ability of an algorithm to solve a problem quickly and efficiently.
Area of Application Use of the Algorithms:
Algorithms play a crucial role in various fields and have many applications. Some of
the key areas where algorithms are used include:
1. Computer Science: Algorithms form the basis of computer programming and are
used to solve problems ranging from simple sorting and searching to complex
tasks such as artificial intelligence and machine learning.
2. Mathematics: Algorithms are used to solve mathematical problems, such as
finding the optimal solution to a system of linear equations or finding the shortest
path in a graph.
3. Operations Research: Algorithms are used to optimize and make decisions in
fields such as transportation, logistics, and resource allocation.
4. Artificial Intelligence: Algorithms are the foundation of artificial intelligence and
machine learning, and are used to develop intelligent systems that can perform
tasks such as image recognition, natural language processing, and decision-
making.
5. Data Science: Algorithms are used to analyze, process, and extract insights from
large amounts of data in fields such as marketing, finance, and healthcare.
These are just a few examples of the many applications of algorithms. The use of
algorithms is continually expanding as new technologies and fields emerge,
making it a vital component of modern society.
6. Web search engines: Use algorithms to search and rank web pages.
7. Social media platforms: Use algorithms to recommend content and connect
users.
8. Financial systems: Use algorithms to analyze and process financial data.
9. Healthcare systems: Use algorithms to diagnose and treat medical conditions.
Example(Algorithm)
Now, use an example to learn how to write algorithms.
Problem: Create an algorithm that multiplies two numbers and displays the output.
Step 1 – Start
Step 2 − declare three integers x, y & z
Step 3 − define values of x & y
Step 4 − multiply values of x & y
Step 5 − store result of step 4 to z
Step 6 − print z
Step 7 – Stop
Algorithms instruct programmers on how to write code. In addition, the algorithm can
be written as:
Step 1 − Start mul
Step 2 − get values of x & y
Step 3 − z ← x * y
Step 4 − display z
Step 5 – Stop
In algorithm design and analysis, the second method is typically used to describe an
algorithm. It allows the analyst to analyze the algorithm while ignoring all unwanted
definitions easily. They can see which operations are being used and how the process
is progressing. It is optional to write step numbers. To solve a given problem, you
create an algorithm. A problem can be solved in a variety of ways.
As a result, many solution algorithms for a given problem can be derived. The
following step is to evaluate the proposed solution algorithms and implement the most
appropriate solution.
As you progress through this "what is an Algorithm" tutorial, you will learn about
some of the components of an algorithm.
Common Problem Solving Operations
Data structures are fundamental tools in computer science, used to organize and store
data efficiently. Here are the most common operations performed on various data
structures:
Basic Operations:
1. Traversal:
o Purpose: Visiting each element in a specific order.
o Examples:
Linear traversal in arrays and linked lists.
Tree traversal (preorder, inorder, postorder) in trees.
Level-order traversal in trees and graphs.
2. Insertion:
o Purpose: Adding a new element to the data structure.
o Examples:
Appending to an array.
Inserting at a specific index in an array or linked list.
Inserting a node in a tree or graph.
3. Deletion:
o Purpose: Removing an existing element from the data structure.
o Examples:
Removing an element at a specific index in an array or linked
list.
Deleting a node in a tree or graph.
4. Searching:
o Purpose: Finding a specific element within the data structure.
o Examples:
Linear search in arrays and linked lists.
Binary search in sorted arrays.
Breadth-first search (BFS) and depth-first search (DFS) in
graphs and trees.
Additional Operations:
5. Sorting:
o Purpose: Arranging elements in a specific order (ascending or
descending).
o Examples:
Bubble sort, insertion sort, selection sort, merge sort, quick
sort.
6. Merging:
o Purpose: Combining two or more sorted data structures into a single
sorted data structure.
o Examples:
Merging two sorted arrays or linked lists.
7. Reversing:
o Purpose: Inverting the order of elements in a data structure.
o Examples:
Reversing an array or linked list.
8. Rotating:
o Purpose: Shifting elements in a circular manner.
o Examples:
Rotating an array or linked list.
9. Splitting:
o Purpose: Dividing a data structure into smaller parts.
o Examples:
Splitting a linked list into two halves.
10. Updating:
Purpose: Modifying the value of an existing element.
Examples:
o Updating an element in an array or linked list.
Example
Problem − Design an algorithm to add two numbers and display the result.
Step 1 − START
Step 2 − declare three integers a, b & c
Step 3 − define values of a & b
Step 4 − add values of a & b
Step 5 − store output of step 4 to c
Step 6 − print c
Step 7 − STOP
General Problem-solving process With Solution formulation and design
The general problem-solving process is a structured approach that helps individuals
and teams analyze, define, and resolve problems efficiently. Here’s a breakdown of
the key steps:
1. Identify the Problem
Understand what the issue is and define it clearly.
Gather relevant information to ensure you are solving the right problem.
2. Analyze the Problem
Examine the problem’s causes and effects.
Look at past experiences, data, or patterns to gain insights.
3. Generate Possible Solutions
Brainstorm different approaches without immediately judging them.
Think creatively and consider multiple perspectives.
4. Evaluate and Choose the Best Solution
Assess each option based on feasibility, impact, and potential risks.
Prioritize solutions that address the root cause effectively.
5. Implement the Solution
Develop an action plan and execute the chosen solution.
Ensure resources and people involved are aligned with the plan.
6. Monitor and Adjust as Needed
Measure the effectiveness of the solution.
Make adjustments or refine the approach if necessary.
Would you like to explore practical examples of this process, or do you have a
specific problem you'd like to solve?
How Do We Formulate an Algorithm?
i. Natural Language: Here, we use everyday English to convey the algorithm. To
comprehend the algorithm from it would be too difficult.
ii. Flow Chart: In this case, we depict the algorithm graphically or visually.
Natural Language is more difficult to grasp than this.
iii. Pseudo Code: In this case, we represent the algorithm as instructive text and
comments in plain English. This is quite close to genuine code, but because it
lacks any syntax resembling a programming language, it cannot be built or
understood by a machine. It is the greatest technique to convey an algorithm since
even a layperson with little programming expertise can understand it.
What is PseudoCode: A Complete Tutorial
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode
does not use any programming language in its representation instead it uses the simple
English language text as it is intended for human understanding rather than machine
reading.
Pseudocode is the intermediate state between an idea and its
implementation(code) in a high-level language.
What is the need for Pseudocode
Pseudocode is an important part of designing an algorithm, it helps the programmer
in planning the solution to the problem as well as the reader in understanding the
approach to the problem. Pseudocode is an intermediate state between algorithm and
program that plays supports the transition of the algorithm into the program.
Pseudocode is an intermediate state between algorithm and program
How to write Pseudocode?
Before writing the pseudocode of any algorithm the following points must be kept in
mind.
Organize the sequence of tasks and write the pseudocode accordingly.
At first, establishes the main goal or the aim.
Use standard programming structures such as if-else, for, while, and cases the
way we use them in programming. Indent the statements if-else, for, while loops
as they are indented in a program, it helps to comprehend the decision control
and execution mechanism. It also improves readability to a great extent.
Example:
IF “1”
print response
“I AM CASE 1”
IF “2”
print response
“I AM CASE 2”
Use appropriate naming conventions. The human tendency follows the approach
of following what we see. If a programmer goes through a pseudo code, his
approach will be the same as per that, so the naming must be simple and distinct.
Reserved commands or keywords must be represented in capital letters.
Example: if you are writing IF…ELSE statements then make sure IF and ELSE
be in capital letters.
Check whether all the sections of a pseudo code are complete, finite, and clear to
understand and comprehend. Also, explain everything that is going to happen in
the actual code.
Don’t write the pseudocode in a programming language. It is necessary that the
pseudocode is simple and easy to understand even for a layman or client,
minimizing the use of technical terms.
Algorithm for Insertion into an Array
I. Define the array and the element to insert: Identify the array where you want
to insert the element and the value of the element.
Ii. Specify the insertion position: Determine the index at which you want to insert
the element.
Iii. Shift elements to the right: Starting from the last element of the array, shift
each element one position to the right until you reach the insertion position.
Iv. Insert the element: Place the new element at the specified index.
V. Update array size (if necessary): If the array was previously full, you might
need to resize it or handle overflow.
Pseudocode for insertion into an array
def insert_element(array, element, index):
// Check if Index position is valid
if index < 0 or index > len(array):
raise IndexError("index out of range")
// Shift elements to the right
array.append(None) # Increase array size temporarily
for i in range(len(array) - 1, position, -1):
array[i] = array[i - 1]
//Insert the element
array[position] = element
return array
Example usage
array = [1, 2, 3, 5]
element = 4
position = 3print(insert_element(array, element, position)) # Output: [1, 2, 3, 4, 5]
Example
Suppose we have an array [1, 2, 3, 4, 5] and we want to insert the element 6 at index
2. The resulting array would be [1, 2, 6, 3, 4, 5].
This algorithm and pseudocode provide a basic framework for inserting an element
into an array. Depending on the programming language and specific requirements,
you may need to modify the implementation.
Sample Algorithm To Search An Array
Linear Search Algorithm
i. Start at the beginning: Begin at the first element of the array (index 0).
ii. Compare elements: Compare the target element with each element in the array.
iii. Check for match: If the target element matches the current element, return the
index.
iv. Continue searching: If no match is found, move to the next element and repeat
steps 2-3.
v. Return result: If the target element is not found after checking all elements, return
a value indicating that the element is not in the array (e.g., -1).
Example in Python
def linear_search(array, target):
for i in range(len(array)):
if array[i] == target:
return i
# Return index of target element
return -1 # Return -1 if target element is not found
index = linear_search(array, target)if index != -1:
print(f"Target element {target} found at index {index}.")else:
print(f"Target element {target} not found in the array.")
Sample
array = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
target = 23
The Complexity of an Algorithm
Complexity of algorithm is the standard through which we measure the efficiency of an algorithm that
is developed in a particular language to choose the most performing one.
The algorithm's performance can be measured in two ways:
i. Time Complexity
The amount of time required to complete an algorithm's execution is
called time complexity. The big O notation is used to represent an algorithm's
time complexity. The asymptotic notation for describing time complexity, in
this case, is big O notation. The time complexity is calculated primarily by
counting the number of steps required to complete the execution. Let us look
at an example of time complexity.
mul = 1;
// Suppose you have to calculate the multiplication of n numbers.
for i=1 to n
mul = mul *1;
// when the loop ends, then mul holds the multiplication of the n numbers
return mul;
The time complexity of the loop statement in the preceding code is at least n,
and as the value of n escalates, so does the time complexity. While the code's
complexity, i.e., returns mul, will be constant because its value is not
dependent on the importance of n and will provide the result in a single step.
The worst-time complexity is generally considered because it is the maximum
time required for any given input size.
Time Complexity: The time complexity of an algorithm refers to the amount of time
required by the algorithm to execute and get the result using all the necessary
execution programming components. This can be for normal operations, conditional
if-else statements, loop statements, etc.
How to Calculate, Time Complexity?
The time complexity of an algorithm is also calculated by determining the following 2
components:
Constant time part: Any instruction that is executed just once comes in this part.
For example, input, output, if-else, switch, arithmetic operations, etc.
Variable Time Part: Any instruction that is executed more than once, say n
times, comes in this part. For example, loops, recursion, etc.
Therefore Time complexity of any algorithm P is T(P) = C + TP(I),
where C is the constant time part and TP(I) is the variable part of the algorithm,
which depends on the instance characteristic I.
Example: In the algorithm of Linear Search above, the time complexity is calculated
as follows:
Step 1: –Constant Time
Step 2: — Variable Time (Taking n inputs)
Step 3: –Variable Time (Till the length of the Array (n) or the index of the found
element)
Step 4: –Constant Time
Step 5: –Constant Time
Step 6: –Constant Time
Hence, T(P) = 1 + n + n(1 + 1) + 1 = 2 + 3n, which can be said as T(n).
How to express an Algorithm?
1. Natural Language:- Here we express the Algorithm in the natural English
language. It is too hard to understand the algorithm from it.
2. Flow Chart:- Here we express the Algorithm by making a graphical/pictorial
representation of it. It is easier to understand than Natural Language.
3. Pseudo Code:- Here we express the Algorithm in the form of annotations and
informative text written in plain English which is very much similar to the real
code but as it has no syntax like any of the programming languages, it can’t be
compiled or interpreted by the computer. It is the best way to express an algorithm
because it can be understood by even a layman with some school-level
knowledge.
What Is Pseudocode?
Pseudocode in is a technique used to describe the distinct steps of an algorithm in a
way that’s easy for anyone with programming knowledge to understand.
In the initial state of solving a problem, it helps to eliminate the limitations offered by
a specific programming language’s syntax rules when we design or validate an
algorithm. By doing this, we can focus our attention on the thought process behind the
algorithm and how it will (or won’t) work instead of focusing on our syntax.
Although pseudocode is a syntax-free description of an algorithm, it must provide a
full description of the algorithm’s logic so that moving from pseudocode to
implementation is merely a task of translating
The Main Constructs of Pseudocode
At its core, pseudocode is the ability to represent six programming constructs (always
written in uppercase): SEQUENCE, CASE, WHILE, REPEAT-UNTIL, FOR, and IF-
THEN-ELSE. These constructs — also called keywords — are used to describe the
control flow of the algorithm.
1. SEQUENCE represents linear tasks sequentially performed one after the
other.
2. WHILE is a loop with a condition at its beginning.
3. REPEAT-UNTIL is a loop with a condition at the bottom.
4. FOR is another way of looping.
5. IF-THEN-ELSE is a conditional statement changing the flow of the
algorithm.
6. CASE is the generalization form of IF-THEN-ELSE.
Although these six constructs are the ones we use most often you can theoretically use
them to implement any algorithm. You might find yourself needing more based on
your specific application. Perhaps the two most needed commands are:
1. Invoking classes or calling functions (using the CALL keyword).
2. Handling exceptions (using EXCEPTION, 5WHEN keywords).
Of course, based on the field you’re working in, you might add more constructs
(keywords) to your pseudocode glossary as long as you never use these keywords as
variable names and ensure they’re well-known within your field or company.
MORE FROM SARA A. METWALLI5 Git Commands That Don’t Get Enough
Hype
How to Write Pseudocode
When writing pseudocode, everyone has their own style of presenting since humans
are reading it and not a computer; pseudocode’s rules are less rigorous than those of
a programming language. However, there are some simple rules that help make
pseudocode more universally understood.
1. Always capitalize the initial word (often one of the main six constructs).
2. Make only one statement per line.
3. Indent to show hierarchy, improve readability and show nested constructs.
4. Always end multi-line sections using any of the END keywords (ENDIF,
ENDWHILE, etc.).
5. Keep your statements programming language independent.
6. Use the naming domain of the problem, not that of the implementation. For
instance: “Append the last name to the first name” instead of “name =
first+last.”
7. Keep it simple, concise and readable.
Why Use Pseudocode?
i. Pseudocode Is Easier to Read
Often, programmers work alongside people from other fields such as mathematicians,
managers and business partners. Using pseudocode to explain the mechanics of the
code makes communicating between different specialties easier and more efficient.
ii. Pseudocode Simplifies Code Construction
When the programmer goes through the process of developing and generating
pseudocode, converting that into real code written in any programming language will
become much easier and faster.
iii. Pseudocode Is a Good Middle Point Between Flowchart and Code
Moving directly from the idea to the flowchart to the code is not always a smooth
ride. That’s where pseudocode presents a way to make the transition between the
different stages somewhat simpler.
iv. Pseudocode Is a Helpful Starting Point for Documentation
Documentation is an essential aspect of building a good project but starting
documentation is often the most difficult part of the process. Pseudocode can
represent a good starting point for what the documentation should include.
Sometimes, programmers even include the pseudocode as a docstring at the beginning
of the code file.
v. Pseudocode Allows for Quick Bug Detection
Since pseudocode is written in a human-readable format, it is easier to edit
and discover bugs before actually writing a single line of code. We can edit
pseudocode more efficiently than testing, debugging and fixing actual code.
Pseudocode is an underestimated and under-utilized tool within the programming
community, but a clear, concise, straightforward pseudocode can make a big
difference on the road from idea to implementation — and a much smoother ride for
the programmer.
Basic Logical Operators Commonly used by Programmers
We have seen the use of logical operators in our examples; if the sale price is > $10
for example. The following code sample shows the typical operators you would see in
programming:
// x is equal to y
x == y
//x doesn't equal y
x != y
//also written as
x <> y
//x is less than y
x<y
//x less than or equal to y
x <= y
//x is greater
x>y
//greater than or equal to
x >= y
//modulo (returns 0 if the division operation has no remainder)
x%y
In our code, we must also make sure to check if conditions are true or false (again, it
boils down to Boolean). That is: if the sale price is > $10 AND the sale price is < $20.
These operators are AND, OR, NOT.
//AND - both x and y must be true
x && y
//OR - either y or x is true
x || y
//The NOT operator is the opposite. Basically, not Y. It returns TRUE if y is FALSE.
What is Control Structure
A control structure, in the context of computer programming, refers to a set of
statements that determine the flow and execution of a program. It enables the
programmer to dictate the order in which the instructions are executed, based on
certain conditions or criteria. Control structures provide decision-making capabilities
and repetitive execution mechanisms, allowing for the creation of complex and
dynamic programs.
A control structure is a block of code that analyzes variables and decides where to
take the program
There are three types of control
structure; sequence, selection(conditional) and iteration(Looping)
Each type has its own benefits and disadvantages
The control structure used depends on the type of task being carried out
Although multiple control structures may work for an algorithm, it's best practice
to chose the most efficient and cleanest control structure to use
Sequence refers to the default control structure, where statements are executed in
the order they appear in the program. This means that each statement is executed
one after another, without any conditional checks or loops. It is the most
straightforward and linear control structure.
Selection control structures, also known as decision-making structures, allow
the program to make choices based on specific conditions. These structures
include if-else statements, switch-case statements, and conditional operators. By
evaluating the conditions specified in these structures, the program can execute
different sets of statements based on the outcome of the evaluation. This enables
the program to adapt its behavior and make decisions dynamically during
runtime.
Iteration control structures, also referred to as loop structures, enable the
repetition of a set of statements until a certain condition is met. These structures
include while loops, for loops, and do-while loops. By repeating a block of code,
programmers can efficiently perform tasks that require iteration, such as
processing data arrays, performing calculations, or executing a series of steps
until a specific condition is satisfied.
Control structures provide programmers with the ability to create powerful and
flexible programs. They allow for the execution of different code paths,
depending on the conditions encountered during runtime. This facilitates the
creation of dynamic and interactive applications that can handle various scenarios
and user inputs.
An Example
Let us analyze flow control by using traffic flow as a model. A vehicle is arriving at
an intersection. Thus, the precondition is the vehicle is in motion. Suppose the traffic
light at the intersection is red. The control structure must determine the proper course
of action to assign to the vehicle.
Precondition: The vehicle is in motion.
Treatments of Information through Control Structures
A. Is the traffic light green? If so, then the vehicle may stay in motion.
B. Is the traffic light red? If so, then the vehicle must stop.
End of Treatment
Post condition: The vehicle comes to a stop.
Thus, upon exiting the control structure, the vehicle is stopped.
Sequence
Sequence is the easiest control structure to use and make sense of
This control structure runs through the code sequentially
This means that steps are followed in order from line 1 of the program to the end
no matter what conditions are met
Selection
The selection control structure allows a program to test conditions based off
certain criterion
Selection follows IF [this] THEN [that] logic
It can be seen as a boolean conditon as the result is going to be true or false
Selection structures also rely on an ELSE statement
When the specified or expected criterion isn't met, the program will follow
the ELSE instructions
CASE example used in Selection from Visual Basic
Dim grade As String
Private Sub Compute_Click( )
grade=txtgrade.Text
Select Case grade
Case "A"
result.Caption="High Distinction"
Case "A-"
result.Caption="Distinction"
Case "B"
result.Caption="Credit"
Case "C"
result.Caption="Pass"
Case Else
result.Caption="Fail"
End Select
End Sub
Iteration
Iteration is another term for looping
A function or program utilizing looping will run a specific block of code until
certain crtierion is met
Examples in Visual Basic HERE
Three main types of iteration exist; while, do-while and for
o WHILE Loops (Test-first)
A while loop can be seen as a repeating IF statement
At the start of the statement, a boolean condition is given
While this statement is true, the code within the WHILE loop will execute
Once this statement is false, the compiler or interpreter will move on to the
next block of code
This is known as test-first because the expression is always considered
before running the loop, meaning that this block of code has the option
to never run if the condition isn't met
Example:
$i = someFunction($value);
while ($i >= 2){
// Do something
}
# Our variable $i will have an arbitrary value from some undefined function.
# While that number is greater than or equal to 2, we'll "do something".
o FOR Loops (Fixed)
FOR loops run until a particular condition is satisfied
A boolean expression is given at the start of the control structure
There is an incremental counter in the for loop expression that tells the
function when to stop
This is known as a fixed control structure as there's a finite number of times
the loop will run (as per determined by the expression)
Example:
for ($i = 1; $i <= 200; $i++){
// Do something
}
# In a FOR loop, we state what value our counter ($i) will begin with (in this
case 1)
# We then tell the control to repeat the code while $i is LESS THAN or
EQUAL TO 200
# Finally, we increment our counter ($i) by 1 to continue the loop.
# This is a fixed loop because we know that the boundaries are 1 <= $i <=
200 (thus looping 200 times)
o DO-WHILE Loops (Test-last)
A DO-WHILE loop will run a condition regardless of the previous outcomes
This is because the boolean expression is evaluated at the end of the control
structure
This means that a DO-WHILE loop is garuanteed to run at least once
Example:
do {
// Do something
$i++;
} while ($i < 4);
# In this example, we're telling the code to run some functions and increment
$i by 1.
# Since this is a test-last, we will always have this code executed at least
once, since $i isn't evaluated until the end of the block.
# $i will increment by 1 until it is equal to 4.
FLOWCHART
A program flowchart is a visual representation of the steps in a software program or
algorithm, using standard symbols and lines to show the flow of data and control. It's
a tool for planning, documenting, and communicating how a program works.
A program flowchart is a diagram illustrating the logical steps involved in a
software program or programming task. One of the first things a programming newbie
will do is create a flowchart. They start with a simple process map and quickly add
more complex stuff. Program flowcharts can be handy for explaining the order of
events in a program. They can also illustrate a computer program's data, processes, or
decision flows. Many diagrams are drawn using flowcharts, including those used to
demonstrate organizational strategies, tasks, or activities.
There are some things you should consider before using a program flowchart:
What kind of project do you want to make?
Do you want to make an app or a website? What type of software will you be
using?
Are there any special requirements or limitations?
The Benefits of Programming Flowcharts:
When it comes to understanding programming or a logical structure,
programming flowcharts are the best way of working.
When a designer is creating a program, there can be certain loopholes that can
hinder the progress. To avoid that, they can design the app or website with
programming flowcharts before working on them.
The engineer working on the debugging process can look at the programming
flowchart, making it easier to debug the program.
For reviewing a program, the designer may need to look at the programming
flowchart.
They can analyze the program with the help of the logical diagram of the
flowchart and then modify it as per their requirement.
The engineers can also use flowcharts as a way of documenting their program
correctly.
As the programming flowcharts work as blueprints, it is time-efficient while
creating a new program or application.
Program Flowchart Symbols
For creating a programming flowchart, the user needs programming flowchart
examples. The flowcharts use diagrams to express an algorithm, and hence flow
charts are very helpful in creating and analyzing the details of a program. The flow
charts use some symbols that can explain the logic of programming connected with
the flowchart elements. Here are some widely-used programming flowchart symbols.
Flow Line: This symbol works as a connector in a programming flowchart.
This line shows the logical flow and relationship among the various steps or
elements of the programming flowchart. The flow lines run between each step
starting from the two terminals to denote the flow of logic.
Terminal (Start/ Stop): The terminal symbols present in every programming
flowchart as the process starts with a "start" command, and a "stop" command
shows the end of the whole process on the flowchart. The example also has
both the start and end symbols represented by a rectangular sign with curved
edges to signify the beginning and end of a programming flowchart procedure.
Input/ Output: The commands of Input and Output in operation are most
crucial. To get a logical flow to go through the processing, the user needs to
give input. The system reads the inputs to give an output. The symbols for
inputs and outputs are parallelograms.
Processing: For a process to complete successfully, the method must include
the function of processing. The processing part occurs between the input and
the output. The rectangle shapes represent the processing work.
On-page connector: When there is a need to connect different flowlines, on-
page connectors are present at the junction.
Off-page connector: The off-page connectors connect different flowlines
when they are present on separate pages.
Decision: When there is a need to decide between true or false, this function
gets used. The diamond-shaped symbols are useful when the function is taking
a series of decisions to get the result.
Predefined process/ function: When a group of some statements performs a
predefined work, its representation occurs with this symbol.
Document: This symbol denotes the printout or report.
If you want to know more comprehensive information about flowchart symbols, you
can click here to learn more.
5. Program Flowchart Examples & Templates
Program flowcharts are diagrams that depict the sequence of steps that must be
followed to achieve an objective. In a flowchart, each series block is a decision point
in the process. At each decision point, there is only one possible outcome. These
blocks can represent any set of choices within a program or system. Flowcharts help
explain to someone what the program does (e.g., they can show where data comes in,
what data is checked, what output is produced), how it works, and why it works that
way. A flowchart provides no information about how to run the program.
You can click and download to use following program flowchart examples for free.
And if you want more flowchart examples, you can click here to get more.
Example 1: Calculating Program Flowchart
This is a calculating program flowchart, you can use this to understand loop program
for calculating.
Click here to download EdrawMax
(For Win)
Calculating Program Flowchart
Example 2: Program Flowchart for "True or false"
Your first program should be a "True or false" program. It is an elementary program,
so learning to write one is very easy. But before writing code, you should draw its
flowchart first to dry run your code and check whether the algorithm is accurate or
not.
Click here to download EdrawMax
(For Win)
Program Flowchart for "True or false"
Example 3: Conditional Statement Program Flowchart
A conditional statement is the fundamental principle of programming. It determines
which instructions will run in the program. In this case, we can use a decision tree. A
decision tree is a type of flowchart that offers an easy way to visualize scenarios and
determine the best course of action. We usually check a number to find whether it is
odd or even. This can be done by using an "if else" statement. For example, if we
enter 2 into the number field, we want to check if the variable's value is even or odd.
We can draw the following flowchart.
Click here to download EdrawMax
(For Win)
Conditional Statement Program Flowchart
ii. Space Complexity
The amount of space an algorithm requires to solve a problem and produce an
output is called its space complexity. Space complexity, like time complexity,
is expressed in big O notation.
Reasons Space Is Required For An Algorithm
i. To store program instructions.
ii. To store track of constant values.
iii. To store track of variable values.
iv. To store track of function calls, jumping statements, and so on.
Space Complexity = Auxiliary Space + Input Size
How to calculate Space Complexity?
The space complexity of an algorithm is calculated by determining the following 2
components:
Fixed Part: This refers to the space that is required by the algorithm. For
example, input variables, output variables, program size, etc.
Variable Part: This refers to the space that can be different based on the
implementation of the algorithm. For example, temporary variables, dynamic
memory allocation, recursion stack space, etc.
Therefore Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C
is the fixed part and S(I) is the variable part of the algorithm, which depends on
instance characteristic I.
Examples of Algorithms and Flowcharts in C