How to resolve the algorithm Loops/Nested step by step in the OCaml programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Loops/Nested step by step in the OCaml programming language

Table of Contents

Problem Statement

Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over

[ 1 , … , 20 ]

{\displaystyle [1,\ldots ,20]}

. The loops iterate rows and columns of the array printing the elements until the value

20

{\displaystyle 20}

is met. Specifically, this task also shows how to break out of nested loops.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Loops/Nested step by step in the OCaml programming language

Source code in the ocaml programming language

$ ocaml

# Random.self_init();;
- : unit = ()

# let m = Array.make_matrix 10 10 0 ;;
val m : int array array =
  [|[|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|];
    [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|];
    [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|];
    [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|];
    [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]; [|0; 0; 0; 0; 0; 0; 0; 0; 0; 0|]|]

# for i = 0 to pred 10 do
    for j = 0 to pred 10 do
      m.(i).(j) <- 1 + Random.int 20
    done;
  done;;
- : unit = ()

# try
    for i = 0 to pred 10 do
      for j = 0 to pred 10 do
        Printf.printf " %d" m.(i).(j);
        if m.(i).(j) = 20 then raise Exit;
      done;
      print_newline()
    done;
  with Exit ->
    print_newline()
  ;;
 15 8 15 9 9 6 1 18 6 18
 17 1 13 15 13 1 16 4 13 9
 15 3 5 19 17 3 1 11 5 2
 1 1 6 19 20
- : unit = ()


  

You may also check:How to resolve the algorithm Execute a system command step by step in the ERRE programming language
You may also check:How to resolve the algorithm Disarium numbers step by step in the jq programming language
You may also check:How to resolve the algorithm Draw a sphere step by step in the DWScript programming language
You may also check:How to resolve the algorithm Count in octal step by step in the 8080 Assembly programming language
You may also check:How to resolve the algorithm Musical scale step by step in the C programming language