Taskintro
Write a while loop
Also called while loop task, loop while a condition is true, halve until zero, repeat until, do-while task, Loops/While, Loops/Do-while.
Halve a number until it is 0 with a while loop, collect each value, and see why the loop needs integer division and why a do-while loop gives a different result for 0.
- Evidence
- Code in 10 languages
Task
Start with a number n, and halve it until it is 0. The function halvings(n) returns each value that the loop sees while the value is greater than 0. For example, halvings(10) is [10, 5, 2, 1]. Each step divides by 2 and drops the remainder.
n is an integer from 0 to 2147483647. The task follows Rosetta Code: "Loop while it is greater than zero"1. The loop does not know the number of passes in advance, so it is a while loop, not a counted loop.
Solutions
| Language | The loop | Integer halving |
|---|---|---|
| Python | while n > 0: |
n //= 2 |
| JavaScript, TypeScript | while (n > 0) |
n = Math.trunc(n / 2) |
| Java, C#, C, C++ | while (n > 0) |
n /= 2 |
| Go | for n > 0 |
n /= 2 |
| Rust | while n > 0 |
n /= 2 |
| Bash | while ((n > 0)) |
((n /= 2)) |
- Python.
/"always returns a float. To do floor division and get an integer result you can use the // operator"2. The solution uses//. - JavaScript and TypeScript. A number can have a fraction, and
3 / 2gives1.53. The solution drops the fraction withMath.trunc. - Java, C#, C, C++ and Rust. The division of two integers gives an integer. A C#
whileloop "executes zero or more times"4, and the other languages have the same rule. - Go. Go has no
whilekeyword. Aforstatement with only a condition repeats the block while the condition is true5. - Bash. Shell arithmetic works on integers only: "Evaluation is done in the largest fixed-width integers available"6. The function prints one value on each line.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
zero: the testn > 0is false at the start, so the body does not run, and the result is empty.one: the loop runs once, and1 / 2is 0.rosetta: 1024 is a power of 2, so each value is exact, and the last value is 1.tenandodd: the remainder is dropped at each step, so 5 becomes 2.limit: 2147483647 gives 31 values. The values only get smaller, so no type overflows.
Pitfalls
- Python
/makes a float, and the loop runs much longer. Withn = n / 2, the values become 0.5, 0.25 and so on. The loop stops only when the float is too small and becomes 0:
n = 1024
count = 0
while n > 0:
count += 1
last = n
n = n / 2
print(count, last)
n = 1024
values = []
while n > 0:
values.append(n)
n = n // 2
print(len(values), values[-1])
1085 5e-324
11 1
- A do-while loop runs the body once before the test. In Java, "A do statement is executed by first executing the Statement"7, and a C#
doloop "executes one or more times"4. The Rosetta Code do-while task needs this: "The loop must execute at least once"8. For this task, it is wrong: withnequal to 0, a do-while loop gives[0]. See do-while loop.
int n = 0;
var a = new List<int>();
while (n > 0)
{
a.Add(n);
n /= 2;
}
n = 0;
var b = new List<int>();
do
{
b.Add(n);
n /= 2;
} while (n > 0);
Console.WriteLine($"while: [{string.Join(", ", a)}] do: [{string.Join(", ", b)}]");
while: [] do: [0]
- A body that does not change
nnever ends. If the step is missing, or it changes a copy ofn, the test stays true. See infinite loops.
Related tasks
- Write a counted loop: a loop with a known number of passes.
- Loop with a step or downward: a counted loop that goes down or by steps.
- FizzBuzz: a loop with a test in each pass.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-while-loop/.
def halvings(n: int) -> list[int]:
"""Return n, n // 2, n // 4, ... while the value is greater than 0."""
out = []
while n > 0:
out.append(n)
# n / 2 would make a float, and the loop would run about 1000 more times.
n //= 2
return out
test_halvings.py 21 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-while-loop/.
import pytest
from halvings import halvings
CASES = {
"rosetta": (1024, [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]),
"ten": (10, [10, 5, 2, 1]),
"zero": (0, []),
"one": (1, [1]),
"odd": (7, [7, 3, 1]),
"limit": (2147483647, [2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1]),
}
@pytest.mark.parametrize("name", CASES)
def test_halvings(name):
n, want = CASES[name]
assert halvings(n) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
#include "halvings.hpp"
#include <vector>
std::vector<int> halvings(int n) {
std::vector<int> out;
while (n > 0) {
out.push_back(n);
n /= 2;
}
return out;
}
halvings.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
#pragma once
#include <vector>
// halvings returns n, n / 2, n / 4, ... while the value is greater than 0.
std::vector<int> halvings(int n);
test_halvings.cpp 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
#include "halvings.hpp"
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, int n, const std::vector<int> &want) {
if (halvings(n) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("rosetta", 1024, std::vector<int>{1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1});
check("ten", 10, std::vector<int>{10, 5, 2, 1});
check("zero", 0, std::vector<int>{});
check("one", 1, std::vector<int>{1});
check("odd", 7, std::vector<int>{7, 3, 1});
check("limit", 2147483647, std::vector<int>{2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
import java.util.ArrayList;
import java.util.List;
final class Halvings {
private Halvings() {}
/** Returns n, n / 2, n / 4, ... while the value is greater than 0. */
static List<Integer> halvings(int n) {
List<Integer> out = new ArrayList<>();
while (n > 0) {
out.add(n);
n /= 2;
}
return out;
}
}
HalvingsTest.java 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class HalvingsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("rosetta", 1024, List.of(1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1)),
Arguments.of("ten", 10, List.of(10, 5, 2, 1)),
Arguments.of("zero", 0, List.of()),
Arguments.of("one", 1, List.of(1)),
Arguments.of("odd", 7, List.of(7, 3, 1)),
Arguments.of("limit", 2147483647, List.of(2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void halvings(String name, int n, List<Integer> want) {
assertEquals(want, Halvings.halvings(n), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
#include "halvings.h"
#include <stddef.h>
size_t halvings(int n, int out[32]) {
size_t count = 0;
while (n > 0) {
out[count++] = n;
n /= 2;
}
return count;
}
halvings.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
#ifndef HALVINGS_H
#define HALVINGS_H
#include <stddef.h>
// halvings writes n, n / 2, n / 4, ... while the value is greater than 0 to
// out, and returns the number of values. out must have room for 32 values.
size_t halvings(int n, int out[32]);
#endif
test_halvings.c 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
#include "halvings.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, int n, const int *want, size_t count) {
int out[32];
size_t got = halvings(n, out);
if (got != count || (count > 0 && memcmp(out, want, count * sizeof *out) != 0)) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
}
#define CHECK(name, n, ...) \
do { \
const int w[] = {__VA_ARGS__}; \
check(name, n, w, sizeof w / sizeof w[0]); \
} while (0)
int main(void) {
CHECK("rosetta", 1024, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1);
CHECK("ten", 10, 10, 5, 2, 1);
check("zero", 0, NULL, 0);
CHECK("one", 1, 1);
CHECK("odd", 7, 7, 3, 1);
CHECK("limit", 2147483647, 2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
public static class Halvings
{
// Returns n, n / 2, n / 4, ... while the value is greater than 0.
public static List<int> Of(int n)
{
var result = new List<int>();
while (n > 0)
{
result.Add(n);
n /= 2;
}
return result;
}
}
HalvingsTests.cs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
using Xunit;
public sealed class HalvingsTests
{
public static TheoryData<string, int, int[]> Cases => new()
{
{ "rosetta", 1024, new int[] { 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1 } },
{ "ten", 10, new int[] { 10, 5, 2, 1 } },
{ "zero", 0, new int[0] },
{ "one", 1, new int[] { 1 } },
{ "odd", 7, new int[] { 7, 3, 1 } },
{ "limit", 2147483647, new int[] { 2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int n, int[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Halvings.Of(n));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
/**
* Returns n, n / 2, n / 4, ... without the remainders, while the value is greater than 0.
* @param {number} n
* @returns {number[]}
*/
export function halvings(n) {
const out = [];
while (n > 0) {
out.push(n);
// n / 2 can have a fraction, so drop it.
n = Math.trunc(n / 2);
}
return out;
}
halvings.test.js 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { halvings } from "./halvings.js";
const cases = [
["rosetta", 1024, [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]],
["ten", 10, [10, 5, 2, 1]],
["zero", 0, []],
["one", 1, [1]],
["odd", 7, [7, 3, 1]],
["limit", 2147483647, [2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1]],
];
for (const [name, n, want] of cases) {
test(name, () => {
assert.deepEqual(halvings(n), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
export function halvings(n: number): number[] {
const out: number[] = [];
while (n > 0) {
out.push(n);
// n / 2 can have a fraction, so drop it.
n = Math.trunc(n / 2);
}
return out;
}
halvings.test.ts 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { halvings } from "./halvings.ts";
const cases: [string, number, number[]][] = [
["rosetta", 1024, [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]],
["ten", 10, [10, 5, 2, 1]],
["zero", 0, []],
["one", 1, [1]],
["odd", 7, [7, 3, 1]],
["limit", 2147483647, [2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1]],
];
for (const [name, n, want] of cases) {
test(name, () => {
assert.deepEqual(halvings(n), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
// Package halvings halves a number with a while loop.
package halvings
// Halvings returns n, n/2, n/4, ... while the value is greater than 0.
func Halvings(n int) []int {
out := []int{}
// A for with only a condition is the while loop of Go.
for n > 0 {
out = append(out, n)
n /= 2
}
return out
}
halvings_test.go 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
package halvings
import (
"slices"
"testing"
)
var cases = []struct {
name string
n int
want []int
}{
{"rosetta", 1024, []int{1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1}},
{"ten", 10, []int{10, 5, 2, 1}},
{"zero", 0, []int{}},
{"one", 1, []int{1}},
{"odd", 7, []int{7, 3, 1}},
{"limit", 2147483647, []int{2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1}},
}
func TestHalvings(t *testing.T) {
for _, c := range cases {
if got := Halvings(c.n); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
/// Returns n, n / 2, n / 4, ... while the value is greater than 0.
pub fn halvings(mut n: i32) -> Vec<i32> {
let mut out = Vec::new();
while n > 0 {
out.push(n);
n /= 2;
}
out
}
tests/halvings_test.rs 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-while-loop/.
use algo_write_a_while_loop::halvings;
#[test]
fn cases() {
let cases: &[(&str, i32, &[i32])] = &[
("rosetta", 1024, &[1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]),
("ten", 10, &[10, 5, 2, 1]),
("zero", 0, &[]),
("one", 1, &[1]),
("odd", 7, &[7, 3, 1]),
("limit", 2147483647, &[2147483647, 1073741823, 536870911, 268435455, 134217727, 67108863, 33554431, 16777215, 8388607, 4194303, 2097151, 1048575, 524287, 262143, 131071, 65535, 32767, 16383, 8191, 4095, 2047, 1023, 511, 255, 127, 63, 31, 15, 7, 3, 1]),
];
for &(name, n, want) in cases {
assert_eq!(halvings(n), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-while-loop/.
# halvings N
# Prints N, N / 2, N / 4, ... while the value is greater than 0, one on each line.
halvings() {
local n=$1
while ((n > 0)); do
printf '%s\n' "$n"
# Shell arithmetic has only integers, so / drops the remainder.
((n /= 2))
done
}
test_halvings.bats 26 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-while-loop/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/halvings.sh"
}
check() { # check N -- WANT...
local n=$1
shift 2
local got want
# The x keeps the trailing newlines, which $(...) removes.
got=$(halvings "$n"; printf x)
want=$(if (($# > 0)); then printf '%s\n' "$@"; fi; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "rosetta" { check 1024 -- 1024 512 256 128 64 32 16 8 4 2 1; }
@test "ten" { check 10 -- 10 5 2 1; }
@test "zero" { check 0 --; }
@test "one" { check 1 -- 1; }
@test "odd" { check 7 -- 7 3 1; }
@test "limit" { check 2147483647 -- 2147483647 1073741823 536870911 268435455 134217727 67108863 33554431 16777215 8388607 4194303 2097151 1048575 524287 262143 131071 65535 32767 16383 8191 4095 2047 1023 511 255 127 63 31 15 7 3 1; }
References
- Loops/While, Rosetta Code (the RosettaCodeData mirror), Task
- An Informal Introduction to Python, The Python Tutorial, 3.1.1 Numbers
- Division (/), MDN Web Docs, Try it
- Iteration statements, C# language reference, The while statement; The do statement
- The Go Programming Language Specification, For statements with single condition
- Bash Reference Manual, 6.5 Shell Arithmetic
- The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.13 The do Statement
- Loops/Do-while, Rosetta Code (the RosettaCodeData mirror), Task description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 3HE9AA Edit this page History Report an error Markdown