Sketching the Logic First, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 1.4 Free with a free account

Sketching the Logic First

C++ Programming · Chapter 1: Foundations of ProgrammingSection 1.4 · lesson 4 of 84video coming soon

← Logical Thinking and Code StructureNext lesson: Sequential Problem-Solving →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

How pseudocode prevents wasted effort.

  • Explain why designing first saves work
  • Write pseudocode with consistent conventions
  • Turn a requirement into ordered steps
  • Desk-check a design with a trace table

Transcript

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

Opening Scenario

Two Programmers, One Billing Assignment

Two people get the same assignment: print a customer's final bill, after a member discount and sales tax. The first opens an editor, and starts typing. Forty lines later, the program runs, and the answers are wrong by a few cents. The cause is an ordering mistake: tax was worked out on the original amount, and the discount subtracted afterward. Fixing it means renaming values, moving lines, relabeling output, and retesting everything.

Contrast

Four Minutes of Sketching Saves the Day

The second person spends four minutes writing a few lines of structured steps, in plain language. Reading them back, the ordering problem is obvious before anything is typed: tax is worked out on the price, before the discount comes off. So one line moves, with a pen stroke. Nothing separates these two people, except the order in which they worked.

Core Argument

A Mistake Costs What Rests on It

The mistake was identical. What differed was how much finished work depended on it, when it was found. That's the whole argument for designing first: a mistake costs whatever has been built on top of it. In a sketch, a wrong step is connected to nothing. It can be crossed out in seconds. Once it's typed as code, it has attachments: the names of stored values, nearby lines, printed messages, test data. Each has to be found and adjusted. And after a program is handed over, a wrong step may have produced results that were written down, or acted on. Those must be corrected too.

Hidden Benefit

Why Disposable Design Work Is Valuable

There's a quieter benefit, too. Design work is cheap, partly because it's disposable. Deleting six lines of pseudocode costs nothing. Deleting sixty lines of code that took an hour to get working is painful. And people who feel that pain tend to defend a poor structure, instead of replacing it.

Definition

What Pseudocode Is and Is Not

Pseudocode describes the steps a solution must carry out, in structured human language, with a small, fixed vocabulary. It states exactly what's read, calculated, stored and displayed, and in what order. And it leaves out everything specific to one language: declarations, punctuation, library names. So it's ordered, precise about data, written with agreed keywords, and cheap to change. It's not executable, not tied to one language, and not vague prose.

Comparison

Pseudocode Exposes What Prose Conceals

Here's the difference from prose: work out the average of the student's three marks, and tell them what it is. Every English speaker understands that, yet it hides three decisions. Where do the marks come from? Divide by what, exactly? And what's displayed: the number alone, or a sentence? Pseudocode forces each of those decisions into the open, which is exactly why it exposes problems that prose conceals.

Conventions

Keywords Used in This Course

There's no worldwide standard for pseudocode, so each course adopts conventions. These are the ones used here, and expected in your work. BEGIN and END mark where the steps start and finish. INPUT reads a value from outside, and stores it under a name. OUTPUT displays a value, or a message. SET, with the arrow, works out the expression on the right, and stores the result under the name on the left. CONSTANT names a value fixed in advance. Arithmetic works as usual, with parentheses forcing the order. And two slashes start a note for human readers: nothing happens because of it.

Style Rules

Five Rules for Writing Pseudocode

Five rules go with them. Keywords in capitals, and data names in lower case. One action per line. Indent everything inside BEGIN and END. Name data for what it holds: hourly rate tells a reader something, x doesn't. And never borrow syntax from a real language, or the design stops being language-neutral.

Key Symbol

The Arrow Is an Action, Not Equality

The arrow is the single most important symbol in pseudocode, and the most often misread. It doesn't mean, is equal to. It describes an action with a direction: work out everything on the right, then place the result into the name on the left, replacing what was there. That settles a line that otherwise looks impossible: set count, arrow, count plus one. As an equation, it says a number equals itself plus one, which is nonsense. As an instruction, it's ordinary. If count holds five, add one to get six, and store six back in count. Students who write an equals sign here keep reading it as an equation, and stay confused for weeks. Students who write the arrow rarely have the problem.

Concept

Linear Tasks and Three Zones

A linear task, also called a sequence, is one where every step runs exactly once, in the order written. Nothing repeats, and nothing is skipped. Almost every linear task falls into three zones: collect the values, calculate the results, and report them. Recognizing those zones turns a blank page into three smaller questions. They're a planning aid, not a law. But one thing is a law, and it follows from the arrow: nothing may be used before it exists. A value must be read or calculated on an earlier line than the one that uses it.

Worked Example

Averaging Three Student Marks

Here's a first worked example: read three marks for one student, work out the average, and display it. The design reads mark one, mark two and mark three, sets total to their sum, sets average to total divided by three, and outputs a message and the average. Three things are worth noticing. First, all three INPUT steps sit above the SET that uses them, which satisfies the sequencing rule. Second, the design invents a name, total, that the requirement never mentions. A one-line version wouldn't be wrong, but naming the intermediate result means that if the answer comes out wrong, you can check the sum and the division separately. Third, it divides by the literal three, not a counted quantity. That's fine only because the requirement fixes the number of marks at three.

Quick Check

Find the Line Used Too Early

Quick check. Here's a classmate's design for the same task. It reads well, and it's broken. Which line uses a value before it exists? Pause, and find it. Line seven. It outputs average one line before the SET that produces it, so there's nothing to display yet. Move the OUTPUT below the SET, and the design is correct.

Method

Five Steps from Requirement to Design

Requirements arrive as sentences, written by people thinking about the problem, not about programming. Converting one isn't guesswork: it follows the same five steps every time. Name the output. Name the inputs. Name the processing. Put the steps in order, by their dependencies. And only then, write it in the conventions. Naming the output first matters: it stops you collecting data you never needed, because everything else exists only to produce the outputs.

Reading Clues

Requirement Wording That Signals Keywords

Steps one to three are mostly a reading exercise, because requirements signal what they want with recognizable wording. Read, ask the user for, or accept, usually becomes an INPUT. Display, print, report or show becomes an OUTPUT. Calculate, work out, or total becomes a SET. Words like always, fixed, standard, or the rate is 8 percent, signal a CONSTANT, never an INPUT. Of and per, as in 8 percent of the subtotal, or rate per hour, mean multiplication or division. And then, after that, and finally are ordering information: they fix the position of lines, not their content.

Extended Example

Designing the Painting Service Invoice

Here's a fuller example. A painting service charges by the hour. The program reads the customer's name, the hours worked, and the hourly rate. A fixed call-out fee of 25 dollars is added to the labor charge, and then 8 percent sales tax is applied to that combined amount. Step one, name the output: the customer's name, the amount before tax, which this design calls subtotal, the tax, and the amount due. Step two, name the inputs: the name, the hours, and the hourly rate. The fee and the tax rate aren't inputs. The requirement fixes them, so asking the user would let a typing error change the price. They're constants. The test is simple: would a reasonable user be surprised to be asked for this value? If so, it's a constant. Step three, the processing: the labor charge, the subtotal, the tax, and the amount due. And step four: the order is forced backward from the total. Read, then labor, subtotal, tax, the amount due, and then display.

Desk Check

Verifying the Design with a Trace Table

A design that looks reasonable can still be wrong. So the last step before typing is a desk check. You play the computer, step through the lines with chosen values, and record what each name holds. That record is a trace table. Choose values you can verify by hand: 6 hours, at 20 dollars an hour. The labor charge is 120. Adding the 25-dollar fee gives 145 before tax. Tax at 8 percent is 11.60, and the amount due is 156.60. The last row matches the hand-worked answer, so the design may be typed.

Edge Case

Testing the Design with Zero Hours

One trace only proves one set of values. A second trace, with an awkward value, is worth the extra minute. Try zero hours. The amount due should still be the fee, plus tax on the fee: 27 dollars. If the design produces zero, the fee never made it into the calculation: a mistake worth finding now, not after a customer is undercharged.

Common Mistakes

Frequent Pseudocode Errors and Their Fixes

A handful of errors show up again and again. An OUTPUT of total above the SET that produces it displays nothing: move the OUTPUT below. Asking for a tax rate the requirement fixes lets the user control it: make it a constant. A single line reading, calculate the bill, restates the problem instead of solving it: break it into arithmetic steps. Writing an equals sign instead of the arrow invites the wrong reading. And borrowed code, like a type declaration or an output command, ties the plan to one language before it's been checked. Finally, reusing one name for two unrelated values means the second SET silently destroys the first. Give each purpose its own name.

Key Takeaways

Summary of Design-First Principles

To summarize. A mistake costs whatever has been built on top of it, which is why the same fault is trivial during design, and expensive after release. Pseudocode is precise about operations and order, and silent about syntax. That's what makes it fast to write and cheap to change. Convert a requirement by naming the output, the inputs and the processing, ordering by dependency, and then writing it down. Values the requirement fixes are constants. And desk-check every design with a trace table, including an awkward value like zero.

Think About It

Hourly Rate Versus Tax Rate

Here's something to think about. The painting invoice asks the user for the hourly rate, but not the tax rate. Both are numbers that could change from one job to the next. So what, exactly, makes one of them an input, and the other a constant?

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. 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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most 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

C++ Programming 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 Sketching the Logic First

Why does designing a program before coding save work?
Designing first saves work because a mistake costs whatever has been built on top of it. A wrong step in a sketch is connected to nothing, so crossing it out takes seconds. Once typed as code, it is tied to variable names, nearby lines, printed messages, and test data, and each of those must be found and fixed.
What does the arrow mean in pseudocode, such as SET count ← count + 1?
The arrow is an action, not an equals sign. It means work out everything on the right, then store the result in the name on the left, replacing the old value. So if count holds 5, SET count ← count + 1 computes 6 and stores 6 back in count. Read as an equation, the line would make no sense.
How do I turn a written requirement into pseudocode steps?
Follow five steps: name the output, name the inputs, name the processing, order the steps by their dependencies, and then write them using your pseudocode conventions. Wording helps: "read" suggests INPUT, "display" suggests OUTPUT, "calculate" suggests SET, and a fixed value such as "8 percent tax" suggests a CONSTANT. Every value must exist before a later line uses it.
How do I desk-check pseudocode with a trace table?
Desk-checking means playing the computer: pick test values you can verify by hand, step through each line, and record what every name holds in a trace table. For 6 hours at 20 dollars an hour, a 25-dollar fee, and 8 percent tax, the amount due should be 156.60. Then try an awkward value, such as zero hours, which should give 27.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) 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 C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 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 C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 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 C++ Programming.

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

C++ Programming
3 credits · NCCRS
Enroll →