Algorithms, Pseudocode, and
Flowcharts
Understanding Algorithms vs. Pseudocode
Algorithm Pseudocode
A systematic, step-by-step procedure using pure English phrases to A high-level representation using a mixture of natural language and
describe problem solutions. Think of it as telling a story of how to solve programming syntax. More structured than algorithms, incorporating
a problem in plain language that anyone can understand. mathematical expressions and programming constructs for precise logic
flow.
Key distinction: Pseudocode is programming language-independent and not executable, but helps you understand algorithm flow before actual
implementation. Both terms are often used interchangeably in practice.
Algorithm vs. Pseudocode Example
We will now write an algorithm and a pseudocode to evaluate an expression, say d = a + b ∗ c. Here a, b, c, and d are known as variables. A variable is a name
given to a memory location that stores some data value. First, let us look at the algorithm for the expression evaluation. Let's examine how the problem
(evaluating d = a + b × c) looks in both formats:
Pseudocode Format
Notice how pseudocode is more concise and uses programming-like syntax, while the algorithm uses detailed English descriptions.
Why Use Pseudocode?
1 Ease of Understanding
Programming language independent - novice developers can understand it easily without knowing specific syntax rules.
2 Focus on Logic
Allows concentration on algorithm logic without worrying about syntax details of specific programming languages.
3 Enhanced Readability
Combines programming constructs with English phrases for precise, legible logic communication.
More Benefits of Pseudocode
Consistency Easy Translation Flaw Identification
Standardized constructs make it useful Programming constructs make mapping Helps identify logical flaws and issues in
for sharing ideas among developers pseudocode to actual program code solution approach before actual
from various programming domains and straightforward and efficient. implementation begins.
backgrounds.
Three Programming Constructs
Structured programming uses three fundamental constructs that ensure linear control flow. These are single entry-single exit constructs:
Sequencing Selection Repetition
Instructions executed in order, one after Decision-making based on conditions. Repeated execution of instruction blocks. Uses
another. Every instruction runs exactly once Different blocks execute based on test while, repeat-until, or for loops for iterative
without skipping. outcomes using if-else structures. processing.
Relational and Logical Operators
Conditions in selection and loop structures use special operators to make decisions:
Operator Meaning
> greater than
< less than
== equal to
>= greater than or equal to
<= less than or equal to
!= not equal to
Logical Operators: AND (&&), OR (||)Example: a > b AND a > c
Selection Structure Example: PersonType(age)
Here's another example of a selection structure, specifically an if-else structure, demonstrated by the PersonType(age) pseudocode. This pseudocode checks
if a person is a major (age 18 or older) or a minor:
In this example, if the value of age is 18 or greater, the message "You are a major" will be printed. Otherwise (if age is less than 18), the message "You are a
minor" will be printed. This ensures that one of the two outcomes is always executed based on the condition.
Selection Structure Example: CompareVars(x,y)
Here's an example of an if-else if-else structure, demonstrated by the CompareVars(x, y) pseudocode. This pseudocode compares two variables x and y and
prints the relation between them:
In this example, the pseudocode first checks if x is greater than y. If true, it prints that x is greater. If false, it then checks if x is less than y. If that is true, it
prints that y is greater. If both conditions are false, it means x and y must be equal, and the final else block is executed to print that the values are equal.
Case Structure
The case structure is a refined alternative to if else if else structure. The pseudocode representation of the case structure is given below.
The general form of this structure is:
The expression (which can also be a single variable) is compared sequentially with value1, value2, and so on. If there is a match, the corresponding block of
statements (e.g., block1 for value1) will be executed. Typically, each block will include a mechanism (like a `break` statement) at the end to exit the case
structure once a match is processed.
If no match is found after comparing the expression with all specified case values, the default_block will be executed. This ensures that a predefined set of
instructions always runs if none of the specific conditions are met.
If the break statement is omitted from the block for the matching case, then the execution continues into subsequent blocks even if there is no match in the
subsequent blocks, until either a break is encountered or the end of the case structure is reached.
Case Structure Example: PrintDirection(dir)
Here's an example of the case structure, demonstrated by the PrintDirection(dir) pseudocode. This pseudocode takes a character input dir and prints the
corresponding full direction name.
This example illustrates how the case structure evaluates the dir expression against multiple possible values. Upon finding a match, the corresponding block
of statements is executed, and the break statement ensures the structure is exited immediately. If no match is found, the default block handles the input by
printing "Invalid direction code".
Specific Cases Break Statement Default Handling
Each case statement (e.g., 'N', 'S') checks The break keyword after each case's logic The default case acts as a fallback. If the
for an exact match with the input is crucial. It terminates the case structure input dir doesn't match 'N', 'S', 'E', or 'W',
character, executing its unique instruction immediately, preventing unintended the default block is executed, ensuring all
set if true. execution of subsequent cases. possibilities are handled.
Loop Structures
Repetition constructs allow a block of instructions to be executed multiple times. Understanding the type of iteration and the loop's core is fundamental.
Repetition & Loops Iteration or Pass Definite Iteration
A fundamental programming construct used Refers to each single execution cycle of the Occurs when the exact number of times the
to execute a specific block of instructions block of instructions within a loop. loop will run is known before the loop
repeatedly. starts.
Indefinite Iteration Loop Body
Also known as conditional iteration, where The specific set of instructions or
the number of repetitions is not statements that are repeatedly executed
predetermined but depends on a condition during each iteration of the loop.
being met.
Loop Structures Explained
while Loop repeat-until Loop for Loop
Entry-controlled indefinite iteration. Tests Exit-controlled indefinite iteration. Executes Definite iteration with counter variable.
condition first, executes body while condition body first, then tests condition. Always Three variants: increment, decrement, and
is true. May execute zero times if condition executes at least once. Stops when condition custom step. Perfect when you know exact
initially false. becomes true. iteration count.
Differences: While vs. Repeat-Until
There are two major differences between while and repeat-until loop constructs:
While Loop: Entry-Controlled Repeat-Until Loop: Exit-Controlled
In a while loop, the condition is tested at the beginning of each iteration. If The repeat-until loop executes its body at least once before the condition is
the condition is initially false, the loop body will not execute even once. tested at the end of the iteration. The loop continues until the specified
condition becomes true.
The key distinction lies in when the condition is evaluated. This difference guarantees that a repeat-until loop will always run its instructions at least once,
unlike a while loop, which might skip execution entirely if its condition is not met from the start.
For Loop: Definite Iteration
The for loop is used for definite iteration, executing a block of instructions a predetermined number of times. It uses a loop variable as a counter, updated after
each pass.
Incrementing Loop Decrementing Loop Custom Step Loop
Counts up from begin to end, increasing the Counts down from begin to end, decreasing the Increments or decrements the variable by a
variable by 1 in each iteration. variable by 1 in each iteration. specified step value, allowing flexible
progression.
Each variant follows a clear pattern: initialization, condition checking, and variable update, ensuring precise control over the number of repetitions. The loop
continues until the counter meets the specified end condition.
Flowcharts: Visual Algorithm
Representation
Flowcharts provide diagrammatic representation of algorithms showing control flow through
interconnected blocks and flow lines.
Standard Symbols
Ovals for start/end, rectangles for processes, diamonds for decisions,
parallelograms for input/output, hexagons for loops.
Flow Direction
Arrows show execution sequence and data flow between blocks. Most blocks
have single entry/exit except decision and loop blocks.
Visual Logic
Makes complex algorithms easier to understand, debug, and communicate to
others through visual representation of logic flow.
Flowchart Fundamentals
Flowcharts visually represent algorithms, illustrating control flow through interconnected blocks and flow-lines. Each block symbolizes a processing stage,
with different types representing various programming constructs.
Blocks and Flow Lines Control Flow Exceptions
Blocks signify distinct processing steps. Flow lines indicate the sequence of Most blocks have single incoming and outgoing flow lines. However,
execution, showing data or control flow into and out of blocks. selection and loop constructs have multiple exits, each representing a
possible outcome or branch.
Flowchart
Diagram Flowchart
Walkthrough
Start
Represented by ovals at the beginning and end of the flowchart.
Input
Parallelograms indicate reading the principal, rate, and years, and printing the simple interest (SI).
Process
A rectangle shows the calculation step: SI = (principal * rate * years) / 100.
Flow Lines
Arrows connect symbols, showing the sequence of operations from start to stop.
Problem Solved: Printing Color Based on Code Value
This problem demonstrates the use of a case structure to select an action based on a specific input value, providing a clear example of multi-way branching in algorithms and flowcharts.
Pseudocode: To Print Color Based on Code Algorithm: To Print Color Based on Code
1. Start
2. Read the input character, `code`.
3. Evaluate the `code`:
4. If `code` is 'R', print "Red" and exit the case structure.
5. If `code` is 'G', print "Green" and exit the case structure.
6. If `code` is 'B', print "Blue" and exit the case structure.
7. If `code` does not match any of the specified cases, print "Wrong code".
8. Stop
Problem Solved: Printing Numbers from 1 to 50 in
Descending Order
This problem demonstrates the use of an iterative structure (loop) to print a sequence of numbers in descending order, showcasing how algorithms handle
repetitive tasks and control flow.
Pseudocode: To Print Numbers 1 to 50 in Descending Order Algorithm: To Print Numbers 1 to 50 in Descending Order
1. Start
2. Set a variable, i, to the initial value of 50.
3. Begin a loop that will continue as long as i is greater than or equal to 1.
4. Inside the loop, display (print) the current value of i.
5. Decrease the value of i by 1 (i.e., i = i - 1).
6. Repeat steps 3-5 until the condition (i >= 1) is false.
7. Stop
Figure : Flowchart to print numbers in descending order
Problem Solved: Calculating the Factorial of a Number
This problem demonstrates the calculation of a factorial for a given non-negative integer, showcasing the use of iterative structures (loops) and conditional logic in algorithm design.
Pseudocode: To Calculate the Algorithm: To Calculate the Factorial
Factorial of N [Link] NStart.
2. Read the non-negative integer N as input.
3. Initialize a variable factorial to 1.
4. If N is negative, print an error message stating that factorial is undefined for negative
5. numbers.
Else if N is 0, set factorial to 1 (since 0! = 1).
6. Else (if N is a positive integer):
1. Initialize a counter i to N.
2. Begin a loop that continues as long as i ≥ 1.
3. Inside the loop, multiply the current factorial value by i and store the result back
4. in factorial. i by 1.
Decrement
5. Repeat steps 6b-6d until the loop condition is false.
7. Display the final calculated factorial.
8. Stop.
Figure 2.7: To find the factorial of a number
Problem Solved: Finding the Largest of N Numbers
This problem outlines an algorithm to efficiently determine the largest value within a given set of 'n' numbers using iterative comparison, presented with pseudocode,
a detailed algorithm, and a flowchart.
Pseudocode: To Determine the Largest of N Algorithm: To Determine the Largest of N Numbers
Numbers
1. Start
2. Read the total count of numbers to process, n, and the first number, num.
3. Initialize a variable named large with the value of the first num read.
4. Begin a loop that iterates n - 1 times, processing the remaining numbers.
5. Inside the loop, read the next num from the input.
6. Compare the current num with the value stored in large.
7. If num is greater than large, update large with the value of num.
8. Continue iterating through the loop until all n - 1 subsequent numbers
9. have been
After evaluated.
the loop completes, display the final value stored in the large
10. variable.
Stop
Figure 2.8: To find the largest of n numbers
Problem Solved: Calculating Average Age of Students
This problem demonstrates how to calculate the average age of a group of students using a `while` loop, where input continues until a sentinel value (age 0) is entered.
It illustrates iterative processing and accumulation.
Pseudocode: To Determine the Algorithm: To Determine the Average
Average Age [Link] Start
2. Initialize a variable `sum` to 0 to accumulate the ages.
3. Initialize a variable `count` to 0 to keep track of the number of students.
4. Read the first `age` from the user.
5. Begin a `while` loop that continues as long as the entered `age` is not equal to 0
1. Add the current `age` to `sum`.
2. Increment `count` by 1.
3. Read the next `age` from the user.
6. Once the loop terminates (when `age` is 0), calculate the `average` by dividing `sum` by
7. `count`.
Display the calculated `average`.
8. Stop
Figure 2.9: To determine the average age using while loop
Problem Solved: Calculating Average Age of Students (Repeat-Until Loop)
This problem demonstrates how to calculate the average age of a group of students using a repeat-until loop, ensuring the loop body executes at least once before checking the
condition. It's a common alternative to the while loop for iterative processing and accumulation.
Pseudocode: To Determine the Average Algorithm: To Determine the Average
Age (Repeat-Until) Age (Repeat-Until)
1. Start.
2. Initialize a variable sum to 0 to accumulate the ages.
3. Initialize a variable count to 0 to keep track of the number of students.
4. Read the first age from the user. This initial read is crucial before entering the loop.
5. Begin a repeat-until loop, which guarantees that the statements within the loop will
[Link]
Addatthe
least once:age to sum.
current
2. Increment count by 1.
3. Read the next age from the user.
6. The loop continues until the entered age is equal to 0.
7. Once the loop terminates (when age is 0), calculate the average by dividing sum by
8. count. the calculated average.
Display
9. Stop.
Figure 2.10: To determine the average age using a repeat-until loop
Problem Solved: Calculating Average Height of Boys and Girls
This problem demonstrates how to calculate the distinct average heights for boys and girls within a group of students using a single loop and conditional logic,
providing a practical example of data categorization and aggregation.
Pseudocode: To Determine Average Height Algorithm: To Determine Average Height of
of Boys and Girls Boys and Girls
1. Start.
2. Read the total number of students, n.
3. Initialize btotal (total height for boys) to 0.
4. Initialize bcount (count of boys) to 0.
5. Initialize gtotal (total height for girls) to 0.
6. Initialize gcount (count of girls) to 0.
7. Begin a loop that iterates from 1 to n.
1. Inside the loop, read the gender and height for the current student.
2. If gender is 'M' (Male):
1. Add height to btotal.
2. Increment bcount by 1.
3. Else (if gender is not 'M', assume 'F' for Female):
1. Add height to gtotal.
2. Increment gcount by 1.
8. After the loop:
1. Calculate bavg = btotal / bcount.
2. Calculate gavg = gtotal / gcount.
9. Display the calculated bavg and gavg.
10. Stop.
Conclusion
In this chapter, we've explored the foundational elements of algorithms, flowcharts, and pseudocode — the essential tools in the development of efficient
and effective programs.
Algorithms Flowcharts Pseudocode
Provide a clear, step-by-step approach to Offer a visual representation that aids in Serves as an intermediary step, bridging
problem-solving. understanding the logical flow. abstract algorithm to actual code.
Together, these tools help in breaking down complex problems into manageable parts, ensuring clarity and precision in programming. Mastering these
concepts is crucial for anyone aiming to develop robust software solutions, serving as a solid foundation for tackling more complex problems.
Thank You!