The while loop in Clojure

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)

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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources