Designing Program Logic Before Writing Any Code, Explained

UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 2.1 Free with a free account

Designing Program Logic Before Writing Any Code

Data Structures and Algorithms · Chapter 2: Planning and Documenting CodeSection 2.1 · lesson 5 of 8714 min · free with a free account

← The Complete Cycle of Writing, Testing, and Fixing Java CodeNext lesson: Documenting Your Code for Clarity and Team Collaboration →

Earn 3 college credits for Data Structures and AlgorithmsRecommended for credit by NCCRS · Computer Science 251 · self-paced · one payment, lifetime access

In this lesson

Plan, write down and test a program's logic before coding.

  • Define a problem by its inputs, outputs, constraints and edge cases
  • Decompose a problem top-down into pieces built from sequence, selection and repetition
  • Write a design as pseudocode or a flowchart and hand-walk it with a trace table
  • Compare alternative approaches against written criteria and record the choice

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 (2,086 words). Read along, or search it.

Opening Question

A Highest Temperature of Zero

Priya is asked for a small program: find the highest temperature in a year of daily readings. It works on her test data. Then a winter station sends readings that are all below zero, and her program reports zero. Zero never appeared in the data. Where did it come from, and how could she have caught it before typing a single line? A mistake on an architect's plan costs an eraser. A mistake in a finished wall costs a demolition crew.

Design Workflow

Every Stage Before Any Code

Programmers use a design workflow, and every stage of it happens before any code is written. First, understand the problem. Then decompose it into pieces. Write the pieces down as pseudocode or a flowchart, and hand-walk the design to test it. Finally, compare it with at least one other approach, and choose. A flaw found while hand-walking sends you back to revise. That's cheap, because nothing is built yet.

Understanding the Problem

Inputs, Outputs and Constraints

Understanding a problem means answering three questions. What goes in? What must come out? What rules or limits apply? Those are the inputs, the outputs, and the constraints. Until all three are answered, any steps are guesses. For Priya, the input is a list of daily readings, each a whole number. The output is one number: the highest reading. The constraints: the list holds zero to three hundred sixty-five readings, values can be negative, and the original list must not change. Look at that middle constraint. It's a warning Priya never wrote down.

Edge Cases

Where Programs Break Most Often

Constraints come in several kinds: limits on size, limits on values, rules about what must not change, and special inputs called edge cases. An edge case sits at the boundary of what the problem allows. An empty list. A list with a single item. Two items that tie. Programs break most often at the edges, so a good problem statement names them.

Precise Requirements

Turning Vague Requests Into Decisions

Vague requests hide all of this. Sort the data, says one. Which way? What about an empty list, or ties? The precise version: given whole numbers, possibly none, produce a new list in ascending order, with equal numbers in their original order. Or, find the best price. Precisely: the seller with the lowest price, the first listed on a tie, and none if there are no offers. Every word in the precise version is a decision the vague one left open.

Sample Cases

Expected Outputs Before Design

Before designing anything, write two or three sample cases: an input, paired with the output you expect. For the highest reading, eighteen, twenty-four, twenty-one, twenty-seven, twenty-two should give twenty-seven. That's a normal, mixed list. Minus five, minus three, minus eight should give minus three. Every value is negative. Twenty, twenty gives twenty: a tie. And an empty list should report, no readings. If you can't predict an output, you don't understand the problem yet. These cases come back later, to test the design.

Decomposition

Top-Down Design of a Shopping Cart

With the problem understood, break it apart. Take a store that must compute the final price of a shopping cart. Decomposition means splitting a problem into smaller problems, and splitting those again, until you know exactly what to do with each piece. Working from the whole down to the details is called top-down design, or stepwise refinement. The cart sounds like one job, but it's four. Add up the prices, work out the discount, add tax, and format the result. Each of those splits into small steps. Adding up means starting the total at zero, then adding each item's price. Three levels, then: the whole problem, the subproblems, and steps that need no further explanation.

Good Pieces

One Job, Clear Inputs, Verb Names

How do you know a piece is a good one? It has one job, describable in a single sentence without the word and. It has clear inputs and outputs: you can say what it receives and what it hands back. It can be tested on its own, without running the rest of the design. And its name starts with a verb, like add tax, or format the result.

Building Blocks

Sequence, Selection and Repetition

Every piece of a design is built from only three shapes of step. Sequence: one action after another. Add up the prices, then apply the discount. Selection: a yes or no test picks the path. If the total passes the threshold, apply the discount. Repetition: repeat until a condition is met. For each item, add its price. Knowing which shape a piece has tells you how to write it down.

Step Order

Coupon Before or After Tax

Subproblems often depend on each other, so their order is part of the design. Take a hundred-dollar cart, a flat ten-dollar coupon, and eight percent tax. Coupon first: a hundred minus ten is ninety, and eight percent tax adds seven dollars twenty, for ninety-seven twenty. Tax first: a hundred plus eight dollars of tax is a hundred and eight, and the coupon brings it to ninety-eight. Same pieces, different order, different answer. Decide the order on paper, not in code.

Pseudocode

Writing the Highest-Reading Design

Now write the pieces down, as pseudocode: a design in structured, plain English. It has no official grammar, but good pseudocode follows a few habits. One action per line, starting with a verb such as set, read, output, or return. If, then, end if, for a choice. For each, end for, or while, for repetition. And indent every line that belongs inside. Name data by meaning, highest, not x, and avoid any one language's symbols. Here's the highest-reading design. Read the readings. The empty list is handled first: output no readings, and stop. Otherwise, set highest to the first reading. Then, for each remaining reading, if it's greater than highest, set highest to it. Finally, output highest. Every step is a plain action you could follow by hand.

Flowchart Symbols

Ovals, Rectangles, Parallelograms and Diamonds

A flowchart draws the same logic as connected shapes, so the path can be followed with a finger. Five symbols are enough. An oval starts or stops the design. A rectangle is a process step. A slanted box, a parallelogram, is input or output. A diamond is a decision, and it always has exactly two exits. Arrows show the flow from one shape to the next.

Flowchart Walkthrough

The Highest Reading as a Flowchart

Here's the same design as a flowchart. Start at the oval, read the readings, and meet the first diamond: is the list empty? Yes leads straight to output, no readings, and stop. No leads on: set highest to the first reading. The next diamond asks, more readings left? If yes, take the next one. Is it greater than highest? If so, update highest. Either way, an arrow returns to the more readings diamond. That return is the loop, once around for each remaining reading. When none remain, leave the loop and output the answer. The first diamond matches pseudocode lines two to five, and the loop, lines seven to eleven.

Choosing a Form

Pseudocode Versus Flowchart

Which form should you use? Pseudocode shows exact wording, nested detail and calculations, and it's easy to edit: change a line. A flowchart shows the branches and the overall path, and people who don't program can follow it. But with many decisions the arrows cross, and moving shapes is slow. Many designs use both. Choose whichever makes the idea clearest to your reader.

Hand-Walking

Desk-Checking With a Trace Table

A design that looks right isn't necessarily right. Hand-walking, also called tracing or desk-checking, means acting as the computer. Pick a sample with a known answer. Draw a trace table, a column for each changing value and each decision. Then execute every line exactly as written. Walk the normal case: eighteen, twenty-four, twenty-one, twenty-seven, twenty-two. Highest starts as eighteen, the first reading. Twenty-four is greater than eighteen, so highest becomes twenty-four. Twenty-one is not. Twenty-seven is, so highest becomes twenty-seven. Twenty-two is not. The output is twenty-seven, and that matches. But a normal case proves little. So one more case is needed.

Finding the Flaw

Why Starting at Zero Fails

Back to Priya. Her design said, set highest to zero. She assumed readings are always positive. Walk it on minus five, minus three, minus eight. The expected output is minus three. Minus three greater than zero? False. Minus eight? False. Highest never moves, and zero is what comes out. The correct design starts at the first reading, minus five. Minus three is greater, minus eight is not, and the output matches. That's Priya's zero. Two minutes with the all-negative sample would have found it, before any code existed.

Missing Guard

Walking the Empty List

Hand-walking also exposes a missing guard. Remove lines two to five, and walk the empty list. Line six asks for the first reading of a list that has none. There's no valid next step. On paper, that costs two minutes. In finished code, it costs a debugging session. And walk it as a computer would. If you catch yourself correcting the design in your head, that's the flaw.

Quick Check

Shortest Wait on an Empty List

Quick check. A design finds the shortest wait in a list of wait times, in minutes. It says: set shortest to one thousand. For each wait, if it's smaller than shortest, set shortest to it. Then output shortest. Hand-walk it on an empty list. What does it output? Pause, and decide. It outputs one thousand. With no waits, the loop body never runs, so shortest keeps its starting value: a number never in the data. It isn't stuck, because this design never asks for a first item. And zero is wrong: nothing sets shortest to zero. A guard at the top, if the list is empty, output no waits, fixes it.

Comparing Designs

A Routine for Choosing an Approach

Most problems have more than one workable design. Committing to the first idea is a gamble. A reliable routine: list the constraints that decide the choice. Sketch at least two approaches. Hand-walk each on the same samples, edge cases included. Compare them against stated criteria. Then choose one, and write down why.

Three Approaches

Finding a Repeated Product Code

Here's a problem: does a list of product codes contain a repeat? Three designs will work. A: compare every pair. Check each code against every code after it. B: sort a copy. In sorted order, repeats sit side by side, so compare each code with its neighbor. C: remember what was seen. Keep a growing collection of the codes met so far, and check each new code against it.

Criteria

Ease, Storage and Number of Checks

Criteria make the comparison fair. All three leave the original list unchanged: B works on a copy. Ease: A is very easy to get right. C is easy. B is moderate, because it needs a sorting step. Extra storage: A needs none. B needs a second list, and C a collection as large as the list. Checks, for a thousand codes: A makes up to 499,500 pair checks. B makes about 999 neighbor checks, after the sort. C makes about a thousand look-ups. These are informal tallies, for intuition. Precise tools for efficiency come later in the course.

Growth

How Pair Checks Outgrow the List

Grow the list from a hundred codes to a thousand. A single pass goes from a hundred checks to a thousand: ten times as many. But the pair checks go from 4,950 to 499,500, about a hundred times as many. No approach wins every row. A is simplest, but its work grows much faster than the list. C is quick, but needs room for every code. The right choice depends on the constraints you wrote down at the start.

Decision Record

Writing Down Why C Was Chosen

For up to fifty thousand codes, with memory to spare, a team writes a decision record. Chosen: C. Rejected: A, because pair checks grow too fast, and B, because sorting adds complexity for no clear gain. And: revisit if memory runs short. The record keeps the reasoning, not just the result.

Quick Check

Repeat Check With Almost No Memory

Quick check, with new constraints. A fitness band must check whether its last ten step counts contain a repeat, and it has almost no spare memory. Which approach fits best: every pair, a sorted copy, or remembering what was seen? Pause, and decide. Every pair. It needs no extra storage, and with only ten counts, its forty-five pair checks are nothing. The tempting choices both need room. A sorted copy is a second list, and remembering what was seen needs a collection as big as the list. The constraints, not habit, made the choice.

Key Takeaways

Understand, Decompose, Walk and Compare

To summarize. A problem is defined by its inputs, outputs and constraints, and edge cases belong in the constraints. Write sample cases first, then decompose until every piece does one job. Write the design as pseudocode or a flowchart, and hand-walk it literally, edge cases included. And compare at least two approaches against written criteria, then record why you chose.

Think About It

A Task Started Without a Plan

Something to think about. Recall a task you started without a plan: a spreadsheet, a piece of furniture, a route across town. Where did you have to backtrack? Which design step would have prevented it, and what would that step have cost you, done first?

About Data Structures and Algorithms at UPI Study

Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. 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: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms

Why take it here

Why students take Data Structures and Algorithms with UPI Study

How programs store and search dataData Structures and Algorithms teaches how to organize data and measure how fast code runs: arrays, linked lists, stacks, queues, trees, heaps, hash tables, sorting and graphs, all written in Java. It is a core course in computer science and software 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

Data Structures and Algorithms 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 Designing Program Logic Before Writing Any Code

What is pseudocode in programming?
Pseudocode is a program design written in structured, plain English instead of a real programming language. It has no official grammar, but good pseudocode puts one action per line starting with a verb such as set, read, output or return. It uses if and end if for choices, for each or while for repetition, indents nested lines, and names data by meaning, such as highest instead of x.
What do the basic flowchart symbols mean?
Five symbols cover most flowcharts. An oval marks start or stop, a rectangle is a process step, and a parallelogram is input or output. A diamond is a decision with exactly two exits, such as yes and no. Arrows connect the shapes and show the flow, and an arrow that returns to an earlier decision diamond forms a loop that repeats once per item.
What is desk-checking an algorithm?
Desk-checking, also called hand-walking or tracing, means acting as the computer and executing a design exactly as written, on paper. Pick a sample with a known answer and draw a trace table with a column for each changing value and decision. A maximum-finding design that starts highest at 0 outputs 0 for -5, -3, -8 instead of -3, exposing the flaw before any code exists.
Why do edge cases matter when designing an algorithm?
Edge cases sit at the boundary of what a problem allows, and programs break most often there. Typical examples are an empty list, a list with a single item, and two items that tie. Naming them in the constraints and writing sample cases for them lets a hand-walk catch flaws early, such as a design that asks for the first reading of an empty list.

About the Data Structures and Algorithms course

How many college credits is Data Structures and Algorithms?
Data Structures and Algorithms (Computer Science 251) 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 Data Structures and Algorithms cost and what is included?
$250, paid once, with lifetime access: all 87 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 Data Structures and Algorithms take?
It is self-paced with no deadlines. The 87 lessons total about 15 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 Data Structures and Algorithms.

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

Data Structures and Algorithms
3 credits · NCCRS
Enroll →