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 the 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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 the 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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 also shows how to break out of nested loops. 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 also shows how to break out of nested loops. 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 A(I, J) = RNDINT(1, 20) 10 CONTINUE 20 CONTINUE   C Print the numbers. DO 40 I = 1, 20 DO 30 J = 1, 20 WRITE (*,5000) I, J, A(I, J)   C If this number is twenty, break out of both loops. IF (A(I, J) .EQ. 20) GOTO 50 30 CONTINUE 40 CONTINUE   C If we had gone to 40, the DO loop would have continued. You can C label STOP instead of adding another CONTINUE, but it is good C form to only label CONTINUE statements as much as possible. 50 CONTINUE STOP   C Print the value so that it looks like one of those C arrays that C makes everybody so comfortable. 5000 FORMAT('A[', I2, '][', I2, '] is ', I2) END   C FORTRAN 77 does not come with a random number generator, but it is C easy enough to type "fortran 77 random number generator" into your C preferred search engine and to copy and paste what you find. C The following code is a slightly-modified version of: C C http://www.tat.physik.uni-tuebingen.de/ C ~kley/lehre/ftn77/tutorial/subprograms.html SUBROUTINE SDRAND (IRSEED) COMMON /SEED/ UTSEED, IRFRST UTSEED = IRSEED IRFRST = 0 RETURN END INTEGER FUNCTION RNDINT (IFROM, ITO) INTEGER IFROM, ITO PARAMETER (MPLIER=16807, MODLUS=2147483647, & & MOBYMP=127773, MOMDMP=2836) COMMON /SEED/ UTSEED, IRFRST INTEGER HVLUE, LVLUE, TESTV, NEXTN SAVE NEXTN IF (IRFRST .EQ. 0) THEN NEXTN = UTSEED IRFRST = 1 ENDIF HVLUE = NEXTN / MOBYMP LVLUE = MOD(NEXTN, MOBYMP) TESTV = MPLIER*LVLUE - MOMDMP*HVLUE IF (TESTV .GT. 0) THEN NEXTN = TESTV ELSE NEXTN = TESTV + MODLUS ENDIF IF (NEXTN .GE. 0) THEN RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + IFROM ELSE RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + ITO + 1 ENDIF RETURN END
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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#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;   var sum: uint8 := 0; while n > 0 loop # odd digit is simply added card := @prev card; n := n - 1; sum := sum + ([card] - '0');   # if uneven amount of digits, stop if n == 0 then break; end if;   # even digit card := @prev card; n := n - 1; var digit := [card] - '0';   # it is good to avoid unnecessary multiplication/ # division, since 8-bit processors and microcontrollers # don't tend to have that in hardware if digit < 5 then sum := sum + digit + digit; else digit := digit - 5; sum := sum + digit + digit + 1; end if; end loop;   # there is no boolean type, comparisons only work # in conditionals; this is the only way to return # a status if sum % 10 == 0 then ok := 1; else ok := 0; end if; end sub;     # Test and print sub test(card: [uint8]) is var msg: [uint8][] := {"Fail", "Pass"}; print(card); print(": "); print(msg[luhn(card)]); print_nl(); end sub;   test("49927398716"); test("49927398717"); test("1234567812345678"); test("1234567812345670");
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)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#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) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true }   fun main(args: Array<String>) { var count = 0 var p = 3 // first odd prime var s: BigInteger var m: BigInteger while (true) { m = bigTwo.shiftLeft(p - 1) - BigInteger.ONE s = bigFour for (i in 1 .. p - 2) s = (s * s - bigTwo) % m if (s == BigInteger.ZERO) { count +=1 print("M$p ") if (count == MAX) { println() break } } // obtain next odd prime while(true) { p += 2 if (isPrime(p)) break } } }
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) (link (cdr (lup Dict W))) (idx 'Dict (cons WC (inc 'Codes)) T) (setq W C) ) ) ) (and W (link (cdr (lup Dict W)))) ) ) ) )   (de lzwDecompress (Lst) (let (Codes 255 Dict) (balance 'Dict (make (for C Codes (link (list C (char C))) ) ) ) (make (let W NIL (for N Lst (let WC (if (lup Dict N) (cdr @) (cons (last W) W)) (chain (reverse WC)) (when W (idx 'Dict (cons (inc 'Codes) (cons (last WC) W)) T) ) (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. While the Cholesky decomposition only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. There are several algorithms for calculating L and U. To derive Crout's algorithm for a 3x3 example, we have to solve the following system: A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}=LU} We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of L {\displaystyle L} are set to 1 l 11 = 1 {\displaystyle l_{11}=1} l 22 = 1 {\displaystyle l_{22}=1} l 33 = 1 {\displaystyle l_{33}=1} so we get a solvable system of 9 unknowns and 9 equations. A = ( a 11 a 12 a 13 a 21 a 22 a 23 a 31 a 32 a 33 ) = ( 1 0 0 l 21 1 0 l 31 l 32 1 ) ( u 11 u 12 u 13 0 u 22 u 23 0 0 u 33 ) = ( u 11 u 12 u 13 u 11 l 21 u 12 l 21 + u 22 u 13 l 21 + u 23 u 11 l 31 u 12 l 31 + u 22 l 32 u 13 l 31 + u 23 l 32 + u 33 ) = L U {\displaystyle A={\begin{pmatrix}a_{11}&a_{12}&a_{13}\\a_{21}&a_{22}&a_{23}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}={\begin{pmatrix}1&0&0\\l_{21}&1&0\\l_{31}&l_{32}&1\\\end{pmatrix}}{\begin{pmatrix}u_{11}&u_{12}&u_{13}\\0&u_{22}&u_{23}\\0&0&u_{33}\end{pmatrix}}={\begin{pmatrix}u_{11}&u_{12}&u_{13}\\u_{11}l_{21}&u_{12}l_{21}+u_{22}&u_{13}l_{21}+u_{23}\\u_{11}l_{31}&u_{12}l_{31}+u_{22}l_{32}&u_{13}l_{31}+u_{23}l_{32}+u_{33}\end{pmatrix}}=LU} Solving for the other l {\displaystyle l} and u {\displaystyle u} , we get the following equations: u 11 = a 11 {\displaystyle u_{11}=a_{11}} u 12 = a 12 {\displaystyle u_{12}=a_{12}} u 13 = a 13 {\displaystyle u_{13}=a_{13}} u 22 = a 22 − u 12 l 21 {\displaystyle u_{22}=a_{22}-u_{12}l_{21}} u 23 = a 23 − u 13 l 21 {\displaystyle u_{23}=a_{23}-u_{13}l_{21}} u 33 = a 33 − ( u 13 l 31 + u 23 l 32 ) {\displaystyle u_{33}=a_{33}-(u_{13}l_{31}+u_{23}l_{32})} and for l {\displaystyle l} : l 21 = 1 u 11 a 21 {\displaystyle l_{21}={\frac {1}{u_{11}}}a_{21}} l 31 = 1 u 11 a 31 {\displaystyle l_{31}={\frac {1}{u_{11}}}a_{31}} l 32 = 1 u 22 ( a 32 − u 12 l 31 ) {\displaystyle l_{32}={\frac {1}{u_{22}}}(a_{32}-u_{12}l_{31})} We see that there is a calculation pattern, which can be expressed as the following formulas, first for U {\displaystyle U} u i j = a i j − ∑ k = 1 i − 1 u k j l i k {\displaystyle u_{ij}=a_{ij}-\sum _{k=1}^{i-1}u_{kj}l_{ik}} and then for L {\displaystyle L} l i j = 1 u j j ( a i j − ∑ k = 1 j − 1 u k j l i k ) {\displaystyle l_{ij}={\frac {1}{u_{jj}}}(a_{ij}-\sum _{k=1}^{j-1}u_{kj}l_{ik})} We see in the second formula that to get the l i j {\displaystyle l_{ij}} below the diagonal, we have to divide by the diagonal element (pivot) u j j {\displaystyle u_{jj}} , so we get problems when u j j {\displaystyle u_{jj}} is either 0 or very small, which leads to numerical instability. The solution to this problem is pivoting A {\displaystyle A} , which means rearranging the rows of A {\displaystyle A} , prior to the L U {\displaystyle LU} decomposition, in a way that the largest element of each column gets onto the diagonal of A {\displaystyle A} . Rearranging the rows means to multiply A {\displaystyle A} by a permutation matrix P {\displaystyle P} : P A ⇒ A ′ {\displaystyle PA\Rightarrow A'} Example: ( 0 1 1 0 ) ( 1 4 2 3 ) ⇒ ( 2 3 1 4 ) {\displaystyle {\begin{pmatrix}0&1\\1&0\end{pmatrix}}{\begin{pmatrix}1&4\\2&3\end{pmatrix}}\Rightarrow {\begin{pmatrix}2&3\\1&4\end{pmatrix}}} The decomposition algorithm is then applied on the rearranged matrix so that P A = L U {\displaystyle PA=LU} Task description The task is to implement a routine which will take a square nxn matrix A {\displaystyle A} and return a lower triangular matrix L {\displaystyle L} , a upper triangular matrix U {\displaystyle U} and a permutation matrix P {\displaystyle P} , so that the above equation is fulfilled. You should then test it on the following two examples and include your output. Example 1 A 1 3 5 2 4 7 1 1 0 L 1.00000 0.00000 0.00000 0.50000 1.00000 0.00000 0.50000 -1.00000 1.00000 U 2.00000 4.00000 7.00000 0.00000 1.00000 1.50000 0.00000 0.00000 -2.00000 P 0 1 0 1 0 0 0 0 1 Example 2 A 11 9 24 2 1 5 2 6 3 17 18 1 2 5 7 1 L 1.00000 0.00000 0.00000 0.00000 0.27273 1.00000 0.00000 0.00000 0.09091 0.28750 1.00000 0.00000 0.18182 0.23125 0.00360 1.00000 U 11.00000 9.00000 24.00000 2.00000 0.00000 14.54545 11.45455 0.45455 0.00000 0.00000 -3.47500 5.68750 0.00000 0.00000 0.00000 0.51079 P 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1
#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); println("L:\n",L.format(),"\nU:\n",U.format());   A:=GSL.Matrix(4,4).set(11.0, 9.0, 24.0, 2.0, // example 2 1.0, 5.0, 2.0, 6.0, 3.0, 17.0, 18.0, 1.0, 2.0, 5.0, 7.0, 1.0); L,U:=luTask(A); println("L:\n",L.format(8,4),"\nU:\n",U.format(8,4));
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 for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 line <> "" then story &:= line & "\n"; end if; until line = ""; pos1 := pos(story, '<'); while pos1 <> 0 and pos2 <> 0 do pos2 := pos(story, '>', pos1); if pos2 <> 0 then field := story[pos1 .. pos2]; write("Enter a value for " <& field <& ": "); story := replace(story, field, getln(IN)); pos1 := pos(story, '<', pos1); end if; end while; writeln; writeln("The story becomes:"); write(story); end func;
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) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. 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/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. 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/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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. if abs(Prod)<1<<27 & J#0 then Prod:=Prod*J; \PROD is small enough & J end; \not 0, then multiply it.   begin \all variables are DECLARED as integers. Prod:= 1; \start with a product of unity. Sum:= 0; \ " " " sum " zero. X:= +5; Y:= -5; Z:= -2; One:= 1; Three:= 3; Seven:= 7;   for J:= -Three to 3*3*3 do [Block; J:= J+Three-1]; for J:= -Seven to +Seven do [Block; J:= J+X-1]; for J:= 555 to 550 - Y do Block; for J:= 22 downto -28 do [Block; J:= J-Three+1]; for J:= 1927 to 1939 do Block; for J:= X downto Y do [Block; J:= J+Z+1]; for J:= IPow(11,X) to IPow(11,X)+One do Block;   \SUM and PROD are used for verification of J incrementation. Text(0, " Sum= "); IntOut(0, Sum); CrLf(0); \display strings to term. Text(0, "Prod= "); IntOut(0, Prod); CrLf(0); \ " " " " end
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= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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: process(j): next j for j = 22 to -28 step -three: process(j): next j for j = 1927 to 1939: process(j): next j for j = x to y step z: process(j): next j for j = (11 ^ x) to (11 ^ x) + one: process(j): next j   print " sum= ", sum using "###,###" print "prod= ", prod using "####,###,###" 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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#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   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#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. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#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 body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#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 ludics = 1:: (#2 (ListPair.unzip(Ludi (ListPair.zip ( List.tabulate(25000,fn i=>i),tabulate (25000,fn i=>i+2)) )) ));   app ((fn e => print (e^" ")) o Int.toString ) (take (ludics,25)); length (filter (fn e=> e <= 1000) ludics); drop (take (ludics,2005),1999);  
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 the 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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 also shows how to break out of nested loops. 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 '' Exits both for loops Next j Print Next i   Print Print "Press any key to quit" Sleep
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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#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}: #{luhn_valid?(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)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#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\.x;", where .isMersennePrime, series 2300
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 inx Bin Fixed(16) Unsigned; Dcl dict_size Bin Fixed(31) Init(256); Dcl hi Bin Fixed(16) Unsigned Init(65535);   Put Edit('str=',str)(Skip,a,a); compressed = compress(str); Put Edit(compressed)(Skip,a); decompressed = decompress(compressed); Put Edit('dec=',decompressed)(Skip,a,a); If decompressed=str Then Put Edit('decompression ok')(Skip,a); Else Put Edit('decompression not ok')(Skip,a);   compress: Proc(s) Returns(Char(80) Var); Dcl s Char(*) Var; Dcl res Char(80) Var; Dcl i Bin Fixed(31); Dcl c Char(1); Dcl w Char(5) Var; Dcl wc Char(5) Var; dict.key=''; Dcl ii Bin Fixed(8) Unsigned; Do i=0 To 255; ii=i; Unspec(c)=unspec(ii); dict.key(i)=c; dict.inx(i)=i; End; res='['; w=''; Do i=1 To length(s); c=substr(s,i,1); wc=w!!c; If dicti(wc)^=hi Then Do; w=wc; End; Else Do; res=res!!trim(dicti(w))!!', '; Call dict_add(wc,dict_size); w=c; End; End; If w^='' Then res=res!!trim(dicti(w))!!', '; substr(res,length(res)-1,1)=']'; Return(res);   dicti: Proc(needle) Returns(Bin Fixed(31)); Dcl needle Char(*) Var; Dcl i Bin Fixed(31); Do i=1 To dict_size; If dict.key(i)=needle Then Return(i); End; Return(hi); End;   dict_add: Proc(needle,dict_size); Dcl needle Char(*) Var; Dcl dict_size Bin Fixed(31); dict.key(dict_size)=needle; dict.inx(dict_size)=dict_size; dict_size+=1; End;   End;   decompress: Proc(s) Returns(Char(80) Var); Dcl s Char(80) Var; Dcl ss Char(80) Var; Dcl words(50) Char(5) Var; Dcl wn Bin Fixed(31); Dcl ww Bin Fixed(31); Dcl c Char(1); Dcl entry Char(5) Var; Dcl w Char(5) Var; Dcl res Char(80) Var; ss=translate(s,' ','[],'); Call mk_words(ss,words,wn); dict.key=''; dict.inx=hi; Dcl i Bin Fixed(31); Dcl ii Bin Fixed(8) Unsigned; Dcl dict(0:300) Char(5) Var; Dcl dict_size Bin Fixed(31); Do i=0 To 255; ii=i; Unspec(c)=unspec(ii); dict(i)=c; End; dict_size=256; ww=words(1); w=dict(ww); res=w; Do i=2 To wn; ww=words(i); Select; When(dict(ww)^='') entry=dict(ww); When(ww=dict_size) entry=w!!substr(w,1,1); Otherwise Put Edit('Bad compressed k: ',ww)(Skip,a,a); End; res=res!!entry; dict(dict_size)=w!!substr(entry,1,1); dict_size+=1; w=entry; End; Return(res); End;   mk_words: Proc(st,arr,arrn); Dcl st Char(*) Var; Dcl sv Char(80) Var; Dcl arr(*) Char(5) Var; Dcl arrn Bin fixed(31); Dcl elem Char(5) Var; arrn=0; sv=st!!' '; elem=''; Do While(length(sv)>0); If left(sv,1)=' ' Then Do; If elem>'' Then Do; arrn+=1; arr(arrn)=elem; elem=''; End; End; Else elem=elem!!left(sv,1); sv=substr(sv,2); End; End; Return;   End;
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 for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. 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/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 forall (n % _ != 0))   if (n < limit + offset) if (isPrime(i)) { printf("n = %-2d  %,19d%n".formatLocal(java.util.Locale.GERMANY, n, i)) loop(i + i + 1, n + 1) } else loop(i + 1, n) }   loop(limit, offset) }
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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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= 1; /*start with a product of unity. */ sum= 0; /* " " " sum " zero. */ x= +5; y= -5; z= -2; one= 1; three= 3; seven= 7; /*(below) ** is exponentiation: 4**3=64 */ do j= -three to 3**3 by three , -seven to +seven by x , 555 to 550 - y , 22 to -28 by -three , 1927 to 1939 , x to y by z , 11**x to 11**x + one; /* ABS(n) = absolute value*/ sum= sum + abs(j); /*add absolute value of J.*/ if abs(prod)<2**27 & j¬=0 then prod=prod*j; /*PROD is small enough & J*/ end; /*not 0, then multiply it.*/ /*SUM and PROD are used for verification of J incrementation.*/ display (' sum= ' || sum); /*display strings to term.*/ display ('prod= ' || prod); /* " " " " */ Task Simulate/translate the above PL/I program snippet as best as possible in your language,   with particular emphasis on the   do   loop construct. The   do   index must be incremented/decremented in the same order shown. If feasible, add commas to the two output numbers (being displayed). Show all output here. A simple PL/I DO loop (incrementing or decrementing) has the construct of:   DO variable = start_expression {TO ending_expression] {BY increment_expression} ; ---or--- DO variable = start_expression {BY increment_expression} {TO ending_expression]  ;   where it is understood that all expressions will have a value. The variable is normally a scaler variable, but need not be (but for this task, all variables and expressions are declared to be scaler integers). If the BY expression is omitted, a BY value of unity is used. All expressions are evaluated before the DO loop is executed, and those values are used throughout the DO loop execution (even though, for instance, the value of Z may be changed within the DO loop. This isn't the case here for this task.   A multiple-range DO loop can be constructed by using a comma (,) to separate additional ranges (the use of multiple TO and/or BY keywords). This is the construct used in this task.   There are other forms of DO loops in PL/I involving the WHILE clause, but those won't be needed here. DO loops without a TO clause might need a WHILE clause or some other means of exiting the loop (such as LEAVE, RETURN, SIGNAL, GOTO, or STOP), or some other (possible error) condition that causes transfer of control outside the DO loop.   Also, in PL/I, the check if the DO loop index value is outside the range is made at the "head" (start) of the DO loop, so it's possible that the DO loop isn't executed, but that isn't the case for any of the ranges used in this task.   In the example above, the clause: x to y by z will cause the variable J to have to following values (in this order): 5 3 1 -1 -3 -5   In the example above, the clause: -seven to +seven by x will cause the variable J to have to following values (in this order): -7 -2 3 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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], [(11).pow(x)..(11).pow(x) + one])){ sum+=j.abs(); /* add absolute value of J */ if(prod.abs()<(2).pow(27) and j!=0) prod*=j; /* PROD is small enough & J */ } /* SUM and PROD are used for verification of J incrementation */ println("sum = %,d\nprod = %,d".fmt(sum,prod));
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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#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. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#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 body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#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 {yield $val} } }} $ludicGenerator $i] } return [lindex $ludicList $n] } # Bootstrap the generator sequence set ludicList [list 1] set ludicGenerator [coroutine L_1 apply {{} { set n 1 yield [info coroutine] while true {yield [incr n]} }}]   # Default of 1000 is not enough interp recursionlimit {} 5000   for {set i 0;set l {}} {$i < 25} {incr i} {lappend l [ludic $i]} puts "first25: [join $l ,]"   for {set i 0} {[ludic $i] <= 1000} {incr i} {} puts "below=1000: $i"   for {set i 1999;set l {}} {$i < 2005} {incr i} {lappend l [ludic $i]} puts "2000-2005: [join $l ,]"   for {set i 0} {[ludic $i] < 256} {incr i} {set isl([ludic $i]) $i} for {set i 1;set l {}} {$i < 250} {incr i} { if {[info exists isl($i)] && [info exists isl([expr {$i+2}])] && [info exists isl([expr {$i+6}])]} { lappend l ($i,[expr {$i+2}],[expr {$i+6}]) } } puts "triplets: [join $l ,]"
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 the 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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 also shows how to break out of nested loops. 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#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 1234567812345670" .split.map!luhnTest.equal([true, false, false, true])); }
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)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#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()) While *c\c <> #Null wc = w + Chr(*c\c) If FindMapElement(dict(), wc) w = wc Else AddElement(result()) result() = dict(w) ;Add wc to the dictionary dict(wc) = dict_size dict_size + 1 ;no check is performed for overfilling the dictionary. w = Chr(*c\c) EndIf *c + 1 Wend   ;Output the code for w If w AddElement(result()) result() = dict(w) EndIf EndProcedure   Procedure.s decompress(List compressed.u()) ;Decompress a list of encoded values to a string If ListSize(compressed()) = 0: ProcedureReturn "": EndIf   ;Build the dictionary. Protected dict_size = 255, i   Dim dict.s(255) For i = 1 To 255 dict(i - 1) = Chr(i) Next   Protected w.s, entry.s, result.s FirstElement(compressed()) w = dict(compressed()) result = w   i = 0 While NextElement(compressed()) i + 1 If compressed() < dict_size entry = dict(compressed()) ElseIf i = dict_size entry = w + Left(w, 1) Else MessageRequester("Error","Bad compression at [" + Str(i) + "]") ProcedureReturn result;abort EndIf result + entry ;Add w + Left(entry, 1) to the dictionary If ArraySize(dict()) <= dict_size Redim dict(dict_size + 256) EndIf dict(dict_size) = w + Left(entry, 1) dict_size + 1 ;no check is performed for overfilling the dictionary.   w = entry Wend ProcedureReturn result EndProcedure   If OpenConsole() ;How to use:   Define initial.s, decompressed.s   Print("Type something: ") initial = Input() NewList compressed.u() compress(initial, compressed()) ForEach compressed() Print(Str(compressed()) + " ") Next PrintN("")   decompressed = decompress(compressed()) PrintN(decompressed)   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole() EndIf
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 for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 END IF RETURN SEG$(TXT$, LHS + LEN(LHS$), RHS-1) END SUB   DECLARE SUB REPLACE$(INTHIS$, FINDTHIS$, WITHTHIS$) LET T = POS(INTHIS$, FINDTHIS$) RETURN INTHIS$ IF T <> 0 THEN MID$(INTHIS$, T, LEN(FINDTHIS$)) = WITHTHIS$ RETURN INTHIS$ END IF END SUB   LET STORY$ = "" LET STORYLINE$ = "" WHILE TRUE LINE INPUT "Enter line of story (empty line to stop)"; STORYLINE$ IF STORYLINE$ = "" THEN EXIT WHILE END IF STORY$ = STORY$ + " " + STORYLINE$ END WHILE   WHILE TRUE LET TXT$ = "" LET KEY$ = BETWEEN$(STORY$, "<", ">", 0) IF KEY$ <> "" THEN PRINT "PLEASE ENTER A " + KEY$; LINE INPUT TXT$ LET SRCH$ = "<" + KEY$ + ">" STORY$ = REPLACE$(STORY$, SRCH$, TXT$) ELSE EXIT WHILE END IF END WHILE   PRINT STORY$
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) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. 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/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 incr(count); end while; result := number rem count <> 0; end if; end func;   const proc: main is func local var integer: i is 42; var integer: n is 0; begin for i range 42 to integer.last until n >= 42 do if isPrime(i) then incr(n); writeln("n = " <& n lpad 2 <& i lpad 16); i +:= i - 1; end if; end for; end func;
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) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. 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/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 >= 0 goto 1@ ]   [ 10 ] *F [ 11 ] SF [ 12 ] PF [ 13 ] AF [ 14 ] MF [ 15 ] @F [ carriage return ] [ 16 ] &F [ line feed ]   [ 17 ] PF   EZPF
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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#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. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#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 body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#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 succeeding ludic numbers For j = 2 To 2005 If list.Count > 0 Then If list(0) <= 1000 Then up_to_1k = up_to_1k + 1 End If ludic.Add list(0) Else Exit For End If increment = list(0) - 1 n = 0 Do While n <= list.Count - 1 list.RemoveAt(n) n = n + increment Loop Next   'the first 25 ludics WScript.StdOut.WriteLine "First 25 Ludic Numbers:" For k = 0 To 24 If k < 24 Then WScript.StdOut.Write ludic(k) & ", " Else WScript.StdOut.Write ludic(k) End If Next WScript.StdOut.WriteBlankLines(2)   'the number of ludics up to 1000 WScript.StdOut.WriteLine "Ludics up to 1000: " WScript.StdOut.WriteLine up_to_1k WScript.StdOut.WriteBlankLines(1)   '2000th - 2005th ludics WScript.StdOut.WriteLine "The 2000th - 2005th Ludic Numbers:" For k = 1999 To 2004 If k < 2004 Then WScript.StdOut.Write ludic(k) & ", " Else WScript.StdOut.Write ludic(k) End If Next WScript.StdOut.WriteBlankLines(2)   'triplets up to 250: x, x+2, and x+6 WScript.StdOut.WriteLine "Ludic Triplets up to 250: " triplets = "" k = 0 Do While ludic(k) + 6 <= 250 x2 = ludic(k) + 2 x6 = ludic(k) + 6 If ludic.IndexOf(x2,1) > 0 And ludic.IndexOf(x6,1) > 0 Then triplets = triplets & ludic(k) & ", " & x2 & ", " & x6 & vbCrLf End If k = k + 1 Loop WScript.StdOut.WriteLine triplets  
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 the 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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 the 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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 also shows how to break out of nested loops. 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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[siCount0, siCount1] = 20 Then bBreak = True Break Endif Next If bBreak Then Break Next   Print "Row " & Str(siCount0) & " column " & Str(siCount1) & " = 20"   End
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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#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 := num* - '0'; even := not even; if even then digit := map[digit] fi; total := total + digit od;   total % 10 = 0 corp   proc nonrec test(*char num) void: writeln(num, ": ", if luhn(num) then "pass" else "fail" fi) corp   proc nonrec main() void: test("49927398716"); test("49927398717"); test("1234567812345678"); test("1234567812345670") corp
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)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#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 = (llResidue == 0);   end   %Because IEEE764 Double is the highest precision number we can %represent in MATLAB, the highest Mersenne Number we can test is 2^52. %In addition, because we have this cap, we can only test up to the %number 30 for Mersenne Primeness. When we input 31 into the %Lucas-Lehmer test, during the computation of the residue, the %algorithm multiplies two numbers together the result of which is %greater than 2^53. Because we require every digit to be significant, %this leads to an error. The Lucas-Lehmer test should say that M31 is a %Mersenne Prime, but because of the rounding error in calculating the %residues caused by floating-point arithmetic, it does not. So M30 is %the largest number we test.   mNumber = (3:30);   [isPrime] = arrayfun(@lucasLehmerTest,mNumber);   mNumber = [2 mNumber(isPrime)]; mersennesPrime = (2.^mNumber) - 1;   end
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: wc = w + c if wc in dictionary: w = wc else: result.append(dictionary[w]) # Add wc to the dictionary. dictionary[wc] = dict_size dict_size += 1 w = c   # Output the code for w. if w: result.append(dictionary[w]) return result     def decompress(compressed): """Decompress a list of output ks to a string.""" from io import StringIO   # Build the dictionary. dict_size = 256 dictionary = dict((i, chr(i)) for i in range(dict_size)) # in Python 3: dictionary = {i: chr(i) for i in range(dict_size)}   # use StringIO, otherwise this becomes O(N^2) # due to string concatenation in a loop result = StringIO() w = chr(compressed.pop(0)) result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] elif k == dict_size: entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) result.write(entry)   # Add w+entry[0] to the dictionary. dictionary[dict_size] = w + entry[0] dict_size += 1   w = entry return result.getvalue()     # How to use: compressed = compress('TOBEORNOTTOBEORTOBEORNOT') print (compressed) decompressed = decompress(compressed) print (decompressed)
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 for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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] { if {[dict exists $mapping $piece]} continue puts -nonewline "Give me a $piece: " flush stdout dict set mapping $piece [gets stdin] }   # Apply the mapping and print... puts [string repeat "-" 70] puts -nonewline [string map $mapping $content] puts [string repeat "-" 70]
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) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. 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/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   n mod 2 <> 0 andalso until divide trymore butlast (n,3)   end;   val loop = fn () => let fun butthislast (_,p,_) = rev p fun wegot42 (n,_,_) = n = 43 fun trymore (n,p,i) = if isprime i then ( n+1, (n,i)::p , i+i ) else ( n , p, i+1) in   until wegot42 trymore butthislast (1,[],42)   end ;   val printp = fn clist:(int*IntInf.int) list => List.app (fn i=>print ((Int.toString (#1 i) )^" : "^ (IntInf.toString (#2 i) )^"\n")) clist ;
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) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. 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/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 i $LIMIT; set n 0} {$n < $LIMIT} {incr i} { if [isPrime $i] { incr n puts "n=$n, i=$i" incr i [expr $i -1] } }
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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference Do while loop Wikipedia.
#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. Task Show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: * ** *** **** ***** 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges Reference For loop Wikipedia.
#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 body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 18 19 20 21 22 23 24 25 26 ... (Loop) Take the first member of the resultant array as the next ludic number   2. Remove every   2nd   indexed item from the array (including the first). 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... (Unrolling a few loops...) Take the first member of the resultant array as the next ludic number   3. Remove every   3rd   indexed item from the array (including the first). 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 ... Take the first member of the resultant array as the next ludic number   5. Remove every   5th   indexed item from the array (including the first). 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 ... Take the first member of the resultant array as the next ludic number   7. Remove every   7th   indexed item from the array (including the first). 7 11 13 17 23 25 29 31 37 41 43 47 53 55 59 61 67 71 73 77 83 85 89 91 97 ... ... Take the first member of the current array as the next ludic number   L. Remove every   Lth   indexed item from the array (including the first). ... Task Generate and show here the first 25 ludic numbers. How many ludic numbers are there less than or equal to 1000? Show the 2000..2005th ludic numbers. Stretch goal Show all triplets of ludic numbers < 250. A triplet is any three numbers     x , {\displaystyle x,}   x + 2 , {\displaystyle x+2,}   x + 6 {\displaystyle x+6}     where all three numbers are also ludic numbers.
#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 } if n < 1 { return [] } if max < 0 { max = max_i32 } mut sieve := []u32{len: 10760} // XXX big enough for 2005 ludics sieve[0] = 1 sieve[1] = 2 if n > 2 { // We start with even numbers already removed for i, j := 2, u32(3); i < sieve.len; i, j = i+1, j+2 { sieve[i] = j } // We leave the ludic numbers in place, // k is the index of the next ludic for k := 2; k < n; k++ { mut l := int(sieve[k]) if l >= max { n = k break } mut i := l l-- // last is the last valid index mut last := k + i - 1 for j := k + i + 1; j < sieve.len; i, j = i+1, j+1 { last = k + i sieve[last] = sieve[j] if i%l == 0 { j++ } } // Truncate down to only the valid entries if last < sieve.len-1 { sieve = sieve[..last+1] } } } if n > sieve.len { panic("program error") // should never happen } return sieve[..n] }   fn has(x []u32, v u32) bool { for i := 0; i < x.len && x[i] <= v; i++ { if x[i] == v { return true } } return false }   fn main() { // ludic() is so quick we just call it repeatedly println("First 25: ${ludic(25, -1)}") println("Numner of ludics below 1000: ${ludic(-1, 1000).len}") println("ludic 2000 to 2005: ${ludic(2005, -1)[1999..]}")   print("Tripples below 250:") x := ludic(-1, 250) for i, v in x[..x.len-2] { if has(x[i+1..], v+2) && has(x[i+2..], v+6) { print(", ($v ${v+2} ${v+6})") } } println('') }
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 the 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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 the 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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 also shows how to break out of nested loops. 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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 [i, j]; fi; od; od; return fail; end;   Find(a, 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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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. Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1 Taking the second, fourth ... and every other even digit in the reversed digits: Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits Sum the partial sums of the even digits to form s2 If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test. For example, if the trial number is 49927398716: Reverse the digits: 61789372994 Sum the odd digits: 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1 The even digits: 1, 8, 3, 2, 9 Two times each even digit: 2, 16, 6, 4, 18 Sum the digits of each multiplication: 2, 7, 6, 4, 9 Sum the last: 2 + 7 + 6 + 4 + 9 = 28 = s2 s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test Task Write a function/method/procedure/subroutine that will validate a number with the Luhn test, and use it to validate the following numbers: 49927398716 49927398717 1234567812345678 1234567812345670 Related tasks   SEDOL   ISIN
#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)) (if odd n (even-val n))) 10))))   (valid "49927398716") → #t (valid "1234567812345670") → #t (valid "1234567812345678") → #f (valid "49927398717") → #f  
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)=(S(n))^{2}-2} , and S ( 1 ) = 4 {\displaystyle S(1)=4} . Task Calculate all Mersenne primes up to the implementation's maximum precision, or the 47th Mersenne prime   (whichever comes first).
#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-hash)) (def (dict-add d w) (hash-set! d w (hash-count d)))  ; build initial dictionary (for ([i (in-range 256)]) (def s (string (integer->char i))) (hash-set! d s s))  ; compress the string (def result '()) (def (emit! i) (set! result (cons i result))) (def w "") (for ([c uncompressed]) (define wc (append-char w c)) (cond [(dict-ref d wc) (set! w wc)] [else (emit! (dict-ref d w)) (dict-add d wc) (set! w (string c))])) (emit! (dict-ref d w)) (reverse result))   ;; Decompress a LZW compressed string (define (decompress compressed) (def d (make-hash)) (def (dict-add! w) (hash-set! d (hash-count d) w))  ; build initial dictionary (for ([i (in-range 256)]) (def s (string (integer->char i))) (hash-set! d s s))  ; decompress the list (def w (first compressed)) (apply string-append w (for/list ([k (rest compressed)]) (def entry (or (dict-ref d k) (if (eqv? k (hash-count d)) (append-first w w) (error 'lzq-decompress "faulty input")))) (dict-add! (append-first w entry)) (set! w entry) entry)))   (def uncompressed "TOBEORNOTTOBEORTOBEORNOT") (displayln uncompressed) (def compressed (compress uncompressed)) (displayln compressed) (def decompressed (decompress compressed)) (displayln decompressed)  
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 for a list of words to substitute for blanks in a story, usually with funny results. Task; Write a program to create a Mad Libs like story. The program should read an arbitrary multiline story from input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be an arbitrary story in the form: <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. Given this example, it should then ask for a name, a he or she and a noun (<name> gets replaced both times with the same value). Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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.StdIn.ReadLine s = Replace(s,"<" & parse_string & ">",input_string) Else Exit Do End If Loop mad_libs = s End Function   WScript.StdOut.Write mad_libs("<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home.") WScript.StdOut.WriteLine
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) at   42   (at iteration time)   increments the index by unity   if the index is prime:   displays the count of primes found (so far) and the prime   (to the terminal)   increments the index such that the new index is now the (old) index plus that prime   terminates the loop when   42   primes are shown Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension. Show all output here. Note Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable. 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/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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) & " : " & RightX(Format(n, "#,##0"), 20)) n = n + n - 1 End If n = n + 1 Loop End Sub 'Main Function IsPrime(n As Currency) Dim i As Currency If n = 2 Or n = 3 Then IsPrime = True ElseIf ModX(n, 2) = 0 Or ModX(n, 3) = 0 Then IsPrime = False Else i = 5 Do While i * i <= n If ModX(n, i) = 0 Or ModX(n, i + 2) = 0 Then IsPrime = False Exit Function End If i = i + 6 Loop IsPrime = True End If End Function 'IsPrime Function ModX(a As Currency, b As Currency) As Currency ModX = a - Int(a / b) * b End Function 'ModX Function RightX(c, n) RightX = Right(Space(n) & c, n) End Function 'RightX
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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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 with a specified step   Loops/Foreachbas   Loops/Increment loop index within loop body   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#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   Loops/Infinite   Loops/N plus one half   Loops/Nested   Loops/While   Loops/with multiple ranges   Loops/Wrong ranges
#EasyLang
EasyLang
for i = 10 downto 0 print i .