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/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.
#Groovy
Groovy
def compress = { text -> def dictionary = (0..<256).inject([:]) { map, ch -> map."${(char)ch}" = ch; map } def w = '', compressed = [] text.each { ch -> def wc = "$w$ch" if (dictionary[wc]) { w = wc } else { compressed << dictionary[w] dictionary[w...
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. Whil...
#Maple
Maple
  A:=<<1.0|3.0|5.0>,<2.0|4.0|7.0>,<1.0|1.0|0.0>>:   LinearAlgebra:-LUDecomposition(A);  
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Python
Python
from __future__ import print_function   def add_reverse(num, max_iter=1000): i, nums = 0, {num} while True: i, num = i+1, num + reverse_int(num) nums.add(num) if reverse_int(num) == num or i >= max_iter: break return nums   #@functools.lru_cache(maxsize=2**20) def reverse...
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...
#Pascal
Pascal
  Program Madlib; Uses DOS, crt; {See, for example, https://en.wikipedia.org/wiki/Mad_Libs} {Reads the lines of a story but which also contain <xxx> sequences. For each value of xxx, found as the lines of the story are read, a request is made for a replacement text. The story is then written out with the correspondin...
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...
#C.2B.2B
C++
  #include "stdafx.h" #include <iostream> #include <math.h> using namespace std;   bool isPrime(double number) { for (double i = number - 1; i >= 2; i--) { if (fmod(number, i) == 0) return false; } return true; } int main() { double i = 42; int n = 0; while (n < 42) { ...
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ALGOL_68
ALGOL 68
DO printf($"SPAM"l$) OD
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ALGOL_W
ALGOL W
begin for i := 1 step 0 until 2 do write( "SPAM" ) 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=...
#FutureBasic
FutureBasic
  window 1, @"Loops with Ranges", ( 0, 0, 400, 400 )   begin globals NSInteger sum = 0 float prod = 1 end globals   local fn process( x as float ) sum += abs(x) if abs(prod) < (2 ^ 27) and x <> 0 then prod = prod * x end fn   NSInteger j NSInteger x = 5, y = -5, z = -2 NSInteger one = 1, three = 3, seven = 7   for...
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=...
#Go
Go
package main   import "fmt"   func pow(n int, e uint) int { if e == 0 { return 1 } prod := n for i := uint(2); i <= e; i++ { prod *= n } return prod }   func abs(n int) int { if n >= 0 { return n } return -n }   func commatize(n int) string { s := fmt.Spri...
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...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program loopwhile.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   /*********************************/ /* Initialized data */ /*********************************/ .data szMess...
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...
#360_Assembly
360 Assembly
* Loops/Downward for 27/07/2015 LOOPDOWN CSECT USING LOOPDOWN,R12 LR R12,R15 set base register BEGIN EQU * * fisrt loop with a BXLE BXLE: Branch on indeX Low or Equal LH R2,=H'11' from 10 (R2=11) index LH ...
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#360_Assembly
360 Assembly
* Do-While DOWHILE CSECT , This program's control section BAKR 14,0 Caller's registers to linkage stack LR 12,15 load entry point address into Reg 12 USING DOWHILE,12 tell assembler we use Reg 12 as base XR 9,9 ...
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. ...
#8th
8th
  ( ( '* putc ) swap times cr ) 1 5 loop  
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Agena
Agena
for i from 2 to 8 by 2 do print( i ) od
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1...
#Pascal
Pascal
program lucid; {$IFDEF FPC} {$MODE objFPC} // useful for x64 {$ENDIF}   const //66164 -> last < 1000*1000; maxLudicCnt = 2005;//must be > 1 type   tDelta = record dNum, dCnt : LongInt; end;   tpDelta = ^tDelta; tLudicList = array of tDelta;   tArrdelta =array[0..0] of ...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#ArnoldC
ArnoldC
IT'S SHOWTIME HEY CHRISTMAS TREE n YOU SET US UP @NO PROBLEMO HEY CHRISTMAS TREE lessThanTen YOU SET US UP @NO PROBLEMO STICK AROUND lessThanTen TALK TO THE HAND n GET TO THE CHOPPER lessThanTen HERE IS MY INVITATION 10 LET OFF SOME STEAM BENNET n ENOUGH TALK BECAUSE I'M GOING TO SAY PLEASE lessThanTen TALK TO THE HAND...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#Arturo
Arturo
print join.with:", " map 1..10 => [to :string]
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#AWK
AWK
BEGIN { rows = 5 columns = 5   # Fill ary[] with random numbers from 1 to 20. for (r = 1; r <= rows; r++) { for (c = 1; c <= columns; c++) ary[r, c] = int(rand() * 20) + 1 }   # Find a 20. b = 0 for (r = 1; r <= rows; r++) { for (c = 1; c <= columns; c++) { v = ary[r, c] printf " %2d", v if (v =...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#R
R
seq(from = -2, to = 2, by = 1)#Output: -2 -1 0 1 2 seq(from = -2, to = 2, by = 0)#Fails: "invalid '(to - from)/by'" seq(from = -2, to = 2, by = -1)#Fails: As in the notes above - "Specifying to - from and by of opposite signs is an error." seq(from = -2, to = 2, by = 10)#Output: -2 seq(from = 2, to = -2, by = 1)#Fai...
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...
#AWK
AWK
  BEGIN { split("Mary had a little lamb", strs, " ") for(el in strs) { print strs[el] } }
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...
#BASIC
BASIC
OPTION COLLAPSE TRUE FOR x$ IN "Hello cruel world" PRINT x$ NEXT   FOR y$ IN "1,2,\"3,4\",5" STEP "," PRINT y$ NEXT
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#BASIC
BASIC
dim card$(5) card$[1]="49927398716" card$[2]="49927398717" card$[3]="1234567812345678" card$[4]="1234567812345670"   for test = 1 to 4 odd = True sum = 0 for n = length(card$[test]) to 1 step -1 num = int(mid(card$[test],n,1)) if odd then sum += num odd = False ...
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)=(...
#Elixir
Elixir
defmodule LucasLehmer do use Bitwise def test do for p <- 2..1300, p==2 or s(bsl(1,p)-1, p-1)==0, do: IO.write "M#{p} " end   defp s(mp, 1), do: rem(4, mp) defp s(mp, n) do x = s(mp, n-1) rem(x*x-2, mp) end end   LucasLehmer.test
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.
#Haskell
Haskell
import Data.List (elemIndex, tails) import Data.Maybe (fromJust)   doLZW :: Eq a => [a] -> [a] -> [Int] doLZW _ [] = [] doLZW as (x:xs) = lzw (return <$> as) [x] xs where lzw a w [] = [fromJust $ elemIndex w a] lzw a w (x:xs) | w_ `elem` a = lzw a w_ xs | otherwise = fromJust (elemIndex w a) : lzw...
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. Whil...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(*Ex1*)a = {{1, 3, 5}, {2, 4, 7}, {1, 1, 0}}; {lu, p, c} = LUDecomposition[a]; l = LowerTriangularize[lu, -1] + IdentityMatrix[Length[p]]; u = UpperTriangularize[lu]; P = Part[IdentityMatrix[Length[p]], p] ; MatrixForm /@ {P.a , P, l, u, l.u}   (*Ex2*)a = {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}}; {l...
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#R
R
  library(gmp) library(magrittr)   cache <- NULL   cache_reset <- function() { cache <<- new.env(TRUE, emptyenv()) } cache_set <- function(key, value) { assign(key, value, envir = cache) } cache_get <- function(key) { get(key, envir = cache, inherits = FALSE) } cache_has_key <- function(key) { exists(key, envir = cache...
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...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict;   my $template = shift; open my $IN, '<', $template or die $!; my $story = do { local $/ ; <$IN> };   my %blanks; undef $blanks{$_} for $story =~ m/<(.*?)>/g;   for my $blank (sort keys %blanks) { print "$blank: "; chomp (my $replacement = <>); $blanks{$blank} = $re...
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...
#Common_Lisp
Common Lisp
  (defun primep (n) ; https://stackoverflow.com/questions/15817350/ (cond ((= 2 n) t) ; Hard-code "2 is a prime" ((= 3 n) t) ; Hard-code "3 is a prime" ((evenp n) nil) ; If we're looking at an even now, i...
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#AmigaE
AmigaE
PROC main() LOOP WriteF('SPAM') ENDLOOP ENDPROC
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#AppleScript
AppleScript
repeat log "SPAM" end repeat
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=...
#Groovy
Groovy
def (prod, sum, x, y, z, one, three, seven) = [1, 0, +5, -5, -2, 1, 3, 7]   for ( j in ( ((-three) .. (3**3) ).step(three) + ((-seven) .. (+seven) ).step(x) + (555 .. (550-y) ) + (22 .. (-28) ).step(three) // This is correct! // Groovy interprets p...
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...
#ArnoldC
ArnoldC
IT'S SHOWTIME HEY CHRISTMAS TREE n YOU SET US UP 1024 STICK AROUND n TALK TO THE HAND n GET TO THE CHOPPER n HERE IS MY INVITATION n HE HAD TO SPLIT 2 ENOUGH TALK CHILL YOU HAVE BEEN TERMINATED
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...
#Arturo
Arturo
i: 1024   while [i>0] [ print i 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...
#6502_Assembly
6502 Assembly
;An OS/hardware specific routine that is setup to display the Ascii character ;value contained in the Accumulator Send = $9000 ;routine not implemented here PrintNewLine = $9050 ;routine not implemented here   *= $8000 ;set base address Start PHA ;push Accumulator and Y register onto stack TYA PHA ...
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...
#68000_Assembly
68000 Assembly
ForLoop: MOVE.W #10,D0 loop: JSR Print_D0_As_Ascii ;some routine that converts the digits of D0 into ascii characters and prints them to screen. DBRA D0,loop ;repeat until D0.W = $FFFF rts
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#6502_Assembly
6502 Assembly
DoWhileSub: PHA TYA PHA ;push accumulator and Y register onto stack   LDY #0 DoWhileLoop: INY JSR DisplayValue ;routine not implemented TYA SEC Modulus: SBC #6 BCS Modulus ADC #6 BNE DoWhileLoop   PLA TAY PLA ;restore Y register and accumulator from stack RTS ;return from subroutine
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. ...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program loop64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.i...
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Aime
Aime
integer i;   i = 0; while (i < 10) { o_winteger(2, i); i += 2; }   o_newline();
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use feature qw{ say };   { my @ludic = (1); my $max = 3; my @candidates;   sub sieve { my $l = shift; for (my $i = 0; $i <= $#candidates; $i += $l) { splice @candidates, $i, 1; } }   sub ludic { my ($type, $n) = ...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#AutoHotkey
AutoHotkey
Loop, 9 ; loop 9 times { output .= A_Index ; append the index of the current loop to the output var If (A_Index <> 9) ; if it isn't the 9th iteration of the loop output .= ", " ; append ", " to the output var } MsgBox, %output%
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#AutoIt
AutoIt
#cs ----------------------------------------------------------------------------   AutoIt Version: 3.3.8.1 Author: Alexander Alvonellos   Script Function: Output a comma separated list from 1 to 10, and on the tenth iteration of the output loop, only perform half of the loop.   #ce ------------------------...
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#BASIC
BASIC
DIM a(1 TO 10, 1 TO 10) AS INTEGER CLS FOR row = 1 TO 10 FOR col = 1 TO 10 a(row, col) = INT(RND * 20) + 1 NEXT col NEXT row   FOR row = LBOUND(a, 1) TO UBOUND(a, 1) FOR col = LBOUND(a, 2) TO UBOUND(a, 2) PRINT a(row, col) IF a(row, col) = 20 THEN ...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Racket
Racket
#lang racket   (require racket/sandbox)   (define tests '([-2 2 1 "Normal"] [-2 2 0 "Zero increment"] [-2 2 -1 "Increments away from stop value"] [-2 2 10 "First increment is beyond stop value"] [2 -2 1 "Start more than stop: positive increment"] ...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Raku
Raku
# Given sequence definitions # start stop inc. Comment for -2, 2, 1, # Normal -2, 2, 0, # Zero increment -2, 2, -1, # Increments away from stop value -2, 2, 10, # First increment is beyond stop value 2, -2, 1, # Start more than stop: positive increment ...
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...
#Batch_File
Batch File
@echo off for %%A in (This is a sample collection) do ( echo %%A )
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...
#bc
bc
a[0] = .123 a[1] = 234 a[3] = 95.6 for (i = 0; i < 4; i++) { a[i] }
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion   call :luhn 49927398716 call :luhn 49927398717 call :luhn 1234567812345678 call :luhn 1234567812345670 exit /b 0   :luhn set "input=%1" set "cnt=0" set "s1=0" set "s2=0" :digit_loop set /a "cnt-=1" set /a "isOdd=(-%cnt%)%%2"   if !isodd! equ 1 ( set /a "s1+=!input:~%cnt%,1!" ...
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)=(...
#Erlang
Erlang
-module(mp). -export([main/0]).   main() -> [ io:format("M~p ", [P]) || P <- lists:seq(2,700), (P == 2) orelse (s((1 bsl P) - 1, P-1) == 0) ].   s(MP,1) -> 4 rem MP; s(MP,N) -> X=s(MP,N-1), (X*X - 2) rem MP.
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.
#J
J
encodeLZW =: 4 : 0 d=. ;/x r=.0$0 wc=.w=.{.y for_c. }.y do. wc=.w,c if. d e.~ <wc do. w=.wc else. r=. r, d i.<w d=.d,<wc w=.c end. end. r, d i.<w )
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. Whil...
#MATLAB_.2F_Octave
MATLAB / Octave
A = [ 1 3 5 2 4 7 1 1 0];   [L,U,P] = lu(A)
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Racket
Racket
#lang racket (require racket/splicing)   (define (reverse-digits_10 N) (let inr ((n N) (m 0)) (match n [0 m] [(app (curryr quotient/remainder 10) q r) (inr q (+ r (* 10 m)))])))   (define (palindrome?_10 n) (= n (reverse-digits_10 n)))   ;; hash of integer? -> one of 'seed 'related #f (splici...
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...
#Phix
Phix
without js -- file i/o, prompt_string string mlfile = "", -- eg story.txt mltxt = iff(length(mlfile)?join(read_lines(mlfile),"\n"):""" <name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home. """) sequence strings = {}, replacements = {} integer startpos, endpos=1 while 1 do ...
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...
#Delphi
Delphi
  program Increment_loop_index_within_loop_body;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function IsPrime(const a: UInt64): Boolean; var d: UInt64; begin if (a < 2) then exit(False);   if (a mod 2) = 0 then exit(a = 2);   if (a mod 3) = 0 then exit(a = 3);   d := 5;   while (d * d <= a)...
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ARM_Assembly
ARM Assembly
  .global main   main:   loop: ldr r0, =message bl printf b loop   message: .asciz "SPAM\n"  
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#ArnoldC
ArnoldC
IT'S SHOWTIME STICK AROUND @NO PROBLEMO TALK TO THE HAND "SPAM" CHILL YOU HAVE BEEN TERMINATED
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=...
#Haskell
Haskell
loop :: (b -> a -> b) -> b -> [[a]] -> b loop = foldl . foldl   example = let x = 5 y = -5 z = -2 one = 1 three = 3 seven = 7 in loop -- body ( \(sum, prod) j -> ( sum + abs j, if abs prod < 2^27 && j /= 0 then prod * j else 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...
#Asymptote
Asymptote
int i = 1024;   while(i > 0) { write(i); i = i # 2; //or also i = quotient(i, 2); }   //# Integer division; equivalent to quotient(x,y). //Noting that the Python3 community adopted the comment symbol (//) for integer division, the //Asymptote community decided to reciprocate and use their comment symbol for i...
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...
#ATS
ATS
#include "share/atspre_staload.hats"   fn loop_while () : void = let fun loop {n : int | 0 <= n} .<n>. (n : uint n) : void = if n <> 0U then begin println! (n); loop (n / 2U) end in loop 1024U end   implement main0 () = loop_while ()
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...
#8086_Assembly
8086 Assembly
.model small ;.exe file, max 128 KB .stack 1024 ;reserve 1 KB for the stack pointer.   .data   ;no data needed   .code start:   mov ax,0100h ;UNPACKED BCD "10" mov cx,0Bh ;loop counter   repeat_countdown: call PrintBCD_IgnoreLeadingZeroes sub ax,1 aas ;ascii adjust for subtr...
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program loopdowhile64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantes...
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. ...
#Action.21
Action!
Proc Main() byte I,J   For I=1 to 5 Do For J=1 to I Do Print("*") Od PrintE("") Od   Return
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#ALGOL_60
ALGOL 60
for i:=5 step 5 until 25 do OUTINTEGER(i)
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1...
#Phix
Phix
constant LUMAX = 25000 sequence ludic = repeat(1,LUMAX) integer n for i=2 to LUMAX/2 do if ludic[i] then n = 0 for j=i+1 to LUMAX do n += ludic[j] if n=i then ludic[j] = 0 n = 0 end if end for end if end for sequence s...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#AWK
AWK
$ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf ", "};print}'
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#Axe
Axe
For(I,1,10) Disp I▶Dec If I=10 Disp i Else Disp "," End End
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#BASIC256
BASIC256
dim a(20, 20)   for i = 0 to 19 for j = 0 to 19 a[i, j] = int(rand * 20) + 1 next j next i   for i = 0 to 19 for j = 0 to 19 print a[i, j];" "; if a[i, j] = 20 then end next j next i   end
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#BBC_BASIC
BBC BASIC
DIM array(10,10) FOR row% = 0 TO 10 FOR col% = 0 TO 10 array(row%,col%) = RND(20) + 1 NEXT NEXT row% FOR row% = 0 TO 10 FOR col% = 0 TO 10 PRINT "row "; row%, "col ";col%, "value "; array(row%,col%) IF array(row%,col%) = 20 EXIT FOR row% ...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#REXX
REXX
/*REXX program demonstrates several versions of DO loops with "unusual" iterations. */ @.=; @.1= ' -2 2 1 ' /*"normal". */ @.2= ' -2 2 0 ' /*"normal", zero increment.*/ @.3= ' -2 2 -1 ' /*...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Ruby
Ruby
examples = [ [ -2, 2, 1], [ -2, 2, 0], [ -2, 2, -1], [ -2, 2, 10], [ 2, -2, 1], [ 2, 2, 1], [ 2, 2, -1], [ 2, 2, 0], [ 0, 0, 0] ]   examples.each do |start, stop, step| as = (start..stop).step(step) puts "...
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...
#Bracmat
Bracmat
( list = Afrikaans Ελληνικά עברית മലയാളം ئۇيغۇرچە )
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...
#C
C
#include <stdio.h> ...   const char *list[] = {"Red","Green","Blue","Black","White"}; #define LIST_SIZE (sizeof(list)/sizeof(list[0]))   int ix; for(ix=0; ix<LIST_SIZE; ix++) { printf("%s\n", list[ix]); }
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#BBC_BASIC
BBC BASIC
FOR card% = 1 TO 4 READ cardnumber$ IF FNluhn(cardnumber$) THEN PRINT "Card number " cardnumber$ " is valid" ELSE PRINT "Card number " cardnumber$ " is invalid" ENDIF NEXT card% END   DATA 49927398716, 49927398717, 1234567812345678, 12345678123...
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)=(...
#ERRE
ERRE
PROGRAM LL_TEST   !$DOUBLE   PROCEDURE LUCAS_LEHMER(P%->RES) LOCAL I%,MP,SN IF P%=2 THEN RES%=TRUE EXIT PROCEDURE END IF IF (P% AND 1)=0 THEN RES%=FALSE EXIT PROCEDURE END IF MP=2^P%-1 SN=4 FOR I%=3 TO P% DO SN=SN^2-2 SN-=(MP*INT(SN/MP)) END FOR RES%=(SN=0) END PR...
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.
#Java
Java
import java.util.*;   public class LZW { /** Compress a string to a list of output symbols. */ public static List<Integer> compress(String uncompressed) { // Build the dictionary. int dictSize = 256; Map<String,Integer> dictionary = new HashMap<String,Integer>(); for (int i = 0; ...
http://rosettacode.org/wiki/LU_decomposition
LU decomposition
Every square matrix A {\displaystyle A} can be decomposed into a product of a lower triangular matrix L {\displaystyle L} and a upper triangular matrix U {\displaystyle U} , as described in LU decomposition. A = L U {\displaystyle A=LU} It is a modified form of Gaussian elimination. Whil...
#Maxima
Maxima
/* LU decomposition is built-in */   a: hilbert_matrix(4)$   /* LU in "packed" form */   lup: lu_factor(a); /* [matrix([1, 1/2, 1/3, 1/4 ], [1/2, 1/12, 1/12, 3/40 ], [1/3, 1, 1/180, 1/120 ], [1/4, 9/10, 3/2, 1/2800]), [1, 2, 3, 4], generalring] */   /* extract actual f...
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#Raku
Raku
my %lychrels; my @seeds; my @palindromes; my $count; my $max = 500; my $limit = '10_000'; my %seen;   for 1 .. $limit -> $int { my @test; my $index = 0; if $int.&is-lychrel { %lychrels.push: ($int => @test).invert; @palindromes.push: $int if $int == $int.flip; $count++; }   s...
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...
#Phixmonti
Phixmonti
"<name> went for a walk in the park. <he or she> found a <noun>. <name> decided to take it home." true while "<" find dup var ini if ">" find ini - 1 + ini swap slice var replace "Replace: " replace " with: " chain chain input var with nl true while replace with subst...
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...
#Dyalect
Dyalect
func isPrime(number) { if number <= 1 { return false } else if number % 2 == 0 { return number == 2 }   var i = 3   while (i * i) < number { if number % i == 0 { return false } i += 2 }   return true }   var i = 42 var n = 0   while n <...
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...
#F.23
F#
  // Well I don't do loops. Nigel Galloway: March 17th., 2019. Let me try to explain where the loopy variables are, for the imperatively constrained. // cUL allows me to claim the rather trivial extra credit (commas in the numbers) let cUL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:uint64)->n.ToString...
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Arturo
Arturo
while [true] [ print "SPAM" ]
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#AutoHotkey
AutoHotkey
Loop MsgBox SPAM `n
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=...
#J
J
  NB. http://rosettacode.org/wiki/Loops/Wrong_ranges#J NB. define range as a linear polynomial start =: 0&{ stop =: 1&{ increment =: 2&{ :: 1: NB. on error use 1 range =: (start , increment) p. [: i. [: >: [: <. (stop - start) % increment   f =: 3 :0 input =. y 'prod sum x y z one three seven' =. 1 0 5 _5 _2 1 3 7 ...
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=...
#Java
Java
  import java.util.ArrayList; import java.util.List;   public class LoopsWithMultipleRanges {   private static long sum = 0; private static long prod = 1;   public static void main(String[] args) { long x = 5; long y = -5; long z = -2; long one = 1; long three = 3; ...
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...
#AutoHotkey
AutoHotkey
i = 1024 While (i > 0) { output = %output%`n%i% i := Floor(i / 2) } MsgBox % output
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...
#AWK
AWK
BEGIN { v = 1024 while(v > 0) { print v v = int(v/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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program loopdownward64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstante...
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...
#Ada
Ada
for I in reverse 0..10 loop Put_Line(Integer'Image(I)); end loop;
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Action.21
Action!
Proc Main() byte A   A=0 Do A==+1 PrintBE(A) Until A Mod 6=0 Od Return
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. ...
#ActionScript
ActionScript
var str:String = ""; for (var i:int = 1; i <= 5; i++) { for (var j:int = 1; j <= i; j++) str += "*"; trace(str); str = ""; }
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#ALGOL_68
ALGOL 68
[ for index ] [ from first ] [ by increment ] [ to last ] [ while condition ] do statements od The minimum form of a "loop clause" is thus: do statements od # an infinite loop #
http://rosettacode.org/wiki/Ludic_numbers
Ludic numbers
Ludic numbers   are related to prime numbers as they are generated by a sieve quite like the Sieve of Eratosthenes is used to generate prime numbers. The first ludic number is   1. To generate succeeding ludic numbers create an array of increasing integers starting from   2. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1...
#Picat
Picat
ludic(N) = Ludic => ludic(2..N, [1], Ludic). ludic([], Ludic0, Ludic) => Ludic = Ludic0.reverse(). ludic(T, Ludic0, Ludic) => T2 = ludic_keep(T), ludic(T2,[T[1]|Ludic0],Ludic).   % which elements to keep ludic_keep([]) = []. ludic_keep([H|List]) = Ludic => ludic_keep(H,1,List,[],Ludic).   ludic_keep(_H,_C,[]...
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#BASIC
BASIC
DIM i AS INTEGER   FOR i=1 TO 10 PRINT i; IF i=10 THEN EXIT FOR PRINT ", "; NEXT i
http://rosettacode.org/wiki/Loops/N_plus_one_half
Loops/N plus one half
Quite often one needs loops which, in the last iteration, execute only part of the loop body. Goal Demonstrate the best way to do this. Task Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of th...
#bc
bc
while (1) { print ++i if (i == 10) { print "\n" break } print ", " }
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#bc
bc
s = 1 /* Seed of the random number generator */   /* Random number from 1 to 20. */ define r() { auto r while (1) { /* * Formula (from POSIX) for random numbers of low * quality, from 0 to 32767. */ s = (s * 1103515245 + 12345) % 4294967296 r = (s / 65536) % 32768   /* Prevent modulo bias. */ if (r...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: testLoop (in integer: start, in integer: stop, in integer: incr, in string: comment) is func local const integer: limit is 10; var integer: number is 0; var integer: count is 0; begin writeln(comment); write("Range(" <& start <& ", " <& stop <& ", " <& inc...
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Smalltalk
Smalltalk
startExpr to:stopExpr by:incExpr do:[..]
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...
#C.23
C#
string[] things = {"Apple", "Banana", "Coconut"};   foreach (string thing in things) { Console.WriteLine(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...
#C.2B.2B
C++
for (container_type::iterator i = container.begin(); i != container.end(); ++i) { std::cout << *i << "\n"; }
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#bc
bc
/* Return 1 if number passes Luhn test, else 0 */ define l(n) { auto m, o, s, x   o = scale scale = 0   m = 1 while (n > 0) { x = (n % 10) * m if (x > 9) x -= 9 s += x m = 3 - m n /= 10 }   s %= 10 scale = o if (s) return(0) return(1) }   l...
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)=(...
#F.23
F#
let rec s mp n = if n = 1 then 4I % mp else ((s mp (n - 1)) ** 2 - 2I) % mp   [ for p in 2..47 do if p = 2 || s ((1I <<< p) - 1I) (p - 1) = 0I then yield p ]