Chapter 3.1: Programming Languages
Introduction
Learning Outcomes
Explain the difference between machine language, assembly language and high-level languages.
Encode and decode binary instructions for a given instruction format.
Explain how the assembler and linker turn source code into an executable; read short programs that make system calls.
Explain why the same program is written differently for x86, 68000, ARM, PowerPC and different operating systems.
Compare compilers, linkers, interpreters and JIT.
Trace one algorithm in several languages and in 8086 assembly.
Software
Software
- Software makes the hardware work correctly, in concert and as intended.
- The operating system
- is the computer's core software;
- it manages the hardware and controls how other software runs.
- Programming languages
- exist to build software;
- there are many languages aimed at different fields.
- The evolution of programming languages mirrors the major advances in computer technology.
Software
Programming Languages: Levels
- Machine languages: the 0s and 1s the processor runs directly.
- Assembly languages: a symbolic (mnemonic) notation for machine instructions.
- High-level languages
- compiled: translated to machine language first, then run;
- interpreted: processed line by line at run time.
Software · Step by step
One Operation at Three Levels: x = a + b
MOV AX, [a] ; load a into AX ADD AX, [b] ; AX = AX + b MOV [x], AX ; store result in xEach line corresponds to one machine instruction.
A1 00 02 ; MOV AX, [0200h] 03 06 02 02 ; ADD AX, [0202h] A3 04 02 ; MOV [0204h], AXAddresses are stored low byte first (little-endian): 0200h →
00 02.Software · Step through the code
Code Trace: How Does x = a + b Run in Memory?
org 100h mov ax, [0200h] ; A1 00 02 add ax, [0202h] ; 03 06 02 02 mov [0204h], ax ; A3 04 02 ret ; C3
IP = 0100h. Fetch: A1 00 02 is read. A1 = “load a word from memory into AX”; the address bytes 00 02 → 0200h (little-endian).
Execute: the bytes at 0200h and 0201h are 15 00 → AX = 0015h (a = 21). IP = 0103h.
Fetch: 03 06 02 02 (4 bytes). 03 = ADD r16, r/m16; ModR/M 06 = “AX, direct address”; address 0202h.
Execute: b = 0027h (39) is read, AX = 15h + 27h = 003Ch (60). IP = 0107h.
Fetch: A3 04 02: A3 = “store AX to memory”, target address 0204h.
Execute: AX is written low byte first: 0204h ← 3C, 0205h ← 00. x = 60.
C3 = RET. The single C line x = a + b; became 3 instructions, 10 bytes of machine code.
Assumption: a = 0015h (21), b = 0027h (39); the data shares the code segment (COM program).
Machine Language
Machine Languages
- The lowest-level language, made of 0s and 1s; the only one the processor understands.
- Entirely processor- and hardware-dependent: machine code written for the 8086 does not run on ARM.
- ENIAC (1945), one of the first general-purpose electronic computers, was programmed directly in hardware with cables and switches.
- Today
- every processor family has its own machine language (instruction set);
- it is not used directly because it is impractical to read and write.
- Assembly languages reduce the dependence on machine language and make programming more human-friendly.
B0 05 mean “load 5 into AL”. On ARM the same job is encoded as a completely different 32-bit word.Machine Language
Designing a Sample Machine Language
| Opcode | Meaning |
|---|---|
0000 | HALT: stop the program |
0001 | ADD: addition |
0010 | SUB: subtraction |
0011 | AND: logical AND |
0100 | OR: logical OR |
- Instructions are 8 bits long.
- 4 registers: R0 =
00, R1 =01, R2 =10, R3 =11. - Meaning: dest ← dest op source.
- A 4-bit opcode can define at most 24 = 16 operations; 5 are used here.
0001 10 11 → ADD R2, R3 → R2 ← R2 + R3Machine Language
Sample Program: Splitting the Fields
| Machine code | Operation | Dest | Source | Meaning |
|---|---|---|---|---|
0001 0001 | ADD | R0 | R1 | R0 ← R0 + R1 |
0011 1011 | AND | R2 | R3 | R2 ← R2 AND R3 |
0100 0110 | OR | R1 | R2 | R1 ← R1 OR R2 |
0000 0000 | HALT | — | — | stop the program |
In hex: 11h, 3Bh, 46h, 00h.
Machine Language · Step through the code
Code Trace: The Sample Machine Program
Initial values (example). PC = 0: the first instruction is about to be fetched.
ADD R0, R1: 5 + 3 = 8 → R0. The source (R1) does not change.
AND R2, R3: 1100 AND 1010 = 1000 → R2 = 8. Only bits that are 1 on both sides survive.
OR R1, R2: 0011 OR 1000 = 1011 → R1 = 11.
HALT: the processor stops. Result: R0 = 8, R1 = 11, R2 = 8, R3 = 10.
0001 0001 ; ADD R0, R1 → R0 ← R0 + R1 0011 1011 ; AND R2, R3 → R2 ← R2 AND R3 0100 0110 ; OR R1, R2 → R1 ← R1 OR R2 0000 0000 ; HALT
Machine Language
Machine Language: Pros and Cons
Pros
- No translation needed; the processor runs it directly.
- Full control over the hardware.
- The smallest and (if written well) fastest code.
Cons
- Very hard to read, write and debug.
- Addresses are computed by hand; inserting one instruction breaks every jump address.
- Not portable: rewritten from scratch for each processor.
- A single bit error changes the program completely.
Assembly Languages
Assembly Languages
- Each machine instruction is written as a memorable mnemonic:
MOV AL, 5instead of10110000 00000101. - Each is tied to an architecture and instruction set: Intel x86, Motorola 68000, ARM, PIC and AVR each have their own assembly language.
- Microcontroller assembly languages are common in embedded systems and electronics.
- They let the programmer make the most of the hardware.
- The program that translates source code into machine language is the assembler.
Assembly Languages
From Source Code to a Running Program
The assembler's listing shows each line's address and machine code side by side:
Address Machine code Source 0100 B4 09 mov ah, 09h 0102 BA 0C 01 mov dx, offset msg 0105 CD 21 int 21h 0107 B8 00 4C mov ax, 4C00h 010A CD 21 int 21h 010C 57 65 6C ... msg db 'Welcome!$'
emu8086 runs all these steps with one key and produces the COM/EXE file directly.
Assembly Languages · Step through the code
Code Trace: The Assembler's Two Passes
org 100h mov ah, 09h mov dx, offset msg int 21h mov ax, 4C00h int 21h msg db 'Welcome!$'
Pass 1 only counts addresses. org 100h sets the location counter (LC) to 0100h; a directive generates no bytes.
mov ah, 09h takes 2 bytes → LC = 0102h. The bytes themselves are not written yet.
offset msg is a forward reference: msg is not defined yet, but the instruction is known to be 3 bytes → LC = 0105h.
int 21h (2), mov ax, 4C00h (3), int 21h (2): LC = 010Ch.
The label msg enters the symbol table with the current LC: msg = 010Ch. A 9-byte string → LC = 0115h.
Pass 2 starts over and generates the bytes: mov ah, 09h → B4 09.
offset msg now comes from the table: 010Ch → BA 0C 01 (address little-endian).
The remaining instructions: CD 21, B8 00 4C, CD 21.
The string's ASCII codes are written: 57 65 6C … 24 ('$'). The output is a 21-byte COM file; when run it prints Welcome!.
Assembly Languages
Assemblers and Their Syntax
| Assembler | Syntax · use |
|---|---|
| MASM | Intel · Microsoft, Windows |
| TASM | Intel · Borland, DOS |
| NASM | Intel · open source, cross-platform |
| GAS (as) | AT&T · GNU/Linux, gcc |
| emu8086 | Intel (MASM-like) · 8086 emulator, this course |
One instruction, two notations
; Intel: dest, source mov eax, 5 add eax, [ebx+4] # AT&T: source, dest movl $5, %eax addl 4(%ebx), %eax
In AT&T, registers take % and constants take $; the size is given by an instruction suffix (l = 32 bits).
Assembly Languages · Step through the code
x86 Assembly: Linux (32-bit, NASM)
Data section: the string plus a newline (10). len is computed as 16 by $ - hello.
The program starts at _start. EAX = 4: the sys_write system call number.
EBX = 1: the file descriptor to write to, stdout (the screen).
ECX = the string's address (not its contents).
EDX = 16 (10h): the number of bytes to write.
int 0x80: the kernel is called and the text is written. On return EAX = bytes written (16).
EAX = 1: sys_exit.
xor ebx, ebx: a number XORed with itself is 0 → exit code 0 (success). Shorter than mov ebx, 0.
The kernel ends the process with exit code 0; this call never returns.
section .data hello db 'Welcome, Linux!', 10 len equ $ - hello ; = 16 bytes section .text global _start _start: mov eax, 4 ; sys_write mov ebx, 1 ; stdout mov ecx, hello ; string address mov edx, len ; byte count int 0x80 ; call the kernel mov eax, 1 ; sys_exit xor ebx, ebx ; exit code 0 int 0x80
“Welcome, Linux!” is 15 bytes; the trailing newline (10) makes the string 16 bytes. equ $ - hello lets the assembler compute the length.
Assembly Languages
How Does a System Call Work?
| Environment | Call | Service number | Parameters |
|---|---|---|---|
| Linux 32-bit | int 0x80 | EAX (4 = write, 1 = exit) | EBX, ECX, EDX |
| Linux 64-bit | syscall | RAX (1 = write, 60 = exit) | RDI, RSI, RDX |
| MS-DOS | int 21h | AH (09h = print, 4Ch = exit) | DX, AL … |
| BIOS | int 10h | AH (0Eh = print char) | AL, BH … |
Assembly Languages · Step through the code
x86 Assembly: DOS (emu8086, COM)
org 100h: a COM program is loaded at offset 100h of its segment (the 256 bytes before it are the PSP). CS = DS = ES = SS.
AH = 09h: the DOS service “print a string ending in $”.
lea dx, msg: DS:DX points to the string. The code is 12 bytes (0100h–010Bh), so msg is at 010Ch.
int 21h: DOS prints characters until it sees '$' (the '$' itself is not printed).
AX = 4C00h: AH = 4Ch “terminate the program”, AL = 00h exit code.
The program ends and control returns to DOS. The data sits after the code, so the processor never mistakes it for instructions.
org 100h ; COM program mov ah, 09h ; DOS 09h: print string lea dx, msg ; DS:DX = address int 21h ; call DOS mov ax, 4C00h ; DOS 4Ch: exit int 21h msg db 'Welcome, DOS!$'
Service 09h expects a '$' terminator; the data goes after the code; placed before it, it would be executed. mov ax, 4C00h also clears AL (the exit code).
Assembly Languages
x86 Assembly: Windows (Win32 API, NASM)
extern MessageBoxA ; user32.dll extern ExitProcess ; kernel32.dll section .data msg db 'Welcome, Windows!', 0 section .text global _start _start: push 0 ; uType = MB_OK push msg ; lpCaption (title) push msg ; lpText (text) push 0 ; hWnd = NULL call MessageBoxA push 0 ; uExitCode = 0 call ExitProcess
- No system call: OS services are called as DLL functions.
- Parameters are pushed onto the stack right to left:
MessageBoxA(hWnd, lpText, lpCaption, uType)in C. - stdcall: the called function cleans up the stack.
- Strings end with 0 (C strings).
- Linking may need the decorated name:
_MessageBoxA@16(16 = parameter bytes).
Assembly Languages · Step through the code
Code Trace: Parameters onto the Stack
Start: ESP = 0012FF80h (sample value). The stack grows toward lower addresses.
push 0: ESP drops by 4; the last parameter (uType) is pushed first.
push msg: the address of the caption string is pushed.
push msg: the address of the text string.
push 0: the first parameter (hWnd) is pushed last → it sits on top. Parameters go on right to left.
call MessageBoxA: the return address is pushed and control jumps to the function; a message box opens.
When the user clicks OK, the function returns with ret 16: under stdcall the callee cleans the stack, so ESP is 0012FF80h again. EAX = 1 (IDOK).
push 0 + call ExitProcess: the process ends with exit code 0; this call never returns.
extern MessageBoxA extern ExitProcess section .data msg db 'Welcome...', 0 section .text global _start _start: push 0 ; uType push msg ; lpCaption push msg ; lpText push 0 ; hWnd call MessageBoxA push 0 ; uExitCode call ExitProcess
Assembly Languages
Motorola 68000 Assembly: Amiga
move.l 4.w,a6 ; a6 = ExecBase lea dosname(pc),a1 ; library name moveq #0,d0 ; any version jsr -552(a6) ; OpenLibrary() tst.l d0 beq.s quit ; failed → quit move.l d0,a6 ; a6 = DOSBase jsr -60(a6) ; Output() → d0 move.l d0,d1 ; file handle move.l #msg,d2 ; string address moveq #16,d3 ; byte count jsr -48(a6) ; Write(d1,d2,d3) move.l a6,a1 move.l 4.w,a6 jsr -414(a6) ; CloseLibrary() quit moveq #0,d0 ; return code 0 rts dosname dc.b 'dos.library',0 msg dc.b 'Welcome, Amiga!',10
- 8 data registers (
d0–d7) and 8 address registers (a0–a7); source, destination order. - Size suffixes:
.b,.w,.l; constants take#. - Services are called at negative offsets from the library base (
-48(a6)). - The library is opened, used and closed.
Assembly Languages
ARM Assembly: Linux (32-bit, GNU as)
.data msg: .ascii "Welcome, ARM!\n" len = . - msg @ 14 bytes .text .global _start _start: mov r7, #4 @ sys_write mov r0, #1 @ stdout ldr r1, =msg @ string address mov r2, #len @ byte count svc #0 @ call the kernel mov r7, #1 @ sys_exit mov r0, #0 @ exit code svc #0
- RISC: 16 registers (
r0–r15), fixed 32-bit instructions. - The service number goes in r7, parameters in r0–r2.
- Entering the kernel:
svc #0(formerlyswi). - Memory is read and written only with
ldr/str.
GNU as uses .ascii, not db; . - msg lets the assembler compute the length.
Assembly Languages
PowerPC (PPC) Assembly: Linux (32-bit)
.data msg: .ascii "Welcome, PowerPC!\n" len = . - msg # 18 bytes .text .globl _start _start: li 0, 4 # r0 = sys_write li 3, 1 # r3 = stdout lis 4, msg@ha # r4 = addr (high) addi 4, 4, msg@l # + low half li 5, len # r5 = byte count sc # call the kernel li 0, 1 # r0 = sys_exit li 3, 0 # r3 = exit code sc
- RISC: 32 general registers; GNU as writes registers as plain numbers (
3= r3). - The service number goes in r0, parameters in r3, r4, r5; the trap is
sc. - A 32-bit address is loaded in two 16-bit halves (
@ha,@l).
Assembly Languages
One “Welcome”, Six Environments
| Environment | Processor | Entering the OS | Service no. | Parameters | String end |
|---|---|---|---|---|---|
| Linux | x86 (32) | int 0x80 | EAX | EBX, ECX, EDX | length given |
| DOS | 8086 | int 21h | AH | DX (address) | '$' |
| Windows | x86 (32) | call to a DLL | function name | stack | 0 |
| AmigaOS | 68000 | jsr -48(a6) | library offset | d1, d2, d3 | length given |
| Linux | ARM | svc #0 | r7 | r0, r1, r2 | length given |
| Linux | PowerPC | sc | r0 | r3, r4, r5 | length given |
; on x86, @ in ARM GNU, # on PowerPC. The big win of high-level languages is handing this dependence to the compiler or interpreter.High-Level Languages
High-Level Languages
- Source code is translated to machine language ahead of time.
- Most errors are caught at compile time.
- The code runs faster.
- Stages: compiling (compiler) and linking (linker).
- The output is specific to one processor + operating system.
- Source code is processed by an interpreter at run time.
- Allows fast development and experimentation.
- Source code is platform-independent: it runs wherever an interpreter exists.
- Errors may only appear when the line in question runs.
- Usually slower.
High-Level Languages · Step by step
The Compilation Process (C, gcc)
#include and #define are expanded → oddeven.i (gcc -E)oddeven.s (gcc -S)oddeven.o (gcc -c)printf/scanf → executable oddeven / oddeven.exemain.In one command: gcc oddeven.c -o oddeven. To see the intermediate assembly: gcc -S -masm=intel oddeven.c.
High-Level Languages · Step through the code
Code Trace: A Loop the Compiler Generated
org 100h mov bx, 0 ; sum = 0 mov cx, 10 ; i = 10 cond: cmp cx, 0 ; i > 0 ? jle done add bx, cx ; sum += i sub cx, 3 ; i -= 3 jmp cond done: mov sum, bx ret sum dw ?
The compiler put the variables in registers: sum → BX, i → CX. The while condition is tested at the top of the loop.
cmp cx, 0 + jle: i = 10 > 0, so no jump; the body runs (the C condition was inverted into an “exit” jump).
Body: sum = 10, i = 7; jmp cond goes back to the test.
cmp cx, 0 + jle: i = 7 > 0, so no jump; the body runs (the C condition was inverted into an “exit” jump).
Body: sum = 17, i = 4; jmp cond goes back to the test.
cmp cx, 0 + jle: i = 4 > 0, so no jump; the body runs (the C condition was inverted into an “exit” jump).
Body: sum = 21, i = 1; jmp cond goes back to the test.
cmp cx, 0 + jle: i = 1 > 0, so no jump; the body runs (the C condition was inverted into an “exit” jump).
Body: sum = 22, i = -2; jmp cond goes back to the test.
i = -2: the condition i > 0 is false (i ≤ 0, SF ≠ OF) → jle done jumps and the loop exits.
The result is stored: sum = 22. One C loop became a compare, a conditional jump and an unconditional jump.
High-Level Languages · Compiled
Compiled Languages
- The compiler examines the whole source before it runs.
- Compiled code runs directly on the processor, so it is faster.
- Type and syntax errors are caught at compile time.
High-Level Languages · Step through the code
Task: Odd/Even from 1 to n — C
Every sample program does the same job: read a number, then print whether each number from 1 to it is odd or even.
The user enters 3. scanf gets the variable's address (&number).
The loop starts: i = 1, the condition 1 ≤ 3 is true.
1 % 2 = 1 ≠ 0 → the else branch: “odd”.
i++ → 2; 2 ≤ 3 is true.
2 % 2 = 0 → “even”.
i = 3; 3 ≤ 3 is true.
3 % 2 = 1 → “odd”.
i = 4; 4 ≤ 3 is false → the loop ends.
return 0: a “success” exit code for the operating system.
#include <stdio.h> int main() { int number; printf("Enter a number: "); scanf("%d", &number); for (int i = 1; i <= number; i++) { if (i % 2 == 0) { printf("%d is even.\n", i); } else { printf("%d is odd.\n", i); } } return 0; }
High-Level Languages · Compiled
C++
#include <iostream> int main() { int number; std::cout << "Enter a number: "; std::cin >> number; for (int i = 1; i <= number; i++) { if (i % 2 == 0) { std::cout << i << " is even." << std::endl; } else { std::cout << i << " is odd." << std::endl; } } return 0; }
- A superset of C; classes, templates, exceptions.
- Streams for I/O:
std::cout <<writes,std::cin >>reads. - Build:
g++ oddeven.cpp -o oddeven std::endladds a newline and flushes the buffer; for many lines'\n'is faster.
High-Level Languages · Compiled (to intermediate code)
C#
using System; class Program { static void Main() { Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); for (int i = 1; i <= number; i++) { if (i % 2 == 0) { Console.WriteLine($"{i} is even."); } else { Console.WriteLine($"{i} is odd."); } } } }
- The .NET platform; compiled to the IL intermediate language, which the CLR JIT-compiles to machine code at run time.
$"{i} …": string interpolation.- Run:
dotnet run int.Parsethrows an exception on non-numeric input;int.TryParseis safer.
High-Level Languages · Compiled (bytecode)
Java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); for (int i = 1; i <= number; i++) { if (i % 2 == 0) { System.out.println(i + " is even."); } else { System.out.println(i + " is odd."); } } } }
javac→ platform-independent bytecode (.class) → JIT on the JVM.- “Write once, run anywhere.”
- Run:
javac Main.javaandjava Main - Everything lives in a class; the file name = the
publicclass name.
High-Level Languages · Compiled
Go
package main import "fmt" func main() { var number int fmt.Print("Enter a number: ") fmt.Scan(&number) for i := 1; i <= number; i++ { if i%2 == 0 { fmt.Printf("%d is even.\n", i) } else { fmt.Printf("%d is odd.\n", i) } } }
- Compiles straight to machine code; one self-contained executable.
- A garbage collector and lightweight threads (goroutines).
- Run:
go run oddeven.go - No parentheses around conditions and loops;
:=infers the type.
High-Level Languages · Compiled
Rust
use std::io; fn main() { let mut input = String::new(); println!("Enter a number:"); io::stdin().read_line(&mut input) .expect("read error"); let number: i32 = input.trim().parse() .expect("parse error"); for i in 1..=number { if i % 2 == 0 { println!("{} is even.", i); } else { println!("{} is odd.", i); } } }
- Memory safety without a garbage collector: ownership rules are checked by the compiler.
- Variables are immutable by default; you need
mut. 1..=number: a range that includes the upper bound.- Run:
rustc oddeven.rsorcargo run
High-Level Languages · Compiled
Fortran
program Main implicit none integer :: number, i write(*,*) 'Enter a number:' read(*,*) number do i = 1, number if (mod(i, 2) == 0) then write(*,*) i, ' is even.' else write(*,*) i, ' is odd.' end if end do end program Main
- The first widely used high-level language: FORmula TRANslation.
- Still common in scientific computing (weather forecasting, physics).
implicit none: every variable must be declared explicitly.- Run:
gfortran oddeven.f90 -o oddeven write(*,*)uses free format; numbers may print with leading spaces.
High-Level Languages · Compiled
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Main is Number : Integer; begin Put ("Enter a number: "); Get (Number); for I in 1 .. Number loop Put (I, Width => 0); if I mod 2 = 0 then Put_Line (" is even."); else Put_Line (" is odd."); end if; end loop; end Main;
- Strong type checking; aviation and defense software.
- Run:
gnatmake main.adb - Integer
Get/PutneedAda.Integer_Text_IO;Put_Lineadds a newline.
High-Level Languages · Interpreted
Interpreted Languages
- Source code is interpreted at run time; there is no separate compile step.
- Fast development and experimentation (interactive shell, REPL).
High-Level Languages · Interpreted
Python
# Read input from the user number = int(input("Enter a number: ")) # Check the numbers from 1 to number for i in range(1, number + 1): if i % 2 == 0: print(f"{i} is even.") else: print(f"{i} is odd.")
- Blocks are marked by indentation, not braces.
range(1, number + 1): the upper bound is excluded, hence the +1.inputreturns text;int(...)converts it to a number.- Run:
python oddeven.py - Dynamically typed: a variable's type is decided at run time.
High-Level Languages · Interpreted (JIT)
JavaScript
// Read input from the user let number = Number(prompt("Enter a number:")); // Check the numbers from 1 to number for (let i = 1; i <= number; i++) { if (i % 2 === 0) { console.log(i + " is even."); } else { console.log(i + " is odd."); } }
- The language of browsers; runs on servers too with Node.js.
- Modern engines (V8) JIT-compile the code to machine code.
promptreturns text; convert it withNumber(...).===: equality without type conversion.
High-Level Languages · Interpreted
Ruby
# Read input from the user print "Enter a number: " number = gets.chomp.to_i # Check the numbers from 1 to number for i in 1..number do if i % 2 == 0 puts "#{i} is even." else puts "#{i} is odd." end end
- Everything is an object:
gets.chomp.to_iis a chain of method calls. chompdrops the newline,to_iconverts to an integer.1..number: a range that includes the upper bound."#{i}": string interpolation.- Run:
ruby oddeven.rb
High-Level Languages · Interpreted
PHP
<?php // Read input from the user echo "Enter a number: "; $number = (int) trim(fgets(STDIN)); // Check the numbers from 1 to number for ($i = 1; $i <= $number; $i++) { if ($i % 2 == 0) { echo $i . " is even.\n"; } else { echo $i . " is odd.\n"; } } ?>
- A server-side web language; can be embedded in HTML.
- Variables start with
$;.concatenates strings. fgets(STDIN)reads a line from the command line;trimdrops the newline.- Run:
php oddeven.php
High-Level Languages · Interpreted
Perl
use strict; use warnings; # Read input from the user print "Enter a number: "; my $number = <STDIN>; chomp $number; # Check the numbers from 1 to number for my $i (1..$number) { if ($i % 2 == 0) { print "$i is even.\n"; } else { print "$i is odd.\n"; } }
- Text processing and system administration; powerful regular expressions.
<STDIN>reads a line,chompdrops the newline.- In a double-quoted string
$iis replaced by its value. use strict; use warnings;catch common mistakes.- Run:
perl oddeven.pl
High-Level Languages · Interpreted
MATLAB
% Read input from the user number = input('Enter a number: '); % Check the numbers from 1 to number for i = 1:number if mod(i, 2) == 0 fprintf('%d is even.\n', i); else fprintf('%d is odd.\n', i); end end
- Matrix-based numerical computing; common in engineering, especially signal processing and control.
1:number: the vector 1, 2, …, number.- A
;at the end of a line suppresses printing the result. - A free, compatible alternative: GNU Octave.
High-Level Languages
One Program, Fourteen Languages
| Language | Model | Loop header | Remainder | Output |
|---|---|---|---|---|
| C | compiled | for (int i = 1; i <= n; i++) | i % 2 | printf |
| C++ | compiled | for (int i = 1; i <= n; i++) | i % 2 | std::cout << |
| C# | IL + JIT | for (int i = 1; i <= n; i++) | i % 2 | Console.WriteLine |
| Java | bytecode + JIT | for (int i = 1; i <= n; i++) | i % 2 | System.out.println |
| Go | compiled | for i := 1; i <= n; i++ | i%2 | fmt.Printf |
| Rust | compiled | for i in 1..=n | i % 2 | println! |
| Fortran | compiled | do i = 1, n | mod(i, 2) | write(*,*) |
| Ada | compiled | for I in 1 .. N loop | I mod 2 | Put_Line |
| Python | interpreted | for i in range(1, n + 1): | i % 2 | print |
| JavaScript | interpreted/JIT | for (let i = 1; i <= n; i++) | i % 2 | console.log |
| Ruby | interpreted | for i in 1..n do | i % 2 | puts |
| PHP | interpreted | for ($i = 1; $i <= $n; $i++) | $i % 2 | echo |
| Perl | interpreted | for my $i (1..$n) | $i % 2 | print |
| MATLAB | interpreted/JIT | for i = 1:n | mod(i, 2) | fprintf |
High-Level Languages
Compiled, Interpreted, Hybrid
| Criterion | Compiled | Interpreted | Hybrid (bytecode + JIT) |
|---|---|---|---|
| Translation time | once, before running | on every run | first to intermediate code, then at run time |
| Speed | highest | lowest | high (after warm-up) |
| What ships | machine code | source code | intermediate code (.class, .dll) |
| Portability | recompile for each platform | anywhere with an interpreter | anywhere with a virtual machine |
| Error detection | mostly at compile time | mostly at run time | type errors at compile time |
| Examples | C, C++, Go, Rust, Fortran, Ada | Python, Ruby, PHP, Perl, MATLAB | Java, C#, JavaScript (V8) |
High-Level Languages · Step through the code
Code Trace: How Does Bytecode Run?
// x = (a + b) * c; iload a // push a iload b // push b iadd // add the top two iload c imul // multiply the top two istore x // pop into x return
For x = (a + b) * c the compiler generated stack-based intermediate code (bytecode). Locals: a = 6, b = 7, c = 3. iload a: local a = 6 is pushed onto the stack.
iload b: local b = 7 is pushed onto the stack.
iadd: the top two items (6, 7) are popped and the sum 13 is pushed. No operand names; everything is on the stack.
iload c: local c = 3 is pushed onto the stack.
imul: 13 × 3 = 39 is pushed.
istore x: the top of the stack is stored in x → x = 39; the stack is empty.
This intermediate code is tied to no processor: the virtual machine (JVM, CLR) either interprets each instruction or JIT-compiles it into real machine code such as 8086/x86.
Bridge · Step through the code
The Same Task in 8086 Assembly (n = 3)
CX serves as the counter (i): i = 1. n = 3 is hard-coded; it is not read from the keyboard.
cmp cx, 3: computes 1 − 3 (the result is discarded) → ZF=0, CF=1 (borrow). ja jumps only if CF=0 and ZF=0 → no jump.
DL = 1 + 30h = 31h: the ASCII code of the digit 1. ADD updates the flags: CF=0.
DOS service 02h prints the character in DL.
test cl, 1: 1 AND 1 = 1 ≠ 0 → ZF=0 → jnz odd jumps. (The lowest bit instead of i % 2.)
DX = the address of the odd_m string; service 09h prints up to the '$'. 0Dh, 0Ah are carriage return + line feed.
inc cx → 2 (INC does not change CF); back to the top of the loop.
2 − 3: CF=1 → continue.
DL = 32h ('2') is printed.
2 AND 1 = 0 → ZF=1 → jnz does not jump: the number is even.
DX = even_m; jmp print goes to the shared print code.
The “even” message is printed.
CX = 3.
3 − 3 = 0 → ZF=1, CF=0. Since ZF=1, ja does not jump (3 ≤ 3).
'3' is printed; 3 AND 1 = 1 → ZF=0 → odd.
The “odd” message is printed.
CX = 4.
4 − 3 = 1 → ZF=0, CF=0 → ja done jumps (4 > 3).
ret: the COM program returns to DOS. C's for + if became pairs of compare + conditional jump.
org 100h
mov cx, 1 ; i = 1
again: cmp cx, 3 ; compare i with n
ja done ; done if i > n
mov dl, cl
add dl, '0' ; digit → ASCII
mov ah, 02h
int 21h ; print DL
test cl, 1 ; lowest bit
jnz odd ; 1 means odd
lea dx, even_m
jmp print
odd: lea dx, odd_m
print: mov ah, 09h
int 21h ; print string
inc cx ; i++
jmp again
done: ret
odd_m db ' is odd.',0Dh,0Ah,'$'
even_m db ' is even.',0Dh,0Ah,'$'
Summary
Summary
- Software runs the hardware; the operating system is the core software, and programming languages are used to build software.
- Machine language is the only language the processor understands: binary instructions made of opcode and operand fields; fully hardware-dependent.
- Assembly language writes machine instructions as mnemonics; the assembler and linker turn it into an executable. The code depends on both the processor and the operating system (int 0x80, int 21h, DLL calls, svc, sc).
- Compiled languages (C, C++, Go, Rust, Fortran, Ada) are translated to machine code ahead of time: fast, but platform-specific.
- Interpreted languages (Python, JavaScript, Ruby, PHP, Perl, MATLAB) are processed at run time: fast development, portable source, slower execution. Java/C# sit in between with intermediate code + JIT.
- A high-level
for/ifis implemented in assembly as compare + conditional jump.
Summary
Exercises
- Encode
SUB R3, R0andOR R0, R2in binary and hex. - Decode the instruction
0010 0111. If R1 = 9 and R3 = 4, what is the result? - How many opcodes fit in this design? How must the format change for 8 registers?
- What happens if the DOS program's string lacks the final
'$'? - In the Linux example, what would be printed if
lenwere hard-coded as 15? - Windows example: why are parameters pushed in reverse? What is ESP right after the
call? - Why can't Java be labeled simply “compiled” or “interpreted”?
Hints / answers
0010 1100= 2Ch;0100 0010= 42h.- SUB R1, R3 → R1 ← 9 − 4 = 5.
- 24 = 16. 8 registers need 3 bits each: 4 + 3 + 3 = 10 bits. To stay at 8 bits the opcode shrinks to 2 bits: only 4 operations fit, not five.
- DOS prints random bytes from memory until it hits the first '$' character.
- “Welcome, Linux!” is printed, but not the newline (the 16th byte).
- C convention: the first parameter must be on top; 4 pushes + return address → ESP = 0012FF80h − 20 = 0012FF6Ch.
- Compiled to bytecode, then interpreted or JIT-compiled on the JVM: a hybrid.
Summary
References
- Tanenbaum and Bos, Modern Operating Systems, 3rd ed., Pearson.
- Brey, The Intel Microprocessors, 8th ed., Pearson.
- Irvine, Assembly Language for x86 Processors, 7th ed., Pearson.
- NASM documentation (nasm.us) and the GNU Binutils as manual.
- Ralf Brown's Interrupt List (DOS INT 21h services); Microsoft Win32 API documentation (
MessageBoxA,ExitProcess). - emu8086 documentation and 8086 instruction set reference.