task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of th... | #Fortran | Fortran | C Loops N plus one half - Fortran IV (1964)
INTEGER I
WRITE(6,301) (I,I=1,10)
301 FORMAT((I3,','))
END |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of th... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
For i As Integer = 1 To 10
Print Str(i);
If i < 10 Then Print ", ";
Next
Print
Sleep |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | 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 als... | #Forth | Forth | include random.fs
10 constant X
10 constant Y
: ,randoms ( range n -- ) 0 do dup random 1+ , loop drop ;
create 2darray 20 X Y * ,randoms
: main
Y 0 do
cr
X 0 do
j X * i + cells 2darray + @
dup .
20 = if unloop unloop exit then
loop
loop ; |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | 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 als... | #Fortran | Fortran | PROGRAM LOOPNESTED
INTEGER A, I, J, RNDINT
C Build a two-dimensional twenty-by-twenty array.
DIMENSION A(20,20)
C It doesn't matter what number you put here.
CALL SDRAND(123)
C Fill the array with random numbers.
DO 20 I = 1, 20
DO 10 J = 1, 20
... |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #GAP | GAP | for p in AlternatingGroup(4) do
Print(p, "\n");
od;
()
(1,3,2)
(1,2,3)
(1,4,3)
(2,4,3)
(1,3)(2,4)
(1,2,4)
(1,4)(2,3)
(2,3,4)
(1,3,4)
(1,2)(3,4)
(1,4,2) |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Go | Go | func printAll(values []int) {
for i, x := range values {
fmt.Printf("Item %d = %d\n", i, x)
}
} |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #Cowgol | Cowgol | include "cowgol.coh";
# Given a string containing the digits of a credit card number,
# see if it passes the Luhn test.
sub luhn(card: [uint8]): (ok: uint8) is
# Scan ahead to last digit, counting digits
var n: uint8 := 0;
while [card] != 0 loop
n := n + 1;
card := @next card;
end loop... |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #Kotlin | Kotlin | // version 1.0.6
import java.math.BigInteger
const val MAX = 19
val bigTwo = BigInteger.valueOf(2L)
val bigFour = bigTwo * bigTwo
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
... |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #PicoLisp | PicoLisp | (de lzwCompress (Lst)
(let (Codes 255 Dict)
(balance 'Dict
(make
(for C Codes
(link (cons (char C) C)) ) ) )
(make
(let W (pop 'Lst)
(for C Lst
(let WC (pack W C)
(if (lup Dict WC)
(setq W WC)
... |
http://rosettacode.org/wiki/LU_decomposition | LU decomposition | Every square matrix
A
{\displaystyle A}
can be decomposed into a product of a lower triangular matrix
L
{\displaystyle L}
and a upper triangular matrix
U
{\displaystyle U}
,
as described in LU decomposition.
A
=
L
U
{\displaystyle A=LU}
It is a modified form of Gaussian elimination.
Whil... | #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
fcn luTask(A){
A.LUDecompose(); // in place, contains L & U
L:=A.copy().lowerTriangle().setDiagonal(0,0,1);
U:=A.copy().upperTriangle();
return(L,U);
}
A:=GSL.Matrix(3,3).set(1,3,5, 2,4,7, 1,1,0); // example 1
L,U:=luTask(A);
printl... |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var string: story is "";
var string: line is "";
var integer: pos1 is 0;
var integer: pos2 is 1;
var string: field is "";
begin
writeln("Enter a story template, terminated by an empty line:");
repeat
readln(line);
if ... |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #Ring | Ring |
# Project : Loops/Increment loop index within loop body
load "stdlib.ring"
i = 42
n = 0
while n < 42
if isprime(i)
n = n + 1
see "n = " + n + " " + i + nl
i = i + i - 1
ok
i = i + 1
end
|
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #Ruby | Ruby |
require 'prime'
limit = 42
i = 42
n = 0
while n < limit do
if i.prime? then
n += 1
puts "n = #{n}".ljust(7) + ":" + "#{i.to_s.reverse.scan(/\d{3}|.+/).join(",").reverse}".rjust(19)
i += i
else
i += 1
end
end
|
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Draco | Draco | proc nonrec main() void:
while true do
writeln("SPAM")
od
corp |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #DWScript | DWScript | while True do
PrintLn('SPAM'); |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod=... | #XPL0 | XPL0 | func IPow(A, B); \Return A**B
int A, B;
return fix(Pow(float(A), float(B)));
int Prod, Sum, X, Y, Z, One, Three, Seven, J;
proc Block;
begin \ABS(n) = absolute value
Sum:= Sum + abs(J); \add absolute value of J.... |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod=... | #Yabasic | Yabasic |
sub process(x)
sum = sum + abs(x)
if abs(prod) < (2 ^ 27) and x <> 0 then prod = prod * x : fi
end sub
prod = 1
sum = 0
x = 5 : y = -5 : z = -2
one = 1 : three = 3 : seven = 7
for j = -three to (3 ^ 3) step three: process(j): next j
for j = -seven to seven step x: process(j): next j
for j = 555 to 550 - y:... |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #Dyalect | Dyalect | var i = 1024
while i > 0 {
print(i)
i /= 2
} |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #E | E | var i := 1024
while (i > 0) {
println(i)
i //= 2
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #Computer.2Fzero_Assembly | Computer/zero Assembly | LDA 28
SUB 29
STA 31
STA 28
BRZ 6 ;branch on zero to STP
JMP 0
STP
...
org 28
byte 11
byte 1
byte 0 |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #Crystal | Crystal | 10.step(to: 0, by: -1).each { |i|
puts i
}
|
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loo... | #Befunge | Befunge | 0>1+:.v
|%6: <
@ |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loo... | #C | C | int val = 0;
do{
val++;
printf("%d\n",val);
}while(val % 6 != 0); |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Axe | Axe | ClrHome
For(I,1,5)
For(J,1,I)
Output(J,I,"*")
End
End |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop b... | #Chapel | Chapel |
// Can be set on commandline via --N=x
config const N = 3;
for i in 1 .. 10 by N {
writeln(i);
}
|
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1... | #Standard_ML | Standard ML |
open List;
fun Ludi [] = []
| Ludi (T as h::L) =
let
fun next (h:: L ) =
let
val nw = #2 (ListPair.unzip (filter (fn (a,b) => a mod #2 h <> 0) L) )
in
ListPair.zip ( List.tabulate(List.length nw,fn i=>i) ,nw)
end
in
h :: Ludi ( next T)
end;
val ludic... |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of th... | #FutureBasic | FutureBasic | window 1
long i, num = 10
for i = 1 to num
print i;
if i = num then break
print @", ";
next i
HandleEvents |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | 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 als... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Randomize
Dim a(1 To 20, 1 To 20) As Integer
For i As Integer = 1 To 20
For j As Integer = 1 To 20
a(i, j) = Int(Rnd * 20) + 1
Next j
Next i
For i As Integer = 1 To 20
For j As Integer = 1 To 20
Print Using "##"; a(i, j);
Print " ";
If a(i, j) = 20 Then Exit For, For ''... |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Groovy | Groovy | def beatles = ["John", "Paul", "George", "Ringo"]
for(name in beatles) {
println name
} |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #Crystal | Crystal | def luhn_valid?(n) # Card values can be numbers or strings
d2sum = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
sum, n = 0, n.to_u64
while n > 0; sum += n%10; n //= 10; sum += d2sum[n%10]; n //= 10 end
sum % 10 == 0
end
cards = [49927398716, "49927398717", 1234567812345678, "1234567812345670"]
cards.each{ |i| puts "#{i}: ... |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #langur | langur | val .isPrime = f .i == 2 or
.i > 2 and not any f(.x) .i div .x, pseries 2 to .i ^/ 2
val .isMersennePrime = f(.p) {
if .p == 2: return true
if not .isPrime(.p): return false
val .mp = 2 ^ .p - 1
for[.s=4] of 3 to .p {
.s = (.s ^ 2 - 2) rem .mp
} == 0
}
writeln join " ", map f $"M\.... |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #PL.2FI | PL/I | *process source xref attributes or(!);
lzwt: Proc Options(main);
Dcl (LEFT,LENGTH,SUBSTR,TRANSLATE,TRIM,UNSPEC) Builtin;
Dcl SYSPRINT Print;
Dcl str Char(50) Var Init('TOBEORNOTTOBEORTOBEORNOT');
Dcl compressed Char(80) Var;
Dcl decompressed Char(80) Var;
Dcl 1 dict(0:300),
2 key Char(5) Var,
2... |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another... | #Sidef | Sidef | var story = ARGF.slurp;
var blanks = Hash.new;
while (var m = /<(.*?)>/.gmatch(story)) {
blanks.append(m[0]);
}
blanks.keys.sort.each { |blank|
var replacement = Sys.scanln("#{blank}: ");
blanks{blank} = replacement;
}
print story.gsub(/<(.*?)>/, {|s1| blanks{s1} }); |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #Scala | Scala | import scala.annotation.tailrec
object LoopIncrementWithinBody extends App {
private val (limit, offset) = (42L, 1)
@tailrec
private def loop(i: Long, n: Int): Unit = {
def isPrime(n: Long) =
n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) &&
((5 to math.sqrt(n).toInt by 2).par... |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Dyalect | Dyalect | while true {
print("SPAM")
} |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | while true:
!print "SPAM" |
http://rosettacode.org/wiki/Loops/With_multiple_ranges | Loops/With multiple ranges | Loops/With multiple ranges
You are encouraged to solve this task according to the task description, using any language you may know.
Some languages allow multiple loop ranges, such as the PL/I example (snippet) below.
/* all variables are DECLARED as integers. */
prod=... | #zkl | zkl | prod,sum := 1,0; /* start with a product of unity, sum of 0 */
x,y,z := 5, -5, -2;
one,three,seven := 1,3,7;
foreach j in (Walker.chain([-three..(3).pow(3),three], // do these sequentially
[-seven..seven,x], [555..550 - y], [22..-28,-three], #[start..last,step]
[1927..1939], [x..y,z], [(1... |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #EasyLang | EasyLang | i = 1024
while i > 0
print i
i = i div 2
. |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #EchoLisp | EchoLisp |
(set! n 1024)
(while (> n 0) (write n) (set! n (quotient n 2)))
1024 512 256 128 64 32 16 8 4 2 1
|
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #D | D | import std.stdio: writeln;
void main() {
for (int i = 10; i >= 0; --i)
writeln(i);
writeln();
foreach_reverse (i ; 0 .. 10 + 1)
writeln(i);
} |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loo... | #C.23 | C# | int a = 0;
do
{
a += 1;
Console.WriteLine(a);
} while (a % 6 != 0); |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #Babel | Babel | ((main { 10 star_triangle ! })
(star_triangle {
dup
<-
{ dup { "*" << } <->
iter - 1 +
times
"\n" << }
->
times })) |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop b... | #ChucK | ChucK |
SinOsc s => dac;
for (0 => int i; i < 2000; 5 +=> i )
{
i => s.freq;
100::ms => now;
}
|
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1... | #Tcl | Tcl | package require Tcl 8.6
proc ludic n {
global ludicList ludicGenerator
for {} {[llength $ludicList] <= $n} {lappend ludicList $i} {
set i [$ludicGenerator]
set ludicGenerator [coroutine L_$i apply {{gen k} {
yield [info coroutine]
while true {
set val [$gen]
if {[incr i] == $k} {set i 0} else ... |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of th... | #Gambas | Gambas | Public Sub Main()
Dim siLoop As Short
For siLoop = 1 To 10
Print siLoop;
If siLoop <> 10 Then Print ", ";
Next
End |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | 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 als... | #Frink | Frink | array = new array[[10,10], {|x,y| random[1,20]}]
println["array is:\n" + formatTable[array, "right"] + "\n"]
[rows,cols] = array.dimensions[]
ROW:
for r = 0 to rows-1
for c = 0 to cols-1
{
print[array@r@c + " " ]
if array@r@c == 20
break ROW
} |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Halon | Halon | $things = ["Apple", "Banana", "Coconut"];
foreach ($things as $thing) {
echo $thing;
} |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Haskell | Haskell | import Control.Monad (forM_)
forM_ collect print |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #D | D | import std.algorithm, std.range, std.string;
enum luhnTest = (in string n) pure /*nothrow*/ @safe /*@nogc*/ =>
retro(n)
.zip(only(1, 2).cycle)
.map!(p => (p[0] - '0') * p[1])
.map!(d => d / 10 + d % 10)
.sum % 10 == 0;
void main() {
assert("49927398716 49927398717 1234567812345678 1234567812... |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Select[Table[M = 2^p - 1;
For[i = 1; s = 4, i <= p - 2, i++, s = Mod[s^2 - 2, M]];
If[s == 0, "M" <> ToString@p, p], {p,
Prime /@ Range[300]}], StringQ]
=> {M3, M5, M7, M13, M17, M19, M31, M61, M89, M107, M127, M521, M607, M1279} |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #PureBasic | PureBasic | Procedure compress(uncompressed.s, List result.u())
;Compress a string to a list of output symbols
;Build the dictionary.
Protected dict_size = 255, i
newmap dict.u()
For i = 0 To 254
dict(Chr(i + 1)) = i
Next
Protected w.s, wc.s, *c.Character = @uncompressed
w = ""
LastElement(result())
W... |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another... | #tbas | tbas | SUB BETWEEN$(TXT$, LHS$, RHS$, AFTER)
LET LHS = POS(TXT$, LHS$, AFTER)
IF LHS = 0 THEN
'LHS$ NOT FOUND IN TXT$. RETURN EMPTY STRING
RETURN ""
EXIT SUB
END IF
LET RHS = POS(TXT$, RHS$, LHS + LEN(LHS$))
IF RHS = 0 THEN
'NO RHS$ FOUND IMMEDIATELY AFTER LHS$ IN TXT$. RETURN EMPTY STRING.
RETURN ""
EXIT SUB... |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func boolean: isPrime (in integer: number) is func
result
var boolean: result is FALSE;
local
var integer: count is 2;
begin
if number = 2 then
result := TRUE;
elsif number > 2 then
while number rem count <> 0 and count * count <= number do
inc... |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #Smalltalk | Smalltalk | numFound := 0.
idx := 42.
[:exit |
idx := idx + 1.
idx isPrime ifTrue:[
numFound := numFound + 1.
'%d %20d\n' printf:{numFound . idx} on:Transcript.
idx := idx + idx - 1.
numFound == 42 ifTrue:exit
].
] loopWithExit. |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #E | E | while (true) {
println("SPAM")
} |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #EDSAC_order_code | EDSAC order code | [ Infinite loop
=============
A program for the EDSAC
Works with Initial Orders 2 ]
T56K
GK
O10@ [ letter shift ]
[ 1 ] A17@ [ a += C(17@) ]
O11@
O12@
O13@
O14@
O15@
O16@
T17@ [ C(17@) = a; a = 0 ]
E1@ [ if a ... |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #EGL | EGL | x int = 1024;
while ( x > 0 )
SysLib.writeStdout( x );
x = MathLib.floor( x / 2 );
end |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #Elena | Elena | public program()
{
int i := 1024;
while (i > 0)
{
console.writeLine:i;
i /= 2
}
} |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #dc | dc | c
[macro s(swap) - (a b : b a)]s.
[Sa Sb La Lb] ss
[macro d(2dup) - (a b : a b a b)]s.
[Sa d Sb La d Lb lsx] sd
[macro m(for) - ]s.
[lfx 1 - ldx !<m ] sm
0 10 ldx [p] sf !<m
q |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #Delphi | Delphi | proc nonrec main() void:
byte i;
for i from 10 downto 0 do
write(i," ")
od
corp |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loo... | #C.2B.2B | C++ | int val = 0;
do{
val++;
std::cout << val << std::endl;
}while(val % 6 != 0); |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #bash | bash |
for i in {1..5}
do
for ((j=1; j<=i; j++));
do
echo -n "*"
done
echo
done
|
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop b... | #Clojure | Clojure | (loop [i 0]
(println i)
(when (< i 10)
(recur (+ 2 i))))
(doseq [i (range 0 12 2)]
(println i)) |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1... | #VBScript | VBScript |
Set list = CreateObject("System.Collections.Arraylist")
Set ludic = CreateObject("System.Collections.Arraylist")
'populate the list
For i = 1 To 25000
list.Add i
Next
'set 1 as the first ludic number
ludic.Add list(0)
list.RemoveAt(0)
'variable to count ludic numbers <= 1000
up_to_1k = 1
'determine the succe... |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of th... | #GAP | GAP | n := 10;
for i in [1 .. n] do
Print(i);
if i < n then
Print(", ");
else
Print("\n");
fi;
od; |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of th... | #GML | GML | str = ""
for(i = 1; i <= 10; i += 1)
{
str += string(i)
if(i != 10)
str += ", "
}
show_message(str) |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | 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 als... | #Gambas | Gambas | Public Sub Main()
Dim siArray As New Short[5, 5]
Dim siCount0, siCount1 As Short
Dim bBreak As Boolean
For siCount0 = 0 To 4
For siCount1 = 0 To 4
siArray[siCount0, siCount1] = Rand(1, 20)
siArray[siCount0, siCount1] = Rand(1, 20)
Next
Next
For siCount0 = 0 To 4
For siCount1 = 0 To 4
If siArray[si... |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Haxe | Haxe | var a = [1, 2, 3, 4];
for (i in a)
Sys.println(i); |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #HicEst | HicEst | CHARACTER days="Monday Tuesday Wednesday Thursday Friday Saturday Sunday "
items = INDEX(days, ' ', 256) ! 256 = count option
DO j = 1, items
EDIT(Text=days, ITeM=j, Parse=today)
WRITE() today
ENDDO |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #Draco | Draco | proc nonrec luhn(*char num) bool:
[10] byte map = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9);
byte total, digit;
*char start;
bool even;
start := num;
total := 0;
even := true;
while num* /= '\e' do num := num + 1 od;
while
num := num - 1;
num >= start
do
digit :... |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #MATLAB | MATLAB | function [mNumber,mersennesPrime] = mersennePrimes()
function isPrime = lucasLehmerTest(thePrime)
llResidue = 4;
mersennesPrime = (2^thePrime)-1;
for i = ( 1:thePrime-2 )
llResidue = mod( ((llResidue^2) - 2),mersennesPrime );
end
isPrime =... |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Python | Python | def compress(uncompressed):
"""Compress a string to a list of output symbols."""
# Build the dictionary.
dict_size = 256
dictionary = dict((chr(i), i) for i in range(dict_size))
# in Python 3: dictionary = {chr(i): i for i in range(dict_size)}
w = ""
result = []
for c in uncompressed... |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another... | #Tcl | Tcl | package require Tcl 8.5
# Read the template...
puts [string repeat "-" 70]
puts "Enter the story template, ending with a blank line"
while {[gets stdin line] > 0} {
append content $line "\n"
}
# Read the mapping...
puts [string repeat "-" 70]
set mapping {}
foreach piece [regexp -all -inline {<[^>]+>} $content]... |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #Standard_ML | Standard ML |
fun until done change dolast x =
if done x
then dolast x
else until done change dolast (change x); (* iteration/generic loop *)
val isprime = fn n :IntInf.int =>
let
fun butlast (_,t) = t*t > n
fun divide (n,t) = n mod t = 0 orelse t*t > n
fun trymore (n,t) = (n,t + 2)
in
... |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #Tcl | Tcl | proc isPrime n {
if {[expr $n % 2] == 0} {
return [expr $n == 2]
}
if {[expr $n % 3] == 0} {
return [expr $n == 3]
}
for {set d 5} {[expr $d * $d] <= $n} {incr d 4} {
if {[expr $n % $d] == 0} {return 0}
incr d 2
if {[expr $n % $d] == 0} {return 0}
}
return 1
}
set LIMIT 42
for {set... |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Ela | Ela | open monad io
loop () = do
putStrLn "SPAM"
loop ()
loop () ::: IO |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Elena | Elena | public program()
{
while (true)
{
console.writeLine:"spam"
}
} |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #Elixir | Elixir | defmodule Loops do
def while(0), do: :ok
def while(n) do
IO.puts n
while( div(n,2) )
end
end
Loops.while(1024) |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #Emacs_Lisp | Emacs Lisp | (let ((i 1024))
(while (> i 0)
(message "%d" i)
(setq i (/ i 2)))) |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #Draco | Draco | proc nonrec main() void:
byte i;
for i from 10 downto 0 do
write(i," ")
od
corp |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #DWScript | DWScript | for i := 10 downto 0 do
PrintLn(i); |
http://rosettacode.org/wiki/Loops/Do-while | Loops/Do-while | Start with a value at 0. Loop while value mod 6 is not equal to 0.
Each time through the loop, add 1 to the value then print it.
The loop must execute at least once.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loo... | #Chapel | Chapel | var val = 0;
do {
val += 1;
writeln(val);
} while val % 6 > 0; |
http://rosettacode.org/wiki/Loops/For | Loops/For | “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code.
Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers.
... | #BASIC | BASIC | FOR i = 1 TO 5
FOR j = 1 TO i
PRINT "*";
NEXT j
PRINT
NEXT i |
http://rosettacode.org/wiki/Loops/For_with_a_specified_step | Loops/For with a specified step |
Task
Demonstrate a for-loop where the step-value is greater than one.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop b... | #CLU | CLU | % This prints all odd digits
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to_by(1, 10, 2) do
stream$putl(po, int$unparse(i))
end
end start_up |
http://rosettacode.org/wiki/Ludic_numbers | Ludic numbers | Ludic numbers are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers.
The first ludic number is 1.
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1... | #Vlang | Vlang | const max_i32 = 1<<31 - 1 // i.e. math.MaxInt32
// ludic returns a slice of ludic numbers stopping after
// either n entries or when max is exceeded.
// Either argument may be <=0 to disable that limit.
fn ludic(nn int, m int) []u32 {
mut n := nn
mut max := m
if max > 0 && n < 0 {
n = max_i32
}
... |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of th... | #Go | Go | package main
import "fmt"
func main() {
for i := 1; ; i++ {
fmt.Print(i)
if i == 10 {
fmt.Println()
break
}
fmt.Print(", ")
}
} |
http://rosettacode.org/wiki/Loops/N_plus_one_half | Loops/N plus one half | Quite often one needs loops which, in the last iteration, execute only part of the loop body.
Goal
Demonstrate the best way to do this.
Task
Write a loop which writes the comma-separated list
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
using separate output statements for the number
and the comma from within the body of th... | #Gosu | Gosu | var out = System.out
for(i in 1..10) {
if(i > 1) out.print(", ")
out.print(i)
} |
http://rosettacode.org/wiki/Loops/Nested | Loops/Nested | 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 als... | #GAP | GAP | # You can't break an outer loop unless you return from the whole function.
n := 40;
a := List([1 .. n], i -> List([1 .. n], j -> Random(1, 20)));;
Find := function(a, x)
local i, j, n;
n := Length(a);
for i in [1 .. n] do
for j in [1 .. n] do
if a[i][j] = x then
return ... |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Hy | Hy | (for [x collection] (print x)) |
http://rosettacode.org/wiki/Loops/Foreach | Loops/Foreach | Loop through and print each element in a collection in order.
Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for... | #Icon_and_Unicon | Icon and Unicon | procedure main()
X := [1,2,3,-5,6,9]
every x := !L do
write(x)
end |
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers | Luhn test of credit card numbers | The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
Reverse the order of the digits in the number.
Tak... | #EchoLisp | EchoLisp |
;; value for 'even' numbers
(define (even-val n) (if (> n 4) (+ n n -9) (+ n n)))
;;Luhn test
;; input : a string of decimal digits
;; output #t or #f
(define (valid nums (odd #f ))
(let ((nums (map string->number (reverse (string->list nums)))))
(= 0 (modulo
(for/sum ((n nums)) (set! odd (not odd)... |
http://rosettacode.org/wiki/Lucas-Lehmer_test | Lucas-Lehmer test | Lucas-Lehmer Test:
for
p
{\displaystyle p}
an odd prime, the Mersenne number
2
p
−
1
{\displaystyle 2^{p}-1}
is prime if and only if
2
p
−
1
{\displaystyle 2^{p}-1}
divides
S
(
p
−
1
)
{\displaystyle S(p-1)}
where
S
(
n
+
1
)
=
(
S
(
n
)
)
2
−
2
{\displaystyle S(n+1)=(... | #Maxima | Maxima | lucas_lehmer(p) := block([s, n, i],
if not primep(p) then false elseif p = 2 then true else
(s: 4,
n: 2^p - 1,
for i: 2 thru p - 1 do s: mod(s*s - 2, n),
is(s = 0))
)$
sublist(makelist(i, i, 1, 200), lucas_lehmer);
/* [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127] */ |
http://rosettacode.org/wiki/LZW_compression | LZW compression | The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
You can read a complete description of it in the Wikipedia article on the subject. It was patented, but it entered the public domain in 2004.
| #Racket | Racket |
#lang racket
; utilities
(define-syntax def (make-rename-transformer #'define))
(define (dict-ref d w) (hash-ref d w #f))
(define (append-char w c) (string-append w (string c)))
(define (append-first w s) (append-char w (string-ref s 0)))
;; Compress a string with LZW
(define (compress uncompressed)
(def d (make... |
http://rosettacode.org/wiki/Mad_Libs | Mad Libs |
This page uses content from Wikipedia. The original article was at Mad Libs. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Mad Libs is a phrasal template word game where one player prompts another... | #VBScript | VBScript | Function mad_libs(s)
Do
If InStr(1,s,"<") <> 0 Then
start_position = InStr(1,s,"<") + 1
end_position = InStr(1,s,">")
parse_string = Mid(s,start_position,end_position-start_position)
WScript.StdOut.Write parse_string & "? "
input_string = WScript.S... |
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body | Loops/Increment loop index within loop body | Sometimes, one may need (or want) a loop which
its iterator (the index
variable) is modified within the
loop body in addition to the normal incrementation by the (do) loop structure index.
Goal
Demonstrate the best way to accomplish this.
Task
Write a loop which:
starts the index (variable... | #VBA | VBA | Sub Main()
'Loops Increment loop index within loop body - 17/07/2018
Dim imax, i As Integer
Dim n As Currency
imax = 42
i = 0: n = 42
Do While i < imax
If IsPrime(n) Then
i = i + 1
Debug.Print ("i=" & RightX(i, 2) & " : " & ... |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Elixir | Elixir | defmodule Loops do
def infinite do
IO.puts "SPAM"
infinite
end
end
Loops.infinite |
http://rosettacode.org/wiki/Loops/Infinite | Loops/Infinite | Task
Print out SPAM followed by a newline in an infinite loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within l... | #Emacs_Lisp | Emacs Lisp | (while t
(message "SPAM")) |
http://rosettacode.org/wiki/Loops/While | Loops/While | Task
Start an integer value at 1024.
Loop while it is greater than zero.
Print the value (with a newline) and divide it by two each time through the loop.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For... | #Erlang | Erlang | -module(while).
-export([loop/0]).
loop() ->
loop(1024).
loop(N) when N div 2 =:= 0 ->
io:format("~w~n", [N]);
loop(N) when N >0 ->
io:format("~w~n", [N]),
loop(N div 2). |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #E | E | for i in (0..10).descending() { println(i) } |
http://rosettacode.org/wiki/Loops/Downward_for | Loops/Downward for | Task
Write a for loop which writes a countdown from 10 to 0.
Related tasks
Loop over multiple arrays simultaneously
Loops/Break
Loops/Continue
Loops/Do-while
Loops/Downward for
Loops/For
Loops/For with a specified step
Loops/Foreach
Loops/Increment loop index within loop body... | #EasyLang | EasyLang | for i = 10 downto 0
print i
. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.