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 (), 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) algorismus / algoritmi (Medieval Latin) algorism (Middle English) algorithm (Modern English) 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 (), which progressively replaced Roman numerals.
Chronological Development of Algorithmic Concepts:
: The Euclidean Algorithm was formulated by Euclid of Alexandria to compute the Greatest Common Divisor ( / FPB) of two integers, standing as one of the oldest recorded non-trivial algorithms in written history.
: 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.
: Alan Mathison Turing introduced the theoretical concept of the Universal Turing Machine, establishing the formal mathematical foundations of modern computability and computer science.
: 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: .
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 wash rinse 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, ):
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 " 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/ENDInput Operations:
INPUT/READOutput Operations:
OUTPUT/PRINTConditional Branching:
IF ... THEN ... ELSE ... END IFConditional Loops:
WHILE ... DO ... END WHILECounted Loops:
FOR ... TO ... DO ... END FORPost-Condition Loops:
REPEAT ... UNTILAssignment 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/falseorYa/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
StartTerminator and conclude at one or more explicitEndTerminators.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:

The pedestrian street-crossing procedure demonstrates a pre-condition loop repeating safety checks until road clearance is verified:

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 toggle PSU depress CPU power switch await BIOS bootstrap load OS).
Mathematical Case: Computing the area of a rectangle ():
Descriptive:
Step 1: Start.
Step 2: Enter length ().
Step 3: Enter width ().
Step 4: Compute .
Step 5: Display .
Step 6: End.
Pseudocode Form:
text BEGIN INPUT panjang INPUT lebar luas <- panjang * lebar OUTPUT luas END
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 yields "LULUS" while lower marks yield "TIDAK LULUS".
Mathematical Case: Finding the maximum of two numbers ( and ):
text BEGIN INPUT a, b IF a > b THEN terbesar <- a ELSE terbesar <- b END IF OUTPUT terbesar END
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
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
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); } }
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-lineor/* 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 . Process computes remainder modulo (). Output reports "Genap" if remainder is , 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
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 ; Input ; Input ; Input .
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 Programming language syntax Binary machine code ( and ) 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 ():
First Generation () — Machine Language (Bahasa Mesin):
Instructions composed directly in binary digits ( and ), 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 () — 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 () — 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 ().
Examples include C, C++, Java, Python, Pascal, and BASIC.
Fourth Generation () — 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 () — 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 |
|---|---|---|---|---|
Machine Language | Binary sequences ( | Extremely Low | Extremely High | |
Assembly Language | Mnemonics ( | Low | High | |
High-Level Language | Java, C, C++, Python, Pascal | High | Moderate | |
Very High-Level Language | SQL, MATLAB | Very High | Low | |
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) Platform-Independent Bytecode (.class) Native Machine Code.The
javaccompiler 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 (), which interprets or Just-In-Time () 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 ().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 ; range spanning to .short: Size of ; range spanning to .int: Size of ; range spanning to (). Standard default choice for whole numbers.long: Size of ; range spanning . Denoted with a trailingLsuffix (e.g.,270000000L).
Floating-Point Types (Bilangan Pecahan):
float: Size of ; provides single-precision storage ( significant decimal digits). Denoted with anfsuffix (e.g.,165.5f).double: Size of ; provides double-precision storage ( significant decimal digits). Default choice for floating-point calculations.
Character and Logical Types:
char: Size of ; stores a single Unicode character, enclosed strictly within single quote literals (e.g.,'A','O').boolean: Stores a binary logic state, taking exclusively eithertrueorfalse.
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 (
0to ). 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
Classes and Objects: A
classserves as a user-defined blueprint establishing data fields and methods. Anobjectis 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; 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 |
|
|
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
Stringobject cannot be altered. Operations that appear to mutate a String construct a newStringobject in memory.Built-in String Manipulation Methods:
length(): Returns character count:"Algoritma".length().toUpperCase(): Converts characters to uppercase:"java".toUpperCase().substring(int beginIndex, int endIndex): Extracts sub-string from indexainclusive tobexclusive:"Algoritma".substring(0, 4).charAt(int index): Returns the character at index:"Java".charAt(0).equals(Object anObject): Evaluates textual equality:"java".equals("Java").trim(): Strips leading and trailing whitespace:" Java ".trim().split(String regex): Splits text by delimiter into an array:"a,b,c".split(",").
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 ().-(Subtraction): Subtracts right operand from left ().*(Multiplication): Multiplies operands ()./(Division): Divides left operand by right. Crucial rule on integer truncation: Dividing twointoperands truncates all decimal remainders downwards (). To obtain decimal precision, at least one operand must be a floating-point type ().%(Modulus): Computes the integer remainder of division ().++(Increment): Increases integer value by .--(Decrement): Decreases integer value by .
Pre-Increment vs. Post-Increment:
Pre-increment (
++a): The variable is incremented by 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 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
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 * 3evaluates as . Conversely,(10 + 2) * 3evaluates as .
Relational (Rational) Comparison Operators:
Evaluate numerical relationships between operands and always return a primitive
boolean(trueorfalse).==: Tests equality ().!=: Tests inequality ().>: Greater than ().<: Less than ().>=: Greater than or equal to ().<=: Less than or equal to ().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 totrueif and only if both operands are true.||(Logical OR): Evaluates totrueif at least one operand is true.!(Logical NOT): Negates the operand's truth value (!truefalse).
Truth Tables for Logical Operators:
Operand A | Operand B | ( | ( | ( |
|---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Short-Circuit Evaluation Architecture:
In a logical AND (
A && B), if the primary conditionAevaluates tofalse, the secondary expressionBis skipped entirely, as the overall expression is guaranteed to be false.In a logical OR (
A || B), if the primary conditionAevaluates totrue, the secondary expressionBis 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"); } Becausepembagi != 0evaluates tofalse, 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; iffalse, execution bypasses the block with no alternate action.Pseudocode Structure:
text IF (kondisi) THEN instruksi END IF
Java Implementation:
java if (kondisi) { instruksi; } 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 discount if total purchases exceed :
Pseudocode:
text BEGIN INPUT totalBelanja IF totalBelanja > 500000 THEN totalBelanja <- totalBelanja - (totalBelanja * 0.1) END IF OUTPUT totalBelanja END
Trace Table:
Input | Condition ( | Output Result |
|---|---|---|
| (Discount applied) | |
| (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
Java Implementation:
java if (kondisi) { instruksi1; } else { instruksi2; } 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, ):
text BEGIN INPUT nilaiAkhir IF nilaiAkhir >= 60 THEN status <- "LULUS" ELSE status <- "TIDAK LULUS" END IF OUTPUT status END 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
Java Implementation:
java if (kondisi1) { instruksi1; } else if (kondisi2) { instruksi2; } else if (kondisi3) { instruksi3; } else { instruksi4; } 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 >= 60first causes scores of , , and 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 Trace Example (nilai = 75): * Step 1: Test75 >= 85false. Advance to next condition. * Step 2: Test75 >= 70true. Assignpredikat = "B"and exit ladder. * Step 3: Condition75 >= 60is skipped entirely.Pure Nested IF: Encapsulates an inner
ifstructure inside an outerifblock. The inner condition is evaluated only after the outer gatekeeping condition evaluates totrue.Worked Case (Credit Facility Approval: Age and Income ):
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"); }
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
Java Implementation:
java switch (variabel) { case nilai1: instruksi1; break; case nilai2: instruksi2; break; default: instruksiDefault; } Supported Java Data Types: Compatible with
byte,short,char,int,String, andenumtypes. 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. Omittingbreak;triggers fall-through, causing the runtime to execute subsequentcaseblocks unconditionally until abreakor 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" } Comparative Architectural Evaluation: Nested IF vs. Switch-Case:
Technical Parameter | Nested IF / Else-If Ladder | Case (Switch-Case) |
|---|---|---|
Evaluation Scope | Continuous ranges ( | 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 ( |
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 () 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 () 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 ( to ) 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 Javaswitch-caseblock.
Applied Algorithmic Problem Sets:
Exercise 1: Construct pseudocode to identify and return the maximum value among three arbitrary real numbers (, , ).
Exercise 2: Draft an ANSI standard flowchart calculating both the area () and circumference () of a circle given radius .
Exercise 3: Apply the six stages of the to engineer a temperature conversion program transforming degrees Celsius to Fahrenheit ( ).
Exercise 4: Formulate an algorithm in descriptive text and pseudocode determining leap year status (divisible by , excluding century years not divisible by ).
Exercise 5: Construct a flowchart and pseudocode algorithm evaluating a student's composite grade: assignments weight , midterm exam weights , and final exam weights .
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 - 1using 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 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 ( / IMT) into Kurus, Normal, Gemuk, and Obesitas categories.
Exercise 10: Write an algorithmic decision system utilizing a
switch-caseto convert letter grades ( ) to grade points ().Exercise 11: Construct a program that calculates freight shipping costs by combining a
switch-casefor destination city zones with a nestedifstructure based on parcel weight tiers.
Reference Bibliography
Primary Textbooks (Pustaka Utama):
Ramadhani, Cipta. (). Dasar Algoritma dan Struktur Data dengan Bahasa Java. Yogyakarta: Andi.
Untoro, Wisnu Yudo. (). Algoritma dan Pemrograman dengan Bahasa Java. Yogyakarta: Graha Ilmu.
Supporting Textbooks (Pustaka Pendukung):
Alsuwaiyel, M. H. (). Algorithms: Design Techniques and Analysis. Singapore: World Scientific.
Singh, Virender. (). Algorithm and Design Application. Oxford: Oxford University Press.