*        Integer sequence      06/05/2016
INTSEQED CSECT
         USING  INTSEQED,12
         LR    12,15
         LA    6,1             i=1
LOOP     CVD   6,DW            binary to pack decimal
         MVC   WTOMSG+4(12),EM12 load mask
         ED    WTOMSG+4(12),DW+2 packed dec to char
         WTO   MF=(E,WTOMSG)   write to console
         LA    6,1(6)          i=i+1
         B     LOOP            goto loop
WTOMSG   DC    0F,H'80',H'0',CL80' '
DW       DS    0D,PL8          pack dec 15num
EM12     DC    X'402020202020202020202120'  mask CL12 11num
         END   INTSEQED


        ORG     0100H
        MVI     A,    0   ; move immediate
LOOP:   INR     A         ; increment
   ; call 'PRINT' subroutine, if required
        JMP     LOOP      ; jump unconditionally

        END


PROC Main()
  CARD i

  i=0
  DO
    PrintF("%U ",i)
    i==+1
  UNTIL i=0
  OD
RETURN


with Ada.Text_IO;
procedure Integers is
   Value : Integer := 1;
begin
   loop
      Ada.Text_IO.Put_Line (Integer'Image (Value));
      Value := Value + 1;  -- raises exception Constraint_Error on overflow
   end loop;
end Integers;


main:
(
  FOR i DO
    printf(($g(0)","$,i))
  OD
)


begin
    % print the integers from 1 onwards                                       %
    % Algol W only has 32-bit integers. When i reaches 2^32,                  %
    % an integer overflow event would be raised which by default,             %
    % should terminate the program                                            %
    integer i;
    i := 1;
    while true do begin
        write( i );
        i := i + 1
    end loop_forever ;
end.


.text
.global main

@ An ARM program that keeps incrementing R0 forever
@
@ If desired, a call to some 'PRINT' routine --
@ which would depend on the OS -- could be included

main:
        mov   r0,   #0          @ start with R0 = 0

repeat:
        @ call to 'PRINT' routine
        add   r0,   r0,   #1    @ increment R0
        b     repeat            @ unconditional branch


IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP @NO PROBLEMO
STICK AROUND @NO PROBLEMO
TALK TO THE HAND n
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET UP @NO PROBLEMO
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED


BEGIN {
    for( i=0; i != i + 1; i++ )
        print( i )
}


While getKey(0)
End
0→I
Repeat getKey(0)
 Disp I▶Dec,i
 I++
EndIf I=0


10 LET A = 0
20 LET A = A + 1
30 PRINT A
40 GO TO 20


i = 1

do
    print i
    i += 1
until i = 0


@echo off
set number=0
:loop
set /a number+=1
echo %number%
goto loop


      *FLOAT 64
      REPEAT
        i += 1
        PRINT TAB(0,0) i;
      UNTIL FALSE


_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
(1+•Show) _while_ (≤⟜∞) 1


#include <stdio.h>

int main()
{
	unsigned int i = 0;
	while (++i) printf("%u\n", i);

	return 0;
}


using System;
using System.Numerics;

class Program
{
    static void Main()
    {
        BigInteger i = 1;
        while (true)
        {
            Console.WriteLine(i++);
        }
    }
}


#include <cstdint>
#include <iostream>
#include <limits>

int main()
{
  auto i = std::uintmax_t{};

  while (i < std::numeric_limits<decltype(i)>::max())
    std::cout << ++i << '\n';
}


module IntegerSequence

import StdEnv

Start = [x \\ x <- [1..]]


% This iterator will generate all integers until the built-in type
% overflows. It is a signed machine-sized integer; so 64 bits on
% a modern machine. After that it will raise an exception.
to_infinity_and_beyond = iter () yields (int)
    i: int := 0
    while true do
        i := i + 1
        yield(i)
    end
end to_infinity_and_beyond

start_up = proc ()
    po: stream := stream$primary_output()

    for i: int in to_infinity_and_beyond() do
        stream$putl(po, int$unparse(i))
    end
end start_up


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Int-Sequence.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
*      *> 36 digits is the largest size a numeric field can have.
       01  I PIC 9(36).

       PROCEDURE DIVISION.
*          *> Display numbers until I overflows.
           PERFORM VARYING I FROM 1 BY 1 UNTIL I = 0
               DISPLAY I
           END-PERFORM

           GOBACK
           .


# This very limited BCD-based collection of functions
# makes it easy to count very large numbers.  All arrays
# start off with the ones columns in position zero.
# Using arrays of decimal-based digits to model integers
# doesn't make much sense for most tasks, but if you
# want to keep counting forever, this does the trick.

BcdInteger =
  from_string: (s) ->
    arr = []
    for c in s
      arr.unshift parseInt(c)
    arr

  render: (arr) ->
    s = ''
    for elem in arr
      s = elem.toString() + s
    s

  succ: (arr) ->
    arr = (elem for elem in arr)
    i = 0
    while arr[i] == 9
      arr[i] = 0
      i += 1
    arr[i] ||= 0
    arr[i] += 1
    arr

# To start counting from 1, change the next line!
big_int = BcdInteger.from_string "199999999999999999999999999999999999999999999999999999"
while true
  console.log BcdInteger.render big_int
  big_int = BcdInteger.succ big_int


MODULE IntegerSequence;
IMPORT StdLog;

PROCEDURE Do*;
VAR
	i: INTEGER;
BEGIN
	FOR i := 0 TO MAX(INTEGER) DO;
		StdLog.Int(i)
	END;
	StdLog.Ln
END Do;

END IntegerSequence.


start:  ADD  one
        JMP  start
one:         1


include "cowgol.coh";

var n: uint32 := 1;
while n != 0 loop;
    print_i32(n);
    print_nl();
    n := n + 1;
end loop;


require "big"

(1.to_big_i ..).each { |i| puts i }


import std.stdio, std.bigint;

void main() {
    BigInt i;
    while (true)
        writeln(++i);
}


$ i = 1
$ loop:
$  write sys$output i
$  i = i + 1
$  goto loop


program IntegerSequence;

{$APPTYPE CONSOLE}

var
  i: Integer;
begin
  for i := 1 to High(i) do
    WriteLn(i);
end.


var i: Integer;

for i:=1 to High(i) do
   PrintLn(i);


var n = 0
while true {
    n += 1
    print(n)
}


1

while /= -- dup dup:
	!. dup
	++

drop


(lib 'bigint) ;; arbitrary length integers
(for ((n (in-naturals))) (writeln n))


[ Integer sequence
  ================

  A program for the EDSAC

  Displays integers 1,2,3...
  in binary form in the first
  word of storage tank 2
  until stopped

  Works with Initial Orders 2  ]

T56K  [ set load point         ]
GK    [ set base address       ]

[email protected]   [ increment accumulator  ]
U64F  [ copy accumulator to 64 ]
[email protected]    [ jump to base address   ]

P0D   [ constant: 1            ]

EZPF  [ begin at load point    ]


class
	APPLICATION
inherit
	ARGUMENTS
create
	make
feature {NONE} -- Initialization
	make
			-- Run application.
		do
			from
				number := 0
			until
				number = number.max_value
			loop
				print(number)
				print(", ")
				number := number + 1
			end
		end
	number:INTEGER_64
end


import extensions;

public program()
{
    var i := 0u;
    while (true)
    {
        console.printLine(i);

        i += 1u
    }
}


Stream.iterate(1, &(&1+1)) |> Enum.each(&(IO.puts &1))


(dotimes (i most-positive-fixnum)
  (message "%d" (1+ i)))


F = fun(FF, I) -> io:format("~p~n", [I]), FF(FF, I + 1) end, F(F,0).


integer i
i = 0
while 1 do
    ? i
    i += 1
end while


// lazy sequence of integers starting with i
let rec integers i =
  seq { yield i
        yield! integers (i+1) }

Seq.iter (printfn "%d") (integers 1)


class Main
{
  public static Void main()
  {
    i := 1
    while (true)
    {
      echo (i)
      i += 1
    }
  }
}


: ints ( -- )
  0 begin 1+ dup cr u. dup -1 = until drop ;


program Intseq
  implicit none

  integer, parameter :: i64 = selected_int_kind(18)
  integer(i64) :: n = 1

! n is declared as a 64 bit signed integer so the program will display up to
! 9223372036854775807 before overflowing to -9223372036854775808
  do
    print*, n
    n = n + 1
  end do
end program


' FB 1.05.0 Win64

' FB does not natively support arbitrarily large integers though support can be added
' by using an external library such as GMP. For now we will just use an unsigned integer (32bit).

Print "Press Ctrl + C to stop the program at any time"
Dim i As UInteger = 1

Do
  Print i
  i += 1
Loop Until i = 0 ' will wrap back to 0 when it reaches 4,294,967,296

Sleep


i=0
while true
{
   println[i]
   i = i + 1
}


InfiniteLoop := function()
	local n;
	n := 1;
	while true do
		Display(n);
		n := n + 1;
	od;
end;

# Prepare some coffee
InfiniteLoop();


package main

import "fmt"

func main() {
    for i := 1;; i++ {
        fmt.Println(i)
    }
}


#INTEGER SEQUENCE.

@width
@height 1

(1,1):START
(3,1):STORE 1
(5,1):CHECKPOINT 0
(7,1):PRINT
(9,1):INCREMENT
(11,1):GOTO 0


// 32-bit 2's-complement signed integer (int/Integer)
for (def i = 1; i > 0; i++) { println i }

// 64-bit 2's-complement signed integer (long/Long)
for (def i = 1L; i > 0; i+=1L) { println i }

// Arbitrarily-long binary signed integer (BigInteger)
for (def i = 1g; ; i+=1g) { println i }


procedure main()
every write(seq(1))        # the most concise way
end


100 FOR I=1 TO INF
110   PRINT I;
120 NEXT


public class Count{
    public static void main(String[] args){
        for(long i = 1; ;i++) System.out.println(i);
    }
}


var i = 0;

while (true)
    document.write(++i + ' ');


i = zero(BigInt)    # or i = big(0)
while true
  println(i += 1)
end


import java.math.BigInteger

// version 1.0.5-2

fun main(args: Array<String>) {
    // print until 2147483647
    (0..Int.MAX_VALUE).forEach { println(it) }

    // print forever
    var n = BigInteger.ZERO
    while (true) {
        println(n)
        n += BigInteger.ONE
    }
}


{def infinite_set
 {lambda {:i}
  {if true                                 // will never change
   then :i {infinite_set {long_add :i 1}}  // extends {+ :i 1}
   else You have reached infinity! }}}     // probably never.
-> infinite_set

{infinite_set 0}
-> 0 1 2 3 ... forever


local(number = 1)
while(#number > 0) => {^
	#number++
	' '
	//#number > 100 ? #number = -2 // uncomment this row if you want to halt the run after proving concept
^}


 while 1
    i=i+1
    locate 1,1
    print i
    scan
wend


implement CountToInfinity;

include "sys.m"; sys: Sys;
include "draw.m";
include "ipints.m"; ipints: IPints;
	IPint: import ipints;

CountToInfinity: module {
	init: fn(nil: ref Draw->Context, nil: list of string);
};

init(nil: ref Draw->Context, nil: list of string)
{
	sys = load Sys Sys->PATH;
	ipints = load IPints IPints->PATH;

	i := IPint.inttoip(0);
	one := IPint.inttoip(1);
	for(;;) {
		sys->print("%s\n", i.iptostr(10));
		i = i.add(one);
	}
}


i = 1
repeat while i>0
  put i
  i = i+1
end repeat


; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.

; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps

;--- The declarations for the external C functions
declare i32 @printf(i8*, ...)

$"FORMAT_STR" = comdat any
@"FORMAT_STR" = linkonce_odr unnamed_addr constant [4 x i8] c"%u\0A\00", comdat, align 1

; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
  %1 = alloca i32, align 4          ;-- allocate i
  store i32 0, i32* %1, align 4     ;-- store i as 0
  br label %loop

loop:
  %2 = load i32, i32* %1, align 4   ;-- load i
  %3 = add i32 %2, 1                ;-- increment i
  store i32 %3, i32* %1, align 4    ;-- store i
  %4 = icmp ne i32 %3, 0            ;-- i != 0
  br i1 %4, label %loop_body, label %exit

loop_body:
  %5 = load i32, i32* %1, align 4   ;-- load i
  %6 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"FORMAT_STR", i32 0, i32 0), i32 %5)
  br label %loop

exit:
  ret i32 0
}

attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }


i = 1

-- in the event that the number inadvertently wraps around,
-- stop looping - this is unlikely with Lua's default underlying
-- number type (double), but on platform without double
-- the C type used for numbers can be changed
while i > 0 do
    print( i )
    i = i + 1
end


\\ easy way
[email protected]
\\ Def statement defines one time (second pass produce error)
Rem : Def Decimal a=1
Rem : Def a as decimal=1
\\ Global shadow any global with same name, but not local
\\ globals can change type, local can't change
\\ to assign value to global need <=
\\ Symbol = always make local variables (and shadows globals)
Rem : Global a as decimal =1
\\Local make a new local and shadow one with same name
Rem : Local a as decimal=1
\\ we can create an "auto rounding" variable
\\ an integer with any type (double, single, decimal, currency, long, integer)
\\ rounding to .5 : up for positive numbers and down to negative
\\ 1.5 round to 2 and -1.5 round to -2
a%[email protected]

\\ variables a, a%, a$, arrays/functions a(), a$(), sub a() and the module a can exist together
\\ A block may act as loop structure using an internal flag
\\ A Loop statement mark a flag in the block, so can be anywhere inside,
\\ this flag reset to false before restart.
{loop : Print a : a++}


a = 1; while (1) printf('%i\n',a); a=a+1; end;


1	П4	ИП4	С/П	КИП4	БП	02


MCSKIP "WITH" NL
"" Integer sequence
"" Will overflow when it reaches implementation-defined signed integer limit
MCSKIP MT,<>
MCINS %.
MCDEF DEMO WITHS NL AS <MCSET T1=1
%L1.%T1.
MCSET T1=T1+1
MCGO L1
>
DEMO


MODULE Sequence;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;

VAR
    buf : ARRAY[0..63] OF CHAR;
    i : CARDINAL;
BEGIN
    i := 1;
    WHILE i>0 DO
        FormatString("%c ", buf, i);
        WriteString(buf);
        INC(i)
    END;
    ReadChar
END Sequence.


let i = 0;
while true
{
    write(i);
    i = i + 1;
}


/* NetRexx */
options replace format comments java crossref symbols binary

k_ = Rexx
bigDigits = 999999999 -- Maximum setting for digits allowed by NetRexx
numeric digits bigDigits

loop k_ = 1
  say k_
  end k_


var i:int64 = 0
while true:
    inc i
    echo i


MODULE IntegerSeq;
IMPORT
  Out,
  Object:BigInt;

  PROCEDURE IntegerSequence*;
  VAR
    i: LONGINT;
  BEGIN
    FOR i := 0 TO MAX(LONGINT) DO
      Out.LongInt(i,0);Out.String(", ")
    END;
    Out.Ln
  END IntegerSequence;

  PROCEDURE BigIntSequence*;
  VAR
    i: BigInt.BigInt;
  BEGIN
    i := BigInt.zero;
    LOOP
      Out.Object(i.ToString() + ", ");
      i := i.Add(BigInt.one);
    END
  END BigIntSequence;

END IntegerSeq.


bundle Default {
  class Count {
    function : Main(args : String[]) ~ Nil {
      i := 0;
      do {
        i->PrintLine();
        i += 1;
      } while(i <> 0);
    }
  }
}


let () =
  let i = ref 0 in
  while true do
    print_int !i;
    print_newline ();
    incr i;
  done


: integers  1 while( true ) [ dup . 1+ ] ;


(let loop ((n 1))
   (print n)
   (loop (+ 1 n)))


#include <order/interpreter.h>

#define ORDER_PP_DEF_8printloop ORDER_PP_FN( \
8fn(8N,                                      \
    8do(8print(8to_lit(8N) 8comma 8space),   \
        8printloop(8inc(8N)))) )

ORDER_PP( 8printloop(1) )


Program IntegerSequenceLimited;
var
  Number: QWord = 0; // 8 bytes, unsigned: 0 .. 18446744073709551615
begin
  repeat
    writeln(Number);
    inc(Number);
  until false;
end.


without javascript_semantics
integer i = 0
while 1 do
    ?i
    i += 1
end while


int i=1;
while(true)
    write("%d\n", i++);


C  :n = 1
*InfiniteLoop
T  :#n
C  :n = n + 1
J  :*InfiniteLoop


infinity: procedure options (main);
   declare k fixed decimal (30);
   put skip edit
      ((k do k = 1 to 999999999999999999999999999998))(f(31));
end infinity;


100H:

/* CP/M CALL AND NUMBER OUTPUT ROUTINE */
BDOS: PROCEDURE (FN, ARG);
    DECLARE FN BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

PRINT: PROCEDURE (STR);
    DECLARE STR ADDRESS;
    CALL BDOS(9, STR);
END PRINT;

PRINT$NUMBER: PROCEDURE (N);
    DECLARE S (8) BYTE INITIAL ('.....',13,10,'$');
    DECLARE (N, P) ADDRESS, C BASED P BYTE;
    P = .S(5);
DIGIT:
    P = P - 1;
    C = N MOD 10 + '0';
    N = N / 10;
    IF N > 0 THEN GO TO DIGIT;
    CALL PRINT(P);
END PRINT$NUMBER;

/* PRINT NUMBERS UNTIL ADDRESS VARIABLE OVERFLOWS */
DECLARE N ADDRESS INITIAL (1);
DO WHILE N <> 0;
    CALL PRINT$NUMBER(N);
    N = N + 1;
END;

CALL BDOS(0,0);
EOF


         L     2,=F'2147483647'   2**31-1
         L     3,=F'1'            1
         AR    2,3                add register3 to register2
         BO    OVERFLOW           branch on overflow
         ....
OVERFLOW EQU   *


To run:
Start up.
Put 1 into a number.
Loop.
Convert the number to a string.
Write the string to the console.
Bump the number.
Repeat.
Shut down.


try
{
    for ([int]$i = 0;;$i++)
    {
        $i
    }
}
catch {break}


loop(I) :-
	writeln(I),
	I1 is I+1,
	loop(I1).


OpenConsole()
Repeat
  a.q+1
  PrintN(Str(a))
ForEver


LDA #$7F
CLC
ADC #$01
BVS ErrorHandler ;this branch will always be taken.


MOVE.W D0,#0000117F
ADD.W #1,D0 ;DOESN'T SET THE OVERFLOW FLAG, SINCE AT WORD LENGTH WE DIDN'T CROSS FROM 7FFF TO 8000

SUB.B #1,D0 ;WILL SET THE OVERFLOW FLAG SINCE AT BYTE LENGTH WE CROSSED FROM 80 TO 7F


with Ada.Text_IO; use Ada.Text_IO;

procedure Overflow is

   generic
      type T is Range <>;
      Name_Of_T: String;
   procedure Print_Bounds; -- first instantiate this with T, Name
                           -- then call the instantiation
   procedure Print_Bounds is
   begin
      Put_Line("   " & Name_Of_T & " " & T'Image(T'First)
		 & " .." & T'Image(T'Last));
   end Print_Bounds;

   procedure P_Int  is new Print_Bounds(Integer,      "Integer ");
   procedure P_Nat  is new Print_Bounds(Natural,      "Natural ");
   procedure P_Pos  is new Print_Bounds(Positive,     "Positive");
   procedure P_Long is new Print_Bounds(Long_Integer, "Long    ");

   type Unsigned_Byte is range 0 .. 255;
   type Signed_Byte   is range -128 .. 127;
   type Unsigned_Word is range 0 .. 2**32-1;
   type Thousand is range 0 .. 999;
   type Signed_Double is range - 2**63 .. 2**63-1;
   type Crazy is range -11 .. -3;

   procedure P_UB is new Print_Bounds(Unsigned_Byte, "U 8  ");
   procedure P_SB is new Print_Bounds(Signed_Byte, "S 8  ");
   procedure P_UW is new Print_Bounds(Unsigned_Word, "U 32 ");
   procedure P_Th is new Print_Bounds(Thousand, "Thous");
   procedure P_SD is new Print_Bounds(Signed_Double, "S 64 ");
   procedure P_Cr is new Print_Bounds(Crazy, "Crazy");

   A: Crazy := Crazy'First;

begin
   Put_Line("Predefined Types:");
   P_Int; P_Nat; P_Pos; P_Long;
   New_Line;

   Put_Line("Types defined by the user:");
   P_UB; P_SB; P_UW; P_Th; P_SD; P_Cr;
   New_Line;

   Put_Line("Forcing a variable of type Crazy to overflow:");
   loop -- endless loop
      Put("  " & Crazy'Image(A) &  "+1");
      A := A + 1; -- line 49 -- this will later raise a CONSTRAINT_ERROR
   end loop;
end Overflow;


#lang racket
(for ([i (in-naturals)]) (displayln i))


BEGIN
   print (max int);
   print (1+max int)
END


big32bit: 2147483646
big64bit: 9223372036854775808

print type big32bit
print type big64bit

print big32bit + 1
print big64bit + 1

print big32bit * 2
print big64bit * 2


1 as $i
repeat TRUE while
   $i "%d\n" print   $i 1000 +  as $i


Red ["Integer sequence"]

i: 1
forever [
    print i
    i: i + 1
]


#0 [ [ n:put spa ] sip n:inc dup n:-zero? ] while drop


/*count all the protons, electrons, & whatnot in the universe, and then */
/*keep counting.  According to some pundits in-the-know, one version of */
/*the big-bang theory is that the universe will collapse back to where  */
/*it started, and this computer program will be still counting.         */
/*┌────────────────────────────────────────────────────────────────────┐
  │ Count all the protons  (and electrons!)  in the universe, and then │
  │ keep counting.  According to some pundits in-the-know, one version │
  │ of the big-bang theory is that the universe will collapse back to  │
  │ where it started, and this computer program will still be counting.│
  │                                                                    │
  │                                                                    │
  │ According to Sir Arthur Eddington in 1938 at his Tamer Lecture at  │
  │ Trinity College (Cambridge), he postulated that there are exactly  │
  │                                                                    │
  │                              136 ∙ 2^256                           │
  │                                                                    │
  │ protons in the universe and the same number of electrons, which is │
  │ equal to around  1.57477e+79.                                      │
  │                                                                    │
  │ Although, a modern estimate is around  10^80.                      │
  │                                                                    │
  │                                                                    │
  │ One estimate of the age of the universe is  13.7  billion years,   │
  │ or  4.32e+17 seconds.    This'll be a piece of cake.               │
  └────────────────────────────────────────────────────────────────────┘*/
numeric digits 1000000000       /*just in case the universe slows down. */

                                /*this version of a DO loop increments J*/
         do j=1                 /*Sir Eddington's number, then a googol.*/
         say j                  /*first, destroy some electrons.        */
         end
say 42                          /*(see below for explanation of 42.)    */
exit

/*This REXX program (as it will be limited to the NUMERIC DIGITS above, */
/*will only count up to  1000000000000000000000000000000000000000000... */
/*000000000000000000000000000000000000000000000000000000000000000000000 */
/*  ... for another (almost) one billion more zeroes  (then subtract 1).*/

/*if we can count  1,000  times faster than the fastest PeeCee, and we  */
/*started at the moment of the big-bang, we'd be at only  1.72e+28,  so */
/*we still have a little ways to go, eh?                                */

/*To clarify, we'd be  28 zeroes  into a million zeroes.   If PC's get  */
/*1,000  times faster again,  that would be  31  zeroes into a million. */

/*It only took   Deep Thought  7.5  million years  to come up with the  */
/*answer to everything  (and it double-checked the answer).  It was  42.*/


size = 10

for n = 1 to size
    see n + nl
next
see nl

for n in [1:size]
    see n + nl
next
see nl

i = n
while n <= size
      see n + nl
      n = n + 1
end


fn main() {
    for i in 0.. {
        println!("{}", i);
    }
}


(let loop ((i 1))
  (display i) (newline)
  (loop (+ 1 i)))


using System;

public class IntegerOverflow
{
    public static void Main() {
        unchecked {
            Console.WriteLine("For 32-bit signed integers:");
            Console.WriteLine(-(-2147483647 - 1));
            Console.WriteLine(2000000000 + 2000000000);
            Console.WriteLine(-2147483647 - 2147483647);
            Console.WriteLine(46341 * 46341);
            Console.WriteLine((-2147483647 - 1) / -1);
            Console.WriteLine();

            Console.WriteLine("For 64-bit signed integers:");
            Console.WriteLine(-(-9223372036854775807L - 1));
            Console.WriteLine(5000000000000000000L + 5000000000000000000L);
            Console.WriteLine(-9223372036854775807L - 9223372036854775807L);
            Console.WriteLine(3037000500L * 3037000500L);
            Console.WriteLine((-9223372036854775807L - 1) / -1);
            Console.WriteLine();

            Console.WriteLine("For 32-bit unsigned integers:");
            //Negating a 32-bit unsigned integer will convert it to a signed 64-bit integer.
            Console.WriteLine(-4294967295U);
            Console.WriteLine(3000000000U + 3000000000U);
            Console.WriteLine(2147483647U - 4294967295U);
            Console.WriteLine(65537U * 65537U);
            Console.WriteLine();

            Console.WriteLine("For 64-bit unsigned integers:");
            // The - operator cannot be applied to 64-bit unsigned integers; it will always give a compile-time error.
            //Console.WriteLine(-18446744073709551615UL);
            Console.WriteLine(10000000000000000000UL + 10000000000000000000UL);
            Console.WriteLine(9223372036854775807UL - 18446744073709551615UL);
            Console.WriteLine(4294967296UL * 4294967296UL);
            Console.WriteLine();
        }

        int i = 2147483647;
        Console.WriteLine(i + 1);
        try {
            checked { Console.WriteLine(i + 1); }
        } catch (OverflowException) {
            Console.WriteLine("Overflow!");
        }
    }

}


$ include "seed7_05.s7i";

  const proc: main is func
    local
      var integer: number is 0;
    begin
      repeat
        incr(number);
        writeln(number);
      until number = 2147483647;
    end func;


i := 0.
[
   Stdout print:i; cr.
   i := i + 1
] loop


let
  fun printInts(n) =
    (
      print(Int.toString(n) ^ "\n");
      printInts(n+1)
    )
in
  printInts(1)
end;


package Multiple_Interfaces is
   type Camera is tagged null record;
   type Mobile_Phone is limited Interface;
   type Camera_Phone is new Camera and Mobile_Phone with null record;
end Multiple_Interfaces;


interface Camera {
}

interface Mobile_Phone {
}

class Camera_Phone implements Camera, Mobile_Phone {
}


i = Routine { inf.do { |i| i.yield } }; // return all integers, represented by a 64 bit signed float.
fork { inf.do { i.next.postln; 0.01.wait } }; // this prints them incrementally


var i = 0
while true {
    println(i++)
}


| The following code will run forever
| Symsyn uses a 64 bit signed integer
| The largest positive integer is 9223372036854775807
| lpi + 1 = -9223372036854775808

lp
 x  []
 + x
 go lp


package require Tcl 8.5
while true {puts [incr i]}


    REM will overflow after 32767
    LET N = 0
10  PRINT N
    LET N = N + 1
    GOTO 10


LET i = 0

DO
   PRINT i
   LET i = i + 1
LOOP

END


IDENTIFICATION DIVISION.
PROGRAM-ID. PROCRUSTES-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01  WS-EXAMPLE.
    05 X            PIC  999.
PROCEDURE DIVISION.
    MOVE     1002   TO   X.
    DISPLAY  X      UPON CONSOLE.
    STOP RUN.


        LDA  ff
        ADD  one

...

ff:          255
one:         1


      INSTALL @lib$+"CLASSLIB"

      DIM Camera{TakePicture}
      PROC_class(Camera{})

      DIM MobilePhone{MakeCall}
      PROC_class(MobilePhone{})

      DIM CameraPhone{methods}
      PROC_inherit(CameraPhone{}, Camera{})
      PROC_inherit(CameraPhone{}, MobilePhone{})
      PROC_class(CameraPhone{})


typedef struct{
	double focalLength;
	double resolution;
	double memory;
}Camera;

typedef struct{
	double balance;
	double batteryLevel;
	char** contacts;
}Phone;

typedef struct{
	Camera cameraSample;
	Phone phoneSample;
}CameraPhone;


interface ICamera {
    // ...
}

class MobilePhone {
    // ...
}

class CameraPhone: ICamera, MobilePhone {
    // ...
}


class Camera
{
  // ...
};

class MobilePhone
{
  // ...
};

class CameraPhone:
  public Camera,
  public MobilePhone
{
  // ...
};


(defprotocol Camera)

(defprotocol MobilePhone)

(deftype CameraPhone []
  Camera
  MobilePhone)


       CLASS-ID. Camera.
           *> ...
       END CLASS Camera.

       CLASS-ID. Mobile-Phone.
           *> ...
       END CLASS Mobile-Phone.

       CLASS-ID. Camera-Phone INHERITS Camera, Mobile-Phone.
       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       REPOSITORY.
           CLASS Camera
           CLASS Mobile-Phone.

           *> ...
       END CLASS Camera-Phone.


$$ MODE TUSCRIPT
LOOP n=0,999999999
n=n+1
ENDLOOP


#!/bin/sh
num=0
while true; do
  echo $num
  num=`expr $num + 1`
done


#
# integer sequence
#

# declare an int and loop until it overflows
decl int i
set i 1
while true
        out i endl console
        inc i
end while


uint i = 0;
while (++i < uint.MAX)
	stdout.printf("%u\n", i);


module main;
  integer  i;

  initial begin
    i = 1;

    while(i > 0) begin
        $display(i);
        i = i + 1;
    end
  $finish ;
  end
endmodule


package main

import "fmt"

func main() {
	// Go's builtin integer types are:
	//    int,  int8,  int16,  int32,  int64
	//   uint, uint8, uint16, uint32, uint64
	//   byte, rune, uintptr
	//
	// int is either 32 or 64 bit, depending on the system
	// uintptr is large enough to hold the bit pattern of any pointer
	// byte is 8 bits like int8
	// rune is 32 bits like int32
	//
	// Overflow and underflow is silent. The math package defines a number
	// of constants that can be helpfull, e.g.:
	//    math.MaxInt64  = 1<<63 - 1
	//    math.MinInt64  = -1 << 63
	//    math.MaxUint64 = 1<<64 - 1
	//
	// The math/big package implements multi-precision
	// arithmetic (big numbers).
	//
	// In all cases assignment from one type to another requires
	// an explicit cast, even if the types are otherwise identical
	// (e.g. rune and int32 or int and either int32 or int64).
	// Casts silently truncate if required.
	//
	// Invalid:
	//    var i int  = int32(0)
	//    var r rune = int32(0)
	//    var b byte = int8(0)
	//
	// Valid:
	var i64 int64 = 42
	var i32 int32 = int32(i64)
	var i16 int16 = int16(i64)
	var i8 int8 = int8(i16)
	var i int = int(i8)
	var r rune = rune(i)
	var b byte = byte(r)
	var u64 uint64 = uint64(b)
	var u32 uint32

	//const c int = -(-2147483647 - 1) // Compiler error on 32 bit systems, ok on 64 bit
	const c = -(-2147483647 - 1) // Allowed even on 32 bit systems, c is untyped
	i64 = c
	//i32 = c                          // Compiler error
	//i32 = -(-2147483647 - 1)         // Compiler error
	i32 = -2147483647
	i32 = -(-i32 - 1)
	fmt.Println("32 bit signed integers")
	fmt.Printf("  -(-2147483647 - 1) = %d, got %d\n", i64, i32)

	i64 = 2000000000 + 2000000000
	//i32 = 2000000000 + 2000000000    // Compiler error
	i32 = 2000000000
	i32 = i32 + i32
	fmt.Printf("  2000000000 + 2000000000 = %d, got %d\n", i64, i32)
	i64 = -2147483647 - 2147483647
	i32 = 2147483647
	i32 = -i32 - i32
	fmt.Printf("  -2147483647 - 2147483647 = %d, got %d\n", i64, i32)
	i64 = 46341 * 46341
	i32 = 46341
	i32 = i32 * i32
	fmt.Printf("  46341 * 46341 = %d, got %d\n", i64, i32)
	i64 = (-2147483647 - 1) / -1
	i32 = -2147483647
	i32 = (i32 - 1) / -1
	fmt.Printf("  (-2147483647-1) / -1 = %d, got %d\n", i64, i32)

	fmt.Println("\n64 bit signed integers")
	i64 = -9223372036854775807
	fmt.Printf("  -(%d - 1): %d\n", i64, -(i64 - 1))
	i64 = 5000000000000000000
	fmt.Printf("  %d + %d: %d\n", i64, i64, i64+i64)
	i64 = 9223372036854775807
	fmt.Printf("  -%d - %d: %d\n", i64, i64, -i64-i64)
	i64 = 3037000500
	fmt.Printf("  %d * %d: %d\n", i64, i64, i64*i64)
	i64 = -9223372036854775807
	fmt.Printf("  (%d - 1) / -1: %d\n", i64, (i64-1)/-1)

	fmt.Println("\n32 bit unsigned integers:")
	//u32 = -4294967295 // Compiler error
	u32 = 4294967295
	fmt.Printf("  -%d: %d\n", u32, -u32)
	u32 = 3000000000
	fmt.Printf("  %d + %d: %d\n", u32, u32, u32+u32)
	a := uint32(2147483647)
	u32 = 4294967295
	fmt.Printf("  %d - %d: %d\n", a, u32, a-u32)
	u32 = 65537
	fmt.Printf("  %d * %d: %d\n", u32, u32, u32*u32)

	fmt.Println("\n64 bit unsigned integers:")
	u64 = 18446744073709551615
	fmt.Printf("  -%d: %d\n", u64, -u64)
	u64 = 10000000000000000000
	fmt.Printf("  %d + %d: %d\n", u64, u64, u64+u64)
	aa := uint64(9223372036854775807)
	u64 = 18446744073709551615
	fmt.Printf("  %d - %d: %d\n", aa, u64, aa-u64)
	u64 = 4294967296
	fmt.Printf("  %d * %d: %d\n", u64, u64, u64*u64)
}


(defclass camera () ())
(defclass mobile-phone () ())
(defclass camera-phone (camera mobile-phone) ())


interface Camera {
    // member function prototypes and static methods
}

interface MobilePhone {
    // member function prototypes and static methods
}

class CameraPhone: Camera, MobilePhone {
    // member function implementations for Camera,
    //   MobilePhone, and CameraPhone
}


type
  ICamera = Interface
    // ICamera methods...
  end;

  IMobilePhone = Interface
    // IMobilePhone methods...
  end;

  TCameraPhone = class(TInterfacedObject, ICamera, IMobilePhone)
    // ICamera and IMobilePhone methods...
  end;


def minherit(self, supers) {
    def forwarder match [verb, args] {
        escape __return {
            if (verb == "__respondsTo") {
                def [verb, arity] := args
                for super ? (super.__respondsTo(verb, arity)) in supers {
                    return true
                }
                return false
            } else if (verb == "__getAllegedType") {
                # XXX not a complete implementation
                return supers[0].__getAllegedType()
            } else {
                def arity := args.size()
                for super ? (super.__respondsTo(verb, arity)) in supers {
                    return E.call(super, verb, args)
                }
                throw(`No parent of $self responds to $verb/$arity`)
            }
        }
    }
    return forwarder
}


    For i As Integer = 0 To Integer.MaxValue
      Console.WriteLine(i)
    Next


let s => import 'stream';

s.new 0 (+ 1)
-> s.map (io.writeln io.stdout)
-> s.drain
;


import "./fmt" for Fmt
import "./big" for BigInt

var max = 2.pow(53) // 9007199254740992 (16 digits)
for (i in 1...max) Fmt.print("$d", i)

var bi = BigInt.new(max.toString)
while (true) {
    Fmt.print("$i", bi)
    bi = bi + 1
}


(defun integer-sequence-from (x)
	(print x)
	(integer-sequence-from (+ x 1)) )

(integer-sequence-from 1)


singleton CameraFeature
{
    cameraMsg
        = "camera";
}

class MobilePhone
{
    mobileMsg
        = "phone";
}

class CameraPhone : MobilePhone
{
    dispatch() => CameraFeature;
}

public program()
{
   var cp := new CameraPhone();

   console.writeLine(cp.cameraMsg);
   console.writeLine(cp.mobileMsg)
}


type Picture = System.Drawing.Bitmap // (a type synonym)

// an interface type
type Camera =
  abstract takePicture : unit -> Picture

// an interface that inherits multiple interfaces
type Camera2 =
  inherits System.ComponentModel.INotifyPropertyChanged
  inherits Camera

// a class with an abstract method with a default implementation
// (usually called a virtual method)
type MobilePhone() =
  abstract makeCall : int[] -> unit
  default x.makeCall(number) = () // empty impl

// a class that inherits from another class and implements an interface
type CameraPhone() =
  inherit MobilePhone()
  interface Camera with
    member x.takePicture() = new Picture(10, 10)


TUPLE: camera ;
TUPLE: mobile-phone ;
UNION: camera-phone camera mobile-phone ;


// a regular class
class Camera
{
  Str cameraMsg ()
  {
    "camera"
  }
}

// a mixin can only contain methods
mixin MobilePhone
{
  Str mobileMsg ()
  {
    "mobile phone"
  }
}

// class inherits from Camera, and mixes in the methods from MobilePhone
class CameraPhone : Camera, MobilePhone
{
}

class Main
{
  public static Void main ()
  {
    cp := CameraPhone ()
    echo (cp.cameraMsg)
    echo (cp.mobileMsg)
  }
}


\ define class camera with method say:
:class camera
 :m say: ." camera " ;m
;class

\ define class phone with method say:
:class phone
 :m say: ." phone " ;m
;class

\ define cameraPhone phone with method say:
\ class cameraPhone inherits from both class
\ camera and class phone
:class cameraPhone super{ camera phone }
 :m say: self say: \ method conflicts in superclasses
                   \ are resolved by left-to-right order
                   \ so self say: will call the say: method
                   \ from class camera
    super> phone say: \ super> phone is used to direct
                      \ this say: method to use the
                      \ method from class phone
 ;m
;class

cameraPhone cp \ instantiate a cameraPhone object named cp

cp say: \ send the say: message to cp

\ output:
camera phone


' FB 1.05.0 Win64

' FB does not currently support multiple inheritance. Composition has to be used instead if one wants
' to (effectively) inherit from more than one class. In some cases, this might arguably be a better
' solution anyway.

Type Camera Extends Object  ' if virtual methods etc needed
  ' ...
End Type

Type Phone Extends Object
  ' ...
End Type

Type CameraPhone Extends Phone ' single inheritance
  cam As Camera ' using composition here
  ' other stuff
End Type


\Displays integers up to 2^31-1 = 2,147,483,647
code CrLf=9, IntOut=11;
int N;
[N:= 1;
repeat  IntOut(0, N);  CrLf(0);
        N:= N+1;
until   N<0;
]


i = 1

repeat
    print i
    i = i + 1
until i = 0
end


org &1000
PrintChar equ &BB5A
ld hl,1 ;START AT ONE
main:
push hl
;PRINT HIGH BYTE
ld a,h
call ShowHex
;THEN PRINT LOW BYTE
ld a,l
call ShowHex

;NEW LINE
ld a,13
call PrintChar
ld a,10
call PrintChar

pop hl
;NEXT HL
inc hl
;COMPARE HL TO ZERO
ld a,h
or l
jr nz,main     ;IF NOT ZERO, REPEAT
ret	       ;RETURN TO BASIC

ShowHex:
	push af
		and %11110000
		rrca
		rrca
		rrca
		rrca
		call PrintHexChar
	pop af
	and %00001111
	;call PrintHexChar
	;execution flows into it naturally.
PrintHexChar:
        ;this converts hexadecimal to ascii.
	or a	;Clear Carry Flag
	daa
	add a,&F0
	adc a,&40
	jp PrintChar
	;ret


[1..].pump(Console.println)  // eager
m:=(1).MAX; [1..m].pump(Console.println)  // (1).MAX is 9223372036854775807
[1..].pump(100,Console.println)  // lazy


// Example of composition of anonymous structs
package main

import "fmt"

// Two ordinary structs
type camera struct {
    optics, sensor string
}

type mobilePhone struct {
    sim, firmware string
}

// Fields are anonymous because only the type is listed.
// Also called an embedded field.
type cameraPhone struct {
    camera
    mobilePhone
}

func main() {
    // Struct literals must still reflect the nested structure
    htc := cameraPhone{camera{optics: "zoom"}, mobilePhone{firmware: "3.14"}}

    // But fields of anonymous structs can be referenced without qualification.
    // This provides some effect of the two parent structs being merged, as
    // with multiple inheritance in some other programming languages.
    htc.sim = "XYZ"
    fmt.Println(htc)
}


class Camera a
class MobilePhone a
class (Camera a, MobilePhone a) => CameraPhone a


class Camera (instanceVars)
    # methods...
    # initializer...
end

class Phone (instanceVars)
    # methods...
    # initializer...
end

class CameraPhone : Camera, Phone (instanceVars)
    # methods...
    # initialiser...
end


Camera := Object clone
Camera click := method("Taking snapshot" println)

MobilePhone := Object clone
MobilePhone call := method("Calling home" println)

CameraPhone := Camera clone
CameraPhone appendProto(MobilePhone)

myPhone := CameraPhone clone
myPhone click	// --> "Taking snapshot"
myPhone call	// --> "Calling home"


Camera = Origin mimic
MobilePhone = Origin mimic
CameraPhone = Camera mimic mimic!(MobilePhone)


coclass 'Camera'

create=: verb define
  NB. creation-specifics for a camera go here
)

destroy=: codestroy

NB. additional camera methods go here

coclass 'MobilePhone'

create=: verb define
  NB. creation-specifics for a mobile phone go here
)

destroy=: codestroy

NB. additional phone methods go here

coclass 'CameraPhone'
coinsert 'Camera MobilePhone'

create=: verb define
  create_Camera_ f. y
  create_MobilePhone_ f. y
  NB. creation details specific to a camera phone go here
)

destroy=: codestroy

NB. additional camera-phone methods go here


public interface Camera{
   //functions here with no definition...
   //ex:
   //public void takePicture();
}


abstract type Phone end

struct DeskPhone <: Phone
    book::Dict{String,String}
end

abstract type Camera end

struct kodak
    roll::Vector{Array{Int32,2}}
end

struct CellPhone <: Phone
    book::Dict{String,String}
    roll::Vector{AbstractVector}
end

function dialnumber(phone::CellPhone)
    println("beep beep")
end

function dialnumber(phone::Phone)
    println("tat tat tat tat")
end

function snap(camera, img)
    println("click")
    push!(camera.roll, img)
end

dphone = DeskPhone(Dict(["information" => "411"]))
cphone = CellPhone(Dict(["emergency" => "911"]), [[]])

dialnumber(dphone)
dialnumber(cphone)


interface Camera {
    val numberOfLenses : Int
}

interface MobilePhone {
    fun charge(n : Int) {
        if (n >= 0)
            battery_level = (battery_level + n).coerceAtMost(100)
    }

    var battery_level : Int
}

data class CameraPhone(override val numberOfLenses : Int = 1, override var battery_level: Int) : Camera, MobilePhone
data class TwinLensCamera(override val numberOfLenses : Int = 2) : Camera

fun main(args: Array<String>) {
    val c = CameraPhone(1, 50)
    println(c)
    c.charge(35)
    println(c)
    c.charge(78)
    println(c)
    println(listOf(c.javaClass.superclass) + c.javaClass.interfaces)
    val c2 = TwinLensCamera()
    println(c2)
    println(listOf(c2.javaClass.superclass) + c2.javaClass.interfaces)
}


define trait_camera => trait {
	require zoomfactor

	provide has_zoom() => {
		return .zoomfactor > 0
	}

}

define trait_mobilephone => trait {
	require brand

	provide is_smart() => {
		return .brand == 'Apple'
	}

}

define cameraphone => type {

	trait {
		import trait_camera, trait_mobilephone
	}

	data public zoomfactor::integer = 0,
		public brand::string

}

local(mydevice = cameraphone)

#mydevice -> brand = 'Apple'
#mydevice -> zoomfactor = 0

#mydevice -> has_zoom
'<br />'
#mydevice -> is_smart


Camera ::= Mixin clone.
MobilePhone ::= Mixin clone.

CameraPhone ::= Object clone.
Camera inject: CameraPhone.
MobilePhone inject: CameraPhone.


using Printf
S = subtypes(Signed)
U = subtypes(Unsigned)

println("Integer limits:")
for (s, u) in zip(S, U)
    @printf("%8s: [%s, %s]\n", s, typemin(s), typemax(s))
    @printf("%8s: [%s, %s]\n", u, typemin(u), typemax(u))
end


-- parent script "Camera"
property resolution

on new (me)
  me.resolution = "1024x768"
  return me
end

on snap (me)
  put "SNAP!"
end


:- object(camera,
    ...).
    ...
:- end_object.


function setmetatables(t,mts) --takes a table and a list of metatables
  return setmetatable(t,{__index = function(self, k)
    --collisions are resolved in this implementation by simply taking the first one that comes along.
    for i, mt in ipairs(mts) do
      local member = mt[k]
      if member then return member end
    end
  end})
end

camera = {}
mobilephone = {}
cameraphone = setemetatables({},{camera,mobilephone})


Module CheckIt {
      Class Camera {
      Private:
            cameratype$
      Class:
            module Camera (.cameratype$){
            }
      }
      \\ INHERITANCE AT CODE LEVEL
      Class MobilePhone {
      Private:
            model$
       Class:
            module  MobilePhone (.model$) {
            }
      }
      Class CameraPhone  as Camera as MobilePhone {
            Module CameraPhone ( .model$, .cameratype$) {
            }
      }
      CP1 =CameraPhone("X-15", "OBSCURE")
      Print CP1 is type CameraPhone = true
      Print CP1 is type Camera = true
      Print CP1 is type MobilePhone = true

      \\ INHERITANCE AT OBJECT LEVEL
      CP2 = MobilePhone("X-9") with Camera("WIDE")
      \\ CP3 has no type
      Group CP3 {
             Module PrintAll {
                   If this is type Camera and this is type MobilePhone then
                         Print .model$, .cameratype$
                   Else
                         Print "Nothing to print"
                   End if
             }
      }
      CP3.PrintAll   ' Nothing to print
      \\ using pointers and prepate inheritance at object level
      CP->(CP1 with CP3)
      CP=>PrintAll
      CP->(CP2 with CP3)
      CP=>PrintAll
}
CheckIt


interface ICamera {
    // ...
}

class MobilePhone {
    // ...
}

class CameraPhone: MobilePhone, ICamera {
    // ...
}


/* NetRexx */
options replace format comments java crossref symbols binary

class RInheritMultiple public
  method main(args = String[]) public static
    iPhone = RInheritMultiple_CameraPhone()
    if iPhone <= RInheritMultiple_Camera then -
      say -
      'Object' hashToString(iPhone) '['iPhone.getClass().getSimpleName()']' -
      'is a' RInheritMultiple_Camera.class.getSimpleName()
    if iPhone <= RInheritMultiple_MobilePhone then -
      say -
      'Object' hashToString(iPhone) '['iPhone.getClass().getSimpleName()']' -
      'is a' RInheritMultiple_MobilePhone.class.getSimpleName()
    say iPhone.snap()
    say iPhone.call()
    return
  method hashToString(that = Object) public static
    return '@'(Rexx that.hashCode()).d2x().right(8, 0)

class RInheritMultiple_Camera private interface
  -- properties follow...
  shutter = 'click...'
  -- method prototypes follow
  method snap() public returns Rexx

class RInheritMultiple_MobilePhone private interface
  -- properties follow...
  ringTone = 'ring...'
  -- method prototypes follow
  method call() public returns Rexx

class RInheritMultiple_CameraPhone private -
  implements -
    RInheritMultiple_Camera, -
    RInheritMultiple_MobilePhone -
  uses -
    RInheritMultiple_Camera, -
    RInheritMultiple_MobilePhone
  method RInheritMultiple_CameraPhone() public
    return
  -- method implementations follow
  method snap() public
    return shutter
  method call() public
    return ringTone


// version 1.0.5-2

/*  Kotlin (like Java) does not have unsigned integer types but we can simulate
    what would happen if we did have an unsigned 32 bit integer type using this extension function */
fun Long.toUInt(): Long = this and 0xffffffffL

@Suppress("INTEGER_OVERFLOW")
fun main(args: Array<String>) {
    // The following 'signed' computations all produce compiler warnings that they will lead to an overflow
    // which have been ignored
    println("*** Signed 32 bit integers ***\n")
    println(-(-2147483647 - 1))
    println(2000000000 + 2000000000)
    println(-2147483647 - 2147483647)
    println(46341 * 46341)
    println((-2147483647 - 1) / -1)
    println("\n*** Signed 64 bit integers ***\n")
    println(-(-9223372036854775807 - 1))
    println(5000000000000000000 + 5000000000000000000)
    println(-9223372036854775807 - 9223372036854775807)
    println(3037000500 * 3037000500)
    println((-9223372036854775807 - 1) / -1)
    // Simulated unsigned computations, no overflow warnings as we're using the Long type
    println("\n*** Unsigned 32 bit integers ***\n")
    println((-4294967295L).toUInt())
    println((3000000000L.toUInt() + 3000000000L.toUInt()).toUInt())
    println((2147483647L - 4294967295L.toUInt()).toUInt())
    println((65537L * 65537L).toUInt())
}


#!/bin/ksh

# Integer overflow

#	# Variables:
#
typeset -si SHORT_INT
typeset -i  INTEGER
typeset -li LONG_INT

 ######
# main #
 ######

(( SHORT_INT = 2**15 -1 )) ; print "SHORT_INT (2^15 -1) = $SHORT_INT"
(( SHORT_INT = 2**15 )) ; print "SHORT_INT (2^15)   : $SHORT_INT"

(( INTEGER = 2**31 -1 )) ; print "  INTEGER (2^31 -1) = $INTEGER"
(( INTEGER = 2**31 )) ; print "  INTEGER (2^31)   : $INTEGER"

(( LONG_INT = 2**63 -1 )) ; print " LONG_INT (2^63 -1) = $LONG_INT"
(( LONG_INT = 2**63 )) ; print " LONG_INT (2^63)   : $LONG_INT"


assert(math.type~=nil, "Lua 5.3+ required for this test.")
minint, maxint = math.mininteger, math.maxinteger
print("min, max int64  = " .. minint .. ", " .. maxint)
print("min-1 underflow =  " .. (minint-1) .. "  equals max? " .. tostring(minint-1==maxint))
print("max+1 overflow  = " .. (maxint+1) .. "  equals min? " .. tostring(maxint+1==minint))


type
  Camera = ref object of RootObj
  MobilePhone = ref object of RootObj
  CameraPhone = object
    camera: Camera
    phone: MobilePhone
proc `is`(cp: CameraPhone, t: typedesc): bool =
  for field in cp.fields():
    if field of t:
      return true
var cp: CameraPhone
echo(cp is Camera)
echo(cp is MobilePhone)


@interface Camera : NSObject {
}
@end

@implementation Camera
@end

@interface MobilePhone : NSObject {
}
@end

@implementation MobilePhone
@end

@interface CameraPhone : NSObject {
  Camera *camera;
  MobilePhone *phone;
}
@end

@implementation CameraPhone

-(instancetype)init {
  if ((self = [super init])) {
    camera = [[Camera alloc] init];
    phone = [[MobilePhone alloc] init];
  }
  return self;
}

-(void)forwardInvocation:(NSInvocation *)anInvocation {
  SEL aSelector = [anInvocation selector];
  if ([camera respondsToSelector:aSelector])
    [anInvocation invokeWithTarget:camera];
  else if ([phone respondsToSelector:aSelector])
    [anInvocation invokeWithTarget:phone];
  else
    [self doesNotRecognizeSelector:aSelector];
}

-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
  return [camera methodSignatureForSelector:aSelector]
  ?: [phone methodSignatureForSelector:aSelector]
  ?: [super methodSignatureForSelector:aSelector];
}

-(BOOL)respondsToSelector:(SEL)aSelector {
  return [camera respondsToSelector:aSelector]
  || [phone respondsToSelector:aSelector]
  || [super respondsToSelector:aSelector];
}

@end


class camera =
  object (self)
    (*functions go here...*)
  end


Property new: Camera
Property new: MobilePhone

Object Class new: CameraPhone
CameraPhone is: Camera
CameraPhone is: MobilePhone


-- inherited classes must be created as mixinclasses.
::class phone mixinclass object

::class camera mixinclass object

-- not a direct subclass of either, but inherits both
::class cameraphone inherit phone camera

-- could also be
::class cameraphone1 subclass phone inherit camera

-- or

::class cameraphone2 subclass camera inherit phone


class Camera
  string cbuf
  method TakePhoto()
  end method
  method ViewPhoto()
  end method
end class

class MobilePhone
  string pbuf
  method MakeCall()
  end method
  method TakeCall()
  end method
end class

class CameraPhone
  has Camera,MobilePhone
end class

CameraPhone cp

cp.ViewPhoto
cp.MakeCall


Long A
Try ok {
      A=12121221212121
}
If not ok then Print Error$ 'Overflow Long
Def Integer B
Try ok {
      B=1212121212
}
If not ok then Print Error$  ' Overflow Integer
Def Currency C
Try ok {
      C=121212121232934392898274327927948
}
If not ok then Print Error$  ' return  Overflow Long, but is overflow Currency
Def Decimal D
Try ok {
      D=121212121232934392898274327927948
}
If not ok then Print Error$  ' return  Overflow Long, but is overflow Decimal

\\ No overflow for unsigned numbers in structs
Structure Struct {
      \\ union a1, a2| b
     {
             a1 as integer
             a2 as integer
      }
      b as long
}
\\ structures are type for Memory Block, or other sttructure
\\ we use Clear to erase internal Memory Block
Buffer Clear DataMem as Struct*20
\\ from a1 we get only the low word
Return DataMem, 0!a2:=0xBBBB, 0!a1:=0xFFFFAAAA
Print Hex$(Eval(DataMem, 0!b))="BBBBAAAA"
Print Eval(DataMem, 0!b)=Eval(DataMem, 0!a2)*0x10000+Eval(DataMem, 0!a1)


try:
  var x: int32 = -2147483647
  x = -(x - 1)  # Raise overflow.
  echo x
except OverflowDefect:
  echo "Overflow detected"


class Camera end

class MobilePhone end

class CameraPhone from Camera MobilePhone end


package Camera;
#functions go here...
1;


class Camra
    string name = "nikkon"
end class
class Mobile
--  string name = "nokia" -- oops!
    string mane = "nokia" -- ok!
end class
class CamraPhone extends Camra,Mobile
    procedure show() ?{name,mane} end procedure
end class
CamraPhone cp = new()
cp.show()


(class +Camera)
(class +MobilePhone)
(class +CameraPhone +MobilePhone +Camera)


;;; load object support
lib objectclass;

define :class Camera;
   ;;; slots go here
enddefine;

define :class MobilePhone;
   ;;; slots go here
enddefine;

define :class CameraPhone is Camera, MobilePhone;
   ;;; extra slots go here
enddefine;

;;; methods go here


class Camera {}
class MobilePhone {}
class CameraPhone : Camera, MobilePhone {}


Class Camera
EndClass

Class Mobil
EndClass

Class CameraMobile Extends Camera Extends Mobil
EndClass


class Camera:
  pass #functions go here...


100H: /* SHOW INTEGER OVERFLOW */

   /* CP/M SYSTEM CALL */
   BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;   END;
   /* CONSOLE I/O ROUTINES */
   PRCHAR:   PROCEDURE( C );   DECLARE C BYTE;      CALL BDOS( 2, C ); END;
   PRSTRING: PROCEDURE( S );   DECLARE S ADDRESS;   CALL BDOS( 9, S ); END;
   PRNL:     PROCEDURE;        CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;
   PRNUMBER: PROCEDURE( N );
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
      N$STR( W := LAST( N$STR ) ) = '$';
      N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
      DO WHILE( ( V := V / 10 ) > 0 );
         N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      END;
      CALL PRSTRING( .N$STR( W ) );
   END PRNUMBER;

   /* TASK */

   /* THE ONLY TYPES SUPPORTED BY THE ORIGINAL PL/M COMPILER ARE */
   /* UNSIGED, BYTE IS 8 BITS AND ADDRESS IS 16 BITS */
   DECLARE SV BYTE, LV ADDRESS;

   SV =   255;   /* MAXIMUM BYTE VALUE */
   LV = 65535;   /* MAXIMUM ADDRESS VALUE */

   CALL PRSTRING( .'8-BIT: $' );
   CALL PRNUMBER( SV );
   CALL PRSTRING( .' INCREMENTS TO: $' );
   SV = SV + 1;
   CALL PRNUMBER( SV );
   CALL PRNL;

   CALL PRSTRING( .'16-BIT: $' );
   CALL PRNUMBER( LV );
   CALL PRSTRING( .' INCREMENTS TO: $' );
   LV = LV + 1;
   CALL PRNUMBER( LV );
   CALL PRNL;

EOF


#lang racket

(define camera<%>       (interface ()))
(define mobile-phone<%> (interface ()))

(define camera-phone%
  (class* object% (camera<%> mobile-phone<%>)
    (super-new)
    ;; implement methods here
    ))


class Camera {}
class MobilePhone {}
class CameraPhone is Camera is MobilePhone {}

say CameraPhone.^mro;     # undefined type object
say CameraPhone.new.^mro; # instantiated object


# Project : Inheritance/Multiple

mergemethods(:CameraPhone,:MobilePhone)

o1 = new CameraPhone
? o1
? o1.testCamera()
? o1.testMobilePhone()

func AddParentClassAttributes oObject,cClass
    # Add Attributes
        cCode = "oTempObject = new " + cClass
        eval(cCode)
        for cAttribute in Attributes(oTempObject)
            AddAttribute(oObject,cAttribute)
            cCode = "oObject." + cAttribute + " = oTempObject." + cAttribute
            eval(cCode)
        next

class Camera
    Name = "Camera"
    func testCamera
        ? "Message from testCamera"

class MobilePhone
    Type = "Android"
    func testMobilePhone
        ? "Message from MobilePhone"

class CameraPhone from Camera

    # Add MobilePhone Attributes
        AddParentClassAttributes(self,:MobilePhone)


module Camera
  # define methods here
end
class MobilePhone
  # define methods here
end
class CameraPhone < MobilePhone
  include Camera
  # define methods here
end


trait Camera {}
trait MobilePhone {}
trait CameraPhone: Camera + MobilePhone {}


trait Camera
trait MobilePhone
class CameraPhone extends Camera with MobilePhone


class Camera {};
class MobilePhone {};
class CameraPhone << Camera, MobilePhone {};


define: #Camera.
define: #MobilePhone.
define: #CameraPhone &parents: {Camera. MobilePhone}.


protocol Camera {

}

protocol Phone {

}

class CameraPhone: Camera, Phone {

}


package require TclOO

oo::class create Camera
oo::class create MobilePhone
oo::class create CameraPhone {
    superclass Camera MobilePhone
}


class Camera {
    construct new() {}
    snap() { System.print("taking a photo") }
}

class Phone {
    construct new() {}
    call() { System.print("calling home") }
}

class CameraPhone is Camera {
    construct new(phone) { _phone = phone } // uses composition for the Phone part
    // inherits Camera's snap() method
    // Phone's call() method can be wrapped
    call() { _phone.call() }
}

var p = Phone.new()
var cp = CameraPhone.new(p)
cp.snap()
cp.call()


class Camera{} class MobilePhone{}
class CameraPhone(Camera,MobilePhone){}
CameraPhone.linearizeParents


#MAX_BYTE =127

#MAX_ASCII=255                  ;=MAX_CHAR Ascii-Mode

CompilerIf #PB_Compiler_Unicode=1
#MAX_CHAR =65535                ;Unicode-Mode
CompilerElse
#MAX_CHAR =255
CompilerEndIf

#MAX_WORD =32767

#MAX_UNIC =65535

#MAX_LONG =2147483647

CompilerIf #PB_Compiler_Processor=#PB_Processor_x86
#MAX_INT  =2147483647           ;32-bit CPU
CompilerElseIf #PB_Compiler_Processor=#PB_Processor_x64
#MAX_INT  =9223372036854775807  ;64-bit CPU
CompilerEndIf

#MAX_QUAD =9223372036854775807

Macro say(Type,maxv,minv,sz)
  PrintN(Type+#TAB$+RSet(Str(minv),30,Chr(32))+#TAB$+RSet(Str(maxv),30,Chr(32))+#TAB$+RSet(Str(sz),6,Chr(32))+" Byte")
EndMacro

OpenConsole()
PrintN("TYPE"+#TAB$+RSet("MIN",30,Chr(32))+#TAB$+RSet("MAX",30,Chr(32))+#TAB$+RSet("SIZE",6,Chr(32)))

Define.b b1=#MAX_BYTE, b2=b1+1
say("Byte",b1,b2,SizeOf(b1))

Define.a a1=#MAX_ASCII, a2=a1+1
say("Ascii",a1,a2,SizeOf(a1))

Define.c c1=#MAX_CHAR, c2=c1+1
say("Char",c1,c2,SizeOf(c1))

Define.w w1=#MAX_WORD, w2=w1+1
say("Word",w1,w2,SizeOf(w1))

Define.u u1=#MAX_UNIC, u2=u1+1
say("Unicode",u1,u2,SizeOf(u1))

Define.l l1=#MAX_LONG, l2=l1+1
say("Long   ",l1,l2,SizeOf(l1))

Define.i i1=#MAX_INT, i2=i1+1
say("Int",i1,i2,SizeOf(i1))

Define.q q1=#MAX_QUAD, q2=q1+1
say("Quad",q1,q2,SizeOf(q1))

Input()


/*REXX program  displays values  when  integers  have an   overflow  or  underflow.     */
numeric digits 9                                 /*the REXX default is 9 decimal digits.*/
call  showResult(  999999997 + 1 )
call  showResult(  999999998 + 1 )
call  showResult(  999999999 + 1 )
call  showResult( -999999998 - 2 )
call  showResult(  40000 * 25000 )
call  showResult( -50000 * 20000 )
call  showResult(  50000 *-30000 )
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
showResult: procedure;  parse arg x,,_;  x=x/1                      /*normalize   X.    */
            if pos(., x)\==0  then  if x>0  then _=' [overflow]'    /*did it  overflow? */
                                            else _=' [underflow]'   /*did it underflow? */
            say right(x, 20) _                                      /*show the result.  */
            return x                                                /*return the value. */


import Math.{addExact => ++, multiplyExact => **, negateExact => ~~, subtractExact => --}

def requireOverflow(f: => Unit) =
  try {f; println("Undetected overflow")} catch{case e: Exception => /* caught */}

println("Testing overflow detection for 32-bit unsigned integers")
requireOverflow(~~(--(~~(2147483647), 1))) // -(-2147483647-1)
requireOverflow(++(2000000000, 2000000000)) // 2000000000 + 2000000000
requireOverflow(--(~~(2147483647), 2147483647)) // -2147483647 + 2147483647
requireOverflow(**(46341, 46341)) // 46341 * 46341
requireOverflow(**(--(~~(2147483647),1), -1)) // same as (-2147483647-1) / -1

println("Test - Expect Undetected overflow:")
requireOverflow(++(1,1)) // Undetected overflow


$ include "seed7_05.s7i";

const proc: writeResult (ref func integer: expression) is func
  begin
    block
      writeln(expression);
    exception
      catch OVERFLOW_ERROR: writeln("OVERFLOW_ERROR");
    end block;
  end func;

const proc: main is func
  begin
    writeResult(-(-9223372036854775807-1));
    writeResult(5000000000000000000+5000000000000000000);
    writeResult(-9223372036854775807 - 9223372036854775807);
    writeResult(3037000500 * 3037000500);
    writeResult((-9223372036854775807-1) div -1);
  end func;


~(~9223372036854775807-1) ;
poly: : error: Overflow exception raised while converting ~9223372036854775807 to int
Int.maxInt ;
val it = SOME 4611686018427387903: int option
~(~4611686018427387903 - 1);
Exception- Overflow raised
 (~4611686018427387903 - 1) div ~1;
Exception- Overflow raised
2147483648 * 2147483648 ;
Exception- Overflow raised


PRINT "Signed 32-bit:"
PRINT -(-2147483647-1)            !-2147483648
PRINT 2000000000 + 2000000000     !4000000000
PRINT -2147483647 - 2147483647    !-4294967294
PRINT 46341 * 46341               !2147488281
!PRINT (-2147483647-1) / -1        !ERROR: Illegal expression
WHEN ERROR IN
     PRINT maxnum * 2             !Run-time ERROR "Overflow"
USE
     PRINT maxnum
     !returns the largest number that can be represented in your computer
END WHEN
END


'Binary Integer overflow - vbs
i=(-2147483647-1)/-1
wscript.echo i
i0=32767 	    '=32767      Integer (Fixed)  type=2
i1=2147483647	    '=2147483647 Long    (Fixed)  type=3
i2=-(-2147483647-1) '=2147483648 Double  (Float)  type=5
wscript.echo Cstr(i0) & " : " & typename(i0) & " , " & vartype(i0) & vbcrlf _
           & Cstr(i1) & " : " & typename(i1) & " , " & vartype(i1) & vbcrlf _
           & Cstr(i2) & " : " & typename(i2) & " , " & vartype(i2)
ii=2147483648-2147483647
if vartype(ii)<>3 or vartype(ii)<>2 then wscript.echo "Integer overflow type=" & typename(ii)
i1=1000000000000000-1 '1E+15-1
i2=i1+1               '1E+15
wscript.echo Cstr(i1) & " , " & Cstr(i2)


Constant expression not representable in type 'Integer/Long/UInteger'


ld a,&7F
add 1
jp pe,ErrorHandler ;pe = parity even, but in this case it represents overflow set


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program inputLoop64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ BUFSIZE,  10000
.equ LINESIZE, 100

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessErreur:     .asciz "Erreur ouverture fichier input.\n"
szMessErreur1:    .asciz "Erreur fermeture fichier.\n"
szMessErreur2:    .asciz "Erreur lecture fichier.\n"
szCarriageReturn: .asciz "\n"
szMessEndLine:    .asciz "<<<<<< End line.\n"

szMessCodeErr: .asciz "Error code décimal :  @ \n"

szNameFileInput:    .asciz "input.txt"

/*******************************************/
/* DONNEES NON INITIALISEES                */
/*******************************************/
.bss
sZoneConv:    .skip 24
sBuffer:      .skip BUFSIZE
sBufferWord:  .skip LINESIZE
/**********************************************/
/* -- Code section                            */
/**********************************************/
.text
.global main
main:
    /* open file */
    mov x0,AT_FDCWD
    ldr x1,qAdrszNameFileInput     // file name
    mov x2,O_RDONLY                //  flags
    mov x3,0                       // mode
    mov x8,OPEN                    // call system OPEN
    svc 0
    cmp x0,0                       // open error ?
    ble erreur
    /* read file  */
    mov x9,x0                      // save File Descriptor
    ldr x1,qAdrsBuffer             // buffer address
    mov x2,BUFSIZE                 // buffer size
    mov x8,READ                    // call system  READ
    svc 0
    cmp x0,0                       // read error ?
    ble erreur2
    mov x2,x0                      // length read characters
    /* buffer analyze   */
    ldr x3,qAdrsBuffer             // buffer address
    ldr x5,qAdrsBufferWord         // buffer address
    mov x7,0                       // word byte counter
    mov x4,0                       // byte counter
    mov x10,1
1:
    ldrb w6,[x3,x4]                // load byte buffer
    cmp x6,' '                     // space ?
    csel x8,xzr,x10,eq             // yes  0-> x8
    beq 2f
    cmp x6,0xA                     // end line ?
    csel x8,x10,xzr,eq             // yes 1 -> x8
    beq 2f
    cmp x6,0xD                     // end line ?
    csel x8,x10,xzr,eq
    beq 3f
    strb w6,[x5,x7]                // store byte
    add x7,x7,1                    // increment word byte counter
    b 4f
2:                                 // word end
    cmp x7,0
    beq 3f
    mov x6,0                       // store 0 final
    strb w6,[x5,x7]
    mov x0,x5                      // display word
    bl affichageMess
    ldr x0,qAdrszCarriageReturn
    bl affichageMess
    mov x7,0                       // raz word byte counter
3:
    cmp x8,1                       // end line ?
    bne 4f
    ldr x0,qAdrszMessEndLine
    bl affichageMess
4:
    add x4,x4,1                    // increment read buffer counter
    cmp x4,x2                      // end bytes ?
    blt 1b                         // no -> loop

4:
    /* close imput file */
    mov x0,x9                      // Fd
    mov x8,CLOSE                   // call system CLOSE
    svc 0
    cmp x0,0                       // close error ?
    blt erreur1

    mov x0,0                       // return code OK
    b 100f
erreur:
    ldr x1,qAdrszMessErreur
    bl displayError
    mov x0,1                       // error return code
    b 100f
erreur1:
    ldr x1,qAdrszMessErreur1
    bl displayError
    mov x0,1                      // error return code
    b 100f
erreur2:
    ldr x1,qAdrszMessErreur2
    bl displayError
    mov x0,1                      // error return code
    b 100f

100:                              // end program
    mov x8,EXIT
    svc 0
qAdrszNameFileInput:      .quad szNameFileInput
qAdrszMessErreur:         .quad szMessErreur
qAdrszMessErreur1:        .quad szMessErreur1
qAdrszMessErreur2:        .quad szMessErreur2
qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrszMessEndLine:        .quad szMessEndLine
qAdrsBuffer:              .quad sBuffer
qAdrsBufferWord:          .quad sBufferWord
/******************************************************************/
/*     display error message                                      */
/******************************************************************/
/* x0 contains error code */
/* x1 contains address error message    */
displayError:
    stp x2,lr,[sp,-16]!            // save  registers
    mov x2,x0                      // save error code
    mov x0,x1                      // display message error
    bl affichageMess
    mov x0,x2
    ldr x1,qAdrsZoneConv           // conversion error code
    bl conversion10S               // decimal conversion
    ldr x0,qAdrszMessCodeErr
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at @ character
    bl affichageMess               // display message final
    ldp x2,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrsZoneConv:        .quad sZoneConv
qAdrszMessCodeErr:    .quad szMessCodeErr
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


PROC ReadStream(BYTE stream)
  CHAR ARRAY line(255)

  WHILE Eof(stream)=0
  DO
    InputSD(stream,line)
    PrintE(line)
  OD
RETURN

PROC Main()
  BYTE streamId=[1]

  Close(streamId)
  Open(streamId,"H6:INPUT_PU.ACT",4)
  PrintE("Reading from stream...") PutE()
  ReadStream(streamId)
  Close(streamId)
RETURN


with Ada.Text_Io; use Ada.Text_Io;

procedure Read_Stream is
   Line : String(1..10);
   Length : Natural;
begin
   while not End_Of_File loop
      Get_Line(Line, Length); -- read up to 10 characters at a time
      Put(Line(1..Length));
      -- The current line of input data may be longer than the string receiving the data.
      -- If so, the current input file column number will be greater than 0
      -- and the extra data will be unread until the next iteration.
      -- If not, we have read past an end of line marker and col will be 1
      if Col(Current_Input) = 1 then
         New_Line;
      end if;
   end loop;
end Read_Stream;


void
read_stream(file f)
{
    text s;

    while (f_line(f, s) != -1) {
        # the read line available as -s-
    }
}


main:(
  PROC raise logical file end = (REF FILE f) BOOL: ( except logical file end );
  on logical file end(stand in, raise logical file end);
  DO
    print(read string);
    read(new line);
    print(new line)
  OD;
  except logical file end:
    SKIP
)


begin
    string(80) line;
    % allow the program to continue after reaching end-of-file %
    % without this, end-of-file would cause a run-time error   %
    ENDFILE := EXCEPTION( false, 1, 0, false, "EOF" );
    % read lines until end of file                             %
    read( line );
    while not XCPNOTED(ENDFILE) do begin
        write( line );
        read(  line )
    end
end.


CONST BUFLEN=1024, EOF=-1

PROC consume_input(fh)
  DEF buf[BUFLEN] : STRING, r
  REPEAT
    /* even if the line si longer than BUFLEN,
       ReadStr won't overflow; rather the line is
       "splitted" and the remaining part is read in
       the next ReadStr */
    r := ReadStr(fh, buf)
    IF buf[] OR (r <> EOF)
      -> do something
      WriteF('\s\n',buf)
    ENDIF
  UNTIL r=EOF
ENDPROC

PROC main()
  DEF fh

  fh := Open('basicinputloop.e', OLDFILE)
  IF fh
    consume_input(fh)
    Close(fh)
  ENDIF
ENDPROC


      h ← ⊃ (⎕fio['read_text'] 'corpus/sample1.txt')
      ⍴h
7 49
      ]boxing 8
      h
┌→────────────────────────────────────────────────┐
↓This is some sample text.                        │
│The text itself has multiple lines, and          │
│the text has some words that occur multiple times│
│in the text.                                     │
│                                                 │
│This is the end of the text.                     │
│                                                 │
└─────────────────────────────────────────────────┘


/* ARM assembly Raspberry PI  */
/*  program inputLoop.s   */

/* REMARK 1 : this program use routines in a include file
   see task Include a file language arm assembly
   for the routine affichageMess conversion10
   see at end of this program the instruction include */

/*********************************************/
/*constantes                                */
/********************************************/
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ READ,   3
.equ WRITE,  4
.equ OPEN,   5
.equ CLOSE,  6
.equ CREATE,  8
/*  file */
.equ O_RDONLY,    0x0        @ open for reading only

.equ BUFSIZE,  10000
.equ LINESIZE, 100

/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessErreur:     .asciz "Erreur ouverture fichier input.\n"
szMessErreur1:    .asciz "Erreur fermeture fichier.\n"
szMessErreur2:    .asciz "Erreur lecture fichier.\n"
szCarriageReturn: .asciz "\n"
szMessEndLine:    .asciz "<<<<<< End line.\n"

szNameFileInput:    .asciz "input.txt"

/*******************************************/
/* DONNEES NON INITIALISEES                */
/*******************************************/
.bss
sBuffer:      .skip BUFSIZE
sBufferWord:  .skip LINESIZE
/**********************************************/
/* -- Code section                            */
/**********************************************/
.text
.global main
main:
    /* open file */
    ldr r0,iAdrszNameFileInput      @ file name
    mov r1,#O_RDONLY                @  flags
    mov r2,#0                       @ mode
    mov r7,#OPEN                    @ call system OPEN
    svc #0
    cmp r0,#0                       @ open error ?
    ble erreur
    /* read file  */
    mov r9,r0                       @ save File Descriptor
    ldr r1,iAdrsBuffer              @ buffer address
    mov r2,#BUFSIZE                 @ buffer size
    mov r7, #READ                   @ call system  READ
    svc 0
    cmp r0,#0                       @ read error ?
    ble erreur2
    mov r2,r0                       @ length read characters
    /* buffer analyze   */
    ldr r3,iAdrsBuffer              @ buffer address
    ldr r5,iAdrsBufferWord          @ buffer address
    mov r7,#0                       @ word byte counter
    mov r4,#0                       @ byte counter
1:
    ldrb r6,[r3,r4]                 @ load byte buffer
    cmp r6,#' '                     @ space ?
    moveq r8,#0                     @ yes
    beq 2f
    cmp r6,#0xA                     @ end line ?
    moveq r8,#1
    beq 2f
    cmp r6,#0xD                     @ end line ?
    beq 3f
    strb r6,[r5,r7]                 @ store byte
    add r7,#1                       @ increment word byte counter
    b 4f
2:                                  @ word end
    cmp r7,#0
    beq 3f
    mov r6,#0                       @ store 0 final
    strb r6,[r5,r7]
    mov r0,r5                       @ display word
    bl affichageMess
    ldr r0,iAdrszCarriageReturn
    bl affichageMess
    mov r7,#0                       @ raz word byte counter
3:
    cmp r8,#1                       @ end line ?
    bne 4f
    ldr r0,iAdrszMessEndLine
    bl affichageMess
4:
    add r4,#1                       @ increment read buffer counter
    cmp r4,r2                       @ end bytes ?
    blt 1b                          @ no -> loop

4:
    /* close imput file */
    mov r0,r9                       @ Fd
    mov r7, #CLOSE                  @ call system CLOSE
    svc 0
    cmp r0,#0                       @ close error ?
    blt erreur1

    mov r0,#0     @ return code OK
    b 100f
erreur:
    ldr r1,iAdrszMessErreur
    bl displayError
    mov r0,#1       @ error return code
    b 100f
erreur1:
    ldr r1,iAdrszMessErreur1
    bl displayError
    mov r0,#1       @ error return code
    b 100f
erreur2:
    ldr r1,iAdrszMessErreur2
    bl displayError
    mov r0,#1       @ error return code
    b 100f

100:        @ end program
    mov r7, #EXIT
    svc 0
iAdrszNameFileInput:      .int szNameFileInput
iAdrszMessErreur:         .int szMessErreur
iAdrszMessErreur1:        .int szMessErreur1
iAdrszMessErreur2:        .int szMessErreur2
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrszMessEndLine:        .int szMessEndLine
iAdrsBuffer:              .int sBuffer
iAdrsBufferWord:          .int sBufferWord
/***************************************************/
/*      ROUTINES INCLUDE                           */
/***************************************************/
.include "../affichage.inc"


Loop, Read, Input.txt, Output.txt
{
   FileAppend, %A_LoopReadLine%`n
}


f = freefile
open f, "test.txt"

while not eof(f)
	linea$ = readline(f)
	print linea$	# echo to the console
end while
close f
end


for /f %%i in (file.txt) do if %%i@ neq @ echo %%i


( put$("This is
a three line
text","test.txt",NEW)
& fil$("test.txt",r)
& fil$(,STR," \t\r\n")
& 0:?linenr
&   whl
  ' ( fil$:(?line.?breakchar)
    &   put
      $ ( str
        $ ( "breakchar:"
            ( !breakchar:" "&SP
            | !breakchar:\t&"\\t"
            | !breakchar:\r&"\\r"
            | !breakchar:\n&"\\n"
            | !breakchar:&EOF
            )
            ", word "
            (1+!linenr:?linenr)
            ":"
            !line
            \n
          )
        )
    )
& (fil$(,SET,-1)|out$"file closed")
);


#include <stdlib.h>
#include <stdio.h>

char *get_line(FILE* fp)
{
	int len = 0, got = 0, c;
	char *buf = 0;

	while ((c = fgetc(fp)) != EOF) {
		if (got + 1 >= len) {
			len *= 2;
			if (len < 4) len = 4;
			buf = realloc(buf, len);
		}
		buf[got++] = c;
		if (c == '\n') break;
	}
	if (c == EOF && !got) return 0;

	buf[got++] = '\0';
	return buf;
}

int main()
{
	char *s;
	while ((s = get_line(stdin))) {
		printf("%s",s);
		free(s);
	}
	return 0;
}


using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // For stdin, you could use
        // new StreamReader(Console.OpenStandardInput(), Console.InputEncoding)

        using (var b = new StreamReader("file.txt"))
        {
            string line;
            while ((line = b.ReadLine()) != null)
                Console.WriteLine(line);
        }
    }
}


#include <istream>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>

// word by word
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
  std::string word;
  while (is >> word)
  {
    // send the word to the output iterator
    *dest = word;
  }
}

// line by line:
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
  std::string line;
  while (std::getline(is, line))
  {
    // store the line to the output iterator
    *dest = line;
  }
}

int main()
{
  // 1) sending words from std. in std. out (end with Return)
  read_words(std::cin,
             std::ostream_iterator<std::string>(std::cout, " "));

  // 2) appending lines from std. to vector (end with Ctrl+Z)
  std::vector<std::string> v;
  read_lines(std::cin, std::back_inserter(v));

  return 0;
}


(defn basic-input [fname]
  (line-seq (java.io.BufferedReader. (java.io.FileReader. fname))))


       IDENTIFICATION DIVISION.
       PROGRAM-ID. input-loop.

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT in-stream ASSIGN TO KEYBOARD *> or any other file/stream
               ORGANIZATION LINE SEQUENTIAL
               FILE STATUS in-stream-status.

       DATA DIVISION.
       FILE SECTION.
       FD  in-stream.
       01  stream-line                 PIC X(80).

       WORKING-STORAGE SECTION.
       01  in-stream-status            PIC 99.
           88  end-of-stream           VALUE 10.

       PROCEDURE DIVISION.
           OPEN INPUT in-stream

           PERFORM UNTIL EXIT
               READ in-stream
                   AT END
                       EXIT PERFORM
               END-READ
               DISPLAY stream-line
           END-PERFORM

           CLOSE in-stream
           .
       END PROGRAM input-loop.


(defun basic-input (filename)
    (with-open-file (stream (make-pathname :name filename) :direction :input)
        (loop for line = (read-line stream nil nil)
            while line
            do (format t "~a~%" line))))


void main() {
    import std.stdio;

    immutable fileName = "input_loop1.d";

    foreach (const line; fileName.File.byLine) {
        pragma(msg, typeof(line)); // Prints: const(char[])
        // line is a transient slice, so if you need to
        // retain it for later use, you have to .dup or .idup it.
        line.writeln; // Do something with each line.
    }

    // Keeping the line terminators:
    foreach (const line; fileName.File.byLine(KeepTerminator.yes)) {
        // line is a transient slice.
        line.writeln;
    }

    foreach (const string line; fileName.File.lines) {
        // line is a transient slice.
        line.writeln;
    }
}


program InputLoop;

{$APPTYPE CONSOLE}

uses SysUtils, Classes;

var
  lReader: TStreamReader; // Introduced in Delphi XE
begin
  lReader := TStreamReader.Create('input.txt', TEncoding.Default);
  try
    while lReader.Peek >= 0 do
      Writeln(lReader.ReadLine);
  finally
    lReader.Free;
  end;
end.


while /= :eof dup !read-line!stdin:
	!print( "Read a line: " !decode!utf-8 swap )
drop
!print "End of file."


repeat
  l$ = input
  until error = 1
  print l$
.


note
	description : "{
There are several examples included, including input from a text file,
simple console input and input from standard input explicitly.
See notes in the code for details.

Examples were compile using Eiffel Studio 6.6 with only the default
class libraries.
}"

class APPLICATION

create
	make

feature

	make
		do
			-- These examples show non-console input (a plain text file)
			-- with end-of-input handling.
			read_lines_from_file
			read_words_from_file

			-- These examples use simplified input from 'io', that
			-- handles the details of whether it's stdin or not
			-- They terminate on a line (word) of "q"
			read_lines_from_console_with_termination
			read_words_from_console_with_termination

			-- The next examples show reading stdin explicitly
			-- as if it were a text file.  It expects and end of file
			-- termination and so will loop indefinitely unless reading
			-- from a pipe or your console can send an EOF.
			read_lines_from_stdin
			read_words_from_stdin

			-- These examples use simplified input from 'io', that
			-- handles the details of whether it's stdin or not,
			-- but have no explicit termination
			read_lines_from_console_forever
			read_words_from_console_forever
		end

	--|--------------------------------------------------------------

	read_lines_from_file
			-- Read input from a text file
			-- Echo each line of the file to standard output.
			--
			-- Some language examples omit file open/close operations
			-- but are included here for completeness.  Additional error
			-- checking would be appropriate in production code.
		local
			tf: PLAIN_TEXT_FILE
		do
			print ("Reading lines from a file%N")
			create tf.make ("myfile") -- Create a file object
			tf.open_read -- Open the file in read mode

			-- The actual input loop

			from
			until tf.end_of_file
			loop
				tf.read_line
				print (tf.last_string + "%N")
			end

			tf.close -- Close the file
		end

	--|--------------------------------------------------------------

	read_words_from_file
			-- Read input from a text file
			-- Echo each word of the file to standard output on a
			-- separate line.
			--
			-- Some language examples omit file open/close operations
			-- but are included here for completeness.  Additional error
			-- checking would be appropriate in production code.
		local
			tf: PLAIN_TEXT_FILE
		do
			print ("Reading words from a file%N")
			create tf.make ("myfile") -- Create a file object
			tf.open_read -- Open the file in read mode

			-- The actual input loop

			from
			until tf.end_of_file
			loop
				-- This instruction is the only difference between this
				-- example and the read_lines_from_file example
				tf.read_word
				print (tf.last_string + "%N")
			end

			tf.close -- Close the file
		end

	--|--------------------------------------------------------------

	read_lines_from_console_with_termination
			-- Read lines from console and echo them back to output
			-- until the line contains only the termination key 'q'
			--
			-- 'io' is acquired through inheritance from class ANY,
			-- the top of all inheritance hierarchies.
		local
			the_cows_come_home: BOOLEAN
		do
			print ("Reading lines from console%N")
			from
			until the_cows_come_home
			loop
				io.read_line
				if io.last_string ~ "q" then
					the_cows_come_home := True
					print ("Mooooo!%N")
				else
					print (io.last_string)
					io.new_line
				end
			end
		end

	--|--------------------------------------------------------------

	read_words_from_console_with_termination
			-- Read words from console and echo them back to output, one
			-- word per line, until the line contains only the
			-- termination key 'q'
			--
			-- 'io' is acquired through inheritance from class ANY,
			-- the top of all inheritance hierarchies.
		local
			the_cows_come_home: BOOLEAN
		do
			print ("Reading words from console%N")
			from
			until the_cows_come_home
			loop
				io.read_word
				if io.last_string ~ "q" then
					the_cows_come_home := True
					print ("Mooooo!%N")
				else
					print (io.last_string)
					io.new_line
				end
			end
		end

	--|--------------------------------------------------------------

	read_lines_from_console_forever
			-- Read lines from console and echo them back to output
			-- until the program is terminated externally
			--
			-- 'io' is acquired through inheritance from class ANY,
			-- the top of all inheritance hierarchies.
		do
			print ("Reading lines from console (no termination)%N")
			from
			until False
			loop
				io.read_line
				print (io.last_string + "%N")
			end
		end

	--|--------------------------------------------------------------

	read_words_from_console_forever
			-- Read words from console and echo them back to output, one
			-- word per line until the program is terminated externally
			--
			-- 'io' is acquired through inheritance from class ANY,
			-- the top of all inheritance hierarchies.
		do
			print ("Reading words from console (no termination)%N")
			from
			until False
			loop
				io.read_word
				print (io.last_string + "%N")
			end
		end

	--|--------------------------------------------------------------

	read_lines_from_stdin
			-- Read input from a stream on standard input
			-- Echo each line of the file to standard output.
			-- Note that we treat standard input as if it were a plain
			-- text file
		local
			tf: PLAIN_TEXT_FILE
		do
			print ("Reading lines from stdin (EOF termination)%N")
			tf := io.input

			from
			until tf.end_of_file
			loop
				tf.read_line
				print (tf.last_string + "%N")
			end
		end

	--|--------------------------------------------------------------

	read_words_from_stdin
			-- Read input from a stream on standard input
			-- Echo each word of the file to standard output on a new
			-- line
			-- Note that we treat standard input as if it were a plain
			-- text file
		local
			tf: PLAIN_TEXT_FILE
		do
			print ("Reading words from stdin (EOF termination)%N")
			tf := io.input

			from
			until tf.end_of_file
			loop
				tf.read_line
				print (tf.last_string + "%N")
			end
		end

end


import system'routines;
import system'io;
import extensions'routines;

public program()
{
    ReaderEnumerator.new(File.assign:"file.txt").forEach(printingLn)
}


defmodule RC do
  def input_loop(stream) do
    case IO.read(stream, :line) do
      :eof -> :ok
      data -> IO.write data
              input_loop(stream)
    end
  end
end

path = hd(System.argv)
File.open!(path, [:read], fn stream -> RC.input_loop(stream) end)


% Implemented by Arjun Sunel
-module(read_files).
-export([main/0]).

main() ->
	Read = fun (Filename) -> {ok, Data} = file:read_file(Filename), Data end,
	Lines = string:tokens(binary_to_list(Read("read_files.erl")), "\n"),
	lists:foreach(fun (Y) -> io:format("~s~n", [Y]) end, lists:zipwith(fun(X,_)->X end, Lines, lists:seq(1, length(Lines)))).


     LOOP
       INPUT(LINE,A$)
       PRINT(A$)
       EXIT IF <condition> ! condition to be implemented to
                           ! to avoid and endless loop
     END LOOP


procedure process_line_by_line(integer fn)
    object line
    while 1 do
        line = gets(fn)
        if atom(line) then
            exit
        end if
        -- process the line
    end while
end procedure


let lines_of_file file =
  seq { use stream = System.IO.File.OpenRead file
        use reader = new System.IO.StreamReader(stream)
        while not reader.EndOfStream do
          yield reader.ReadLine() }


"file.txt" utf8 [ [ process-line ] each-line ] with-file-reader


class Main
{
  public static Void main ()
  {
    // example of reading by line
    str := "first\nsecond\nthird\nword"
    inputStream := str.in

    inputStream.eachLine |Str line|
    {
      echo ("Line is: $line")
    }

    // example of reading by word
    str = "first second third word"
    inputStream = str.in

    word := inputStream.readStrToken // reads up to but excluding next space
    while (word != null)
    {
      echo ("Word: $word")
      inputStream.readChar // skip over the preceding space!
      word = inputStream.readStrToken
    }
  }
}


4096 constant max-line
: read-lines
  begin  stdin pad max-line read-line throw
  while  pad swap   \ addr len is the line of data, excluding newline
         2drop
  repeat ;


program BasicInputLoop

  implicit none

  integer, parameter        :: in = 50, &
                               linelen = 1000
  integer                   :: ecode
  character(len=linelen)    :: l

  open(in, file="afile.txt", action="read", status="old", iostat=ecode)
  if ( ecode == 0 ) then
     do
        read(in, fmt="(A)", iostat=ecode) l
        if ( ecode /= 0 ) exit
        write(*,*) trim(l)
     end do
     close(in)
  end if

end program BasicInputLoop


' FB 1.05.0 Win64

Dim line_ As String  ' line is a keyword
Open "input.txt" For Input As #1

While Not Eof(1)
  Input #1, line_
  Print line_  ' echo to the console
Wend

Close #1
Print
Print "Press any key to quit"
Sleep


while (line = readStdin[]) != undef
   println[line]


include "NSLog.incl"

local fn ReadTextFile
  CFURLRef    url
  CFStringRef string

  url = openpanel 1, @"Select text file..."
  if ( url )
    string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL )
    if ( string )
      NSLog(@"%@",string)
    end if
  else
    // user cancelled
  end if
end fn

fn ReadTextFile

HandleEvents


package main

import (
	"bufio"
	"io"
	"log"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	for {
		s, err := in.ReadString('\n')
		if err != nil {
			// io.EOF is expected, anything else
			// should be handled/reported
			if err != io.EOF {
				log.Fatal(err)
			}
			break
		}
		// Do something with the line of text
		// in string variable s.
		_ = s
	}
}


def lineMap = [:]
System.in.eachLine { line, i ->
    lineMap[i] = line
}
lineMap.each { println it }


import System.IO

readLines :: Handle -> IO [String]
readLines h = do
  s <- hGetContents h
  return $ lines s

readWords :: Handle -> IO [String]
readWords h = do
  s <- hGetContents h
  return $ words s


CHARACTER name='myfile.txt', string*1000

   OPEN(FIle=name, OLD, LENgth=bytes, IOStat=errorcode, ERror=9)

   DO line = 1, bytes  ! loop terminates with end-of-file error at the latest
      READ(FIle=name, IOStat=errorcode, ERror=9) string
      WRITE(StatusBar) string
   ENDDO

 9 WRITE(Messagebox, Name) line, errorcode


software {
	loop {
		read()
		errors {
			exit
		}
	}
}


link str2toks
# call either words or lines depending on what you want to do.
procedure main()
   words()
end

procedure lines()
   while write(read())
end

procedure words()
   local line
   while line := read() do line ? every write(str2toks())
end


#!/Applications/j602/bin/jconsole
NB. read input until EOF
((1!:1) 3)(1!:2) 4
exit ''


import java.io.InputStream;
import java.util.Scanner;

public class InputLoop {
    public static void main(String args[]) {
        // To read from stdin:
        InputStream source = System.in;

        /*
        Or, to read from a file:
        InputStream source = new FileInputStream(filename);

        Or, to read from a network stream:
        InputStream source = socket.getInputStream();
        */

        Scanner in = new Scanner(source);
        while(in.hasNext()){
            String input = in.next(); // Use in.nextLine() for line-by-line reading

            // Process the input here. For example, you could print it out:
            System.out.println(input);
        }
    }
}


$ js -e 'while (line = readline()) { do_something_with(line); }' < inputfile


/* Input loop in Jsish */

var line;
var cs = 0, ls = 0;

while (line = console.input()) { cs += line.length; ls += 1; }

printf("%d lines, %d characters\n", ls, cs);


stream = IOBuffer("1\n2\n3\n4\n\n6")

while !eof(stream)
    line = readline(stream)
    println(line)
end


// version 1.1

import java.util.*

fun main(args: Array<String>) {
    println("Keep entering text or the word 'quit' to end the program:")
    val sc = Scanner(System.`in`)
    val words = mutableListOf<String>()
    while (true) {
        val input: String = sc.next()
        if (input.trim().toLowerCase() == "quit") {
            if (words.size > 0) println("\nYou entered the following words:\n${words.joinToString("\n")}")
            return
        }
        words.add(input)
    }
}


: read-lines do read . "\n" . eof if break then loop ;
: ==>contents
    '< swap open 'fh set fh fin read-lines fh close ;

'file.txt ==>contents


local(
	myfile		= file('//path/to/file.txt'),
	textresult	= array
)

#myfile -> foreachline => {
	#textresult -> insert(#1)
}

#textresult -> join('<br />')


filedialog "Open","*.txt",file$
if file$="" then end
open file$ for input as #f
while not(eof(#f))
    line input #f, t$
    print t$
wend
close #f
end


#
# canread test (note that canread is not available in LIL/FPLIL itself
# but provided by the command line interfaces in main.c/lil.pas)
#
# You can either call this and enter lines directly (use Ctrl+Z/Ctrl+D
# to finish) or a redirect (e.g. lil canread.lil < somefile.txt)
#
# Normally this is how you are supposed to read multiple lines from
# the standard input using the lil executable.  For an alternative way
# that uses error catching via try see the eoferror.lil script.
#

set count 0
while {[canread]} {
    readline
    inc count
}
print $count lines


string sNOTECARD = "Input_Loop_Data_Source.txt";
default {
	integer iNotecardLine = 0;
	state_entry() {
		llOwnerSay("Reading '"+sNOTECARD+"'");
		llGetNotecardLine(sNOTECARD, iNotecardLine);
	}
	dataserver(key kRequestId, string sData) {
		if(sData==EOF) {
			llOwnerSay("EOF");
		} else {
			llOwnerSay((string)iNotecardLine+": "+sData);
			llGetNotecardLine(sNOTECARD, ++iNotecardLine);
		}
	}
}


lines = {}
str = io.read()
while str do
    table.insert(lines,str)
    str = io.read()
end


Document A$={1st Line
      2nd line
      3rd line
      }
Save.Doc A$, "test.txt", 0   ' 0 for utf16-le
\\ we use Wide for utf16-le \\ without it we open using ANSI
Open "test.txt" For Wide Input Exclusive as #N
      While Not Eof(#N) {
            Line Input #N, ThisLine$
            Print ThisLine$
      }
Close #N
Clear A$
Load.Doc A$, "test.txt"
\\ print proportional text, all lines
Report A$
\\ Print one line, non proportional
\\ using paragraphs
For i=0 to Doc.par(A$)-1
      Print Paragraph$(A$, i)
Next i
\\ List of current variables (in any scope, public only)
List


readinput:=proc(filename)
local line,file;
file:="";
line:=readline(filename);
while line<>0 do
line:=readline(filename);
file:=cat(file,line);
end do;
end proc;


        TITLE Input Loop

COMMENT !
       Input-loop example, PDP-10 assembly language, kjx 2022.
           Assembler: MACRO-10   Operating system: TOPS-20

   This program opens the file "test.txt" and prints it's contents.

   Note that the PDP-10 is a word-addressable machine with 36bit words,
   and text-files use 7bit ASCII. That means one word fits 5 characters
   and the buffer length of 20 (octal!) makes room for 80 (decimal) char-
   acters.

   The system-call used, SIN%, can also read until a specific character
   (like CR) is seen, so reading one-line-at-a-time is also possible with
   minimal changes.
!

        SEARCH MONSYM,MACSYM
        .REQUIRE SYS:MACREL

        STDAC.                          ;Define standard register names.

        ;;
        ;; Buffers and data:
        ;;

        PDLLEN==20
PDL:    BLOCK PDLLEN                    ;Callstack (for ERCAL later).

        MAXBUF==20                      ;Use 20 36bit words for buffer.
        MAXCHR==MAXBUF*5                ;One 36bit words fits 5 7bit bytes.
IN.BUF: BLOCK MAXBUF                    ;Buffer for lines read from file.

IN.JFN: BLOCK 1                         ;Space for file-descriptor (JFN)

        ;;
        ;; Execution begins here:
        ;;

GO::    RESET%                          ;Initialize process.
        MOVE  P,[IOWD PDLLEN,PDL]       ;Initialize stack.

        ;;
        ;; To open a file, we first have to get a file-handle (JFN):
        ;;

        MOVX  T1,GJ%OLD+GJ%SHT          ;Flags go into T1:
                                        ; GJ%OLD = File already exists.
                                        ; GJ%SHT = Short system call.
        HRROI T2,[ASCIZ /test.txt/]     ;File name goes to T2.
        GTJFN%                          ;Get a JFN for this file.
          ERJMPS ERROR                  ;  On error jump to ERROR.
        MOVEM T1,IN.JFN                 ;Save the JFN.

        ;;
        ;; Now we can open the file:
        ;;

        HRRZ  T1,IN.JFN                 ;Right half-word of JFN into T1 +
                                        ;zero out left half to get rid of
					;flags returned by GTJFN%.
        MOVX  T2,FLD(7,OF%BSZ)+OF%RD    ;7bit characters, read-only.
        OPENF%                          ;Open file.
          ERJMPS ERROR                  ;  On error jump to ERROR.

        ;;
        ;; Now we're reading MAXCHR 7bit bytes from that file
        ;; into IN.BUF and print that. If we'll see EOF, Q1 is
        ;; set to 1, and the loop is exited.
        ;;

        SETZ  Q1                        ;Clear Q1 (we use that as an EOF marker)
        DO.
          MOVE  T1,IN.JFN               ;Read from IN.JFN (opened file)
          HRROI T2,IN.BUF               ;and write into IN.BUF.
          MOVNI T3,MAXCHR               ;Read maximum of MAXCHR characters.
          SIN%                          ;Read string from file.
            ERCAL [ MOVE  T1,IN.JFN     ;  Error occured...
                    GTSTS%              ;  Get file status.
                    TXNN  T2,GS%EOF     ;  End-of-file reached?
                      JRST ERROR        ;    No: Something else happened...
                    MOVEI Q1,1          ;  Yes: Set Q1 to 1.
                    RET ]               ;  Continue.
          MOVEI T1,.PRIOU               ;Write to standard output.
          HRROI T2,IN.BUF               ;Buffer to write.
          ADDI  T3,MAXCHR               ;Substract chars read from
          MOVN  T3,T3                   ;maximum buffer length.
          SOUT%                         ;Print string.
          CAIN  Q1,1                    ;Is Q1 == 1?
            JRST ENDPRG                 ;  Yes: EOF was found above.
          LOOP.                         ;Q1 is 0, so no EOF, continue.
        ENDDO.

        ;;
        ;; ENDPRG: Close file and halt.
        ;;

ENDPRG: HRRZ  T1,IN.JFN                 ;Put JFN into T1.
        CLOSF%                          ;Close that file.
          ERJMPS ERROR                  ;  Go print error-msgs on error.
        HALTF%                          ;Halt program.
        JRST  GO                        ;Allow for 'continue'-command.

        ;;
        ;; ERROR: Print standardized error-message and halt.
        ;;

ERROR:  MOVEI T1,.PRIOU                 ;Print error on terminal (.PRIOU)
        MOVE  T2,[.FHSLF,,-1]           ;Own process, most recent error.
        SETZ  T3,                       ;No limit on size of message.
        ERSTR%                          ;Print that error message.
          JFCL                          ;  Ignore errors from ERSTR.
          JFCL                          ;  dito.
        HALTF%                          ;Stop program.
        JRST GO                         ;Allow for continuation.

        END GO


stream = OpenRead["file.txt"];
While[a != EndOfFile, Read[stream, Word]];
Close[stream]


fn ReadAFile FileName =
(
	local in_file = openfile FileName
	while not eof in_file do
	(
		--Do stuff in here--
		print (readline in_file)
	)
	close in_file
)


:- module input_loop.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    io.stdin_stream(Stdin, !IO),
    io.stdout_stream(Stdout, !IO),
    read_and_print_lines(Stdin, Stdout, !IO).

:- pred read_and_print_lines(io.text_input_stream::in,
    io.text_output_stream::in, io::di, io::uo) is det.

read_and_print_lines(InFile, OutFile, !IO) :-
    io.read_line_as_string(InFile, Result, !IO),
    (
        Result = ok(Line),
        io.write_string(OutFile, Line, !IO),
        read_and_print_lines(InFile, OutFile, !IO)
    ;
        Result = eof
    ;
        Result = error(IOError),
        Msg = io.error_message(IOError),
        io.stderr_stream(Stderr, !IO),
        io.write_string(Stderr, Msg, !IO),
        io.set_exit_status(1, !IO)
    ).


var %n = 1
while (%n <= $lines(input.txt)) {
  write output.txt $read(input.txt,%n)
  inc %n
}