Writing Pseudocode and Designing Step-by-Step Solutions

UPI Study › Courses › Introduction to Artificial Intelligence › Free lessons › Lesson 3.1 Free with a free account

Writing Pseudocode and Designing Step-by-Step Solutions

Introduction to Artificial Intelligence · Chapter 3: Programming Foundations and SecuritySection 3.1 · lesson 18 of 6911 min · free with a free account

← Agents That Improve Through ExperienceNext lesson: Programming Foundations: Writing, Testing, and Fixing Code →

Earn 3 college credits for Introduction to Artificial IntelligenceRecommended for credit by NCCRS · Computer Science 373 · self-paced · one payment, lifetime access

In this lesson

Design, decompose, flowchart, and hand-trace a solution before coding.

  • Write precise pseudocode using sequence, selection, iteration, and functions
  • Decompose a problem into sub-tasks and functions through stepwise refinement
  • Hand-trace a design with a trace table, including edge cases
  • Translate pseudocode into Python while avoiding common translation traps

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,581 words). Read along, or search it.

Opening Question

Plan Before Laying Any Bricks

A builder doesn't start laying bricks without a plan. And a programmer shouldn't start typing code without one, either. The better habit is to design the solution first, in a form people can read, question, and correct quickly. So how can you plan a solution so clearly, that any person, or any programming language, could carry it out? Write the steps in pseudocode, split the problem up, draw the paths, check them by hand, and only then, write the code.

Definition

Structured Plain Language for People

Pseudocode is a structured, plain-language description of the steps in a solution. It looks a little like code, but it follows no particular language, and no computer runs it. Its readers are people. Because it ignores punctuation rules and data types, you can focus on the logic: what happens, in what order, and under which conditions. Compare one instruction, written three ways. Everyday language says: give a pass if the average is good enough. But good enough is open to interpretation. Pseudocode says: IF average is at least 60, THEN DISPLAY Pass. The condition is exact. And program code is a strict version that a computer can run.

Building Blocks

Sequence, Selection, Iteration, and Functions

Almost every design, however large, is built from the same four blocks. Sequence runs steps in order, top to bottom, with words like SET, READ, and DISPLAY. Selection chooses a path by testing a condition: IF, THEN, ELSE, and END IF. Iteration repeats a block, while a condition holds, or once for each item: WHILE, or FOR EACH. And a function packages steps under a name. It takes inputs, and returns a result.

Usage Tips

FOR EACH, WHILE, and Nested Blocks

Two choices come up often. Use FOR EACH when you have a collection, and want every item. Use WHILE when you repeat until something changes, like: while the answer isn't valid. Blocks can also sit inside one another. A selection inside a loop is one of the most common patterns, and the design coming up uses one. In a function, a parameter is an input it receives: here, score. The return value is the result it hands back. After that, the design just uses its name.

Writing Clearly

One Exact Action per Line

Pseudocode has no official rulebook. But clear writing separates a useful design from a vague one. Do the math with the numbers, becomes SET total TO total plus score: one clear action per line. Loop through stuff, becomes FOR EACH s IN scores: name what repeats, and over what. And check if it's good, becomes IF score is at least 60: the exact condition. Use meaningful names with starting values, like SET count TO 0, not make a variable x. And close every block with its END word, indenting what's inside.

Decomposition

Averaging Valid Quiz Scores

Large problems become manageable when you split them. Decomposition means breaking a problem into sub-tasks, then breaking those down again, until each step fits in a line or two. It's also called stepwise refinement. Here's the problem we'll follow for the rest of the lesson. Given a list of quiz scores, ignore any score outside zero to a hundred, and average the rest. Report Pass if the average is at least 60, and Retry otherwise. And if no valid scores remain, say so instead.

Stepwise Refinement

Four Steps to Three Functions

Decompose it in four steps. State the problem in one sentence, with its input, the scores, and its output, a verdict. Split it into three to five sub-tasks that cover the whole job. Refine each one until every step is a simple action, or a decision. Then choose functions. A sub-task with clear inputs, one result, and that could be tested alone, makes a good function. Here that gives three: is valid checks one score, average averages the valid ones, and verdict turns an average into Pass or Retry. A main routine calls them.

Flowcharts

Boxes, Diamonds, Ovals, and Arrows

A flowchart shows the same logic as a picture. On paper, boxes are steps, diamonds are decisions with two exits, ovals mark the start and end, and arrows show the order. Here's the average sub-task. Set total and count to zero. Then a decision: any scores left? If not, leave the loop. If so, another decision: is this score valid? If yes, add it, and count it. Either way, the path returns to the first decision. That return is the loop. A flowchart makes the paths easy to see, which suits small or tricky logic. Pseudocode holds more detail in less space, which suits whole designs.

Complete Design

is valid, average, verdict, and main

Here's the complete design. is valid returns whether a score is between zero and a hundred. average sets total and count to zero. For each score, if it's valid, it adds it, and counts it: a selection, nested inside a loop. If nothing was counted, it returns none, so there's nothing to divide. Otherwise it returns total over count. verdict turns an average into Pass or Retry. And main runs it all on four scores: 70, 105, 50, and 90.

Hand-Tracing

Filling In a Trace Table

Before any code exists, test the design by hand-tracing it. Act as the computer, follow one line at a time with a sample input, and record every change in a trace table. Start: total and count are both zero. The first score, 70, is valid, so total becomes 70, and count, 1. Next, 105. It's outside the range, so it's skipped. Nothing changes. Then 50: total 120, count 2. Then 90: total 210, count 3. Count isn't zero, so average returns 210 over 3, which is 70. And verdict of 70 gives Pass.

Edge Cases

Empty Lists and Boundary Scores

One normal case isn't enough. Good designers also trace edge cases: unusual inputs that sit at a boundary, or break an assumption. An empty list: the loop never runs, count stays zero, and the design reports no valid scores. Scores of 105 and minus 5: both skipped, with the same result. A single 60 sits on the boundary: 60 is at least 60, so Pass. A single 59 gives Retry. Suppose the designer had left out the check for a zero count. Tracing the empty list reaches total over count, both zero: a division by zero, found on paper, in minutes.

Quick Check

Catching Less Than Versus At Most

Quick check. A designer wrote the validity test as: score less than 100, instead of at most 100. Which one of these edge cases would catch that mistake? Pause, and decide. The list with just 100. The design accepts it, and says Pass. But less than 100 is false for 100, so the buggy test skips it: no valid scores. Zero passes both tests, so it can't tell them apart. And 105 and minus 5 are skipped either way.

Translation

From Pseudocode Constructs to Python

Once a design survives tracing, translating it is mostly swapping each construct for its match in a language. We'll use Python. The same design could just as easily become Java. Translate one function at a time, smallest first, and finish with main. And if translating reveals a flaw, fix the design first, then the code. SET total TO 0 becomes total equals 0. FOR EACH s IN scores becomes, for s in scores, with a colon. IF count equals 0 becomes if count, double equals, 0. RETURN none becomes return None, with a capital N. And there are no END words: in Python, the indentation ends each block.

Common Mistake

Single Equals Versus Double Equals

Watch for a few translation traps. First, one symbol, two jobs. In pseudocode, equals can mean is equal to. In Python, a single equals stores a value, and double equals compares. Copy the pseudocode's equals straight into Python, and the program won't even start. Python points at the line, and even suggests the fix: maybe you meant double equals. With that fixed, it runs. Second, structure markers differ: Python uses a colon and indentation, where pseudocode uses END words. Third, names change style. is valid becomes is underscore valid. Keep the meaning, even when the spelling changes.

Running the Code

The Program Prints 70.0, Pass

Here's the whole design in Python, every function translated the same way. Run it on the four scores, and it prints 70.0, Pass. In Python, a single slash always gives a decimal, so the average shows as 70.0. 105 was skipped, just as the trace table predicted. The code and the design agree.

Debugging

Reading a ZeroDivisionError Traceback

Remember the missing check? Here's average without it, called on an empty list. Python stops with a traceback. Read it from the bottom: ZeroDivisionError, division by zero, raised in average, at return total over count. Tracing the empty list found the same flaw on paper, before any code existed.

Quick Check

Predicting the Verdict for New Scores

Quick check. The same Python program now runs on four new scores: 100, 0, 101, and 40. What verdict does it report, and about what average? Pause, and predict. Retry, with an average of about 46.7. Zero is a valid score: it's inside zero to a hundred, so it counts. Only 101 is skipped. So the total is 140, over a count of 3. If you got 60.25, you kept the 101. If you got 70, you threw out the zero.

Key Takeaways

Design, Trace, Then Translate

To sum up. Pseudocode describes a solution in precise, plain language that people can read and check. Every design is built from sequence, selection, iteration, and functions. Decomposition splits a problem, and flowcharts show its paths. Hand-tracing with a trace table, edge cases included, finds flaws before any code exists. And translation swaps each construct for its match. Watch for traps, like a single equals that should be double.

Reflection

Writing a Daily Routine as Pseudocode

Something to think about. Choose a routine you follow every day, like making tea, and write it as pseudocode, with at least one IF and one loop. Which step was hardest to state precisely? And what would someone who'd never done the routine get wrong from your first draft?

About Introduction to Artificial Intelligence at UPI Study

Introduction to Artificial Intelligence (Computer Science 373) is a self-paced online course of 69 video lessons in 9 chapters, from intelligent agents and search to game strategy, neural networks, logic and reasoning, machine learning, language, robotics and AI ethics. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: AI vs Current Trends in CS and IT

Why take it here

Why students take Introduction to Artificial Intelligence with UPI Study

How machines search, reason and learnIntroduction to Artificial Intelligence covers how AI systems are built: intelligent agents, search and heuristics, game strategy, logic, neural networks, machine learning, language and perception, and the ethics of AI. It is a common upper-level course in computer science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Introduction to Artificial Intelligence carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Writing Pseudocode and Designing Step-by-Step Solutions

What is pseudocode?
Pseudocode is a structured, plain-language description of the steps in a solution, written for people rather than computers. It looks a little like code but follows no particular programming language, so it skips punctuation rules and data types and focuses on logic: what happens, in what order, and under which conditions. For example, IF average is at least 60, THEN DISPLAY Pass states an exact condition anyone can check.
What are the four basic building blocks of an algorithm?
Most designs are built from sequence, selection, iteration, and functions. Sequence runs steps in order, using words like SET, READ, and DISPLAY. Selection picks a path by testing a condition with IF, THEN, and ELSE. Iteration repeats a block with WHILE or FOR EACH. A function packages steps under a name, takes inputs called parameters, and returns a result. Blocks can nest, such as a selection inside a loop.
How do you hand-trace an algorithm with a trace table?
To hand-trace, act as the computer, follow the design one line at a time with a sample input, and record every variable change in a trace table. Averaging the scores 70, 105, 50, and 90 while skipping values outside 0 to 100 gives totals of 70, 120, and 210 over a count of 3, so the average is 70. Tracing edge cases, such as an empty list, can reveal flaws before coding.
What is stepwise refinement in programming?
Stepwise refinement, also called decomposition, means breaking a problem into sub-tasks and then breaking those down again until each step is a simple action or decision. A typical approach states the problem in one sentence with its input and output, splits it into three to five sub-tasks, and refines each one. A sub-task with clear inputs and one result that can be tested alone makes a good function.

About the Introduction to Artificial Intelligence course

How many college credits is Introduction to Artificial Intelligence?
Introduction to Artificial Intelligence (Computer Science 373) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Introduction to Artificial Intelligence cost and what is included?
$250, paid once, with lifetime access: all 69 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Introduction to Artificial Intelligence take?
It is self-paced with no deadlines. The 69 lessons total about 16 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Introduction to Artificial Intelligence.

69 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Introduction to Artificial Intelligence
3 credits · NCCRS
Enroll →