Count in octal: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added D version)
(Link task to integer sequence. Tweak AWK. Add bc. Add UNIX Shell alternative.)
Line 2: Line 2:


The task is to produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number. Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.
The task is to produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number. Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.

* [[Integer sequence]] is a similar task without the use of octal numbers.


=={{header|Ada}}==
=={{header|Ada}}==
Line 32: Line 34:
8#17#
8#17#
8#20#</pre>
8#20#</pre>

=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
Line 64: Line 67:
8r00000000021
8r00000000021
</pre>
</pre>

=={{header|AWK}}==
=={{header|AWK}}==
The awk extraction and reporting language uses the underlying C library to provide support for the printf command. This enables us to use that function to output the counter value as octal:
The awk extraction and reporting language uses the underlying C library to provide support for the printf command. This enables us to use that function to output the counter value as octal:


<lang awk>BEGIN {
<lang awk>BEGIN {
for (l = 1; l < 2147483647; l++) {
for (l = 0; l <= 2147483647; l++) {
printf("%o\n", l);
printf("%o\n", l);
}
}
}</lang>
}</lang>

=={{header|bc}}==
<lang bc>obase = 8 /* Output base is octal. */
for (num = 0; 1; num++) num /* Loop forever, printing counter. */</lang>

The loop never stops at a maximum value, because bc uses [[arbitrary-precision integers (included)|arbitrary-precision integers]].


=={{header|C}}==
=={{header|C}}==
Line 360: Line 370:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==

We use the bc calculator to increment our octal counter:
We use the bc calculator to increment our octal counter:


Line 368: Line 377:
echo $num
echo $num
num=`echo "obase=8;ibase=8;$num+1"|bc`
num=`echo "obase=8;ibase=8;$num+1"|bc`
done</lang>

----
If the shell has <code>$(( ... ))</code> arithmetic, then we can increment a decimal counter and use <code>printf(1)</code> to print it in octal. Our loop stops when the counter overflows to negative.

{{works with|pdksh|5.2.14}}

<lang sh>num=0
while test 0 -le $num; do
printf '%o\n' $num
num=$((num + 1))
done</lang>
done</lang>



Revision as of 21:38, 21 July 2011

Task
Count in octal
You are encouraged to solve this task according to the task description, using any language you may know.

The task is to produce a sequential count in octal, starting at zero, and using an increment of a one for each consecutive number. Each number should appear on a single line, and the program should count until terminated, or until the maximum value of the numeric type in use is reached.

Ada

<lang Ada>with Ada.Text_IO;

procedure Octal is

  package IIO is new Ada.Text_IO.Integer_IO(Integer);

begin

  for I in 0 .. Integer'Last loop
     IIO.Put(I, Base => 8);
     Ada.Text_IO.New_Line;
  end loop;

end Octal;</lang> First few lines of Output:

       8#0#
       8#1#
       8#2#
       8#3#
       8#4#
       8#5#
       8#6#
       8#7#
      8#10#
      8#11#
      8#12#
      8#13#
      8#14#
      8#15#
      8#16#
      8#17#
      8#20#

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny.

<lang algol68>#!/usr/local/bin/a68g --script #

INT oct width = (bits width-1) OVER 3 + 1; main: (

 FOR i TO 17 # max int # DO
   printf(($"8r"8r n(oct width)dl$, BIN i))
 OD

)</lang> Output:

8r00000000001
8r00000000002
8r00000000003
8r00000000004
8r00000000005
8r00000000006
8r00000000007
8r00000000010
8r00000000011
8r00000000012
8r00000000013
8r00000000014
8r00000000015
8r00000000016
8r00000000017
8r00000000020
8r00000000021

AWK

The awk extraction and reporting language uses the underlying C library to provide support for the printf command. This enables us to use that function to output the counter value as octal:

<lang awk>BEGIN {

 for (l = 0; l <= 2147483647; l++) {
   printf("%o\n", l);
 }

}</lang>

bc

<lang bc>obase = 8 /* Output base is octal. */ for (num = 0; 1; num++) num /* Loop forever, printing counter. */</lang>

The loop never stops at a maximum value, because bc uses arbitrary-precision integers.

C

<lang C>#include <stdio.h>

int main() {

       unsigned int i = 0;
       do { printf("%o\n", i++); } while(i);
       return 0;

}</lang>

C#

<lang csharp>using System;

class Program {

   static void Main()
   {
       var number = 0;
       do
       {
           Console.WriteLine(Convert.ToString(number, 8));
       } while (++number > 0);
   }

}</lang>

C++

This prevents an infinite loop by counting until the counter overflows and produces a 0 again. This could also be done with a for or while loop, but you'd have to print 0 (or the last number) outside the loop.

<lang cpp>#include <iostream>

  1. include <iomanip>

using namespace std;

int main() {

 unsigned i = 0;
 do
 {
   cout << setbase(8) << i << endl;
   ++i;
 } while(i != 0);

}</lang>

D

<lang d>import std.stdio;

void main() {

   ubyte i;
   do writefln("%o", i++);
   while(i);

}</lang>

Euphoria

<lang euphoria>integer i i = 0 while 1 do

   printf(1,"%o\n",i)
   i += 1

end while</lang>

Output:

...
6326
6327
6330
6331
6332
6333
6334
6335
6336
6337

Fortran

Works with: Fortran version 95 and later

<lang fortran>program Octal

 implicit none
 
 integer, parameter :: i64 = selected_int_kind(18)
 integer(i64) :: n = 0
 

! Will stop when n overflows from ! 9223372036854775807 to -92233720368547758078 (1000000000000000000000 octal)

 do while(n >= 0)
   write(*, "(o0)") n
   n = n + 1
 end do

end program</lang>

Go

<lang go>package main

import (

   "fmt"
   "math"

)

func main() {

   for i := int8(0); ; i++ {
       fmt.Printf("%o\n", i)
       if i == math.MaxInt8 {
           break
       }
   }

}</lang> Output:

0
1
2
3
4
5
6
7
10
11
12
...
175
176
177

Note that to use a different integer type, code must be changed in two places. Go has no way to query a type for its maximum value. Example: <lang go>func main() {

   for i := uint16(0); ; i++ {  // type specified here
       fmt.Printf("%o\n", i)
       if i == math.MaxUint16 { // maximum value for type specified here
           break
       }
   }

}</lang> Output:

...
177775
177776
177777

Note also that if floating point types are used for the counter, loss of precision will prevent the program from from ever reaching the maximum value. If you stretch interpretation of the task wording "maximum value" to mean "maximum value of contiguous integers" then the following will work: <lang go>import "fmt"

func main() {

   for i := 0.; ; {
       fmt.Printf("%o\n", int64(i))
       /* uncomment to produce example output
       if i == 3 {
           i = float64(1<<53 - 4) // skip to near the end
           fmt.Println("...")
       } */
       next := i + 1
       if next == i {
           break
       }
       i = next
   }

}</lang> Output, with skip uncommented:

0
1
2
3
...
377777777777777775
377777777777777776
377777777777777777
400000000000000000

Big integers have no maximum value, but the Go runtime will panic when memory allocation fails. The deferred recover here allows the program to terminate silently should the program run until this happens. <lang go>import (

   "big"
   "fmt"

)

func main() {

   defer func() {
       recover()
   }()
   one := big.NewInt(1)
   for i := big.NewInt(0); ; i.Add(i, one) {
       fmt.Printf("%o\n", i)
   }

}</lang> Output:

0
1
2
3
4
5
6
7
10
11
12
13
14
...

Icon and Unicon

<lang unicon>link convert # To get exbase10 method

procedure main()

   limit := 8r37777777777
   every write(exbase10(seq(0)\limit, 8))

end</lang>

J

Solution: <lang J> disp=.[:smoutput [:,@:(":"0) 8&#.^:_1

  (>:[disp)^:_ ]0</lang>

Java

<lang java>public class Count{

   public static void main(String[] args){
       for(int i = 0;i <= Integer.MAX_VALUE;i++){
           System.out.println(Integer.toOctalString(i)); //optionally use "Integer.toString(i, 8)"
       }
   }

}</lang>

Lua

<lang lua>for l=1,2147483647 do

 print(string.format("%o",l))

end</lang>

Modula-2

<lang modula2>MODULE octal;

IMPORT InOut;

VAR num  : CARDINAL;

BEGIN

 num := 0;
 REPEAT
   InOut.WriteOct (num, 12);           InOut.WriteLn;
   INC (num)
 UNTIL num = 0

END octal.</lang>

PARI/GP

Both versions will count essentially forever; the universe will succumb to proton decay long before the counter rolls over even in the 32-bit version.

Manual: <lang parigp>oct(n)=n=binary(n);if(#n%3,n=concat([[0,0],[0]][#n%3],n));forstep(i=1,#n,3,print1(4*n[i]+2*n[i+1]+n[i+2]));print; n=0;while(1,oct(n);n++)</lang>

Automatic:

Works with: PARI/GP version 2.4.3 and above

<lang parigp>n=0;while(1,printf("%o\n",n);n++)</lang>

Perl

Since task says "system register", I take it to mean "no larger than machine native integer limit": <lang perl>use POSIX; printf "%o\n", $_ for (0 .. POSIX::UINT_MAX);</lang> Otherwise: <lang perl>use bigint; my $i = 0; printf "%o\n", $i++ while 1</lang>

Perl 6

<lang perl6>say .fmt: '%o' for 0 .. *;</lang>

PicoLisp

<lang PicoLisp>(for (N 0 T (inc N))

  (prinl (oct N)) )</lang>

Python

<lang Python>import sys for n in xrange(sys.maxint):

   print oct(n)</lang>

Retro

Integers in Retro are signed.

<lang Retro>octal 17777777777 [ putn cr ] iter</lang>

Tcl

<lang tcl>package require Tcl 8.5; # arbitrary precision integers; we can count until we run out of memory! while 1 {

   puts [format "%llo" [incr counter]]

}</lang>

UNIX Shell

We use the bc calculator to increment our octal counter:

<lang sh>#!/bin/sh num=0 while true; do

 echo $num
 num=`echo "obase=8;ibase=8;$num+1"|bc`

done</lang>


If the shell has $(( ... )) arithmetic, then we can increment a decimal counter and use printf(1) to print it in octal. Our loop stops when the counter overflows to negative.

Works with: pdksh version 5.2.14

<lang sh>num=0 while test 0 -le $num; do

 printf '%o\n' $num
 num=$((num + 1))

done</lang>