How to resolve the algorithm Loops/Break step by step in the Zig programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Loops/Break step by step in the Zig programming language

Table of Contents

Problem Statement

Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers.
Otherwise, generate and print a second random number before restarting the loop.
If the number 10 is never generated as the first number in a loop, loop forever.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Loops/Break step by step in the Zig programming language

Source code in the zig programming language

const std = @import("std");

pub fn main() !void {
    const RndGen = std.rand.DefaultPrng;
    var rnd = RndGen.init(42);
    // possible improvement: make rng fair
    var rand_num1: u5 = undefined;
    var rand_num2: u5 = undefined;
    while (true) {
        rand_num1 = rnd.random().int(u5) % 20;
        try std.io.getStdOut().writer().print("{d}\n", .{rand_num1});
        if (rand_num1 == 10)
            break;
        rand_num2 = rnd.random().int(u5) % 20;
        try std.io.getStdOut().writer().print("{d}\n", .{rand_num2});
    }
}

  

You may also check:How to resolve the algorithm Start from a main routine step by step in the BASIC programming language
You may also check:How to resolve the algorithm Accumulator factory step by step in the Lua programming language
You may also check:How to resolve the algorithm Empty directory step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Farey sequence step by step in the Crystal programming language
You may also check:How to resolve the algorithm Sorting algorithms/Patience sort step by step in the AppleScript programming language