Module 1 · CLO1

Introduction to Problem Solving

Before we write a single line of Java, we need a method for turning a fuzzy real-world problem into a working, tested program — and a way to describe the steps as an algorithm. This module walks you through that journey with diagrams, real Java code, and interactive demos.

Learning Objectives

  1. Explain the concept of the computer program development method. (CLO1)
  2. Apply the software development method steps to define business problems.
  3. Describe the key steps in algorithm development.
How to use this page. Read top-to-bottom for first pass, then jump back via the top navigation. Every code block is real Java you can paste into any IDE. Try the visualizer and quiz at the end.

1 · The Software Development Method

A program development method is a repeatable, disciplined procedure that takes you from a real-world need to a working, maintainable program. Writing code is only one step — and usually not the first one. The most common model is a five-stage cycle:

① Analyze the Problem

Understand inputs, outputs, constraints, and the success criteria. No code yet.

② Design the Solution

Plan algorithms, data structures, classes, and modules.

③ Code the Program

Translate the design into Java — the language is the easy part if design is good.

④ Test & Debug

Verify against the success criteria. Fix defects. Re-test.

⑤ Maintain & Document

Deploy, fix issues found in production, evolve features.

🔁 Iterate

Most projects loop back: testing reveals design gaps; new requirements restart analysis.

Why a method? Without one, you jump to coding and produce fragile, hard-to-change code. With one, you spend 30% of your time thinking and 70% building — and you ship faster.

The cycle, visually

       ┌──────────────────┐
       │ 1. Analyze       │
       └────────┬─────────┘
                ▼
       ┌──────────────────┐
       │ 2. Design        │◀──┐
       └────────┬─────────┘   │
                ▼             │
       ┌──────────────────┐   │
       │ 3. Code          │   │
       └────────┬─────────┘   │
                ▼             │
       ┌──────────────────┐   │
       │ 4. Test & Debug  │───┘  (loop back when tests fail)
       └────────┬─────────┘
                ▼
       ┌──────────────────┐
       │ 5. Maintain      │
       └──────────────────┘
      

2 · Applying the Software Development Method

Let's run the method on a real business problem. Suppose a café owner says: "I want to know how much each customer's order costs, including a 6% service tax, and I want a grand total at the end of the day."

  1. Analyze. Inputs: list of items (name + price). Process: sum prices, add 6% tax per order. Output: order subtotal, tax, total, and a daily grand total. Constraints: handle empty input gracefully.
  2. Design. We need a loop reading items, accumulators for subtotal/tax/grand-total, and formatted output. Decide on double for money (we'll discuss BigDecimal later) and Scanner for input.
  3. Code. Translate the design into Java. See the snippet below.
  4. Test & Debug. Try: 0 items, 1 item, 100 items, items with decimals, sentinel value to stop.
  5. Maintain. Later: support discounts, multiple tax rates, file I/O.

The Java code for this problem

import java.util.Scanner;

public class CafeBilling {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        final double TAX_RATE = 0.06;
        double dailyTotal = 0.0;

        System.out.print("Number of orders today: ");
        int n = sc.nextInt();

        for (int i = 1; i <= n; i++) {
            double subtotal = 0.0;
            System.out.println("\nOrder #" + i + " — enter prices (0 to finish):");
            while (true) {
                double price = sc.nextDouble();
                if (price == 0) break;
                if (price < 0) {
                    System.out.println("Price cannot be negative, ignored.");
                    continue;
                }
                subtotal += price;
            }
            double tax      = subtotal * TAX_RATE;
            double total    = subtotal + tax;
            dailyTotal          += total;

            System.out.printf("Subtotal: %.2f  Tax: %.2f  Total: %.2f%n",
                              subtotal, tax, total);
        }
        System.out.printf("%nDaily Grand Total: %.2f%n", dailyTotal);
        sc.close();
    }
}
Money precision: double is fine for learning, but production systems use BigDecimal to avoid floating-point rounding errors.

3 · Introduction to Algorithms

An algorithm is a finite, well-defined sequence of steps that solves a class of problems or computes a result. Three properties matter:

  • Definite — every step is unambiguous.
  • Finite — it must eventually stop.
  • Effective — each step can actually be carried out.

Algorithm vs. Program

Algorithm

Language-independent logic. Can be written in pseudocode, drawn as a flowchart, or expressed as math.

Algorithm: FindMax(numbers)
  max ← numbers[0]
  for each n in numbers
    if n > max then max ← n
  return max
          

Program

Algorithm encoded in a programming language, plus syntax, I/O, error handling.

static int findMax(int[] a) {
    int max = a[0];
    for (int n : a)
        if (n > max) max = n;
    return max;
}
          

Two ways to describe an algorithm

            ┌───────────────┐
            │     Start     │
            └──────┬────────┘
                   ▼
            ┌───────────────┐
            │  max ← a[0]   │
            └──────┬────────┘
                   ▼
            ┌───────────────┐     ┌──────┐
            │  more items?  │─No─▶│ Print│
            └──────┬────────┘     │ max  │
                   │Yes           └──┬───┘
                   ▼                 ▲
            ┌───────────────┐        │
            │  n > max ?    │──Yes──▶┤
            └──────┬────────┘        │
                   │ No              │
                   ▼                 │
            ┌───────────────┐        │
            │  next item    │────────┘
            └───────────────┘
        
# Pseudocode: Linear Search
function linearSearch(list, target):
    for i from 0 to length(list)-1:
        if list[i] == target:
            return i
    return -1

4 · Steps in Algorithm Development

Algorithms are not just written — they are developed. A reliable flow looks like this:

  1. Understand the problem. Restate it in your own words. What is given? What is the result? Any edge cases?
  2. Identify inputs and outputs. Name them, give them types, decide on units.
  3. Work through examples by hand. Trace small cases. This often reveals the algorithm itself.
  4. Choose an approach. Brute force? Divide & conquer? Greedy? Iteration vs. recursion?
  5. Write the algorithm. Use pseudocode or a flowchart first — not Java.
  6. Test the algorithm on paper. Walk through it step-by-step with multiple inputs, including edge cases.
  7. Translate to code. Only now — with a clean plan in hand — implement it in Java.
  8. Refine for clarity & efficiency. Reduce duplication, improve variable names, then look at Big-O complexity.

Example: Average of N numbers — full walkthrough

  1. Problem: compute the average of N numbers entered by the user.
  2. Inputs: an integer N, then N double values. Output: the arithmetic mean.
  3. By hand: inputs 3, [10, 20, 30] → (10+20+30)/3 = 20.
  4. Approach: iterate once, accumulate a sum, divide by N at the end. Avoid re-reading or re-looping.
  5. Pseudocode:
    sum ← 0
    for i from 1 to N:
        read x
        sum ← sum + x
    average ← sum / N
    print average
    
  6. Translate to Java:
    import java.util.Scanner;
    
    public class Average {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("How many numbers? ");
            int n = sc.nextInt();
            if (n <= 0) {
                System.out.println("Count must be positive.");
                return;
            }
            double sum = 0;
            for (int i = 0; i < n; i++) sum += sc.nextDouble();
            System.out.printf("Average = %.2f%n", sum / n);
            sc.close();
        }
    }
    
  7. Refine: rename variables, handle n <= 0, consider BigDecimal if needed.

5 · Live Code Examples

Three classic starter problems solved with the method above. Click any tab.

import java.util.Scanner;
public class LargestOfThree {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter three integers: ");
        int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
        int max = a;
        if (b > max) max = b;
        if (c > max) max = c;
        System.out.println("Largest = " + max);
    }
}
import java.util.Scanner;
public class EvenOdd {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = sc.nextInt();
        System.out.println(n + " is " + (n % 2 == 0 ? "Even" : "Odd"));
    }
}
import java.util.Scanner;
public class Sum1ToN {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter N: ");
        long n = sc.nextLong();
        if (n < 0) { System.out.println("N must be ≥ 0"); return; }
        long sum = n * (n + 1) / 2;   // O(1) Gauss
        System.out.println("Sum 1.." + n + " = " + sum);
    }
}
Notice the constant-time formula vs. an O(n) loop — that's the difference an algorithm choice makes.

6 · Algorithm Visualizer — Bubble Sort

Watch an algorithm run step by step. Yellow = comparing, red = swapping, green = sorted.

Default Comparing Swapping Sorted

7 · Worked Problems

Try the SDM on each one before peeking at the solution.

Problem 1 — Grade Classifier

Task: Given a score 0–100, print A (≥90), B (80–89), C (70–79), D (60–69), F (<60).

💡 Hint

Use if / else if / else in descending order. Validate the range first.

✅ Show solution
if (score < 0 || score > 100) System.out.println("Invalid");
else if (score >= 90) System.out.println("A");
else if (score >= 80) System.out.println("B");
else if (score >= 70) System.out.println("C");
else if (score >= 60) System.out.println("D");
else                      System.out.println("F");

Problem 2 — Sum of Digits

Task: Given an integer, return the sum of its digits (e.g. 1729 → 1+7+2+9 = 19).

💡 Hint

Use n % 10 to peel off the last digit, and n /= 10 to shrink. Loop until n == 0.

✅ Show solution
int digitSum(int n) {
    n = Math.abs(n);
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n   /= 10;
    }
    return sum;
}

Problem 3 — Reverse a String

Task: Reverse a string without using library reverse.

💡 Hint

Swap chars from both ends moving inward — a classic two-pointer algorithm.

✅ Show solution
String reverse(String s) {
    char[] a = s.toCharArray();
    int i = 0, j = a.length - 1;
    while (i < j) {
        char t = a[i]; a[i] = a[j]; a[j] = t;
        i++; j--;
    }
    return new String(a);
}

8 · Check Your Understanding

Q1. In the Software Development Method, which step comes before writing code?

Q2. An algorithm must be:

Q3. The first step in developing an algorithm is:

Q4. Pseudocode is useful because: