Quiz 2

Week 2: Pseudocode Basics

2368 words
12 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Week 2: Pseudocode Basics > **BSCS1001 — IIT Madras BS Degree** **Prerequisite:** Week 1 (Flowcharts, Iteration) **Cross-links:** BSCS1002-Python (Week 2 — Control Flow), BSCS2002-PDSA (Week 1 — Algorithms) ## 1. Motivation: From Pictures to Text In Week 1, we used **flowcharts** to visualize algorithms.

Week 2: Pseudocode Basics

BSCS1001 — IIT Madras BS Degree Prerequisite: Week 1 (Flowcharts, Iteration) Cross-links: BSCS1002-Python (Week 2 — Control Flow), BSCS2002-PDSA (Week 1 — Algorithms)

1. Motivation: From Pictures to Text

In Week 1, we used flowcharts to visualize algorithms. Flowcharts are great for understanding, but they have problems:
Problem with FlowchartsSolution
Large algorithms need huge diagramsText is compact
Hard to share (images)Text can be copied, emailed, version-controlled
Difficult to editText can be searched and replaced
No standard detail levelPseudocode has conventions
Pseudocode is the middle ground: it looks like a programming language but is meant for humans to read. It's the language of this course.
💡 Key Insight: Think of pseudocode as "programming in English" — precise enough for a computer, but readable by a human.

The Evolution

(Diagram) In this course, we stop at pseudocode. In BSCS1002 (Python), you'll learn to convert pseudocode to actual Python code.

2. What is Pseudocode?

Pseudocode is a compact, textual notation for describing algorithms. It uses:
  • Standard phrases like while, if, else
  • Mathematical notation for operations
  • Indentation (or braces {}) to show blocks
  • Dot notation (.) for record field access

Example: Counting Cards

Flowchart version (Week 1): (Diagram) Pseudocode version:
sql
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Count = Count + 1
}
Notice: The pseudocode is shorter, more precise, and easier to modify than the flowchart. But both describe the same algorithm.

Pseudocode Conventions in This Course

ConventionMeaningExample
=Assignment (not equality!)Sum = 0
==Equality checkif (X.Gender == "M")
{ }Block of statementswhile (condition) { ... }
.Field access on a recordX.Maths, X.Name
// or nothingComments// This is a comment

3. Core Pseudocode Constructs

Pseudocode has just a few building blocks. Once you learn these, you can write any algorithm. (Diagram)
ConstructPurposeExample
AssignmentStore or update a valueSum = Sum + X.Maths
SequenceSteps execute in orderPick X then Move X then Update
ConditionalMake a decisionif (X.Gender == "M")
IterationRepeat a blockwhile (Pile 1 has more cards)

4. Assignment Statement

The assignment statement is the most basic operation. It stores a value in a variable.

Syntax

pseudo
VariableName = Expression

How It Works

  1. Evaluate the expression on the right side using current variable values
  2. Store the result in the variable on the left side

Examples

StatementWhat Happens
Count = 0Store the value 0 in Count
Sum = Sum + 85Take current Sum, add 85, store back in Sum
Max = X.MathsCopy the Maths field of card X into Max
Found = TrueStore the Boolean value True in Found

Tracing Assignment

Suppose Sum = 50 initially.
StatementRight Side EvaluationNew Value of Sum
Sum = Sum + 1050 + 10 = 6060
Sum = Sum + 560 + 5 = 6565
Sum = Sum / 265 / 2 = 32.532.5
⚠️ Important: The = sign is not mathematical equality. Sum = Sum + 1 does NOT mean "Sum equals Sum plus 1" (which is impossible in math). It means "increase Sum by 1."

5. Conditional Execution

Conditional execution lets the algorithm make decisions.

If Statement

pseudo
if (condition) {
    Statement 1
    Statement 2
    ...
}
The block inside { } executes only if the condition is True.

If-Else Statement

pseudo
if (condition) {
    Statements for True case
}
else {
    Statements for False case
}

Flowchart of If-Else

(Diagram)

Worked Example: Separate Boy/Girl Sums

sql
BoySum = 0
GirlSum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == "M") {
        BoySum = BoySum + X.Maths
    }
    else {
        GirlSum = GirlSum + X.Maths
    }
}
Tracing with dataset:
CardNameGenderMathsConditionActionBoySumGirlSum
Initial00
1AliceF85F == M? ❌Else: GirlSum += 85085
2BobM72M == M? ✅If: BoySum += 727285
3CharlieM91M == M? ✅If: BoySum += 9116385
4DianaF68F == M? ❌Else: GirlSum += 68163153
Result: BoySum = 163, GirlSum = 153

Nested Conditionals

Conditions can be nested inside other conditions:
pseudo
if (X.Gender == "M") {
    if (X.Maths > 80) {
        Count = Count + 1
    }
}
This counts only boys who scored above 80 in Maths.

6. Iteration with while

The while loop is the primary iteration construct in our pseudocode.

Syntax

pseudo
while (condition) {
    // Block of statements to repeat
}

How It Works

  1. Check the condition
  2. If True → execute the block, then go back to step 1
  3. If False → exit the loop and continue after }

Flowchart of While Loop

(Diagram)

The Standard Dataset Iteration Pattern

Almost every algorithm in Weeks 1-4 follows this pattern:
sql
Initialize variables
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    // Update variables based on X
}

Why "Pile 1 has more cards"?

This is the course's standard way of saying "there are still unprocessed items." It's a condition that:
  • Starts as True (if the dataset is non-empty)
  • Becomes False after the last card is moved
  • Guarantees every card is processed exactly once

7. Equality vs Assignment

This is the most common source of confusion for beginners. Let's be very clear:
SymbolNameMeaningExample
=AssignmentStore right value in left variableSum = 0
==EqualityCompare two values, return Booleanif (X.Gender == "M")

How to Read Them Aloud

WrittenRead As
Count = 0"Count becomes 0" or "Set Count to 0"
Count == 0"Count equals 0?" or "Is Count equal to 0?"

Why Two Different Symbols?

Consider this common mistake:
pseudo
// WRONG - this is assignment, not comparison!
if (X.Gender = "M") {
This would set X.Gender to "M" instead of checking if it is "M" — completely changing the data! The course wisely uses == for comparison to avoid this catastrophe.

Memory Aid

Think of = asThink of == as
An arrow ←A question mark ?
"Goes to""Is equal to?"
A commandA test
Changes the worldAsks a question

8. Complete Pseudocode Examples

Example 1: Sum of All Maths Marks

sql
Sum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Sum = Sum + X.Maths
}
Dataset: [Alice: 85, Bob: 72, Charlie: 91, Diana: 68]
IterationCardX.MathsSum BeforeSum After
1Alice85085
2Bob7285157
3Charlie91157248
4Diana68248316
Final Sum: 316

Example 2: Finding Maximum with Card ID

sql
MaxM = 0
MaxCard = -1
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths > MaxM) {
        MaxM = X.Maths
        MaxCard = X.Id
    }
}
Dataset: [ID1:45, ID2:78, ID3:62, ID4:91, ID5:53]
IterX.IdX.MathsMaxM BeforeConditionMaxM AfterMaxCard
1145045>0 ✅451
22784578>45 ✅782
33627862>78 ❌782
44917891>78 ✅914
55539153>91 ❌914
Result: Max Maths = 91, achieved by Student ID = 4.

Example 3: Below Average Students

This uses TWO iterations in sequence (non-nested):
sql
// First pass: calculate average
Sum = 0
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Sum = Sum + X.Maths
    Count = Count + 1
}
Average = Sum / Count
// Second pass: find below-average students
BelowCount = 0
while (Pile 2 has more cards) {   // Note: cards are now in Pile 2!
    Pick a card X from Pile 2
    Move X to Pile 1              // Moving back to Pile 1
    if (X.Maths < Average) {
        BelowCount = BelowCount + 1
    }
}
StepWhat's HappeningVariables
Pass 1Sum all marks, count studentsSum = 316, Count = 4
After Pass 1Calculate averageAverage = 316/4 = 79
Pass 2Count marks < 79BelowCount = 2 (Bob:72, Diana:68)

9. Flowchart to Pseudocode Translation

Translation Guide

Flowchart ElementPseudocode Equivalent
Oval (Start/End)Implicit (start at top, end at bottom)
Rectangle (Process)Assignment statement
Diamond (Decision)if (condition) { ... }
Loop back arrowwhile (condition) { ... }
Arrow pathsSequence (top to bottom)

Worked Translation

Flowchart: (Diagram) Pseudocode:
sql
Sum = 0
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Sum = Sum + X.Maths
    Count = Count + 1
}
Average = Sum / Count
💡 Tip: The loop back arrow in the flowchart maps directly to the while keyword. Everything inside the loop body is what's inside the rectangle and diamond shapes in the loop path.

10. Practice Questions

Basic Questions

Q1. What is the value of x after this pseudocode executes?
pseudo
x = 10
x = x + 5
x = x * 2
Show Answer
StepStatementx
1x = 1010
2x = 10 + 5 = 1515
3x = 15 × 2 = 3030
Q2. What is the difference between = and == in pseudocode?
Show Answer
= is assignment (store a value). == is equality comparison (check if two values are the same, returns True/False). Q3. Trace this pseudocode for input values [4, 8, 2, 6]:
sql
Sum = 0
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X > 5) {
        Sum = Sum + X
    }
    Count = Count + 1
}
Show Answer
IterXX > 5?SumCount
Start00
14❌ No01
28✅ Yes82
32❌ No83
46✅ Yes144
Final: Sum = 14, Count = 4 Q4. Write pseudocode to find the minimum value in a dataset. Show Answer
sql
Min = INFINITY   // Very large number
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X < Min) {
        Min = X
    }
}
Alternatively, initialize Min to the first card's value.

Intermediate Questions

Q5. Convert this flowchart to pseudocode: (Diagram)
Show Answer
sql
Total = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == "F" AND X.Maths > 70) {
        Total = Total + X.Maths
    }
}
Q6. What happens if you forget to move the card from Pile 1 to Pile 2?
Show Answer
If you don't move the card, the same card will be picked again in the next iteration! The condition Pile 1 has more cards will remain True forever, creating an infinite loop — the algorithm never ends.
This is why Move X to Pile 2 is a critical step in every iteration. Q7. Write pseudocode that counts the number of students who scored between 60 and 80 (inclusive) in Maths. Show Answer
sql
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths >= 60 AND X.Maths <= 80) {
        Count = Count + 1
    }
}
Q8. What is wrong with this pseudocode?
sql
Sum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Sum = Sum + X.Maths
}
Show Answer
The card X is never moved to Pile 2. The same card will be picked repeatedly, creating an infinite loop. The fix is to add Move X to Pile 2 after picking the card.

Advanced Questions

Q9. Write pseudocode to find both the maximum and minimum values in a single pass through the data.
Show Answer
sql
Max = -INFINITY
Min = INFINITY
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X > Max) {
        Max = X
    }
    if (X < Min) {
        Min = X
    }
}
This requires only one pass (one iteration) to find both. Q10. Trace the execution: What does this pseudocode output for dataset [2, 5, 1, 8, 3]?
sql
Result = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X > Result) {
        Result = X
    }
    else {
        Result = Result - X
    }
}
Show Answer
IterXConditionActionResult
Start0
122 > 0 ✅Result = 22
255 > 2 ✅Result = 55
311 > 5 ❌Result = 5 - 1 = 44
488 > 4 ✅Result = 88
533 > 8 ❌Result = 8 - 3 = 55
Final Result = 5 Q11. What is the "standard dataset iteration pattern"? Why is every piece necessary? Show Answer
The standard pattern is:
sql
Initialize variables
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    // Process X
}
Each piece is necessary:
  • Initialize: Without this, variables start with garbage values
  • Check condition: Ensures we stop when done
  • Pick a card: Gets the next item
  • Move to Pile 2: Ensures progress (prevents infinite loop)
  • Process: Does the actual work Q12. Compare and contrast: flowchart vs pseudocode. When would you use each? Show Answer
AspectFlowchartPseudocode
FormatVisual (diagram)Textual
Ease of understandingExcellent for beginnersGood
CompactnessBulky for large algorithmsCompact
Share/editDifficult (images)Easy (text)
Version controlNot practicalYes (git)
Best forTeaching, small algorithmsComplex algorithms, documentation
Use flowcharts when explaining to beginners or debugging logic visually. Use pseudocode when writing real algorithms, collaborating, or preparing to code.

📚 Cross-References

CourseTopicConnection
BSCS1002 (Python)Week 2 — If/ElsePython if, else
BSCS1002 (Python)Week 2 — While loopsPython while
BSCS2002 (PDSA)Week 1 — Algorithm representationAlgorithm notation

Quiz Tip: Quiz 1 heavily tests your ability to trace pseudocode. Practice with the tracing tables! Join Discord PreviousData Types & RepresentationNextIteration & Filtering
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.