First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Algorithms, flowcharts and problem solving

Algorithms, pseudocode, flowcharts, and problem-solving steps with C programs that implement them, including examples (sum of N numbers, Euclid’s GCD, linear search), syntax to remember, exam-focused definitions, diagrams to draw, and common mistakes.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers solve real-world problems by converting vague requirements into precise steps that a computer can execute. Algorithms, pseudocode, and flowcharts help you plan before coding in C, reducing bugs, saving time, and producing maintainable programs.

Key ideas

  • Pseudocode: A language-independent, structured description of an algorithm using simple keywords (like IF, WHILE) and indentation, close to English but precise like code. It guides coding without language syntax errors.
  • Flowchart: A diagram using standard symbols and arrows to represent the control flow of an algorithm.
    • Symbols and their meanings:
      • Terminator (Start/End): oval; labels “Start” or “End”.
      • Process: rectangle; a computation like sum = sum + x.
      • Input/Output: parallelogram; e.g., Read n, Print sum.
      • Decision: diamond; a yes/no test like i < n? with two outgoing arrows labeled “Yes” and “No”.
      • Flow lines: arrows; show direction of control.
      • Connector (if used): small circle; connects breaks in flow.
  • Stepwise refinement (top-down design): Start with a high-level solution, break into sub-steps, keep refining until each step is directly implementable in C.
  • Control structures: The three basic ways to control program flow:
    • Sequence: steps executed one after another.
    • Selection: choose between alternatives (IF, SWITCH in C).
    • Iteration: repeat steps (WHILE, FOR, DO…WHILE in C).
  • Variables and data (refer to Data types, variables and constants): Decide what data you need and their types before coding.
  • Tracing: Manually simulating the algorithm step by step with sample input, often using a table of variable values, to check correctness.
  • Test cases: Chosen inputs to exercise normal cases, edge cases, and invalid cases (if required), to verify behavior.
  • Correctness: An algorithm is correct if, for every valid input under the problem’s assumptions, it terminates and returns the specified output.
  • Complexity (informal here): Rough measure of resource usage as input size grows.
    • Time complexity: counts basic operations as a function of input size n; e.g., linear search is O(n).
    • Space complexity: memory used as a function of input size.
    • Big-O gives an upper bound up to constant factors, for large n.

Exact statements and commonly asked derivations:

  • Definition (Algorithm): “An algorithm is a finite sequence of unambiguous, effective instructions, each of which can be carried out in finite time, that, given any input from a specified set, produces a corresponding output and halts.”
  • Properties of a good algorithm: correctness, efficiency (time and space), readability, maintainability, and robustness (graceful handling of unexpected inputs when specified).
  • Derivation pattern (Stepwise refinement example: sum of n numbers):
    1. High-level: Read n and n numbers, compute sum, print sum.
    2. Refine: Initialize sum = 0; loop i from 1 to n; add each number to sum.
    3. Refine loop: Use counter i = 0; while i < n: read x, sum += x, i++.
  • Drawing a flowchart (what to draw and label):
    • For “Sum of n numbers”: Draw an oval labeled Start. Arrow to a parallelogram labeled “Read n”. Arrow to a rectangle “sum = 0; i = 0”. Arrow to a diamond “i < n?”. From the diamond, Yes arrow to a parallelogram “Read x”, arrow to rectangle “sum = sum + x; i = i + 1”, arrow back to the diamond. From the diamond, No arrow to parallelogram “Print sum”. Arrow to oval labeled End. Label the decision branches “Yes” and “No”.
    • For Euclid’s GCD: Start oval → parallelogram “Read a, b” → diamond “b ≠ 0?”; Yes → rectangle “r = a % b; a = b; b = r” → back to diamond; No → parallelogram “Print a (GCD)” → End oval.
    • For linear search: Start → Read n and array A, key k → rectangle “i = 0” → diamond “i < n?”; Yes → diamond “A[i] == k?”; Yes → Print “Found at index i” → End; No → rectangle “i = i + 1” → back to “i < n?”; If “i < n?” is No → Print “Not found” → End.

Problem-solving steps to follow before coding in C:

  1. Understand the problem: inputs, outputs, constraints, examples, and what to do on invalid input (if specified).
  2. Choose a method/algorithm; justify briefly (e.g., linear search vs binary search depends on sorting).
  3. Design using pseudocode and/or a flowchart.
  4. Trace with a small example; identify edge cases.
  5. Implement in C (refer to Structure of a C program, Input and output, Decision making: if and switch, Loops).
  6. Test, measure, and refine.

Formulas

READ x, PRINT x, IF condition THEN … ELSE … ENDIF, WHILE condition DO … ENDWHILE, FOR i ← start TO end DO … ENDFOR, REPEAT … UNTIL condition, RETURN value.

  • Flowchart symbols to remember (text labels): Start/End: oval, Process: rectangle, Input/Output: parallelogram, Decision: diamond, Flow: arrows, Connector: small circle.
  • C control structure syntax (minimal forms): if (condition) { … } else { … } switch (expr) { case C1: … break; … default: … } for (init; condition; update) { … } while (condition) { … } do { … } while (condition);
  • Basic I/O in C (stdio): scanf("%d", &x); // read int printf("%d", x); // print int printf("%s", s); // print string

Worked examples

Example 1: Algorithm, flowchart description, and C program to compute the sum of n integers

  • Problem: Read an integer n, then read n integers, and print their sum.
  • Algorithm (pseudocode):
    1. READ n
    2. sum ← 0; i ← 0
    3. WHILE i < n DO READ x sum ← sum + x i ← i + 1 ENDWHILE
    4. PRINT sum
  • Flowchart to draw and label: As described in Key ideas (sum of n numbers).
  • C program:
#include <stdio.h>

int main(void) {
    int n, i, x;
    long long sum = 0; // use wider type to reduce overflow risk for many inputs
    printf("Enter count N: ");
    if (scanf("%d", &n) != 1 || n < 0) {
        printf("Invalid N\n");
        return 0;
        
    }
    printf("Enter %d integers: ", n);
    for (i = 0; i < n; i++) {
        if (scanf("%d", &x) != 1) {
            printf("\nInvalid input\n");
            return 0;
        }
        sum += x;
    }
    printf("\nSum = %lld\n", sum);
    return 0;
}
  • Sample input:
5
2 4 6 8 10
  • Exact output produced:
Enter count N: Enter 5 integers: 
Sum = 30

Example 2: Euclid’s algorithm for GCD with flowchart and C program

  • Problem: Read two positive integers a and b, and print their greatest common divisor (GCD).
  • Algorithm (pseudocode):
    1. READ a, b
    2. WHILE b ≠ 0 DO r ← a mod b a ← b b ← r ENDWHILE
    3. PRINT a
  • Why it works (brief reasoning): At each step, gcd(a, b) = gcd(b, a mod b), and b decreases to 0 in finitely many steps. When b = 0, a is the GCD.
  • Flowchart to draw and label: As described in Key ideas (Euclid’s GCD).
  • Time complexity (high level): O(log min(a, b)) basic divisions in the worst case.
  • C program:
#include <stdio.h>

int main(void) {
    long long a, b, r;
    printf("Enter two positive integers: ");
    if (scanf("%lld %lld", &a, &b) != 2 || a <= 0 || b <= 0) {
        printf("Invalid input\n");
        return 0;
    }
    while (b != 0) {
        r = a % b;
        a = b;
        b = r;
    }
    printf("GCD = %lld\n", a);
    return 0;
}
  • Sample input:
48 18
  • Exact output produced:
Enter two positive integers: GCD = 6

Example 3: Linear search with tracing, flowchart, complexity, and C program

  • Problem: Read n and an array A of n integers, then read key k. If k is present, print its index (0-based). Otherwise, print “Not found”.
  • Algorithm (pseudocode):
    1. READ n, A[0..n−1], k
    2. i ← 0
    3. WHILE i < n DO IF A[i] = k THEN PRINT i; RETURN ELSE i ← i + 1 ENDWHILE
    4. PRINT “Not found”
  • Flowchart to draw and label: As described in Key ideas (linear search).
  • Tracing table (for A = [10, 20, 30, 40, 50], k = 40):
    • Step 1: i = 0, A[i] = 10 ≠ 40 → increment i
    • Step 2: i = 1, A[i] = 20 ≠ 40 → increment i
    • Step 3: i = 2, A[i] = 30 ≠ 40 → increment i
    • Step 4: i = 3, A[i] = 40 = 40 → print 3, stop
  • Complexity: Worst-case time O(n); best-case O(1); space O(1) extra.
  • C program:
#include <stdio.h>

int main(void) {
    int n, i, k;
    printf("Enter size: ");
    if (scanf("%d", &n) != 1 || n < 0) {
        printf("Invalid size\n");
        return 0;
    }
    int A[1000]; // simple fixed limit for demo; ensure n <= 1000
    if (n > 1000) {
        printf("Size too large\n");
        return 0;
    }
    printf("Enter %d integers: ", n);
    for (i = 0; i < n; i++) {
        if (scanf("%d", &A[i]) != 1) {
            printf("\nInvalid input\n");
            return 0;
        }
    }
    printf("Enter key: ");
    if (scanf("%d", &k) != 1) {
        printf("Invalid key\n");
        return 0;
    }
    for (i = 0; i < n; i++) {
        if (A[i] == k) {
            printf("Found at index %d\n", i);
            return 0;
        }
    }
    printf("Not found\n");
    return 0;
}
  • Sample input:
5
10 20 30 40 50
40
  • Exact output produced:
Enter size: Enter 5 integers: Enter key: Found at index 3

Model theory answer (sample long question): Q: Define algorithm. Explain the properties of a good algorithm. Compare pseudocode and flowcharts. Illustrate with a small example. A: An algorithm is a finite sequence of unambiguous, effective instructions that, given inputs from a specified set, produces corresponding outputs and halts. A good algorithm has: (i) Correctness: produces the required output for all valid inputs; (ii) Efficiency: uses reasonable time and memory; (iii) Readability: easy to understand and review; (iv) Maintainability: easy to modify for new requirements; (v) Robustness: handles edge cases gracefully if specified. Pseudocode is a textual, language-independent description using control keywords (IF, WHILE) and indentation, useful for quick writing and version control. Flowcharts are graphical diagrams using standard symbols (ovals, rectangles, parallelograms, diamonds) and arrows; they are visually clear for branching and loops and good for presentations. Example (sum of n numbers): Pseudocode—READ n; sum ← 0; FOR i from 1 to n DO READ x; sum ← sum + x; ENDFOR; PRINT sum. Flowchart—Start → Read n → sum = 0; i = 0 → i < n? (Yes) → Read x → sum = sum + x; i = i + 1 → back to i < n?; (No) → Print sum → End.

Common mistakes

  • Off-by-one errors in loops (i <= n instead of i < n).
  • Not labeling decision branches “Yes/No” in flowcharts, or drawing arrows without clear direction.
  • Mixing 1-based logic in pseudocode with 0-based array indices in C programs.
  • Skipping edge cases in test cases (n = 0, repeated elements, equal numbers for GCD, very large or very small values).
  • Using int where overflow is possible; not considering long long for sums or products.
  • In C I/O, forgetting & in scanf, or mismatching format specifiers with types.
  • Assuming input is always valid; not checking scanf return values in programs.

For your exam

  • Short notes: Flowchart symbols and their meanings; compare pseudocode vs flowchart; tracing and test cases; basic complexity (Big-O idea only).
  • Diagrams: Draw flowcharts for simple tasks (sum of n numbers, find max of three, factorial, GCD).
  • Algorithms/pseudocode: Write algorithm and/or pseudocode for searching, summing, counting vowels, reversing digits, etc.
  • Programs: Implement the designed algorithm in C (use loops, if/switch, arrays) and show correct I/O.
  • Reasoning: Explain why Euclid’s algorithm terminates and yields the GCD; discuss time complexity of linear search.
  • Full-marks answers usually include: precise definitions; clear, unambiguous steps; correctly labeled diagrams; correct C syntax; sample I/O; brief justification of algorithm choice; mention of edge cases and complexity if asked.

Quick check

  1. State the five essential properties of an algorithm.
  2. Which flowchart symbol represents a decision, and what must you label on its outgoing arrows?
  3. What is the worst-case time complexity of linear search, and why?

Answers: (1) Input, Output, Finiteness, Definiteness, Effectiveness. (2) Diamond; label branches “Yes” and “No”. (3) O(n), because in the worst case you compare the key with each of the n elements once.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?