Algoritma dan Pemrograman: Konsep Dasar dan Langkah Pembuatan Program

Foundations of Algorithms and Computation

  • Etymology and Historical Evolution of the Term "Algorithm":

    • The word algorithm originates from the name of Muhammad ibn Musa al-Khawarizmi (±780−850 CE\pm 780-850\text{ CE}), a Persian scientist, mathematician, and astronomer working in the House of Wisdom in Baghdad.

    • Al-Khawarizmi authored the landmark mathematical treatise Al-Kitab al-Mukhtasar fi Hisab al-Jabr wa'l-Muqabala, which established the foundations of modern algebra (al-jabr).

    • The linguistic progression evolved chronologically: Al-Khawarizmi (Arabic) →\rightarrow algorismus / algoritmi (Medieval Latin) →\rightarrow algorism (Middle English) →\rightarrow algorithm (Modern English) →\rightarrow algoritma (Indonesian).

    • During the European Middle Ages, the term algorismus specifically denoted the revolutionary technique of performing arithmetic utilizing the Hindu-Arabic positional numeral system (0−90-9), which progressively replaced Roman numerals.

  • Chronological Development of Algorithmic Concepts:

    • ±300 BCE\pm 300\text{ BCE}: The Euclidean Algorithm was formulated by Euclid of Alexandria to compute the Greatest Common Divisor (GCD\text{GCD} / FPB) of two integers, standing as one of the oldest recorded non-trivial algorithms in written history.

    • ±825 CE\pm 825\text{ CE}: Al-Khawarizmi formalized systematic, step-by-step procedures for solving linear and quadratic algebraic equations.

    • 19th Century: Augusta Ada Lovelace authored what is recognized as the world's first computer algorithm, designed specifically for Charles Babbage's mechanical general-purpose computer, the Analytical Engine.

    • 19361936: Alan Mathison Turing introduced the theoretical concept of the Universal Turing Machine, establishing the formal mathematical foundations of modern computability and computer science.

    • 19681968: Donald Ervin Knuth published The Art of Computer Programming, formally codifying the definitive properties, mathematical analysis, and quality criteria of algorithms.

    • 21st Century: Algorithmic structures expanded into foundational drivers of artificial intelligence, deep learning, big data analytics, distributed systems, and quantum computing.

    • Algorithms represent a universal, cross-epoch product of human rational inquiry and exist independently of physical electronic computers.

  • Multi-Perspective Definitions of an Algorithm:

    • Mathematical Perspective: A precise finite sequence of rigorous computational instructions that transforms a set of inputs into a distinct set of outputs.

    • Computer Science Perspective: An abstract, systematic procedural description capable of being translated into machine-executable software instructions across various programming languages.

    • Practical Perspective: A standardized "recipe" or step-by-step protocol executed to accomplish an intended objective or solve a concrete problem.

    • Kamus Besar Bahasa Indonesia (KBBI) Formal Definition: A logical sequence of decision-making steps designed for problem resolution, rendered in textual or graphic representations.

    • Donald E. Knuth Formal Definition: A finite set of precise rules providing a sequence of operations for solving a specific type of problem.

    • Synthesized Foundational Definition: An ordered sequence of logical steps formulated systematically, finite in quantity, unambiguous in definition, and guaranteed to yield a correct solution when followed precisely.

  • Conceptual Paradigm of Problem Solving:

    • The computational pipeline operates through four progressive transformations: Real-World Problem→Algorithm (Solution Logic)→Program (Concrete Source Code)→Validated Output / Solution\text{Real-World Problem} \rightarrow \text{Algorithm (Solution Logic)} \rightarrow \text{Program (Concrete Source Code)} \rightarrow \text{Validated Output / Solution}.

    • Without a sound algorithm, code cannot be written reliably; computer code is merely the syntactic translation of an algorithmic design.

  • Execution Entities of Algorithms:

    • Human Actors: Execute algorithmic steps in everyday scenarios, such as preparing meals from written culinary recipes, completing multi-page bureaucratic forms sequentially, or executing standardized emergency building evacuation protocols.

    • Non-Computer Mechanical Machines: Electromechanical appliances execute rigid sequences governed by internal timers or logic circuits, such as an automated washing machine progressing sequentially through fill →\rightarrow wash →\rightarrow rinse →\rightarrow spin cycles.

    • Digital Computers: Microprocessors execute machine instructions compiled or interpreted from algorithms to perform data processing at high speed.

    • The underlying algorithm remains conceptually invariant; the defining divergence lies entirely in the nature and constraints of the executing entity.

  • George Pólya's Four-Stage Problem-Solving Framework (How to Solve It, 19451945):

    • Stage 1: Understanding the Problem (Memahami Masalah): Identifying given inputs, unknown variables, desired outputs, boundary constraints, and business rules.

    • Stage 2: Devising a Plan (Merencanakan Solusi): Formulating structural strategy, decomposing large hurdles, and identifying analogies with previously solved problems.

    • Stage 3: Carrying Out the Plan (Melaksanakan Rencana): Formalizing the abstract strategy into concrete algorithmic representations (descriptive text, flowcharts, or pseudocode).

    • Stage 4: Looking Back / Reviewing (Memeriksa Kembali): Tracing the algorithmic execution manually via desk checks with boundary and edge test data to ensure correctness and absence of logic flaws.

  • The Four Pillars of Computational Thinking:

    • Decomposition (Dekomposisi): Partitioning a complex, multi-faceted problem into self-contained, manageable sub-problems.

    • Pattern Recognition (Pengenalan Pola): Identifying recurring structures, symmetries, or commonalities between the current challenge and historical solutions.

    • Abstraction (Abstraksi): Filtering out non-essential operational details to concentrate exclusively on core elements and data models.

    • Algorithm Design (Perancangan Algoritma): Formulating systematic, step-by-step procedural guidelines based on the synthesized insights of decomposition, pattern recognition, and abstraction.

Characteristics and Quality Criteria of Algorithms

  • Donald E. Knuth's Five Mandatory Algorithmic Criteria:

    • Finiteness (Keterbatasan): An algorithm must unconditionally terminate after a finite, countable number of operational steps. It must never trap execution in an unending loop. Example violation: A directive stating "while computer power remains on, add 11" fails finiteness because it lacks an exit condition and never produces a final state.

    • Definiteness (Kepastian): Every step must be unambiguous, precisely defined, and leave no room for multiple interpretations. Every operation must have an exact specification.

    • Input (Masukan): An algorithm must possess zero or more distinct input values provided externally before or during execution.

    • Output (Keluaran): An algorithm must produce one or more distinct output values that bear an explicit, mathematically sound relationship to the provided inputs.

    • Effectiveness (Efektivitas): Every instruction must be sufficiently basic, realistic, and simple such that it can, in principle, be carried out exactly and in a finite duration by an agent using pencil and paper.

  • Qualitative Metrics for Algorithmic Excellence:

    • Efficiency (Efisiensi): Minimizing computational resource consumption, structured along two primary theoretical dimensions: Time Complexity (minimizing execution steps / CPU cycles) and Space Complexity (minimizing primary memory allocation).

    • Generality (Generalitas): An algorithm must not be restricted to a single bespoke instance; it must handle an entire class of equivalent inputs across variable parameter ranges.

    • Simplicity (Kesederhanaan): Clear structural readability that minimizes convoluted logic without sacrificing operational correctness.

    • Independence (Independensi): Freedom from the unique architectural quirks of specific computing hardware platforms or syntactic eccentricities of programming languages.

Algorithmic Representation Techniques and Standards

  • Descriptive Sentences (Kalimat Deskriptif):

    • Expresses sequential steps using natural everyday human language, arranged chronologically with explicit step numbering.

    • Advantage: Instantly comprehensible to non-technical stakeholders without requiring specialized training.

    • Disadvantage: Verbose, prone to semantic ambiguity, and cumbersome when expressing intricate conditional branching or nested repetition.

  • Pseudocode:

    • An informal high-level representation of algorithmic logic that mirrors programming language syntax without strict adherence to the formal grammatical rules of any specific compiler.

    • Keywords: Structured in capitalized English verbs:

      • Block Demarcation: BEGIN / END

      • Input Operations: INPUT / READ

      • Output Operations: OUTPUT / PRINT

      • Conditional Branching: IF ... THEN ... ELSE ... END IF

      • Conditional Loops: WHILE ... DO ... END WHILE

      • Counted Loops: FOR ... TO ... DO ... END FOR

      • Post-Condition Loops: REPEAT ... UNTIL

      • Assignment Operators: <- or :=

    • Advantage: Compact, precise, and seamlessly translatable into commercial 3GL source code.

    • Disadvantage: Requires basic familiarity with standard procedural programming constructs.

  • Flowcharts (Diagram Alir):

    • A standardized graphical representation tracking programmatic logic, data flow, and control structures through standardized geometrical shapes connected by directional arrows.

    • Flowchart Classifications:

      • System Flowchart: Maps macro-level operational data flows across physical corporate departments and system components.

      • Document Flowchart: Traces audit trails and paper document routing through an administrative process.

      • Schematic Flowchart: Integrates pictorial representations of physical hardware peripherals alongside standard symbols.

      • Program Flowchart: Delineates detailed procedural step-by-step logic, branching, and memory processing inside a software program.

      • Process Flowchart: Utilized extensively in industrial engineering to diagram industrial manufacturing steps.

  • ANSI Standard Flowchart Symbols:

    • Terminator (Pill / Rounded Oval): Denotes the explicit initialization (START) or termination (END) of an algorithmic procedure.

    • Input / Output (Parallelogram): Represents receiving external data inputs or transmitting processed information outputs.

    • Process (Rectangle): Signifies arithmetic computations, variable assignments, or general internal data manipulations.

    • Decision (Diamond / Rhombus): Represents conditional bifurcation testing an expression for a boolean result (true/false or Ya/Tidak), always emitting at least two distinct outbound flow lines.

    • Predefined Process (Double-Struck Rectangle): Designates a call to a self-contained sub-routine, function, or external modular procedure.

    • Connector (Small Circle): Merges separated flow lines or junctions within the boundaries of the same page.

    • Off-page Connector (Pentagon / Home-Plate Shape): Bridges disconnected flow paths traversing across multiple distinct physical pages.

    • Flow Line (Arrowed Line): Directs the strict execution trajectory from one symbol to its immediate successor.

    • Document Symbol (Rectangle with Wavy Base): Represents hardcopy printed document inputs or outputs.

    • Manual Input (Trapezoid with Slanted Top): Signifies user input entered manually through peripheral devices such as a keyboard.

  • Syntactic Rules for Flowchart Construction:

    • Every flowchart must strictly commence with exactly one Start Terminator and conclude at one or more explicit End Terminators.

    • Standard directional flow proceeds monotonically from top to bottom or from left to right.

    • Every operational symbol must have an incoming and outgoing flow line; orphaned or dangling symbols are strictly invalid.

    • Decision diamonds must clearly label their alternative outbound branches with evaluation outcomes (e.g., "Ya" vs. "Tidak").

  • Worked Visual Flowchart Examples:

    • The conditional bifurcation between broth and fried noodle preparations illustrates multi-path decision logic:


Flowchart for preparing instant noodles showing conditional branch for broth or fried variants
  • The pedestrian street-crossing procedure demonstrates a pre-condition loop repeating safety checks until road clearance is verified:


Flowchart for crossing the street illustrating a repetition loop

Foundational Algorithmic Control Structures

  • Sequence Structure (Runtutan):

    • Commands execute sequentially from the initial instruction to the final instruction without skipping or jumping.

    • Concrete Paradigm: Powering on a desktop workstation sequentially (plug in mains →\rightarrow toggle PSU →\rightarrow depress CPU power switch →\rightarrow await BIOS bootstrap →\rightarrow load OS).

    • Mathematical Case: Computing the area of a rectangle (luas=p×l\text{luas} = p \times l):

      • Descriptive:

        • Step 1: Start.

        • Step 2: Enter length (pp).

        • Step 3: Enter width (ll).

        • Step 4: Compute luas=p×l\text{luas} = p \times l.

        • Step 5: Display luas\text{luas}.

        • Step 6: End.

      • Pseudocode Form: text BEGIN INPUT panjang INPUT lebar luas <- panjang * lebar OUTPUT luas END &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Selection Structure (Percabangan):

    • Directs programmatic flow into alternate operational branches predicated on the truth value of a conditional boolean test.

    • Concrete Paradigm: Evaluating student examination performance where a score of ≥60\ge 60 yields "LULUS" while lower marks yield "TIDAK LULUS".

    • Mathematical Case: Finding the maximum of two numbers (aa and bb): text BEGIN INPUT a, b IF a > b THEN terbesar <- a ELSE terbesar <- b END IF OUTPUT terbesar END &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Repetition Structure (Perulangan / Iteration):

    • Executes a designated block of code repeatedly as long as a governing boolean condition remains satisfied.

    • Pre-Condition Loop (WHILE ... DO): Evaluates the boolean condition prior to executing the loop body. If initially false, the loop body never runs. text BEGIN INPUT N counter <- 1 WHILE counter <= N DO OUTPUT counter counter <- counter + 1 END WHILE END &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Counted Loop (FOR ... TO ... DO): Automatically increments an internal index variable across a predetermined numerical span. text BEGIN INPUT N FOR counter <- 1 TO N DO OUTPUT counter END FOR END &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

The Program Development Life Cycle (PDLC)

  • Iterative Architecture of Software Engineering:

    • Program development is fundamentally an iterative lifecycle consisting of six discrete, sequential stages. When defects are caught during testing, execution returns to planning or coding phases.

    • Failure to establish problem parameters in early phases compounds across subsequent stages under the principle: "Understand before you solve."

  • Phase 1: Problem Analysis (Analisis Masalah):

    • Defines four foundational pillars: Input (data schemas received), Process (mathematical and logical manipulations required), Output (reporting formats expected), and Constraints (performance, security, memory, or business rules).

    • Case Application (Payroll System): Inputs include basic salary, overtime hours, allowances, and statutory tax deductions; Process applies organizational salary formulas; Output produces itemized pay slips and net compensation.

  • Phase 2: Algorithm Design (Perancangan Algoritma):

    • Architects the solution logic into descriptive notations, flowcharts, or pseudocode, divorced entirely from compiler-specific syntax.

    • Utilizes desk checking (manual tracing with structured trace tables and sample data vectors) to detect and correct logic flaws prior to code implementation.

  • Phase 3: Program Coding (Penulisan Kode Program):

    • Translates the validated algorithm into concrete source code utilizing a selected programming language (such as Java).

    • Demands adherence to three technical pillars: syntactic accuracy, appropriate data structure selection, and robust formatting conventions (standardized identifier casing, consistent indentation hierarchies, and documentation comments).

    • Example Implementation (LuasPersegiPanjang.java):java public class LuasPersegiPanjang { public static void main(String[] args) { int panjang = 10; int lebar = 5; int luas = panjang * lebar; System.out.println("Luas = " + luas); } } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Phase 4: Testing and Debugging (Pengujian dan Debugging):

    • Syntax Errors: Violations of the programming language's grammatical rules (e.g., omitted semicolons, mismatched braces). Detected automatically by compilers and interpreters prior to execution.

    • Logic Errors: Flaws in the underlying algorithm where code compiles and runs without crashes, but yields mathematically incorrect results. Difficult to detect, requiring trace tables and systematic input checks.

    • Methodological Testing Levels:

      • Unit Testing: Validates individual functions, algorithms, or sub-routines in strict isolation.

      • Integration Testing: Validates interoperability and communication interfaces between integrated sub-systems.

      • Data Diversity Testing: Evaluates system boundaries using normal valid data, extreme boundary data (edge cases), and invalid data to test error-handling routines.

  • Phase 5: Documentation (Dokumentasi):

    • Internal Documentation: Inline comments embedded directly within the source code (// single-line or /* multi-line */) to explain non-obvious algorithms and variable roles to maintenance programmers.

    • External Documentation: Collateral materials maintained separately from the codebase, encompassing formal software requirements specifications, architecture diagrams, user manuals, and deployment runbooks.

  • Phase 6: Program Maintenance (Pemeliharaan Program):

    • Corrective Maintenance: Diagnosing and patching residual runtime bugs and logical errors reported post-deployment.

    • Adaptive Maintenance: Modifying software interfaces to maintain compatibility across updated operating systems, database engines, or hardware architectures.

    • Perfective Maintenance: Refactoring existing codebase structures to enhance operational throughput, minimize latency, or integrate newly requested enterprise features.

    • Lifecycle Economic Reality: Program maintenance typically accounts for the largest fraction of long-term software expenditures; high-quality algorithms and clean documentation significantly lower lifetime maintenance overhead.

  • Complete Lifecycle Case Study: Odd / Even Integer Determination:

    • Analysis: Input is an integer bb. Process computes remainder modulo 22 (b(mod2)b \pmod 2). Output reports "Genap" if remainder is 00, else "Ganjil".

    • Algorithm Design (Pseudocode):text BEGIN INPUT bilangan sisa <- bilangan MOD 2 IF sisa = 0 THEN OUTPUT "Genap" ELSE OUTPUT "Ganjil" END IF END &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Coding Implementation (Java): ```java import java.util.Scanner;

    public class CekGenapGanjil {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int b = in.nextInt();
            if (b % 2 == 0) {
                System.out.println("Genap");
            } else {
                System.out.println("Ganjil");
            }
        }
    }
    

            ```

  • Testing Matrix: Verified via test vectors: Input 4→Genap4 \rightarrow \text{Genap}; Input 7→Ganjil7 \rightarrow \text{Ganjil}; Input 0→Genap0 \rightarrow \text{Genap}; Input −3→Ganjil-3 \rightarrow \text{Ganjil}.

  • Documentation: Inline comments explaining the modulus operation.

  • Maintenance: Adding input validation to intercept non-integer characters.

Programming Languages and Translation Paradigms

  • Linguistic Architecture of Programming Languages:

    • A programming language is a standardized instruction system featuring defined syntactic and semantic rules, enabling humans to command computer hardware to execute intended algorithms.

    • Serves as an operational cognitive bridge: Human natural language and high-level logic ⟷\longleftrightarrow Programming language syntax ⟷\longleftrightarrow Binary machine code (00 and 11) interpreted by central processing units.

  • Tripartite Linguistic Components:

    • Syntax (Sintaks): The strict grammatical and structural rules dictating the arrangement of keywords, identifiers, and operators. Dictates the form of an instruction.

    • Semantics (Semantik): The logical meaning, operational behavior, and mathematical consequences conveyed by syntactically valid statements. Dictates the intent of an instruction.

    • Pragmatics (Pragmatik): The contextual usage environment, including software idioms, idiomatic naming conventions, architectural design patterns, and programming style guides.

  • Common Contemporary Languages and Industry Applications:

    • Java: Enterprise-scale business platforms, Android operating system applications, cross-platform distributed microservices.

    • Python: Machine learning models, data science pipelines, statistical analysis, web backends, and rapid system scripting.

    • C / C++: Operating system kernels, device drivers, embedded systems, graphics engines, and performance-critical game software.

    • JavaScript: Universal web development across client browsers and server runtime environments (via Node.js).

    • PHP: Server-side web backend development and content management systems.

    • SQL (Structured Query Language): Declarative management, query processing, and transactional manipulation of relational databases.

  • The Five Generations of Programming Languages (5GL\text{5GL}):

    • First Generation (1GL\text{1GL}) — Machine Language (Bahasa Mesin):

      • Instructions composed directly in binary digits (00 and 11), matching the internal instruction register sets of specific microprocessors (e.g., 10110000 01100001).

      • Executes at maximum physical speed with zero translation overhead.

      • Extremely difficult to compose, read, or debug; entirely dependent on underlying physical processor architectures.

    • Second Generation (2GL\text{2GL}) — Assembly Language (Bahasa Rakitan):

      • Replaces raw binary sequences with readable mnemonic shorthand abbreviations (e.g., MOV AL, 61h, ADD AL, BL, JMP label).

      • Requires an Assembler program to convert mnemonics into machine code.

      • Hardware-dependent; primarily utilized today for low-level device drivers, operating system kernels, and constrained microcontroller firmware.

    • Third Generation (3GL\text{3GL}) — High-Level Languages (Bahasa Tingkat Tinggi):

      • Adopts structured, English-like statements and mathematical expressions (e.g., int total = harga * jumlah; System.out.println(total);).

      • Hardware-independent and portable across disparate processor architectures.

      • Requires translation through compilers or interpreters.

      • Introduces structured programming constructs, procedural abstraction, sub-routines, and Object-Oriented Programming (OOP\text{OOP}).

      • Examples include C, C++, Java, Python, Pascal, and BASIC.

    • Fourth Generation (4GL\text{4GL}) — Very High-Level Languages (Bahasa Tingkat Sangat Tinggi):

      • Non-procedural and declarative: developers specify what data output is needed rather than how to procedurally fetch it (e.g., SELECT nama, ipk FROM mahasiswa WHERE ipk >= 3.5;).

      • Drastically reduces total lines of code required for database retrieval, mathematical computation, and data visualization.

      • Examples include SQL and MATLAB.

    • Fifth Generation (5GL\text{5GL}) — Artificial Intelligence / Constraint Languages:

      • Designed to solve problems using declarative constraints and formal logic rules rather than explicit step-by-step algorithms.

      • Computers infer solutions using automated deduction algorithms and inference engines.

      • Examples include Prolog and LISP, as well as modern natural language processing interface engines.

  • Summary Matrix of Programming Language Generations:

Generation

Category Name

Primary Code Examples

Human Proximity

Machine Proximity

1GL\text{1GL}

Machine Language

Binary sequences (01100001)

Extremely Low

Extremely High

2GL\text{2GL}

Assembly Language

Mnemonics (MOV, ADD, JMP)

Low

High

3GL\text{3GL}

High-Level Language

Java, C, C++, Python, Pascal

High

Moderate

4GL\text{4GL}

Very High-Level Language

SQL, MATLAB

Very High

Low

5GL\text{5GL}

AI / Logic Language

Prolog, LISP

Near Natural Language

Extremely Low

  • Language Translators: Compilers vs. Interpreters:

    • Compilers: Translate the entire source codebase in a single pass into a standalone, hardware-executable binary file prior to program launch. The executable file runs independently thereafter without re-translation. Compilation halts and reports all encountered syntax errors simultaneously; the binary cannot be created until all syntax errors are resolved. Examples: C, C++, Pascal.

    • Interpreters: Read, translate, and immediately execute source code line-by-line in real time without producing a separate machine-code binary. Execution halts immediately upon reaching the exact line containing an error. Ideal for interactive exploration and rapid prototyping, but runs with higher runtime overhead due to continuous translation. Examples: Python, JavaScript, PHP.

Comparative Dimension

Compiler (Kompiler)

Interpreter (Interpreter)

Translation Process

Translates entire source code simultaneously

Translates and executes instruction line-by-line

Output Artifact

Standalone machine-code binary executable

No independent executable; runs via interpreter

Execution Speed

Fast post-compilation runtime execution

Slower due to inline translation overhead

Error Reporting

Global report of all errors compiled at end

Halts execution directly on line with defect

Development Loop

Requires complete re-compilation on edit

Flexible for incremental testing and debugging

Representative Languages

C, C++, Pascal, Rust

Python, JavaScript, PHP, Ruby

  • The Hybrid Translation Architecture (Java):

    • Java combines both compilation and interpretation stages to achieve structural platform independence under the paradigm: "Write Once, Run Anywhere" (WORA).

    • Pipeline: Java Source File (.java) →javac compiler\xrightarrow{\text{javac compiler}} Platform-Independent Bytecode (.class) →Java Virtual Machine (JVM)\xrightarrow{\text{Java Virtual Machine (JVM)}} Native Machine Code.

    • The javac compiler does not output physical CPU-specific instructions; it generates intermediate bytecode.

    • Every host operating system utilizes a platform-specific implementation of the Java Virtual Machine (JVM\text{JVM}), which interprets or Just-In-Time (JIT\text{JIT}) compiles bytecode into native machine instructions.

  • Deep Contrast: Syntax vs. Semantics:

    • Syntax: Governs typographical and grammatical validity. An omitted semicolon (int a = 10) triggers an immediate compile-time diagnostic flag.

    • Semantics: Governs underlying mathematical meaning. A statement computing rectangle area as int luas = panjang + lebar; is grammatically valid Java syntax, yet semantically defective because it performs addition instead of multiplication (panjang×lebarpanjang \times lebar).

    • Systemic Risk: Syntax defects are captured automatically by developer tools. Semantic logic defects execute cleanly, silently corrupting calculations or business records, making robust unit testing and trace tables essential.

Data Types in Programming

  • Primitive Data Types (Tipe Data Sederhana):

    • Predefined types built directly into the language specification, acting as foundational value-type storage units that hold their raw data values directly within memory stack locations without dynamic heap pointers.

    • Fixed-Size Integer Types (Bilangan Bulat):

      • byte: Size of 8 bit8\text{ bit}; range spanning −128-128 to 127127.

      • short: Size of 16 bit16\text{ bit}; range spanning −32,768-32,768 to 32,76732,767.

      • int: Size of 32 bit32\text{ bit}; range spanning −2,147,483,648-2,147,483,648 to 2,147,483,6472,147,483,647 (±2.1 billion\pm 2.1\text{ billion}). Standard default choice for whole numbers.

      • long: Size of 64 bit64\text{ bit}; range spanning ±9.22×1018\pm 9.22 \times 10^{18}. Denoted with a trailing L suffix (e.g., 270000000L).

    • Floating-Point Types (Bilangan Pecahan):

      • float: Size of 32 bit32\text{ bit}; provides single-precision storage (±6−7\pm 6-7 significant decimal digits). Denoted with an f suffix (e.g., 165.5f).

      • double: Size of 64 bit64\text{ bit}; provides double-precision storage (±15−16\pm 15-16 significant decimal digits). Default choice for floating-point calculations.

    • Character and Logical Types:

      • char: Size of 16 bit16\text{ bit}; stores a single Unicode character, enclosed strictly within single quote literals (e.g., 'A', 'O').

      • boolean: Stores a binary logic state, taking exclusively either true or false.

  • Composite and Reference Data Types (Tipe Data Composite):

    • Structured types assembled by aggregating primitive types or other composite structures. Instead of directly encapsulating raw data in-place, composite variables store reference handles (memory heap addresses).

    • Arrays (Larik): Homogeneous linear collections storing a fixed quantity of data items sharing an identical type. Elements are accessed via zero-based indexing (0 to length−1\text{length} - 1). Size is static once instantiated. java int[] nilaiUjian = {80, 75, 90, 88, 95}; System.out.println(nilaiUjian[0]); // Outputs 80 System.out.println(nilaiUjian[2]); // Outputs 90 System.out.println(nilaiUjian.length); // Outputs 5 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Classes and Objects: A class serves as a user-defined blueprint establishing data fields and methods. An object is a concrete runtime instance of that class possessing distinct state values. java class Mahasiswa { String nama; String nim; double ipk; } Mahasiswa mhs1 = new Mahasiswa(); mhs1.nama = "Budi Santoso"; mhs1.ipk = 3.75; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    • Java Collections Framework:

      • ArrayList: A resizable dynamic list array that expands as elements are appended.

      • HashSet: An unordered collection storing unique elements, automatically eliminating duplicates.

      • HashMap: A keyed associative data structure storing data as key-value pairs.

  • Comparison: Primitive vs. Composite Data Types:

Technical Attribute

Primitive Data Types

Composite Data Types

Value Capacity

Encapsulates a single value per variable

Manages multiple values within a single structure

Memory Storage

Directly stores the value

Stores an indirect reference / memory address

Memory Footprint

Static and pre-allocated by the language

Dynamic, scaling with allocated element count

Representative Examples

byte, short, int, long, float, double, char, boolean

Array, Class / Object, ArrayList, HashMap

  • The String Data Type in Java:

    • A sequence of characters represented as an immutable composite reference object (wrapping an internal character array).

    • String literals must be enclosed strictly within double quotes (" "), contrasting with character single quotes (' ').

    • Immutability: Once instantiated on the heap, the contents of a String object cannot be altered. Operations that appear to mutate a String construct a new String object in memory.

    • Built-in String Manipulation Methods:

      • length(): Returns character count: "Algoritma".length() →9\rightarrow 9.

      • toUpperCase(): Converts characters to uppercase: "java".toUpperCase() →"JAVA"\rightarrow \text{"JAVA"}.

      • substring(int beginIndex, int endIndex): Extracts sub-string from index a inclusive to b exclusive: "Algoritma".substring(0, 4) →"Algo"\rightarrow \text{"Algo"}.

      • charAt(int index): Returns the character at index: "Java".charAt(0) →’J’\rightarrow \text{'J'}.

      • equals(Object anObject): Evaluates textual equality: "java".equals("Java") →false\rightarrow \text{false}.

      • trim(): Strips leading and trailing whitespace: " Java ".trim() →"Java"\rightarrow \text{"Java"}.

      • split(String regex): Splits text by delimiter into an array: "a,b,c".split(",") →["a","b","c"]\rightarrow [\text{"a"}, \text{"b"}, \text{"c"}].

  • The Identity Trap: == vs. .equals() in Java:

    • The equality operator == compares memory references (heap addresses) when applied to composite reference objects.

    • The method .equals() inspects and validates the actual character content stored inside the objects.

    • Demonstration Code: ```java String a = "Java"; String b = new String("Java");

      System.out.println(a == b); // Evaluates to false (distinct memory addresses) System.out.println(a.equals(b)); // Evaluates to true (identical character content)         ```

Operators and Expressions

  • Numeric Arithmetic Operators:

    • + (Addition): Adds numerical operands (10+3=1310 + 3 = 13).

    • - (Subtraction): Subtracts right operand from left (10−3=710 - 3 = 7).

    • * (Multiplication): Multiplies operands (10×3=3010 \times 3 = 30).

    • / (Division): Divides left operand by right. Crucial rule on integer truncation: Dividing two int operands truncates all decimal remainders downwards (10/3=310 / 3 = 3). To obtain decimal precision, at least one operand must be a floating-point type (10.0/3=3.333333333333333510.0 / 3 = 3.3333333333333335).

    • % (Modulus): Computes the integer remainder of division (10(mod3)=110 \pmod 3 = 1).

    • ++ (Increment): Increases integer value by 11.

    • -- (Decrement): Decreases integer value by 11.

  • Pre-Increment vs. Post-Increment:

    • Pre-increment (++a): The variable is incremented by 11 first, and the new value is returned to the surrounding expression.

    • Post-increment (a++): The current value of the variable is evaluated in the expression first, and the variable is incremented by 11 afterward.

    • Demonstration Code:java int a = 5; System.out.println(a++); // Prints 5, internal state of 'a' becomes 6 System.out.println(++a); // Internal state becomes 7, prints 7 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Operator Precedence Hierarchy:

    • 1st Priority: Parentheses ( ) evaluate before all other operations.

    • 2nd Priority: Multiplicative operations: *, /, % (evaluated left-to-right).

    • 3rd Priority: Additive operations: +, - (evaluated left-to-right).

    • Evaluation Example: 10 + 2 * 3 evaluates as 10+6=1610 + 6 = 16. Conversely, (10 + 2) * 3 evaluates as 12×3=3612 \times 3 = 36.

  • Relational (Rational) Comparison Operators:

    • Evaluate numerical relationships between operands and always return a primitive boolean (true or false).

    • ==: Tests equality (10==3→false10 == 3 \rightarrow \text{false}).

    • !=: Tests inequality (10!=3→true10 != 3 \rightarrow \text{true}).

    • >: Greater than (10>3→true10 > 3 \rightarrow \text{true}).

    • <: Less than (10<3→false10 < 3 \rightarrow \text{false}).

    • >=: Greater than or equal to (10>=3→true10 >= 3 \rightarrow \text{true}).

    • <=: Less than or equal to (10<=3→false10 <= 3 \rightarrow \text{false}).

    • Divergence between assignment and comparison: Single equals = assigns a value to a memory variable (int a = 10;); double equals == evaluates value equality (if (a == 10)).

  • Boolean Logical Operators:

    • Operate on boolean operands to synthesize a consolidated boolean output.

    • && (Logical AND): Evaluates to true if and only if both operands are true.

    • || (Logical OR): Evaluates to true if at least one operand is true.

    • ! (Logical NOT): Negates the operand's truth value (!true →\rightarrow false).

  • Truth Tables for Logical Operators:

Operand A

Operand B

A∧BA \land B (A && B)

A∨BA \lor B (A || B)

¬A\neg A (!A)

true

true

true

true

false

true

false

false

true

false

false

true

false

true

true

false

false

false

false

true

  • Short-Circuit Evaluation Architecture:

    • In a logical AND (A && B), if the primary condition A evaluates to false, the secondary expression B is skipped entirely, as the overall expression is guaranteed to be false.

    • In a logical OR (A || B), if the primary condition A evaluates to true, the secondary expression B is skipped entirely, as the overall expression is guaranteed to be true.

    • Defensive Coding Application (Preventing Division by Zero):java int pembagi = 0; if (pembagi != 0 && (10 / pembagi > 1)) { System.out.println("Hasil valid"); } else { System.out.println("Pembagi tidak valid"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;         Because pembagi != 0 evaluates to false, the sub-expression (10 / pembagi > 1) is never executed, preventing a runtime arithmetic crash (ArithmeticException: / by zero).

Conditional Logic and Selection Structures

  • Conceptual Architecture of Selection:

    • Conditional statements direct programmatic control flow based on the runtime evaluation of boolean expressions.

    • Mirrors human decision-making: "IF condition is met, THEN execute action."

    • Four structural classifications of selection exist: Single IF, Dual IF (IF-ELSE), Nested IF / Else-If Ladder, and Case (Switch-Case).

  • Single IF (IF Tunggal):

    • Applies a single conditional test linked to a single instruction block. If the condition evaluates to true, the block executes; if false, execution bypasses the block with no alternate action.

    • Pseudocode Structure:text IF (kondisi) THEN instruksi END IF &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Java Implementation: java if (kondisi) { instruksi; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Flowchart Topology: The false ("Tidak") branch routes directly to the terminal endpoint without passing through any intermediate action blocks.

  • Worked Case (Retail Store Discount): A store awards a 10%10\% discount if total purchases exceed Rp500.000\text{Rp}500.000:

    • Pseudocode: text BEGIN INPUT totalBelanja IF totalBelanja > 500000 THEN totalBelanja <- totalBelanja - (totalBelanja * 0.1) END IF OUTPUT totalBelanja END &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Trace Table:

Input totalBelanja

Condition (> 500000)

Output Result

600.000600.000

true

540.000540.000 (Discount applied)

300.000300.000

false

300.000300.000 (Unchanged)

  • Dual Alternative IF (IF Jamak / IF-ELSE):

    • Evaluates a single condition linked to two mutually exclusive alternative blocks. Guarantees that exactly one branch executes; execution never bypasses both.

    • Pseudocode Structure:text IF (kondisi) THEN instruksi1 ELSE instruksi2 END IF &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Java Implementation: java if (kondisi) { instruksi1; } else { instruksi2; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Flowchart Topology: Both outbound paths from the decision diamond pass through an action block before re-converging at the terminal node.

  • Worked Case (Academic Qualification, Passing Standard=60\text{Passing Standard} = 60): text BEGIN INPUT nilaiAkhir IF nilaiAkhir >= 60 THEN status <- "LULUS" ELSE status <- "TIDAK LULUS" END IF OUTPUT status END &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Nested IF and Else-If Ladder (IF Bertingkat):

    • Else-If Ladder: Chains multiple conditional evaluations sequentially to classify input data across more than two distinct categorical tiers.

      • Pseudocode Structure: text IF (kondisi1) THEN instruksi1 ELSE IF (kondisi2) THEN instruksi2 ELSE IF (kondisi3) THEN instruksi3 ELSE instruksi4 END IF &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Java Implementation: java if (kondisi1) { instruksi1; } else if (kondisi2) { instruksi2; } else if (kondisi3) { instruksi3; } else { instruksi4; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Evaluation Rule: Conditions are tested top-down. The moment a condition evaluates to true, its block executes and the entire remaining chain is skipped.

  • Ordering Constraint: Conditions must be structured strictly from most restrictive (highest threshold) to least restrictive. Inverting this hierarchy introduces severe logic defects (e.g., checking nilai >= 60 first causes scores of 7575, 8585, and 9090 to incorrectly receive grade "C").

  • Worked Case (Letter Grade Classification): text BEGIN INPUT nilai IF nilai >= 85 THEN predikat <- "A" ELSE IF nilai >= 70 THEN predikat <- "B" ELSE IF nilai >= 60 THEN predikat <- "C" ELSE predikat <- "D" END IF OUTPUT predikat END &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;             Trace Example (nilai = 75): * Step 1: Test 75 >= 85 →\rightarrow false. Advance to next condition. * Step 2: Test 75 >= 70 →\rightarrow true. Assign predikat = "B" and exit ladder. * Step 3: Condition 75 >= 60 is skipped entirely.

  • Pure Nested IF: Encapsulates an inner if structure inside an outer if block. The inner condition is evaluated only after the outer gatekeeping condition evaluates to true.

    • Worked Case (Credit Facility Approval: Age ≥21\ge 21 and Income ≥Rp5.000.000\ge \text{Rp}5.000.000): java if (usia >= 21) { if (penghasilan >= 5000000) { System.out.println("Pengajuan kredit DISETUJUI"); } else { System.out.println("DITOLAK: penghasilan tidak mencukupi"); } } else { System.out.println("DITOLAK: usia belum memenuhi syarat"); } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Case Selection Structure (Switch-Case):

    • Matches the scalar value of a single designated variable against fixed literal constants. Provides a cleaner, more readable alternative to an Else-If ladder when working with discrete, exact-match values.

    • Pseudocode Structure:text CASE (variabel) OF nilai1 : instruksi1 nilai2 : instruksi2 nilai3 : instruksi3 OTHERWISE : instruksiDefault END CASE &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Java Implementation: java switch (variabel) { case nilai1: instruksi1; break; case nilai2: instruksi2; break; default: instruksiDefault; } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Supported Java Data Types: Compatible with byte, short, char, int, String, and enum types. Floating-point types (float, double) and relational range checks cannot be evaluated in a standard switch construct.

  • The Break Statement and Fall-Through Defect: The break; command terminates switch execution once a matching branch finishes. Omitting break; triggers fall-through, causing the runtime to execute subsequent case blocks unconditionally until a break or the end of the switch block is encountered. java // Defective Fall-Through Demonstration (kodeHari = 2) int kodeHari = 2; switch (kodeHari) { case 1: System.out.println("Senin"); case 2: System.out.println("Selasa"); // Prints "Selasa" case 3: System.out.println("Rabu"); // Unintentionally prints "Rabu" default: System.out.println("Selesai"); // Unintentionally prints "Selesai" } &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

  • Comparative Architectural Evaluation: Nested IF vs. Switch-Case:

Technical Parameter

Nested IF / Else-If Ladder

Case (Switch-Case)

Evaluation Scope

Continuous ranges (>=, <) and complex boolean logic (&&, ||)

Discrete scalar values (exact matching)

Variable Scope

Can evaluate multiple distinct variables simultaneously

Bound to a single evaluation variable

Code Readability

Becomes verbose across extensive branch counts

Clean and readable across numerous discrete options

Data Types Supported

All data types supporting relational operators

Primitives (int, char, byte), String, and enum

Primary Use Cases

Grade brackets, continuous scales, composite criteria

Menu options, day indices, categorical status codes

Review Exercises and Applied Problem Sets

  • Conceptual Understanding Exercises:

    • Question 1: Define an algorithm, define programming, and explain the conceptual relationship between them.

    • Question 2: Enumerate and explain the five core algorithmic characteristics formulated by Donald E. Knuth, including an example of an operational violation.

    • Question 3: Contrast the structural trade-offs of descriptive sentences, flowcharts, and pseudocode.

    • Question 4: Explain the three fundamental control structures (Sequence, Selection, Repetition) with real-world examples.

    • Question 5: Detail the six iterative stages of the Program Development Life Cycle (PDLC\text{PDLC}) and explain why problem analysis precedes code writing.

    • Question 6: Track the historical evolution of the term "algorithm" from Al-Khawarizmi to modern computing theory.

    • Question 7: Distinguish between algorithms executed by human agents, electromechanical machines, and microprocessors.

    • Question 8: Enumerate George Pólya's four problem-solving stages (19451945) and the four pillars of computational thinking.

    • Question 9: Detail the memory footprints and ranges of the eight primitive Java data types.

    • Question 10: Explain why String is a composite reference type in Java, and detail the technical hazards of evaluating Strings with == rather than .equals().

    • Question 11: Explain the operational mechanics of short-circuit evaluation in boolean expressions, and describe how it prevents runtime exceptions.

    • Question 12: Classify the five generations of programming languages (1GL\text{1GL} to 5GL\text{5GL}) and describe their execution models.

    • Question 13: Compare compilers and interpreters regarding execution speed, error reporting mechanisms, and intermediate file generation.

    • Question 14: Describe the hybrid compilation and interpretation process employed by Java to achieve cross-platform portability.

    • Question 15: Explain the differences between syntax errors and semantic (logic) errors, detailing their detection methods and impact.

    • Question 16: Explain the structural differences between Single IF, Dual Alternative IF, Nested IF, and Switch-Case statements.

    • Question 17: Explain why conditions in an Else-If ladder must be arranged from most restrictive to least restrictive.

    • Question 18: Describe the execution hazard of omitting break; statements within a Java switch-case block.

  • Applied Algorithmic Problem Sets:

    • Exercise 1: Construct pseudocode to identify and return the maximum value among three arbitrary real numbers (aa, bb, cc).

    • Exercise 2: Draft an ANSI standard flowchart calculating both the area (A=πr2A = \pi r^2) and circumference (K=2πrK = 2 \pi r) of a circle given radius rr.

    • Exercise 3: Apply the six stages of the PDLC\text{PDLC} to engineer a temperature conversion program transforming degrees Celsius to Fahrenheit (F=(C×9/5)+32F = (C \times 9/5) + 32 ).

    • Exercise 4: Formulate an algorithm in descriptive text and pseudocode determining leap year status (divisible by 44, excluding century years not divisible by 400400).

    • Exercise 5: Construct a flowchart and pseudocode algorithm evaluating a student's composite grade: assignments weight 30%30\%, midterm exam weights 30%30\%, and final exam weights 40%40\%.

    • Exercise 6: Write an algorithm that allocates a 5-element integer array, populates it with examination scores, and extracts the maximum value.

    • Exercise 7: Trace the manual evaluation of the mathematical expression 15 + 5 * 2 % 3 - 1 using formal operator precedence rules, and write Java code to verify the result.

    • Exercise 8: Construct a conditional boolean expression determining scholarship eligibility: a student must have an IPK≥3.5\text{IPK} \ge 3.5 AND must not currently hold an active scholarship.

    • Exercise 9: Construct a flowchart and pseudocode script implementing an Else-If ladder to classify Body Mass Index (BMI\text{BMI} / IMT) into Kurus, Normal, Gemuk, and Obesitas categories.

    • Exercise 10: Write an algorithmic decision system utilizing a switch-case to convert letter grades (A,B,C,D,EA, B, C, D, E ) to grade points (4,3,2,1,04, 3, 2, 1, 0).

    • Exercise 11: Construct a program that calculates freight shipping costs by combining a switch-case for destination city zones with a nested if structure based on parcel weight tiers.

Reference Bibliography

  • Primary Textbooks (Pustaka Utama):

    • Ramadhani, Cipta. (20152015). Dasar Algoritma dan Struktur Data dengan Bahasa Java. Yogyakarta: Andi.

    • Untoro, Wisnu Yudo. (20102010). Algoritma dan Pemrograman dengan Bahasa Java. Yogyakarta: Graha Ilmu.

  • Supporting Textbooks (Pustaka Pendukung):

    • Alsuwaiyel, M. H. (20162016). Algorithms: Design Techniques and Analysis. Singapore: World Scientific.

    • Singh, Virender. (20162016). Algorithm and Design Application. Oxford: Oxford University Press.