Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Modula2

Learn Modula2 - 10 Code Examples & CST Typing Practice Test

Modula-2 is a statically typed, modular, procedural programming language designed for systems programming and teaching structured programming concepts, created as a successor to Pascal.

View all 10 Modula2 code examples →
Modula-2 Counter and Theme ToggleModula-2 Random Number GeneratorModula-2 Todo ListModula-2 Dice RollerModula-2 Countdown TimerModula-2 Prime CheckerModula-2 Temperature ConverterModula-2 Shopping CartModula-2 Name GreetingModula-2 Stopwatch

Learn MODULA2 with Real Code Examples

Updated Nov 21, 2025

Explain

Modula-2 emphasizes modularity, strong typing, and separate compilation of modules.

It introduces a module system to organize code, enabling encapsulation and namespace management.

Widely used in academia for teaching structured and systems programming, and in embedded or systems-level applications.

Core Features

Procedures, functions, and type-safe operations

Modules with exported and hidden interfaces

Record and array data structures

Set, pointer, and enumeration types

Control structures: IF, CASE, WHILE, FOR, REPEAT

Basic Concepts Overview

Variables, constants, and types

Procedures and functions

Modules for encapsulation

Control structures (IF, CASE, loops)

Data structures: arrays, records, sets, pointers

Project Structure

Modules/ - source code files

Definitions/ - module interface files

Lib/ - standard or third-party libraries

Bin/ - compiled object files and executables

Docs/ - documentation and project notes

Building Workflow

Design program architecture using modules

Define interfaces in module definition files

Implement module procedures and functions

Compile individual modules separately

Link modules to form the final executable

Difficulty Use Cases

Beginner: small console-based Modula-2 programs

Intermediate: multi-module academic projects

Advanced: systems programming with OS or embedded targets

Expert: building compilers or modular software architectures

Enterprise: legacy systems requiring Modula-2 maintenance

Comparisons

Successor to Pascal with modular features

Stronger type safety and separate compilation

Less flexible than modern object-oriented languages

Excellent for structured and systems programming

Smaller ecosystem than C or Python

Versioning Timeline

1978 - Developed by Niklaus Wirth at ETH Zurich

1980s - Adopted in academic courses for structured programming

1985 - ISO standardization

1990s - Niche use in embedded and OS development

2025 - Primarily studied in computer science education

Glossary

Module: encapsulated code unit with interface and implementation

Procedure: subroutine with optional parameters

Record: structured data type

Pointer: reference to memory location

Separate compilation: compiling modules independently

Installation Setup

Obtain a Modula-2 compiler (e.g., XDS Modula-2, GNU Modula-2)

Install compiler on your OS (Windows, Linux, or macOS)

Set environment variables for compiler paths

Compile sample modules to ensure setup

Run a simple program to verify functionality

Environment Setup

Install Modula-2 compiler for your OS

Set environment variables for compiler paths

Create project directories for modules and binaries

Compile test modules to verify setup

Run sample programs to ensure correctness

Config Files

*.mod - module implementation

*.def - module definition/interface

*.m2 - project files (compiler-dependent)

Lib/ - libraries and modules

Bin/ - compiled binaries or object files

Cli Commands

m2c file.mod - compile module

m2link … - link modules into executable

m2run program - execute compiled program

m2doc file.mod - generate documentation

m2check file.mod - verify syntax and types

Internationalization

ASCII or Unicode support via compiler

Manual handling of text and localization

Resource files for messages (custom implementations)

No built-in i18n libraries

Used mostly in academic context with simple output

Accessibility

Readable syntax for beginners

Strong typing reduces programming errors

Clear separation of modules

Teaching-friendly for structured programming

Limited modern tooling or IDE support

Ui Styling

No built-in GUI support

CLI or embedded system interfaces only

Output formatting via text I/O

External libraries may provide GUI

Focus on structured code and modularity

State Management

Variables scoped to modules or procedures

Constants for immutable values

Encapsulation via exported/imported symbols

Pointer-based references for dynamic data

Module-level initialization routines

Data Management

Primitive types: INTEGER, BOOLEAN, REAL, CHAR

Structured types: ARRAY, RECORD, SET

Pointers for dynamic memory

I/O through standard libraries

Module-level constants and global variables

Architecture

Source code modules (.mod) and interface files (.def)

Compiler generates object code or executables

Module linking for separate compilation

Standard libraries for I/O and basic operations

Runtime system for memory management and program execution

Rendering Model

Parse source code and module definitions

Compile procedures and functions separately

Link modules to produce executable

Execute code with runtime system handling memory

Manage I/O through standard libraries

Architectural Patterns

Modular programming with interface/implementation separation

Procedural decomposition of tasks

Encapsulation via modules

Low-level memory access via pointers

Structured program control flow

Real World Architectures

Academic teaching of structured programming

Embedded system modules

Compiler and OS research projects

Modular libraries for algorithms

Legacy industrial control systems

Design Principles

Strong typing and type safety

Modular programming with separate compilation

Clear and readable syntax

Procedural and structured approach

Minimalist runtime and efficient execution

Scalability Guide

Organize large programs with multiple modules

Reuse common procedures in library modules

Minimize inter-module dependencies

Profile code for performance-critical sections

Apply modular design principles for maintainability

Migration Guide

Port Pascal code to Modula-2 for modularity

Separate monolithic code into modules

Adapt type declarations to strong typing

Replace procedural calls with module imports

Test module interfaces thoroughly

Performance Notes

Compiled code is efficient for systems programming

Separate compilation reduces rebuild times

Strong typing reduces runtime errors

Modules optimize namespace management

Low-level control allows memory-efficient programs

Security Notes

Type safety prevents many common programming errors

Pointer misuse can still lead to undefined behavior

Modules allow controlled exposure of procedures

No inherent protection for concurrency or threads

Secure coding depends on careful module design

Monitoring Analytics

Track module execution times

Debug pointer and array operations

Monitor memory usage manually

Log program output for correctness

Profile critical functions if needed

Code Quality

Follow consistent indentation and naming conventions

Use module interfaces for encapsulation

Document procedures and modules

Validate type correctness

Unit test modules independently

Practical Examples

Implementing a modular calculator

Creating a library of reusable procedures

Building simple file I/O applications

Developing a small embedded system module

Constructing compiler or interpreter components

Troubleshooting

Check module interface and implementation consistency

Ensure correct compilation order of modules

Verify type compatibility and procedure parameters

Debug pointer and record operations

Test module linkage for executable creation

Testing Guide

Test each module independently

Verify procedure inputs and outputs

Check record and pointer manipulations

Use sample datasets for functional testing

Validate module interfaces against definitions

Deployment Options

Compile and run executables on supported OS

Distribute source modules for educational use

Embed compiled modules in low-level systems

Include documentation and usage instructions

Archive for academic or archival purposes

Tools Ecosystem

XDS Modula-2 compiler

GNU Modula-2 compiler

Text editors for source code

Debugger tools (platform-dependent)

Sample libraries for teaching and systems

Integrations

Linking with C libraries (platform-dependent)

Embedded systems programming

Compiler or OS kernel development

Educational software for modular programming

Academic projects for algorithm demonstration

Productivity Tips

Organize code into reusable modules

Use descriptive procedure and variable names

Separate interface and implementation cleanly

Keep module dependencies minimal

Document interfaces for clarity

Challenges

Organize complex code into modules

Manage dependencies between modules

Debug pointer and record usage

Maintain type safety across modules

Apply Modula-2 concepts to systems-level tasks

Learning Path

Learn basic Pascal syntax

Understand modules and separate compilation

Practice writing procedures and functions

Explore records, arrays, and pointers

Build small modular projects

Skill Improvement Plan

Week 1: Variables, types, and control structures

Week 2: Procedures, functions, and modules

Week 3: Records, arrays, and pointers

Week 4: Multi-module projects and linking

Week 5: Systems programming exercises

Interview Questions

What is Modula-2 and how does it differ from Pascal?

Explain the module system in Modula-2.

How do you handle pointers and records?

Describe separate compilation and linking in Modula-2.

What are typical applications of Modula-2?

Cheat Sheet

MODULE Name; … END Name. - define module

IMPORT ModuleName; - use another module

VAR x: INTEGER; - declare variable

PROCEDURE Foo(); - define procedure

BEGIN … END; - block or program body

Books

Programming in Modula-2 by Niklaus Wirth

Modula-2: An Introduction to Modular Programming

The Programming Language Modula-2

Structured Programming with Modula-2

Systems Programming in Modula-2

Tutorials

Basic Modula-2 syntax and types

Procedures, functions, and control flow

Module interface and implementation

Records, arrays, sets, and pointers

Building multi-module programs

Official Docs

Niklaus Wirth Modula-2 publications

ISO/IEC 10514 standard documents

Compiler manuals (XDS Modula-2, GNU Modula-2)

Community Links

Modula-2 mailing lists

Academic forums for structured programming

GitHub repositories for Modula-2 projects

Compiler-specific forums

University course materials

Community Support

Modula-2 mailing lists

Academic forums and university courses

Legacy compiler communities

GitHub and source archives for reference

Documentation from Niklaus Wirth and ETH Zurich

Monetization

Academic teaching materials

Embedded system solutions

Legacy system maintenance

Consulting on structured programming

Specialized industrial applications

Future Roadmap

Mainly academic and legacy use

Focus on teaching structured programming concepts

Emphasis on modularity and readability

Potential archival and research projects

Integration with modern teaching tools for historic context

When Not To Use

Modern web or mobile development

GUI-intensive applications

High-level scripting or automation tasks

Projects requiring extensive third-party libraries

Enterprise software expecting active community support

Final Summary

Modula-2 is a modular, strongly typed procedural language.

Designed for systems programming, teaching, and structured software design.

Emphasizes separate compilation and module encapsulation.

Mostly used in academic and legacy contexts today.

Introduced concepts foundational to later languages like Oberon.

Faq

Is Modula-2 still used?

Mostly academic or legacy systems; active development is minimal.

Can Modula-2 handle low-level programming?

Yes, it supports pointers and system-level operations.

Does Modula-2 support modularity?

Yes, with a clear module interface and implementation separation.

Is Modula-2 object-oriented?

No, it is procedural and modular, not object-oriented.

Is Modula-2 cross-platform?

Compilers exist for Windows, Linux, and some legacy OSes.

Code Sample Descriptions

1

Modula-2 Counter and Theme Toggle

MODULE CounterTheme;

VAR
    count: INTEGER := 0;
    isDark: BOOLEAN := FALSE;

PROCEDURE updateUI;
BEGIN
    WriteString("Counter: "); WriteInt(count, 0); WriteLn;
    IF isDark THEN
        WriteString("Theme: Dark"); WriteLn
    ELSE
        WriteString("Theme: Light"); WriteLn;
    END;
END updateUI;

PROCEDURE increment;
BEGIN
    count := count + 1;
    updateUI;
END increment;

PROCEDURE decrement;
BEGIN
    count := count - 1;
    updateUI;
END decrement;

PROCEDURE reset;
BEGIN
    count := 0;
    updateUI;
END reset;

PROCEDURE toggleTheme;
BEGIN
    isDark := NOT isDark;
    updateUI;
END toggleTheme;

BEGIN
    updateUI;
    increment;
    increment;
    toggleTheme;
    decrement;
    reset;
END CounterTheme.

Demonstrates a simple counter with theme toggling using Modula-2 variables and procedures.

Let’s Try →
2

Modula-2 Random Number Generator

MODULE RandomGen;
IMPORT InOut;
VAR i, num: INTEGER;
BEGIN
    FOR i := 1 TO 3 DO
        num := RANDOM(100) + 1;
        InOut.WriteString("Random "); InOut.WriteInt(i,0); InOut.WriteString(": "); InOut.WriteInt(num,0); InOut.WriteLn;
    END;
END RandomGen.

Generates random numbers between 1 and 100 and prints them.

Let’s Try →
3

Modula-2 Todo List

MODULE TodoList;
IMPORT InOut;
VAR todos: ARRAY 10 OF ARRAY 50 OF CHAR; count: INTEGER := 0;

PROCEDURE addTask(task: ARRAY OF CHAR);
BEGIN
    todos[count] := task; count := count + 1;
    FOR i := 0 TO count-1 DO InOut.WriteString(todos[i]); InOut.WriteLn END;
END addTask;

PROCEDURE removeTask(idx: INTEGER);
VAR i: INTEGER;
BEGIN
    FOR i := idx TO count-2 DO todos[i] := todos[i+1] END;
    count := count - 1;
    FOR i := 0 TO count-1 DO InOut.WriteString(todos[i]); InOut.WriteLn END;
END removeTask;

BEGIN
    addTask("Buy milk");
    addTask("Write Modula-2 code");
    removeTask(0);
END TodoList.

Maintains a simple todo list with add and remove functionality.

Let’s Try →
4

Modula-2 Dice Roller

MODULE DiceRoll;
IMPORT InOut;
VAR i, roll: INTEGER;
BEGIN
    FOR i := 1 TO 3 DO
        roll := RANDOM(6) + 1;
        InOut.WriteString("Roll "); InOut.WriteInt(i,0); InOut.WriteString(": "); InOut.WriteInt(roll,0); InOut.WriteLn;
    END;
END DiceRoll.

Rolls a six-sided dice three times.

Let’s Try →
5

Modula-2 Countdown Timer

MODULE Countdown;
IMPORT InOut;
VAR count: INTEGER;
BEGIN
    count := 5;
    WHILE count >= 0 DO
        InOut.WriteString("Countdown: "); InOut.WriteInt(count,0); InOut.WriteLn;
        count := count - 1;
    END;
    InOut.WriteString("Done!"); InOut.WriteLn;
END Countdown.

Counts down from 5 to 0.

Let’s Try →
6

Modula-2 Prime Checker

MODULE PrimeCheck;
IMPORT InOut;
VAR nums: ARRAY 3 OF INTEGER := [7,10,13];
VAR n, i: INTEGER;
VAR isPrime: BOOLEAN;
BEGIN
    FOR n IN nums DO
        isPrime := TRUE;
        FOR i := 2 TO n-1 DO
        IF n MOD i = 0 THEN isPrime := FALSE END;
        END;
        InOut.WriteInt(n,0);
        IF isPrime THEN InOut.WriteString(" is Prime") ELSE InOut.WriteString(" is Not Prime") END;
        InOut.WriteLn;
    END;
END PrimeCheck.

Checks if numbers are prime.

Let’s Try →
7

Modula-2 Temperature Converter

MODULE TempConv;
IMPORT InOut;
VAR c,f: REAL;

PROCEDURE cToF(c: REAL): REAL;
BEGIN RETURN c*9/5+32 END cToF;

PROCEDURE fToC(f: REAL): REAL;
BEGIN RETURN (f-32)*5/9 END fToC;

BEGIN
    InOut.WriteString("25°C = "); InOut.WriteReal(cToF(25),2); InOut.WriteLn;
    InOut.WriteString("77°F = "); InOut.WriteReal(fToC(77),2); InOut.WriteLn;
END TempConv.

Converts Celsius to Fahrenheit and Fahrenheit to Celsius.

Let’s Try →
8

Modula-2 Shopping Cart

MODULE ShoppingCart;
IMPORT InOut;
VAR cart: ARRAY 10 OF ARRAY 50 OF CHAR; prices: ARRAY 10 OF INTEGER; count: INTEGER := 0;

PROCEDURE addItem(item: ARRAY OF CHAR; price: INTEGER);
BEGIN
    cart[count] := item; prices[count] := price; count := count + 1;
    (* print cart and total *)
END addItem;

PROCEDURE removeItem(idx: INTEGER);
VAR i: INTEGER;
BEGIN
    FOR i := idx TO count-2 DO cart[i] := cart[i+1]; prices[i] := prices[i+1] END;
    count := count -1;
    (* print cart and total *)
END removeItem;

BEGIN
    addItem("Apple", 2);
    addItem("Banana", 3);
    removeItem(0);
END ShoppingCart.

Adds and removes items in a shopping cart with total cost.

Let’s Try →
9

Modula-2 Name Greeting

MODULE Greet;
IMPORT InOut;
PROCEDURE greet(name: ARRAY OF CHAR);
BEGIN
    InOut.WriteString("Hello, "); InOut.WriteString(name); InOut.WriteString("! Welcome!"); InOut.WriteLn;
END greet;

BEGIN
    greet("Saurav");
    greet("Alice");
    greet("Bob");
END Greet.

Greets users by name.

Let’s Try →
10

Modula-2 Stopwatch

MODULE Stopwatch;
IMPORT InOut;
VAR time: INTEGER := 0;
BEGIN
    WHILE time < 5 DO
        InOut.WriteString("Stopwatch: "); InOut.WriteInt(time,0); InOut.WriteLn;
        time := time + 1;
    END;
    InOut.WriteString("Done!"); InOut.WriteLn;
END Stopwatch.

Simulates a stopwatch incrementing seconds.

Let’s Try →

Frequently Asked Questions about Modula2

What is Modula2?

Modula-2 is a statically typed, modular, procedural programming language designed for systems programming and teaching structured programming concepts, created as a successor to Pascal.

What are the primary use cases for Modula2?

Teaching structured and modular programming. Systems programming and embedded applications. Operating system and compiler development. Prototyping modular software architectures. Applications requiring strong type safety

What are the strengths of Modula2?

Enforces disciplined programming with strong typing. Supports modular software design. Good for systems programming and low-level operations. Readable syntax similar to Pascal. Facilitates separate compilation and encapsulation

What are the limitations of Modula2?

Limited modern library ecosystem. Mostly academic or legacy use today. No native support for GUI programming. Not widely adopted in industry. Less flexible compared to modern object-oriented languages

How can I practice Modula2 typing speed?

CodeSpeedTest offers 10+ real Modula2 code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.