Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clojure
loops
communitycreator

The while loop in Clojure

Chinweuba Elijah Azubuike

Overview

What is a loop?

A loop repeatedly executes a code block until a condition is satisfied.

What is a while loop in Clojure?

A Clojure while loop evaluates a conditional expression and if the condition returns true, it executes the codes in the do block until the conditional expression returns false.

The "while" loop in Clojure

Syntax

(while(expression)
   (do
      codeblock))

Code example

(ns clojure.examples.hello
   (:gen-class))

;; This program displays Hello World
(defn looping []
   (def y (atom 1))
   (while ( < @y 9 )
      (do
         (println @y)
         (swap! y inc))))
(looping)
An example of the "while" loop

Code explanation

  • Line 5: We create a function to demonstrate the while loop.

  • Line 6: We define a variable y with the atom keyword, so that the variable can be changed.

  • Line 7: We declare the while loop with a condition that will continue running as long as y is less than 9.

  • Line 8: The do block is used to identify the code that will be repeated.

  • Line 9: We print the value of y.

  • Line 10: We use swap! to populate the changed values of y.

  • Line 11: We call the looping function that we created earlier.

RELATED TAGS

clojure
loops
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring