Chapter 4.3: Introduction to Programming

Computer Fundamentals and Introduction to Programming
LanguagesTranslationProblem solvingSoftware processBasic constructs
Sercan KÜLCÜ · Giresun University

Introduction

Learning Outcomes

Concepts

Distinguish source code, machine language and programming languages.

Execution

Explain compiled, interpreted and hybrid execution.

Problem solving

Follow the path from algorithm to program.

Constructs

Recognize variables, decisions, loops, functions and arrays.

Basic Concepts

What Is a Programming Language?

  • A formal language that lets people express the steps a computer should carry out.
  • Syntax defines which constructs can be written; semantics defines what they do.
  • The same problem can be solved in different languages; the choice depends on requirements and environment.
Algorithm: add a and b, printJavaSystem.out.println(a + b);Pythonprint(a + b)Cprintf("%d", a + b);Output: 8for a = 3, b = 5

Basic Concepts

Source Code and Machine Language

Source codepeople read and write itsum = a + b;compiler translatesAssemblysymbolic names for instructionsLOAD R1, a · ADD R1, b · STORE R1, sumassembler translatesMachine languagethe CPU runs it (binary)0001 0001 1000 · 0011 0001 1001 · 0010 0001 1010Illustrative machine code (real encodings depend on the CPU).
  • Source code is the program text a developer can read and edit; machine language is the binary instructions the CPU executes.
  • A compiler or interpreter bridges the gap: the programming language and the processor's language are not the same thing.

Execution · Step by step

How Does a Program Run?

Source codeAdd.javaTranslatecompilerMachine / bytecodeAdd.classExecutionCPU / JVMOutput8

The programmer writes the source code in a text file. The computer cannot run this text directly.

Source codeAdd.javaTranslatecompilerMachine / bytecodeAdd.classExecutionCPU / JVMOutput8✗ compile error

Translation: the compiler checks the syntax. A forgotten semicolon causes a compile error here, and the program never runs.

Source codeAdd.javaTranslatecompilerMachine / bytecodeAdd.classExecutionCPU / JVMOutput8

If there are no errors, machine code is produced, or, as in Java, intermediate code (bytecode).

Source codeAdd.javaTranslatecompilerMachine / bytecodeAdd.classExecutionCPU / JVMOutput8✗ runtime error

Execution: the instructions run on the CPU (in Java, via the JVM). Runtime errors such as division by zero show up here.

Source codeAdd.javaTranslatecompilerMachine / bytecodeAdd.classExecutionCPU / JVMOutput8

The output depends on the input (a = 3, b = 5) and on the program's logic. With a logic error, the program runs but gives a wrong result.

Kinds of errors: compile-time (a syntax rule), runtime (during execution), logic (a wrong result).

Execution

Ways to Run a Program

ApproachHow it worksExample
CompiledTranslated ahead of time into the target machine codeC, C++, Rust
InterpretedStatements are evaluated while the program runsPython, JavaScript
HybridIntermediate code runs on a virtual machineJava, C#
Compiledsource.ccompilerprogram.exeCPUInterpretedsource.pyinterpreterCPUHybrid (Java)Add.javajavacAdd.classJVMCPUorange: translation tool

Execution · Step by step

Compiler and Interpreter Step by Step

Compiler: translate everything first, then run1print "Hello"translating2x ← 10translating3print x / 0translatingconsole

The compiler reads the whole program from start to end; no line has run yet.

Compiler: translate everything first, then run1print "Hello"✓2x ← 10✓3print x / 0✓console

Dividing by zero on line 3 is not a syntax error; translation succeeds and an executable file is produced.

Compiler: translate everything first, then run1print "Hello"▶ running2x ← 10✓3print x / 0✓consoleHello

Now execution starts: line 1 → output Hello.

Compiler: translate everything first, then run1print "Hello"✓2x ← 10✓3print x / 0✗ errorconsoleHelloERROR

Line 3 causes a runtime error (division by zero), the kind of error a compiler cannot catch.

Interpreter: translate and run line by line1print "Hello"▶ running2x ← 103print x / 0consoleHello

An interpreter works in a translate-run loop: line 1 is translated and run at once → Hello.

Interpreter: translate and run line by line1print "Hello"✓2x ← 10▶ running3print x / 0consoleHello

Line 2 is translated and run: x = 10. Line 3 has not even been read.

Interpreter: translate and run line by line1print "Hello"✓2x ← 10✓3print x / 0✗ errorconsoleHelloERROR

At line 3, an error. The earlier lines have already run. A simple line-by-line interpreter would notice even a syntax error only on reaching that line.

A compiler catches syntax errors before the program runs; an interpreter starts at once and (in simple interpreters) sees an error only on reaching that line. Modern interpreters such as Python and JavaScript parse the whole file first and report syntax errors up front; Python also compiles to bytecode.

Execution

Why Is Python Called “Interpreted”?

Source code (.py)
Bytecode
(compile)
Virtual machine
(execute)
  • CPython first compiles the source to bytecode, then executes it instruction by instruction on a virtual machine; no machine-code file is produced.
  • The “interpreted” label comes from this way of executing; the compile step is hidden from the programmer.
  • Modern JavaScript engines (e.g. V8) use a JIT: they translate frequently run code into machine code while the program runs.
JavaScript engine (e.g. V8): interprets first, then JIT-compiles hot code into machine codeSource code.jsInterpreterruns instruction by instructionhot codeJIT compilertranslates while runningMachine codedirectly on the CPULater calls skip interpretation; the program speeds up as it runs.
Compiled versus interpreted is a property of the implementation, not the language; in practice most systems combine both.

Execution · Step by step

Phases of a Compiler

LexicalanalysisSyntaxanalysisSemanticanalysisIR andoptimizationCodegenerationSource line:area = width * height + 2;areaidentifier=operatorwidthidentifier*operatorheightidentifier+operator2literal;separatorwhitespace dropped · 8 tokens · each token has a known kind

Lexical analysis: the character stream is split into meaningful pieces called tokens; whitespace and comments are dropped. A character the language lacks, such as #, or an unclosed string is caught here.

LexicalanalysisSyntaxanalysisSemanticanalysisIR andoptimizationCodegeneration=area+*2widthheight* is deeper:computed firstroot of the tree: assignment

Syntax analysis: the tokens are arranged into a syntax tree by the language's grammar. A missing ; or an unclosed parenthesis is caught at this phase.

LexicalanalysisSyntaxanalysisSemanticanalysisIR andoptimizationCodegenerationwidth→ declared · type int ✓height→ declared · type int ✓width * height + 2→ int × int + int → int ✓area ← int→ area is int: types match ✓if height were never declared → error: cannot find symbol

Semantic analysis: checks that names are declared and types are compatible. Undefined variables and type mismatches are found here.

LexicalanalysisSyntaxanalysisSemanticanalysisIR andoptimizationCodegenerationthree-address codet1 = width * heightt2 = t1 + 2area = t2optimization exampleif width = 3, height = 4 are constant:area = 14computed before runningconstant folding: operations whose result never changes are done at compile time

Intermediate code and optimization: the expression is broken into simple instructions that each do one operation; unnecessary work is removed and constant expressions are precomputed.

LexicalanalysisSyntaxanalysisSemanticanalysisIR andoptimizationCodegenerationtarget CPU instructionsLOAD R1, widthMUL R1, heightADD R1, #2STORE R1, areato binarymachine code0001 0001 1000 …javac produces bytecode instead:iload iload imul iconst_2 iadd istore

Code generation: instructions for the target CPU are chosen and encoded in binary. The Java compiler's target is not a real CPU but the JVM.

The first three phases look for errors and report them with a line number; the last two produce the code that runs. No phase catches value-dependent errors such as division by zero.

Execution

Linker and Loader

main.ccalc.ccompilereach file separatelymain.ocalc.olibraryprecompiled codelinkerprogram.exeloader (OS)memory → CPUobject files (.o / .obj) cannot run on their own
  • Large programs consist of many source files; the compiler turns each into a separate object file.
  • The linker combines the object files and any library code used into one executable. If a called function is defined nowhere, it reports a link error.
  • The loader is part of the operating system: it brings the file into memory, attaches shared libraries (.dll, .so) and starts execution at the first instruction.
  • Java has no separate link step: the JVM's class loader loads .class files as they are needed.

Execution

Compile or Interpret?

CriterionCompiled (C)Interpreted (Python)Hybrid (Java)
SpeedUsually fastest: direct machine codeSlower: statements are decoded at run timeClose to compiled, thanks to the JIT
Error reportingSyntax and type errors before runningType errors usually only when that line runsMost at compile time, the rest while running
DistributionA separate file for each OS and CPUSource code + an interpreter installed on the targetOne .class / .jar + a JVM on every platform
Development cycleRecompile after every changeSave and run at onceCompile, then run
StartupStarts at once, no extra softwareThe interpreter loads firstThe JVM starts first
It is a trade-off: speed and early error checking on one side, quick experiments and flexibility on the other. That is why one language can have both a compiler and an interpreter.

Languages

Language Levels

Machine language10110000 01100001AssemblyMOV AL, 61hCx = x + 1;Java, C#System.out.println(x);Pythonprint(x)more abstraction, closer to human language →← closer to hardware, finer control
  • Low-level languages are close to the hardware; high-level languages let you express a problem in human terms.
  • Level describes the degree of abstraction, not whether a language is good or bad.

Languages

The Evolution of Programming Languages

19501960197019801990200020102020Assembly1949FORTRAN1957COBOL1959BASIC1964C1972C++1983Python1991Java, JavaScript1995C#2000Go2009Rust 1.02015
1940–1970

Machine language and assembly; the first high-level languages, FORTRAN and COBOL.

1970–1990

C brought structured, portable systems programming; C++ added the object-oriented approach.

After 1990

Python, Java, JavaScript, C#: the web, managed runtimes, open-source ecosystems.

Languages

Application Areas

Web

Clients, servers and web services.

Mobile

Phone and tablet apps.

Data and AI

Analysis, modeling and automation.

Systems

Operating systems, drivers and embedded software.

Scientific computing

Simulation and engineering solutions.

Games

Game engines, graphics and interaction.

Languages

Kinds of Languages

General-purpose

Offer variables, decisions, loops and functions for any problem: Java, C, Python.

for (int i = 0; i < 3; i++)
Domain-specific

Focus on one job: SQL queries a database, an Excel formula computes in a cell.

SELECT name FROM student WHERE avg >= 60;
Scripting languages

Automate repetitive tasks, usually interpreted: Python, JavaScript, Bash, PowerShell.

Copy-Item *.txt backup\
Markup languages

HTML, XML and Markdown describe the structure of content; with no decisions or loops, they are not programming languages.

<h1>Title</h1>

In block-based languages such as Scratch, you drag blocks to build programs; since syntax errors are impossible, they are used to teach programming.

Languages

Programming Paradigms

  • The imperative approach states step by step how the work is done.
  • The object-oriented approach combines data and behavior in objects.
  • The functional approach emphasizes transformations and immutable data.
  • Java can combine several approaches.
One task, three approaches: the sum of the array grades = {70, 90, 80} (240)ImperativeObject-orientedFunctionalint sum = 0;for (int n : grades) sum += n;sum: 0 → 70 → 160 → 240state changes step by stepstudent : Studentgrades = {70, 90, 80}sum() → 240student.sum()data and behavior together{70, 90, 80}sum240Arrays.stream(grades).sum()a transformation; the array is unchanged

Languages

Choosing a Language

  • Consider the problem domain and the target platform.
  • Weigh the library ecosystem, the community and the maintenance cost.
  • Think about performance, security, team experience and deployment together.
Problem domain / platformCommon choicesWeb front end (browser)JavaScript, TypeScriptAndroid appKotlin, JavaiOS appSwiftData analysis, AIPython, REmbedded systems, driversC, C++, RustEnterprise serverJava, C#, GoThe final call depends on the library ecosystem, performance, security, team experience and maintenance cost.
Popularity alone is not enough to pick the right language.

Languages

Static and Dynamic Typing

Java: static

int x = 5;
x = "five";   // won't compile
error: incompatible types:
String cannot be converted to int

Python: dynamic

x = 5
x = "five"    # fine
print("a" + 1)
TypeError: can only concatenate
str (not "int") to str
  • With static typing, a variable's type is declared in the source and checked at compile time: Java, C, C#. Errors are found before the program ever runs.
  • With dynamic typing, the type travels with the value and is checked at run time: Python, JavaScript. The same name can hold a number, then text; Python reports the error only when that line runs.
  • Some languages convert types silently: in JavaScript "5" * 2 → 10, but "5" + 2 → "52".

Languages

From Pseudocode to Languages

PseudocodeJavaPython
read xx = in.nextInt();x = int(input())
print "Sum: ", tSystem.out.println("Sum: " + t);print("Sum:", t)
x ← x + 1x = x + 1;x = x + 1
if x > 0 then … else …if (x > 0) { … } else { … }if x > 0: … else: …
for each i ← 1 … nfor (int i = 1; i <= n; i++)for i in range(1, n + 1):
while condition is true, repeatwhile (cond) { … }while cond:
  • Java marks blocks with braces, Python with indentation; in Python, wrong indentation changes the program's meaning.
  • Java ends every statement with ; and requires variable types to be declared; Python requires neither.
  • Pseudocode uses ← for assignment so it is not confused with equality. In Java, in is a Scanner object reading from the keyboard.

Problem Solving · Step by step

From Problem to Program

Define the problemInput: width, heightOutput: areaConstraint: width, height > 0Try examples3, 4 → 125, 5 → 25width 0 → invalidBuild the algorithmread width, heightarea ← width × heightprint areaTranslate to codearea = width * height;println(area);(Java)Test3, 4 → 12 ✓-2, 4 → -8 ✗→ add a constraint check

First pin down what is asked: the area of a rectangle. Write the input, output and constraint.

Define the problemInput: width, heightOutput: areaConstraint: width, height > 0Try examples3, 4 → 125, 5 → 25width 0 → invalidBuild the algorithmread width, heightarea ← width × heightprint areaTranslate to codearea = width * height;println(area);(Java)Test3, 4 → 12 ✓-2, 4 → -8 ✗→ add a constraint check

Solve a few examples by hand; consider the boundary case (0) too.

Define the problemInput: width, heightOutput: areaConstraint: width, height > 0Try examples3, 4 → 125, 5 → 25width 0 → invalidBuild the algorithmread width, heightarea ← width × heightprint areaTranslate to codearea = width * height;println(area);(Java)Test3, 4 → 12 ✓-2, 4 → -8 ✗→ add a constraint check

Write a language-independent algorithm (pseudocode).

Define the problemInput: width, heightOutput: areaConstraint: width, height > 0Try examples3, 4 → 125, 5 → 25width 0 → invalidBuild the algorithmread width, heightarea ← width × heightprint areaTranslate to codearea = width * height;println(area);(Java)Test3, 4 → 12 ✓-2, 4 → -8 ✗→ add a constraint check

Translate the algorithm into the chosen language (Java).

Define the problemInput: width, heightOutput: areaConstraint: width, height > 0Try examples3, 4 → 125, 5 → 25width 0 → invalidBuild the algorithmread width, heightarea ← width × heightprint areaTranslate to codearea = width * height;println(area);(Java)Test3, 4 → 12 ✓-2, 4 → -8 ✗→ add a constraint checkgo back

Test: a negative input gave a wrong result → orange arrow: go back to the algorithm and add the step "error unless width, height > 0".

  • Each stage's output is the next stage's input.
  • A badly defined problem can become a program that works correctly but does the wrong job.

Problem Solving · Run the pseudocode step by step

Tracing the Algorithm: Rectangle Area

width3height—area—

Run 1: read width = 3; it goes into the memory box named "width".

width3height4area—

Read height = 4.

width3height4area—

Condition: 3 > 0 and 4 > 0 → true.

width3height4area12

area = 3 × 4 = 12.

width3height4area12

The result is printed. The "else" branch is skipped this time.

width-2height—area—

Run 2: read width = -2; it goes into the memory box named "width".

width-2height4area—

Read height = 4.

width-2height4area—

Condition: -2 > 0 and 4 > 0 → false (width is negative) → take the else branch.

width-2height4area—

A warning is printed; the area is never computed. The bug found in testing is now fixed.

read width
read height
if width > 0 and height > 0 then
    area ← width × height
    print "Area: ", area
else
    print "Invalid size"

Software · Step by step

The Software Development Process

1. Requirements2. Design3. Coding4. Test5. Deployment6. Maintenance

Requirements: what does the user want? E.g. "an app that computes a student's grade average".

1. Requirements2. Design3. Coding4. Test5. Deployment6. Maintenance

Design: plan the screens, data and algorithms (this is where flowcharts come in).

1. Requirements2. Design3. Coding4. Test5. Deployment6. Maintenance

Coding: implement the design in code.

1. Requirements2. Design3. Coding4. Test5. Deployment6. Maintenance

Testing: compare expected and actual results; if there are bugs, go back to coding.

1. Requirements2. Design3. Coding4. Test5. Deployment6. Maintenance

Deployment: deliver the program to users (installation, release).

1. Requirements2. Design3. Coding4. Test5. Deployment6. Maintenance

Maintenance: bugs are fixed and new requests arrive → the cycle restarts with new requirements.

  • Depending on the project, the stages can run in sequence or iteratively; user feedback can change the requirements and the design.

Software

Development Approaches

WaterfallRequirementsDesignCodingTestDistributionAgilecycle 1plan·code·testcycle 2plan·code·testcycle 3plan·code·testa working version + feedback at the end of each cycle
ApproachStrengthCaution
Waterfall modelClear stages and documentsGoing back for changes is costly
AgileGets feedback in short cyclesNeeds constant communication
PrototypingMakes vague requirements visibleDon't mistake the prototype for the product

Software

Development Tools

Code editor / IDE

Writing code, completion and project management.

Compiler / runtime

Translating and running the program.

Debugger

Inspecting program state step by step.

Version control

Change history and teamwork.

Testing tools

Checking expected behavior automatically.

Package manager

Managing dependencies.

One development round: each tool steps in at a different point of the cycleIDE / editorwriteCompilertranslate, runTesting toolsverifyDebuggerfind the bugfix and try againVersion control: records every changePackage manager: fetches libraries

Software

Version Control

C1first versionC2area addedC3perimeter addedC4mergeE1experiment branch: new calcmain brancheach commit: who, when, what changed
  • Each commit stores the files as they are at that moment, with who changed what and when. After a bad change you can go back to an earlier version.
  • A branch lets you experiment without breaking the main code; when the work is done, the branch is merged into the main branch.
  • Team members work on the same files; if two people change the same line, the tool flags the conflict and asks someone to choose.
  • The most widely used tool is Git; GitHub and GitLab are services that host repositories online.

Basic Constructs

Variables and Data Types

  • A variable is a named box in memory holding a value; the value can change while the program runs.
  • A data type fixes how a value is represented and which operations apply to it.
  • Meaningful names make a program's purpose visible.
age19type: integerheight1.75type: floating pointname"Ali"type: stringpassedtruetype: boolean

In Java: int, double, String, boolean.

Basic Constructs

Operator Precedence

  1. Parentheses
  2. Multiplication, division, mod (remainder)
  3. Addition, subtraction
  4. Equal levels go left to right
ExpressionResult
2 + 3 × 414
(2 + 3) × 420
20 / 4 × 210 (left to right)
10 − 4 − 33
7 mod 3 + 12
+2×34first: 12then: 2 + 12 = 14
Forget the parentheses in a formula and the program gives no error, just a wrong result: avg ← a + b / 2 divides b first. This is a logic error; only testing finds it.

Basic Constructs

Decisions and Loops

YesNocondition ?process Aprocess B

Decision: only one of two paths

YesrepeatNocondition ?bodyexit

Loop: an arrow going back

  • A decision picks one of several paths by a condition; a loop repeats a group of steps while a condition holds.
  • In both, it must be clear when the condition changes (otherwise: an infinite loop).

Basic Constructs · Run the pseudocode step by step

Loop Trace: An Infinite Loop

First version (no line 4)i1conditioni ≤ 3times the body ran0

First version: line 4 is missing. i ← 1 sets up the loop variable.

First version (no line 4)i1condition1 ≤ 3 → truetimes the body ran0

Condition 1 ≤ 3 → true: enter the loop body.

First version (no line 4)i1conditioni ≤ 3times the body ran1

print i → 1. The body is done; back to the condition.

First version (no line 4)i1condition1 ≤ 3 → truetimes the body ran1

The condition is again 1 ≤ 3 → true: no line in the body changes i.

First version (no line 4)i1conditioni ≤ 3times the body ran2

The same output again: 1. The state is identical to the previous round.

First version (no line 4)i1condition1 ≤ 3 → truetimes the body ran…↻ ∞

Nothing ever makes the condition false, so the loop never ends: an infinite loop. A console program can only be stopped with Ctrl+C.

Fixed versioni1conditioni ≤ 3times the body ran0

Fixed version: i ← i + 1 added to the body. Start again: i = 1.

Fixed versioni2condition1 ≤ 3 → truetimes the body ran1

1 ≤ 3 is true: print 1, then i ← 2. The loop variable now advances each round.

Fixed versioni3condition2 ≤ 3 → truetimes the body ran2

2 ≤ 3 is true: print 2, i ← 3.

Fixed versioni4condition3 ≤ 3 → truetimes the body ran3

3 ≤ 3 is also true (equality): print 3, i ← 4.

Fixed versioni4condition4 ≤ 3 → falsetimes the body ran3

Condition 4 ≤ 3 → false: leave the loop.

Fixed versioni4conditioni ≤ 3times the body ran3

The line after the loop: done. The body ran 3 times and the condition was checked 4 times.

i ← 1
while i ≤ 3 repeat
    print i
    i ← i + 1      // missing at first
print "done"

Basic Constructs

Functions and Arrays

4inputsquare(x)return x × xresult16grades array85[0]72[1]90[2]64[3]indices start at 0
  • A function names a task; it can take input and return a result.
  • An array stores many values of the same type, by index.
  • These constructs help split a program into small, testable pieces.

Basic Constructs · Run the pseudocode step by step

Function Trace: Call and Return

main programa = — b = —The definition is skipped; execution starts at line 5.area(3, 4) is about to be calledcall stack (the top frame is running)

A function definition is only recorded, not run. The program starts at line 5 and meets the call area(3, 4).

main programa = — b = —areawidth = 3 height = 4A new frame opened.arguments copied into parameterscall stack (the top frame is running)

A new frame for area is pushed onto the call stack: 3 → width, 4 → height.

main programa = — b = —areawidth = 3 height = 4 result = 12result ← 3 × 4 = 12call stack (the top frame is running)

The body runs: result = 12. This variable lives only in this frame.

main programa = — b = —areawidth = 3 height = 4 result = 12return 12 ↓the frame will be removedcall stack (the top frame is running)

return result: 12 goes back to the caller and the function ends.

main programa = 12 b = —a ← 12width, height, result are gonecall stack (the top frame is running)

The frame is popped; the returned value is assigned to a: a = 12.

main programa = 12 b = —areawidth = 2 height = 5area(2, 5) calledsame function, new framecall stack (the top frame is running)

The same function is called with different arguments: a brand-new frame, width = 2, height = 5.

main programa = 12 b = —areawidth = 2 height = 5 result = 10result ← 2 × 5 = 10call stack (the top frame is running)

result = 10. The 12 from the previous call is not visible in this frame.

main programa = 12 b = —areawidth = 2 height = 5 result = 10return 10 ↓call stack (the top frame is running)

10 is returned and the frame closes.

main programa = 12 b = 10b ← 10call stack (the top frame is running)

The returned value is assigned to b: b = 10.

main programa = 12 b = 10print 12 + 10 → 22call stack (the top frame is running)

22 is printed. A function written once was used twice; the area formula lives in one place.

function area(width, height)
    result ← width × height
    return result
end
a ← area(3, 4)
b ← area(2, 5)
print a + b

Basic Constructs · Run the pseudocode step by step

Array Trace: Average of Grades

grades85[0]72[1]90[2]64[3]sum—

The array holds four grades under one name; cells are selected by the indices 0, 1, 2, 3.

grades85[0]72[1]90[2]64[3]sum0

sum ← 0: the accumulator starts at zero. Without a starting value, the sum would be undefined.

grades85[0]72[1]90[2]64[3]i = 0 ▼sum85

i = 0: grades[0] = 85 → sum = 0 + 85 = 85.

grades85[0]72[1]90[2]64[3]i = 1 ▼sum157

i = 1: grades[1] = 72 → sum = 85 + 72 = 157.

grades85[0]72[1]90[2]64[3]i = 2 ▼sum247

i = 2: grades[2] = 90 → sum = 157 + 90 = 247.

grades85[0]72[1]90[2]64[3]i = 3 ▼sum311

i = 3: grades[3] = 64 → sum = 247 + 64 = 311.

grades85[0]72[1]90[2]64[3]sum311avg = 77.75

The loop ends after 4 rounds. avg = 311 / 4 = 77.75. The last index is 3: length − 1.

grades85[0]72[1]90[2]64[3]sum311avg = 77.75

The result is printed. Had the loop reached grades[4], it would have gone past the end: a 4-element array has no cell 4.

grades ← [85, 72, 90, 64]
sum ← 0
for each i ← 0, 1, 2, 3 do
    sum ← sum + grades[i]
avg ← sum / 4
print "Average: ", avg

Basic Constructs

Libraries and APIs

Your programroot ← sqrt(16)print root → 4.0API: name, input, outputcall sqrt(16)returns 4.0LibraryNewton's method, floating-point details …internals hidden
  • A library is a collection of ready-made functions others have written and tested; it saves rewriting the same work in every program.
  • An API (application programming interface) defines the functions a library or service exposes, with their inputs and return values. Callers need not know the internals.
CallLanguageResult
Math.sqrt(16)Java4.0
Math.max(3, 8)Java8
len("Giresun")Python7

Debugging

Debugging Techniques

  • Reproduce the bug: does the same input trigger it every time?
  • Print intermediate values: print variables before and after the suspicious line.
  • Set a breakpoint: the program pauses at that line so you can inspect variables.
  • Step through: after each line, see which value changed.
  • Narrow it down: disable half the code and find which half holds the bug.
  • Explain it out loud: walking someone (or a toy on your desk) through the code line by line often reveals the bug.
DebuggerStepContinue1n1 ← 702n2 ← 853n3 ← 90▶avg ← n1 + n2 + n3 / 35print "Average: ", avgVariables: n1 = 70 n2 = 85 n3 = 90breakpoint: paused at line 4

Paused, the program shows that n3 / 3 = 30 will be computed: the average comes out as 185, but 81.67 is expected.

Debugging · Run the pseudocode step by step

Finding a Bug by Tracing: The Largest Number

Test 1: 7, 12, 5a7b12c5max—

Test 1: inputs 7, 12, 5; expected output 12.

Test 1: 7, 12, 5a7b12c5max0

max ← 0: a starting value for the largest.

Test 1: 7, 12, 5a7b12c5max77 > 0true → max = 7

7 > 0 is true: max = 7.

Test 1: 7, 12, 5a7b12c5max1212 > 7true → max = 12

12 > 7 is true: max = 12.

Test 1: 7, 12, 5a7b12c5max125 > 12false

5 > 12 is false: max stays. Output 12 ✓. One passing test does not prove a program correct.

Test 2: −5, −2, −9a-5b-2c-9max—

Test 2: all negative, −5, −2, −9; expected output −2.

Test 2: −5, −2, −9a-5b-2c-9max0

max ← 0. This value comes from none of the inputs.

Test 2: −5, −2, −9a-5b-2c-9max0-5 > 0 · -2 > 0 · -9 > 0all three false

All three comparisons are false: no input exceeds 0, so max never changes.

Test 2: −5, −2, −9a-5b-2c-9max0output 0, expected -2✗ logic error

Output 0 ✗. The trace points to the culprit: the starting value on line 2 comes from outside the inputs.

Fix: max ← aa-5b-2c-9max-2rerun with max ← a✓ Largest: -2

Fix: max ← a. max = −5 → −2 > −5 true, max = −2 → −9 > −2 false. Output −2 ✓. Test 1 is rerun as well: still 12.

read a, b, c
max ← 0
if a > max then max ← a
if b > max then max ← b
if c > max then max ← c
print "Largest: ", max

Debugging

Common Mistakes

MistakeExampleWhat happens?
Missing or wrong initial valuesum ← sum + x without initializing sumJava won't compile it; some languages compute with a garbage value
Off-by-one errorfor each i ← 1 … n − 1the last element is skipped, or one extra round runs
Infinite loopthe loop variable is not updated in the bodythe program never ends
Division by zeroavg ← sum / n, n = 0runtime error
Going past the end of an arraygrades[4] in a 4-element arrayruntime error
Forgetting parenthesesavg ← a + b / 2wrong result (logic error)
Not validating inputaccepting −3 as an agemeaningless results, errors in later steps
Boundary cases (0, an empty list, the smallest and largest values, negative numbers) expose most of these bugs.

Debugging

The Cost of Software Bugs

Ariane 5 (1996)

A 64-bit floating-point velocity value overflowed when converted to a 16-bit integer. The navigation software shut down; about 37 seconds after liftoff the rocket veered off course and broke up within seconds.

Mars Climate Orbiter (1999)

One piece of software produced thrust data in imperial units (pound-force·seconds) while another expected metric units (newton·seconds). The probe came too close to Mars and was lost.

Therac-25 (1985–1987)

A timing bug in a radiotherapy machine's software bypassed a safety check when the operator typed quickly; patients received massive radiation overdoses.

  • None of the three could be caught by a compiler: one was a boundary case, one a unit mismatch, one a timing-dependent logic error.
  • The shared lesson: test, try boundary cases, state units explicitly, and have someone else review the code.

Debugging

Readable Code

Works, but unreadable

a ← read()
b ← read()
c ← a*b/2
print c

The same program, readable

// triangle area = base × height / 2
base ← read()
height ← read()
area ← base × height / 2
print "Area: ", area
  • Meaningful names: area instead of c; the reader learns the variable's role from its name.
  • Consistent indentation and spacing: the bounds of nested blocks are visible at a glance.
  • A named constant instead of a magic number: VAT_RATE ← 0.20 instead of 0.20; when the rate changes, you fix one line.
  • Move repetition into a function: if the same formula appears in three places, every fix must be made three times.
  • A comment explains why the code does something, not what it does. Code is written once and read many times.

Summary

Chapter Summary

  • A programming language expresses an algorithm in a form the computer can execute.
  • Source code runs through compilation, interpretation or a hybrid process.
  • Languages are classified by level, kind and paradigm.
  • Software development is an iterative process from requirements to maintenance.
  • Variables, decisions, loops, functions and arrays are the basic programming constructs.
  • Bugs are found by testing with boundary cases and tracing the program step by step.
ProblemrequirementsAlgorithmfinite, clear stepsSource codeprogramming languagecompilationinterpretationRunning programCPU / virtual machinevariable · decision · loop · function · arraymaintenance and new requirements: the process is iterative

Summary

Review Questions

  1. What is the difference between source code and machine language?
  2. How do compiled and interpreted programs differ?
  3. Why can an algorithm be designed independently of a programming language?
  4. What is the purpose of software testing?
  5. How do the roles of a decision and a loop differ?
  6. What do the linker and the loader do to get a program running?
  7. When is a type error detected under static and under dynamic typing?
  8. How do the imperative and functional approaches express the sum of an array differently?
  9. Why does a loop become an infinite loop?

Summary

Exercises

  1. Classify these as compile-time, runtime or logic errors: forgetting a semicolon; dividing the sum by n + 1 instead of n for an average; dividing by zero.
  2. Write the input, output and constraints for the problem "compute the average of a student's three exam grades".
  3. Write pseudocode for the same problem and trace it with (70, 85, 90); the result should be 81.67.
  4. Add a perimeter calculation to the rectangle-area algorithm: perimeter = 2 × (width + height). What outputs do you expect for width = 3, height = 4?
  5. For a phone app, name one task done in each stage of the software development process.
  6. Classify Java, Python and C as compiled / interpreted / hybrid and draw their execution pipelines.
Hints
  1. In order: compile-time, logic, runtime.
  2. Input: three grades (0–100); output: the average.
  3. (70 + 85 + 90) / 3 = 81.67
  4. Area 12, perimeter 14.
  5. —
  6. C is compiled, Python interpreted, Java hybrid.

Summary

References

  • Sebesta, Concepts of Programming Languages, 12th ed., Pearson, 2019.
  • Aho, Lam, Sethi and Ullman, Compilers: Principles, Techniques, and Tools, 2nd ed., Addison-Wesley.
  • Sedgewick and Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016.
  • Downey and Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online edition).
  • Oracle, The Java Tutorials: Getting Started.

The End

Chapter 4.3: Introduction to Programming
Previous: Chapter 4.2: Flowcharts · Next: Chapter 5: Getting Started with Java
1 / 1Sercan KÜLCÜ. All rights reserved.