Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Certified Zig Programming Expert · Lesson 2 of 5

Module One

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
2
Certified Zig Programming Expert – Module One

Module One: Zig Foundations and Core Syntax – Your First Steps into Zig

“Certified Zig Programming Expert” – Master the language of modern systems programming

Module Introduction

Welcome, young programmer! Have you ever wondered how computer programs are made? Programs are written in special languages called programming languages. There are many languages, like Python, JavaScript, and C. Today, we are going to learn a very special language called Zig.

Zig is a modern programming language that is simple, fast, and safe. It is used to build operating systems, games, servers, and many other important programs. Zig was created to fix problems in older languages like C. It gives you control over your computer while keeping you safe from common mistakes.

In this module, we will start from the very beginning. You don't need any experience with programming. We will learn what Zig is, how to set it up, and how to write your first programs. We will learn about variables, data types, control flow, functions, structs, and more. By the end of this module, you will be able to write simple Zig programs with confidence.

Let's begin!

Learning Objectives

After finishing this module, you will be able to:

  • Explain what Zig is and why it is special.
  • Install Zig and set up your coding environment.
  • Write and run your first Zig program.
  • Use variables and constants.
  • Understand Zig's primitive data types.
  • Use control flow statements: if, while, for, switch.
  • Write and call functions.
  • Create and use structs and enums.
  • Work with arrays, slices, and strings.
  • Complete a mini project and practical assignment.

Warm-up Story: Chidi’s First Program

Chidi is 13 years old and lives in Lagos. He loves computers and wants to learn how to make his own programs. One day, his uncle, who is a software engineer, told him about a new language called Zig.

“Zig is amazing,” his uncle said. “It is simple, fast, and safe. It lets you build things that are very close to the computer's heart.” Chidi was curious. “Can I learn it?” he asked. “Of course!” his uncle replied. “Let's start today.”

Chidi’s uncle helped him install Zig on his computer. They opened a code editor and wrote a simple program. It printed the words “Hello, Zig!” on the screen. Chidi was so happy. He had written his first program!

Next, they learned about variables. Chidi created a variable called “name” and put his name in it. He created another variable called “age” and put his age in it. Then they learned about functions, structs, and arrays. Every new idea was like a new toy to play with.

By the end of the day, Chidi had written five small programs. He felt like a real programmer. “Zig is fun!” he said. His uncle smiled. “This is just the beginning. Keep learning, and you will build amazing things.”

Moral of the story: Programming is like learning a new language. Zig is a simple, powerful language that anyone can learn. Start with small steps, and you will go far.

Main Lessons

Lesson 1: What is Zig?

Definition: Zig is a modern programming language used to build fast, safe, and reliable software.

Why it is important: Zig is designed to fix problems in older languages and make programming simpler.

Simple explanation: Imagine you have a toolbox. Some tools are old and rusty. Zig is a new, shiny tool that works better.

Real-life example: Companies use Zig to build operating systems, web servers, and games.

School example: A student uses Zig to build a simple calculator program.

Home example: A family uses a Zig program to organize their shopping list.

Nigerian example: A Nigerian startup uses Zig to build a fast payment system.

Illustration:

  Zig = Modern Programming Language
        |
        V
  Simple, Fast, Safe
        |
        V
  Used for:
  - Operating systems
  - Web servers
  - Games
  - Tools
  

Mini summary: Zig is a modern programming language. It is simple, fast, and safe. It is used to build many kinds of software.

Lesson 2: Why Learn Zig?

Definition: Learning Zig means you can build powerful programs that run very fast.

Why it is important: Zig gives you control and safety at the same time.

Simple explanation: Imagine driving a car that is both fast and safe. That is Zig.

Real-life example: Game developers use Zig for high-performance games.

School example: Students learn Zig to understand how computers really work.

Home example: Hobbyists use Zig to build small tools and games.

Nigerian example: Nigerian developers use Zig for efficient software.

Illustration:

  Why Learn Zig?
  +---------------------+
  | Fast                |
  +---------------------+
  | Safe                |
  +---------------------+
  | Simple              |
  +---------------------+
  | Powerful            |
  +---------------------+
  | Modern              |
  +---------------------+
  

Mini summary: Zig is fast, safe, simple, and powerful. It is a great language to learn.

Lesson 3: Installing Zig

Definition: Installing Zig means putting the Zig compiler on your computer.

Why it is important: You need the compiler to turn your code into a program.

Simple explanation: Like installing a new app on your phone before you can use it.

Real-life example: Developers install Zig to build software.

School example: Students install Zig on school computers.

Home example: Families install Zig on home computers.

Nigerian example: Nigerian developers install Zig to build tools.

Illustration:

  Installing Zig:
  1. Go to ziglang.org
  2. Download the version for your computer
  3. Extract the file
  4. Add Zig to your PATH
  5. Open a terminal and type: zig version
  6. You should see the version number 🎉
  

Step-by-step:

  1. Visit the official Zig website (ziglang.org).
  2. Download the version for your operating system.
  3. Extract the downloaded file to a folder.
  4. Add that folder to your system PATH.
  5. Open a terminal and type zig version.
  6. If you see a version number, Zig is installed!

Mini summary: Install Zig by downloading it and adding it to your PATH. Check with zig version.

Lesson 4: Your First Zig Program

Definition: A Zig program is a set of instructions that tells the computer what to do.

Why it is important: Writing your first program is the start of your journey.

Simple explanation: Like writing your first sentence in a new language.

Real-life example: Programmers start with “Hello, World!”

School example: Students write “Hello, World!” in class.

Home example: Families write simple programs for fun.

Nigerian example: Nigerian students write “Hello, Nigeria!”

Illustration:

  hello.zig:

  const std = @import("std");

  pub fn main() void {
      std.debug.print("Hello, Zig!\n", .{});
  }

  Run it:
  zig run hello.zig

  Output:
  Hello, Zig!
  

Step-by-step:

  1. Create a file called hello.zig.
  2. Type the code above.
  3. Open a terminal.
  4. Type zig run hello.zig.
  5. See the output “Hello, Zig!”

Mini summary: Your first Zig program prints “Hello, Zig!” to the screen. Run it with zig run.

Lesson 5: Variables and Constants

Definition: A variable is a box that holds a value that can change. A constant holds a value that cannot change.

Why it is important: Variables and constants let you store and use data.

Simple explanation: Imagine a labeled box. You can put things in and take them out (variable). A sealed box cannot be changed (constant).

Real-life example: A bank stores your balance in a variable.

School example: A teacher stores a student's score in a variable.

Home example: A family stores the number of eggs in a variable.

Nigerian example: A trader stores the price of rice in a variable.

Illustration:

  Variables and Constants:

  var age: u8 = 13;       // can change
  const pi: f32 = 3.14;   // cannot change

  age = 14;  // OK
  pi = 3.15; // ERROR
  

Step-by-step:

  1. Use var to create a variable.
  2. Use const to create a constant.
  3. Give a type (like u8 for small numbers).
  4. Give a name.
  5. Assign a value with =.

Mini summary: Variables can change; constants cannot. Use var and const.

Lesson 6: Primitive Data Types

Definition: Data types describe what kind of value a variable holds: numbers, text, true/false, etc.

Why it is important: Knowing data types helps you store data correctly.

Simple explanation: Like different containers for different things: bottles for water, boxes for books.

Real-life example: Banks use numbers for money and text for names.

School example: Teachers use numbers for scores and text for names.

Home example: Families use numbers for ages and text for addresses.

Nigerian example: Businesses use numbers for prices and text for product names.

Illustration:

  Common Zig Types:
  +----------+---------------------------+
  | Type     | What It Holds             |
  +----------+---------------------------+
  | u8       | Small positive number     |
  | i32      | Whole number (positive/neg)|
  | f64      | Decimal number            |
  | bool     | true or false             |
  | []u8     | Text (string)             |
  +----------+---------------------------+
  

Mini summary: Zig has many data types: numbers (u8, i32, f64), booleans (bool), and text ([]u8).

Lesson 7: Control Flow – if and switch

Definition: Control flow lets your program make decisions.

Why it is important: Decisions make programs smart.

Simple explanation: Like choosing what to wear based on the weather.

Real-life example: A bank checks if you have enough money before you withdraw.

School example: A teacher gives a pass or fail based on a score.

Home example: A family decides to buy food based on the budget.

Nigerian example: A trader decides to sell based on the price.

Illustration:

  if statement:

  const score: u8 = 85;
  if (score >= 70) {
      std.debug.print("Pass!\n", .{});
  } else {
      std.debug.print("Fail.\n", .{});
  }

  switch statement:

  const day: u8 = 3;
  switch (day) {
      1 => std.debug.print("Monday\n", .{}),
      2 => std.debug.print("Tuesday\n", .{}),
      3 => std.debug.print("Wednesday\n", .{}),
      else => std.debug.print("Other day\n", .{}),
  }
  

Step-by-step:

  1. Use if to test a condition.
  2. Use else for the other case.
  3. Use switch to choose between many options.
  4. Test your program with different values.

Mini summary: Use if and switch to make decisions in your program.

Lesson 8: Control Flow – while and for

Definition: Loops let you repeat a block of code many times.

Why it is important: Loops save time and let you process lists.

Simple explanation: Like doing push-ups 10 times in a row.

Real-life example: A bank processes many transactions in a loop.

School example: A teacher adds up the scores of all students.

Home example: A family counts all items in a shopping list.

Nigerian example: A trader calculates total sales for the day.

Illustration:

  while loop:

  var i: u8 = 1;
  while (i <= 5) : (i += 1) {
      std.debug.print("{d}\n", .{i});
  }

  for loop:

  const numbers = [_]u8{10, 20, 30};
  for (numbers) |n| {
      std.debug.print("{d}\n", .{n});
  }
  

Step-by-step:

  1. Use while to repeat while a condition is true.
  2. Use for to go through a list of items.
  3. Make sure your loop ends.
  4. Test with small numbers first.

Mini summary: Use while and for to repeat code. Loops are powerful tools.

Lesson 9: Functions

Definition: A function is a block of code that does a specific job and can be reused.

Why it is important: Functions make programs cleaner and easier to reuse.

Simple explanation: Like a recipe you can use again and again.

Real-life example: A bank uses a function to calculate interest.

School example: A teacher uses a function to calculate averages.

Home example: A family uses a function to calculate budget totals.

Nigerian example: A trader uses a function to calculate prices.

Illustration:

  Function Example:

  fn add(a: i32, b: i32) i32 {
      return a + b;
  }

  pub fn main() void {
      const result = add(3, 4);
      std.debug.print("Sum: {d}\n", .{result});
  }
  

Step-by-step:

  1. Use fn to start a function.
  2. Give the function a name.
  3. List its inputs (parameters).
  4. Write its return type.
  5. Write the body with return.

Mini summary: Functions are reusable blocks of code. Use fn to define them and call them by name.

Lesson 10: Structs and Enums

Definition: A struct groups related data together. An enum is a list of named values.

Why it is important: They help you organize your data clearly.

Simple explanation: A struct is like a bag with labeled pockets. An enum is like a list of choices on a menu.

Real-life example: A bank uses structs for customer info and enums for account types.

School example: A teacher uses structs for student info and enums for grades.

Home example: A family uses structs for family members and enums for roles.

Nigerian example: A trader uses structs for products and enums for categories.

Illustration:

  Struct and Enum:

  const Color = enum { red, green, blue };

  const Person = struct {
      name: []const u8,
      age: u8,
      favorite: Color,
  };

  const ada = Person{
      .name = "Ada",
      .age = 13,
      .favorite = .green,
  };
  

Step-by-step:

  1. Use struct to group related data.
  2. Use enum to list named values.
  3. Create instances and set fields.
  4. Access fields with dots: ada.name.

Mini summary: Structs group data; enums list named values. They make your code organized and clear.

Lesson 11: Arrays and Slices

Definition: An array is a fixed-size list. A slice is a view into a part of an array.

Why it is important: Arrays and slices let you work with many values at once.

Simple explanation: An array is like a row of boxes. A slice points to some of those boxes.

Real-life example: A bank uses an array for transaction history.

School example: A teacher uses an array for class scores.

Home example: A family uses an array for shopping items.

Nigerian example: A trader uses an array for daily sales.

Illustration:

  Array and Slice:

  const numbers = [_]u8{1, 2, 3, 4, 5};  // array
  const part = numbers[1..4];            // slice

  for (part) |n| {
      std.debug.print("{d}\n", .{n});
  }
  

Step-by-step:

  1. Create an array with [_]type{values}.
  2. Create a slice with array[start..end].
  3. Use for to loop through them.

Mini summary: Arrays hold fixed lists; slices point to parts of lists. Both are used with loops.

Lesson 12: Strings in Zig

Definition: A string is a list of characters. In Zig, strings are slices of bytes: []const u8.

Why it is important: Strings let you work with text.

Simple explanation: Like writing a sentence using letters.

Real-life example: Banks store customer names as strings.

School example: Teachers store student names as strings.

Home example: Families store addresses as strings.

Nigerian example: Businesses store product names as strings.

Illustration:

  String Example:

  const name: []const u8 = "Ada";
  std.debug.print("Hello, {s}!\n", .{name});

  Output:
  Hello, Ada!
  

Step-by-step:

  1. Create a string with const name = "text";.
  2. Use {s} in print to show it.
  3. You can slice strings like arrays.

Mini summary: Strings are slices of bytes. Use {s} to print them.

Lesson 13: Compiling and Running Zig Programs

Definition: Compiling means turning your code into a program the computer can run.

Why it is important: You need to compile before you can run your program.

Simple explanation: Like baking a cake. You mix ingredients (write code), then bake (compile), then eat (run).

Real-life example: Developers compile their code into apps.

School example: Students compile their first program.

Home example: Families compile small tools.

Nigerian example: Businesses compile their software.

Illustration:

  Compile and Run:

  zig build-exe hello.zig    // compile
  ./hello                     // run (Linux/Mac)
  hello.exe                   // run (Windows)

  Or simply:

  zig run hello.zig           // compile and run
  

Step-by-step:

  1. Open a terminal.
  2. Type zig run hello.zig.
  3. See the output.
  4. Or use zig build-exe to create an executable.

Mini summary: Use zig run to compile and run in one step, or zig build-exe to create a program.

Lesson 14: Common Mistakes in Zig

Definition: Mistakes happen. Knowing them helps you avoid them.

Why it is important: A small mistake can stop your program.

Simple explanation: Like a spelling mistake in a sentence.

Real-life example: Developers use tools to find mistakes.

School example: Students learn from errors in their code.

Home example: Families check their code twice.

Nigerian example: Businesses test their code carefully.

Table of common mistakes:

MistakeWhat HappensHow to Fix
Missing semicolonError messageAdd ; at the end
Wrong typeError messageUse the correct type
Forgetting const/varError messageAdd the keyword
Unused variableWarning/errorRemove or use it
Forgetting importsUnknown nameAdd @import
Mismatched typesErrorConvert types properly

Mini summary: Common mistakes include missing semicolons and wrong types. Read error messages carefully.

Lesson 15: Best Practices in Zig

Definition: Best practices are good habits that make your code clean and safe.

Why it is important: Good habits prevent bugs and save time.

Simple explanation: Like keeping your room tidy. It is easier to find things.

Real-life example: Developers write clean code for their teams.

School example: Students write neat code for projects.

Home example: Families keep their tools organized.

Nigerian example: Businesses write clear code for maintenance.

List of best practices:

  • Use const by default.
  • Use clear variable names.
  • Keep functions short and focused.
  • Handle errors properly.
  • Comment your code where needed.
  • Use defer to clean up resources.
  • Format your code with zig fmt.
  • Test your code often.
  • Read error messages carefully.
  • Keep learning from the Zig community.

Mini summary: Best practices: use const, clear names, short functions, handle errors, test often.

Key Vocabulary

WordSimple Definition
ZigA modern programming language.
CompilerA tool that turns code into a program.
VariableA box that holds a value that can change.
ConstantA box that holds a value that cannot change.
Data typeWhat kind of value a variable holds.
FunctionA reusable block of code.
StructA group of related data.
EnumA list of named values.
ArrayA fixed-size list.
SliceA view into part of an array.
StringA list of characters.
LoopCode that repeats.
ConditionA test that is true or false.
ParameterAn input to a function.
ReturnThe result a function gives back.

Important Concepts

  • Zig is modern: Simple, fast, and safe.
  • Install with PATH: Then use zig version.
  • First program: Prints “Hello, Zig!”.
  • Variables and constants: Use var and const.
  • Data types: u8, i32, f64, bool, []u8.
  • Control flow: if, switch, while, for.
  • Functions: Reusable blocks with fn.
  • Structs and enums: Group data and list named values.
  • Arrays and slices: Lists of values.
  • Compile and run: Use zig run.

Step-by-step Explanations

How to install Zig step by step

  1. Visit ziglang.org.
  2. Download the correct version.
  3. Extract to a folder.
  4. Add the folder to PATH.
  5. Run zig version.

How to write your first program step by step

  1. Create hello.zig.
  2. Type the code.
  3. Save the file.
  4. Run zig run hello.zig.
  5. See the output.

How to create a variable step by step

  1. Type var or const.
  2. Give a name.
  3. Add a colon and a type.
  4. Assign a value with =.
  5. End with ;.

How to write a function step by step

  1. Type fn.
  2. Give the function a name.
  3. Add parameters in parentheses.
  4. Add return type.
  5. Write the body with return.

How to run a loop step by step

  1. Choose while or for.
  2. Set the condition or list.
  3. Write the body.
  4. Make sure the loop ends.
  5. Test with small numbers.

Real-life Examples

  • Games: Use loops for animations.
  • Banks: Use structs for customer data.
  • Schools: Use arrays for scores.
  • Homes: Use functions for calculations.
  • Businesses: Use enums for categories.

Nigerian Examples

  • Banks: Nigerian banks use Zig for fast systems.
  • Startups: Nigerian startups build tools with Zig.
  • Schools: Nigerian students learn Zig in coding clubs.
  • Businesses: Nigerian businesses use Zig for efficiency.
  • Freelancers: Nigerian developers use Zig for projects.

Fun Examples Children Can Relate To

  • Games: Write a simple guessing game.
  • Stories: Print a story on screen.
  • Math: Build a calculator.
  • Lists: Organize your toys in code.
  • Quizzes: Build a quiz program.

Everyday Examples

  • Shopping: Add up prices.
  • Homework: Calculate averages.
  • Family: Track chores.
  • Time: Print a countdown.
  • Money: Track savings.

Parent Tips

  • Encourage your child to code every day.
  • Help them install Zig properly.
  • Celebrate their first program.
  • Be patient with errors.
  • Read error messages together.
  • Let them teach you what they learned.
  • Use examples from daily life.
  • Keep it fun and simple.
  • Encourage practice with small projects.
  • Support their learning journey.

Interesting Facts

  • Zig was first released in 2016.
  • Zig can compile C and C++ code.
  • Zig has no hidden memory allocations.
  • Zig uses comptime for compile-time code.
  • Zig is used by companies like Uber and Bun.
  • Zig is open source.
  • Zig has a built-in formatter.
  • Zig is growing fast.

Did You Know?

  • Did you know that Zig can replace C compilers?
  • Did you know that Zig has no garbage collector?
  • Did you know that Zig uses try and catch for errors?
  • Did you know that Zig supports cross-compilation easily?
  • Did you know that Zig has a standard library called std?
  • Did you know that Zig can run on tiny devices?
  • Did you know that Zig is used in game development?
  • Did you know that Nigeria has Zig developers?

Remember This

  • Zig is a modern programming language.
  • Install Zig from ziglang.org.
  • Use var for variables and const for constants.
  • Types include u8, i32, f64, bool, []u8.
  • Use if, switch, while, and for for control flow.
  • Functions are reusable blocks of code.
  • Structs group data; enums list named values.
  • Arrays hold lists; slices view parts.
  • Strings are slices of bytes.
  • Run code with zig run.

Common Mistakes

  • Missing semicolons.
  • Wrong data types.
  • Forgetting var or const.
  • Unused variables.
  • Missing imports.
  • Type mismatches.
  • Infinite loops.
  • Not reading error messages.

Best Practices

  • Use const by default.
  • Use clear variable names.
  • Keep functions short.
  • Handle errors properly.
  • Comment where needed.
  • Use defer for cleanup.
  • Format with zig fmt.
  • Test often.
  • Read error messages carefully.
  • Keep learning.

Illustrations and Diagrams

Zig Program Structure

  hello.zig
  +---------------------------+
  | @import("std")            |
  +---------------------------+
  | pub fn main() void {      |
  |     print("Hello, Zig!")  |
  | }                         |
  +---------------------------+
  

Variables vs Constants

  var age: u8 = 13;      // Can change
  const pi: f32 = 3.14;  // Cannot change
  

Control Flow

  if (score >= 70) {
      Pass
  } else {
      Fail
  }
  

Loop Structure

  while (i <= 5) : (i += 1) {
      print(i)
  }
  

Function Diagram

  Input → Function → Output
    3, 4    add()      7
  

Your Learning Journey

  Module 1: Zig Basics
        |
        V
  Module 2: Memory & Errors
        |
        V
  Module 3: Advanced Features
        |
        V
  Module 4: Real Projects
        |
        V
  Zig Expert 🎉
  

Comparison Tables

Zig vs Python vs C

FeatureZigPythonC
SpeedVery FastSlowVery Fast
SafetyHighHighLow
MemoryManualAutomaticManual
LearningMediumEasyHard

var vs const

Featurevarconst
Can change?YesNo
Use forChanging valuesFixed values
Best practiceOnly when neededDefault choice

Array vs Slice

FeatureArraySlice
SizeFixedCan vary
Owns dataYesNo
Best forFixed listsPassing parts

Struct vs Enum

FeatureStructEnum
PurposeGroup dataList choices
ExamplePerson { name, age }Color { red, green }
UseComplex objectsNamed values

Lesson Summaries

Lesson 1: Zig is a modern programming language.

Lesson 2: Zig is fast, safe, simple, and powerful.

Lesson 3: Install Zig from ziglang.org and check with zig version.

Lesson 4: Your first program prints “Hello, Zig!”.

Lesson 5: Use var for variables and const for constants.

Lesson 6: Zig types include u8, i32, f64, bool, []u8.

Lesson 7: Use if and switch for decisions.

Lesson 8: Use while and for for loops.

Lesson 9: Functions are reusable blocks of code.

Lesson 10: Structs group data; enums list named values.

Lesson 11: Arrays hold lists; slices view parts.

Lesson 12: Strings are slices of bytes.

Lesson 13: Compile and run with zig run.

Lesson 14: Common mistakes include missing semicolons.

Lesson 15: Best practices: use const, clear names, test often.

End-of-Module Summary

Congratulations! You have finished Module One of the Certified Zig Programming Expert course. You learned what Zig is and why it is special. You learned how to install Zig and write your first program. You learned about variables, constants, and data types. You learned control flow with if, switch, while, and for. You learned about functions, structs, enums, arrays, slices, and strings. You learned how to compile and run Zig programs. You learned common mistakes and best practices. Most importantly, you now have a solid foundation in Zig. In the next module, you will learn about memory management and error handling. Keep practising, and you will become a Zig expert!

Frequently Asked Questions

  1. What is Zig? A modern programming language.
  2. Why learn Zig? It is fast, safe, simple, and powerful.
  3. How do I install Zig? Download from ziglang.org and add to PATH.
  4. How do I run a Zig program? Use zig run file.zig.
  5. What is the difference between var and const? var can change; const cannot.
  6. What are Zig's data types? u8, i32, f64, bool, []u8, and more.
  7. How do I write a function? Use fn with parameters and return type.
  8. What is a struct? A group of related data.
  9. What is an enum? A list of named values.
  10. How do I handle errors? Use try and catch (in later modules).

Matching Exercises

Match the term to its meaning.

TermMeaning
1. ZigA. A group of related data
2. VariableB. A modern programming language
3. FunctionC. A box that can change
4. StructD. A reusable block of code
5. EnumE. A list of named values

Answers: 1-B, 2-C, 3-D, 4-A, 5-E

Scenario-based Exercises

  1. Scenario: You want to store a student's name. What do you use?
    Answer: A constant string: const name = "Ada";
  2. Scenario: You want to store a score that can change. What do you use?
    Answer: A variable: var score: u8 = 70;
  3. Scenario: You want to choose between pass and fail. What do you use?
    Answer: if statement.
  4. Scenario: You want to add up five numbers. What do you use?
    Answer: A for loop with a function.
  5. Scenario: You want to list colors. What do you use?
    Answer: An enum.

Group Activity

Title: “Write a Simple Calculator Together”

Instructions: In groups of 3–4, write a Zig program that adds, subtracts, multiplies, and divides two numbers. One person writes the code, one person tests it, one person fixes errors, and one person presents. Share your calculator with the class.

Goal: Practice using functions, variables, and control flow.

Individual Activity

Task: Write a Zig program that:

  • Creates a constant with your name.
  • Creates a variable with your age.
  • Prints both to the screen.
  • Uses an if statement to check if your age is above 12.

Hint: Use std.debug.print with {s} and {d}.

Mini Project

Project: “My First Zig Program”

Write a Zig program that does the following:

  • Prints a greeting with your name.
  • Prints your age.
  • Prints whether you are a teenager.
  • Uses a loop to count from 1 to 5.
  • Uses a function to add two numbers.
  • Uses a struct to describe yourself.

Example output:

  Hello, my name is Ada.
  I am 13 years old.
  I am a teenager.
  Count: 1 2 3 4 5
  Sum: 7
  Person: Ada, age 13
  

Practical Assignment

Assignment: Write a Zig program that acts as a simple quiz. The program should:

  1. Store three questions and answers in variables.
  2. Print the questions to the screen.
  3. Use if statements to check answers.
  4. Print a score at the end.
  5. Use at least one function and one struct.
  6. Add comments to explain your code.

Submit: Your .zig file and a screenshot of the output.

Key Takeaways

  • Zig is a modern programming language.
  • Install from ziglang.org.
  • Use var and const for variables and constants.
  • Types include u8, i32, f64, bool, []u8.
  • Control flow: if, switch, while, for.
  • Functions are reusable blocks.
  • Structs group data; enums list named values.
  • Arrays hold lists; slices view parts.
  • Strings are slices of bytes.
  • Run code with zig run.

Classroom Discussion Questions

  1. What is Zig, and why is it special?
  2. How do you install Zig?
  3. What is the difference between a variable and a constant?
  4. What are the main data types in Zig?
  5. How do you make decisions in Zig?
  6. How do you repeat code in Zig?
  7. What is a function, and why is it useful?
  8. What is a struct, and what is an enum?
  9. What is the difference between an array and a slice?
  10. What did Chidi learn from writing his first program?

Preparation for Module Two

In Module Two, we will learn about memory management and error handling in Zig. We will cover:

  • Pointers and memory layout.
  • Allocators (GeneralPurposeAllocator, ArenaAllocator).
  • Manual memory management and defer/errdefer.
  • Optionals (?T) and error unions (!T).
  • try, catch, and error handling patterns.
  • Comptime basics and generics.

To prepare, make sure you have completed the practical assignment and have your Zig environment ready. Review the key vocabulary. Think about how memory works in a computer. Bring your curiosity!

See you in Module Two!


End of Module One – Certified Zig Programming Expert

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→