WeixiangYan/CodeTransOcean huggingface dataset:
Task: Test integerness








VB: #define isInteger(x)  iif(Int(val(x)) = val(x), 1, 0)

Dim As String test(1 To 8) = {"25.000000", "24.999999", "25.000100", "-2.1e120", "-5e-2", "NaN", "Inf", "-0.05"}

For i As Integer = 1 To Ubound(test)
    Dim As String s = test(i)
    
    Print s,
    If isInteger(s) then Print "is integer" Else Print "is not integer"
Next i

Sleep



Fortran:       MODULE ZERMELO	
       CONTAINS
        LOGICAL FUNCTION ISINTEGRAL(X)	
         REAL*8 X	
         INTEGER*8 N	
          IF (ISNAN(X)) THEN	
            ISINTEGRAL = .FALSE.	
          ELSE			
            N = KIDINT(X)		
            ISINTEGRAL = N .EQ. X	
          END IF		
        END FUNCTION ISINTEGRAL	

        LOGICAL FUNCTION ISINTEGRALZ(Z)	
         DOUBLE COMPLEX Z	
          ISINTEGRALZ = ISINTEGRAL(DBLE(Z)) .AND. ISINTEGRAL(DIMAG(Z))	
        END FUNCTION ISINTEGRALZ
      END MODULE ZERMELO	

      PROGRAM TEST
      USE ZERMELO
      DOUBLE COMPLEX Z

      WRITE (6,*) "See if some numbers are integral..."
      WRITE (6,*) ISINTEGRAL(666D0),666D0
      Z = DCMPLX(-3D0,4*ATAN(1D0))
      WRITE (6,*) ISINTEGRALZ(Z),Z
      END
Task: Type detection








VB: 
 


#macro typeDetector(arg)
    #if TypeOf(foo) = TypeOf(Byte)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(Short)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(Integer)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(LongInt)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(UByte)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(UShort)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(UInteger)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(ULongInt)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(Single)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(Double)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(integer ptr)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(byte ptr)
      Print arg; " -> It
    #elseif TypeOf(foo) = TypeOf(String)
      Print arg; " -> It
    #endif
#endmacro




Var foo = "Rosetta Code"     

typeDetector (foo)
Sleep



Fortran: program input_type_detection_demo
  implicit none

  type text_block_t
     character(len = 10000), allocatable :: lines(:)
  end type text_block_t

  type(text_block_t) :: text_block
  integer :: i

  call print_text ('Print me.')

  allocate (text_block%lines(1:10))
  do i = 1, 10
     write (text_block%lines(i), '("i = ", I0)') i
  end do
  call print_text (text_block)

  open (100, file = 'type_detection-fortran.f90', action = 'read')
  call print_text (100)
  close (100)

contains

  subroutine print_text (source)
    class(*), intent(in) :: source

    select type (source)

    type is (character(len = *))
       
       write (*, '(A)') source

    class is (text_block_t)
       
       block
         integer :: i
         do i = lbound (source%lines, 1), ubound (source%lines, 1)
            write (*, '(A)') trim (source%lines(i))
         end do
       end block

    type is (integer)
       
       block
         character(len = 10000) :: line_buffer
         integer :: stat
         read (source, '(A)', iostat = stat) line_buffer
         do while (stat == 0)
            write (*, '(A)') trim (line_buffer)
            read (source, '(A)', iostat = stat) line_buffer
         end do
       end block

    class default
       
       error stop

    end select
  end subroutine print_text

end program input_type_detection_demo
Task: Arithmetic-geometric mean_Calculate Pi








VB: Dim As Short digits = 500
Dim As Double an = 1
Dim As Double bn = Sqr(0.5)
Dim As Double tn = 0.5^2
Dim As Double pn = 1
Dim As Double prevAn

While pn <= digits
    prevAn = an
    an = (bn + an) / 2
    bn = Sqr(bn * prevAn)
    prevAn -= an
    tn -= (pn * prevAn^2)
    pn *= 2
Wend
Dim As Double pi = ((an + bn)^2) / (tn * 4)
Print pi

Sleep



Fortran: program CalcPi
    
    use iso_fortran_env, only: rf => real128
    implicit none
    real(rf) :: a,g,s,old_pi,new_pi
    real(rf) :: a1,g1,s1
    integer :: k,k1,i

    old_pi = 0.0_rf;
    a = 1.0_rf; g = 1.0_rf/sqrt(2.0_rf); s = 0.0_rf; k = 0

    do i=1,100
        call approx_pi_step(a,g,s,k,a1,g1,s1,k1)
        new_pi = 4.0_rf * (a1**2.0_rf) / (1.0_rf - s1)
        if (abs(new_pi - old_pi).lt.(2.0_rf*epsilon(new_pi))) then
            
            
            exit
        end if
        write(*,*) 'Iteration:',k1,' Diff:',abs(new_pi - old_pi),' Pi:',new_pi
        old_pi = new_pi
        a = a1; g = g1; s = s1; k = k1
    end do

    contains

    subroutine approx_pi_step(x,y,z,n,a,g,s,k)
        real(rf), intent(in) :: x,y,z
        integer, intent(in) :: n
        real(rf), intent(out) :: a,g,s
        integer, intent(out) :: k

        a = 0.5_rf*(x+y)
        g = sqrt(x*y)
        k = n + 1
        s = z + (2.0_rf)**(real(k)+1.0_rf) * (a**(2.0_rf) - g**(2.0_rf))
    end subroutine
end program CalcPi
Task: Statistics_Normal distribution








VB: Public Sub standard_normal()
    Dim s() As Variant, bins(71) As Single
    ReDim s(20000)
    For i = 1 To 20000
        s(i) = WorksheetFunction.Norm_S_Inv(Rnd())
    Next i
    For i = -35 To 35
        bins(i + 36) = i / 10
    Next i
    Debug.Print "sample size"; UBound(s), "mean"; mean(s), "standard deviation"; standard_deviation(s)
            t = WorksheetFunction.Frequency(s, bins)
    For i = -35 To 35
        Debug.Print Format((i - 1) / 10, "0.00");
        Debug.Print "-"; Format(i / 10, "0.00"),
        Debug.Print String$(t(i + 36, 1) / 10, "X");
        Debug.Print
    Next i
End Sub



Fortran: program Normal_Distribution
  implicit none

  integer, parameter :: i64 = selected_int_kind(18)
  integer, parameter :: r64 = selected_real_kind(15)
  integer(i64), parameter :: samples = 1000000_i64
  real(r64) :: mean, stddev
  real(r64) :: sumn = 0, sumnsq = 0
  integer(i64) :: n = 0 
  integer(i64) :: bin(-50:50) = 0
  integer :: i, ind
  real(r64) :: ur1, ur2, nr1, nr2, s
  
  n = 0
  do while(n <= samples)
    call random_number(ur1)
    call random_number(ur2)
    ur1 = ur1 * 2.0 - 1.0
    ur2 = ur2 * 2.0 - 1.0
    
    s = ur1*ur1 + ur2*ur2  
    if(s >= 1.0_r64) cycle
      
    nr1 = ur1 * sqrt(-2.0*log(s)/s)
    ind = floor(5.0*nr1)
    bin(ind) = bin(ind) + 1_i64
    sumn = sumn + nr1
    sumnsq = sumnsq + nr1*nr1
    
    nr2 = ur2 * sqrt(-2.0*log(s)/s)
    ind = floor(5.0*nr2)
    bin(ind) = bin(ind) + 1_i64
    sumn = sumn + nr2
    sumnsq = sumnsq + nr2*nr2
    n = n + 2_i64
  end do
 
  mean = sumn / n
  stddev = sqrt(sumnsq/n - mean*mean)
  
  write(*, "(a, i0)") "sample size = ", samples
  write(*, "(a, f17.15)") "Mean :   ", mean,
  write(*, "(a, f17.15)") "Stddev : ", stddev
  
  do i = -15, 15 
    write(*, "(f4.1, a, a)") real(i)/5.0, ": ", repeat("=", int(bin(i)*500/samples))
  end do
       
end program
Task: Singly-linked list_Element removal








VB:     Module Module1

      Public Class ListEntry
        Public value As String
        Public [next] As ListEntry
      End Class

      Public Head As ListEntry

      
      
      
      
      Sub RemoveListEntryTasteless(entry As ListEntry)

        Dim prev As ListEntry = Nothing
        Dim walk = Head

        
        While walk IsNot entry
          prev = walk
          walk = walk.next
        End While

        
        If prev Is Nothing Then
          Head = entry.next
        Else
          prev.next = entry.next
        End If
      End Sub

      
      
      
      
      Sub RemoveListEntryTastefull(entry As ListEntry)

        Dim indirect = New ListEntry
        indirect.next = Head

        
        
        While indirect.next IsNot entry
          indirect = indirect.next
        End While

        
        indirect.next = entry.next

      End Sub

End Module



Fortran:       MODULE SIMPLELINKEDLIST	
       CONTAINS			
        SUBROUTINE LLREMOVE(LINK,X)	
         INTEGER LINK(0:)	
         INTEGER X		
         INTEGER IT		
          IT = 0		
          DO WHILE(LINK(IT).GT.0)	
            IF (LINK(IT).EQ.X) THEN		
              LINK(IT) = LINK(LINK(IT))		
              RETURN				
            END IF			
            IT = LINK(IT)		
          END DO		
        END SUBROUTINE LLREMOVE	

        SUBROUTINE LLFOLLOW(LINK)	
         INTEGER LINK(0:)	
          IT = 0			
          WRITE (6,1) "Head",IT,LINK(IT)	
    1     FORMAT (A6,I3," -->",I3)		
    2     IT = LINK(IT)		
          IF (IT.LE.0) RETURN		
          WRITE (6,1) "at",IT,LINK(IT)	
          GO TO 2			
        END SUBROUTINE LLFOLLOW	
      END MODULE SIMPLELINKEDLIST	

      PROGRAM POKE
      USE SIMPLELINKEDLIST	
      INTEGER LINK(0:5)		
      DATA LINK/3, 2,4,1,5,0/	

      WRITE (6,*) "A linked-list, no cargo."
      CALL LLFOLLOW(LINK)

      WRITE (6,*) "The element at one suffers disfavour."
      CALL LLREMOVE(LINK,1)
      CALL LLFOLLOW(LINK)

      WRITE (6,*) "Off with the head
      CALL LLREMOVE(LINK,LINK(0))	
      CALL LLFOLLOW(LINK)

      WRITE (6,*) "And off with the tail."
      CALL LLREMOVE(LINK,5)		
      CALL LLFOLLOW(LINK)		

      END
Task: Gauss-Jordan matrix inversion








VB: Private Function inverse(mat As Variant) As Variant
    Dim len_ As Integer: len_ = UBound(mat)
    Dim tmp() As Variant
    ReDim tmp(2 * len_ + 1)
    Dim aug As Variant
    ReDim aug(len_)
    For i = 0 To len_
        If UBound(mat(i)) <> len_ Then Debug.Print 9 / 0 
        aug(i) = tmp
        For j = 0 To len_
            aug(i)(j) = mat(i)(j)
        Next j
        
        aug(i)(i + len_ + 1) = 1
    Next i
    aug = ToReducedRowEchelonForm(aug)
    Dim inv As Variant
    inv = mat
    
    For i = 0 To len_
        For j = len_ + 1 To 2 * len_ + 1
            inv(i)(j - len_ - 1) = aug(i)(j)
        Next j
    Next i
    inverse = inv
End Function
 
Public Sub main()
    Dim test As Variant
    test = inverse(Array( _
        Array(2, -1, 0), _
        Array(-1, 2, -1), _
        Array(0, -1, 2)))
    For i = LBound(test) To UBound(test)
        For j = LBound(test(0)) To UBound(test(0))
            Debug.Print test(i)(j),
        Next j
    Debug.Print
    Next i
End Sub



Fortran: 












      SUBROUTINE GJINV (A, LDA, N, B, LDB, IERR)
       IMPLICIT NONE
       INTEGER LDA, N, LDB, IERR
       REAL A(LDA,N), B(LDB,N)

       REAL EPS                                  
       PARAMETER (EPS = 1.1920929E-07)
       INTEGER I, J, K, P                        
       REAL F, TOL




       IF (N < 1) THEN            
         IERR = -1
         RETURN
       ELSE IF (N > LDA .OR. N > LDB) THEN
         IERR = -2
         RETURN
       END IF
       IERR = 0

       F = 0.                     
       DO J = 1, N
         DO I = 1, N
           F = F + A(I,J)**2
         END DO
       END DO
       F = SQRT(F)
       TOL = F * EPS

       DO J = 1, N                
         DO I = 1, N
           IF (I .EQ. J) THEN
             B(I,J) = 1.
           ELSE
             B(I,J) = 0.
           END IF
         END DO
       END DO


       DO K = 1, N
         F = ABS(A(K,K))          
         P = K
         DO I = K+1, N
           IF (ABS(A(I,K)) > F) THEN
             F = ABS(A(I,K))
             P = I
           END IF
         END DO

         IF (F < TOL) THEN        
           IERR = 1
           RETURN
         END IF

         IF (P .NE. K) THEN       
           DO J = K, N
             F = A(K,J)
             A(K,J) = A(P,J)
             A(P,J) = F
           END DO
           DO J = 1, N
             F = B(K,J)
             B(K,J) = B(P,J)
             B(P,J) = F
           END DO
         END IF

         F = 1. / A(K,K)          
         DO J = K, N
           A(K,J) = A(K,J) * F
         END DO
         DO J = 1, N
           B(K,J) = B(K,J) * F
         END DO

         DO 10 I = 1, N           
           IF (I .EQ. K) GO TO 10
           F = A(I,K)
           DO J = K, N
             A(I,J) = A(I,J) - A(K,J) * F
           END DO
           DO J = 1, N
             B(I,J) = B(I,J) - B(K,J) * F
           END DO
  10     CONTINUE
       END DO

       RETURN
      END
Task: Executable library

C: #ifndef HAILSTONE
#define HAILSTONE       
                                
long hailstone(long, long**);   
void free_sequence(long *);

#endif
Task: Draw a pixel

C: #include<graphics.h>

int main()
{
	initwindow(320,240,"Red Pixel");
	
	putpixel(100,100,RED);
	
	getch();
	
	return 0;
}
Task: Keyboard input_Flush the keyboard buffer

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

int main(int argc, char* argv[])
{
    
    
    char text[256];
    getchar();

    
    
    
    

    
    
    fseek(stdin, 0, SEEK_END);

    
    
    

    
    
    fgets(text, sizeof(text), stdin);
    puts(text);

    return EXIT_SUCCESS;
}
Task: Raster bars




Go: package main

import (
    "image"
    "image/color"
    "image/gif"
    "log"
    "os"
)

var (
    c0 = color.RGBA{166, 124, 0, 255}
    c1 = color.RGBA{191, 155, 48, 255}
    c2 = color.RGBA{255, 191, 0, 255}
    c3 = color.RGBA{255, 207, 64, 255}
    c4 = color.RGBA{255, 220, 115, 255}
)

var palette = []color.Color{c0, c1, c2, c3, c4}

func hline(img *image.Paletted, x1, y, x2 int, ci uint8) {
    for ; x1 <= x2; x1++ {
        img.SetColorIndex(x1, y, ci)
    }
}

func vline(img *image.Paletted, x, y1, y2 int, ci uint8) {
    for ; y1 <= y2; y1++ {
        img.SetColorIndex(x, y1, ci)
    }
}

func drawHbar(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {
    for ; y1 <= y2; y1++ {
        hline(img, x1, y1, x2, ci)
    }
}

func drawVbar(img *image.Paletted, x1, y1, x2, y2 int, ci uint8) {
    for ; x1 <= x2; x1++ {
        vline(img, x1, y1, y2, ci)
    }
}

func main() {
    const nframes = 40
    const delay = 15 
    width, height := 500, 500
    anim := gif.GIF{LoopCount: 9} 
    rect := image.Rect(0, 0, width, height)

    for f := 0; f < nframes; f++ {
        img := image.NewPaletted(rect, palette)
        c := uint8(f % 2)
        if f < nframes/2 {
            for y := 0; y < height; y += 20 {
                drawHbar(img, 0, y, width, y+19, c)
                c++
                if c == 5 {
                    c = 0
                }
            }
        } else {
            for x := 0; x < width; x += 20 {
                drawVbar(img, x, 0, x+19, height, c)
                c++
                if c == 5 {
                    c = 0
                }
            }
        }
        anim.Delay = append(anim.Delay, delay)
        anim.Image = append(anim.Image, img)
    }

    file, err := os.Create("raster_bars.gif")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    if err2 := gif.EncodeAll(file, &anim); err != nil {
        log.Fatal(err2)
    }
}
Task: Erdős-primes




Go: package main

import "fmt"

func sieve(limit int) []bool {
    limit++
    
    c := make([]bool, limit) 
    c[0] = true
    c[1] = true
    for i := 4; i < limit; i += 2 {
        c[i] = true
    }
    p := 3 
    for {
        p2 := p * p
        if p2 >= limit {
            break
        }
        for i := p2; i < limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    return c
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    if n < 0 {
        s = s[1:]
    }
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    if n >= 0 {
        return s
    }
    return "-" + s
}

func main() {
    limit := int(1e6)
    c := sieve(limit - 1)
    var erdos []int
    for i := 2; i < limit; {
        if !c[i] {
            found := true
            for j, fact := 1, 1; fact < i; {
                if !c[i-fact] {
                    found = false
                    break
                }
                j++
                fact = fact * j
            }
            if found {
                erdos = append(erdos, i)
            }
        }
        if i > 2 {
            i += 2
        } else {
            i += 1
        }
    }
    lowerLimit := 2500
    var erdosLower []int
    for _, e := range erdos {
        if e < lowerLimit {
            erdosLower = append(erdosLower, e)
        } else {
            break
        }
    }
    fmt.Printf("The %d Erdős primes under %s are\n", len(erdosLower), commatize(lowerLimit))
    for i, e := range erdosLower {
        fmt.Printf("%6d", e)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    show := 7875
    fmt.Printf("\n\nThe %s Erdős prime is %s.\n", commatize(show), commatize(erdos[show-1]))
}
Task: Enforced immutability



C#: readonly DateTime now = DateTime.Now;







COBOL: ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
    SYMBOLIC CHARACTERS NUL IS 0, TAB IS 9.
Task: Address of a variable



C#: int i = 5;
int* p = &i;







COBOL: data division.
working-storage section.
01 ptr usage pointer.
01 var pic x(64).

procedure division.
set ptr to address of var.
Task: Loops_Infinite



C#: while (true)
{
    Console.WriteLine("SPAM");
}







COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. Spam.

       PROCEDURE DIVISION.
           PERFORM UNTIL 1 <> 1
               DISPLAY "SPAM"
           END-PERFORM

           GOBACK
           .
Task: Function definition



C#: static double multiply(double a, double b)
{
    return a * b;
}







COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. myTest.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  x   PIC 9(3) VALUE 3.
       01  y   PIC 9(3) VALUE 2.
       01  z   PIC 9(9).
       PROCEDURE DIVISION.
           CALL "myMultiply" USING 
               BY CONTENT x, BY CONTENT y, 
               BY REFERENCE z.
           DISPLAY z.
           STOP RUN.
       END PROGRAM myTest.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. myMultiply.
       DATA DIVISION.
       LINKAGE SECTION.
       01  x   PIC 9(3).
       01  y   PIC 9(3).
       01  z   PIC 9(9).
       PROCEDURE DIVISION USING x, y, z.
           MULTIPLY x BY y GIVING z.
           EXIT PROGRAM.
       END PROGRAM myMultiply.
Task: Terminal control_Dimensions



C#: static void Main(string[] args)
{
    int bufferHeight = Console.BufferHeight;
    int bufferWidth = Console.BufferWidth;
    int windowHeight = Console.WindowHeight;
    int windowWidth = Console.WindowWidth;

    Console.Write("Buffer Height: ");
    Console.WriteLine(bufferHeight);
    Console.Write("Buffer Width: ");
    Console.WriteLine(bufferWidth);
    Console.Write("Window Height: ");
    Console.WriteLine(windowHeight);
    Console.Write("Window Width: ");
    Console.WriteLine(windowWidth);
    Console.ReadLine();
}







COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. terminal-dimensions.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  num-lines PIC 9(3).
       01  num-cols  PIC 9(3).

       SCREEN SECTION.
       01  display-screen.
           03  LINE 01 COL 01 PIC 9(3) FROM num-lines.
           03  LINE 01 COL 05 VALUE "rows by " .
           03  LINE 01 COL 13 PIC 9(3) FROM num-cols.
           03  LINE 01 COL 16 VALUE " columns.".

       PROCEDURE DIVISION.
           ACCEPT num-lines FROM LINES
           ACCEPT num-cols FROM COLUMNS

           DISPLAY display-screen

      *    This pauses the program, as ncurses will immediately revert
      *    back to the console when the program ends.
           CALL "C$SLEEP" USING BY CONTENT 3

           GOBACK
           .
Task: Execute HQ9+



C#: using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void RunCode(string code)
    {
        int accumulator = 0;
        var opcodes = new Dictionary<char, Action>
        {
            {'H', () => Console.WriteLine("Hello, World!"))},
            {'Q', () => Console.WriteLine(code) },
            {'9', () => Console.WriteLine(Enumerable.Range(1,100).Reverse().Select(n => string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around\n{1} bottles of beer on the wall\n", n, n-1)).Aggregate((a,b) => a + "\n" + b))},
            {'+', () => accumulator++ }
        }

        foreach(var c in code)
            opcodes[c]();
    }
}







COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. Exec-Hq9.

       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       78  Code-Length VALUE 256.

       01  i           PIC 999.
       01  accumulator PIC 999.

       01  bottles     PIC 999.

       LINKAGE SECTION.
       01  hq9-code    PIC X(Code-Length).
       
       PROCEDURE DIVISION USING BY VALUE hq9-code.
           PERFORM VARYING i FROM 1 BY 1 UNTIL Code-Length < i
               EVALUATE hq9-code (i:1)
                   WHEN "Q"
                       DISPLAY FUNCTION TRIM(hq9-code)

                   WHEN "H"
                       DISPLAY "Hello, World!"

                   WHEN "9"
                       MOVE 99 TO bottles
                       PERFORM UNTIL bottles = ZERO
                           DISPLAY
                               bottles " bottles of beer on the wall"
                           DISPLAY bottles " bottles of beer"
                           DISPLAY "Take one down, pass it around"
                           SUBTRACT 1 FROM bottles
                           DISPLAY
                               bottles " bottles of beer on the wall"
                           DISPLAY SPACE
                       END-PERFORM

                   WHEN "+"
                       ADD 1 TO accumulator
               END-EVALUATE
           END-PERFORM

           GOBACK
           .
Task: Find the last Sunday of each month



C#: using System;

namespace LastSundayOfEachMonth
{
    class Program
    {
        static void Main()
        {
            Console.Write("Year to calculate: ");

            string strYear = Console.ReadLine();
            int year = Convert.ToInt32(strYear);

            DateTime date;
            for (int i = 1; i <= 12; i++)
            {
                date = new DateTime(year, i, DateTime.DaysInMonth(year, i), System.Globalization.CultureInfo.CurrentCulture.Calendar);
                
                
                int daysOffset = date.DayOfWeek - dayOfWeek; 
                if (daysOffset < 0) daysOffset += 7; 
                date = date.AddDays(-daysOffset ); 
                Console.WriteLine(date.ToString("yyyy-MM-dd"));
            }
        }
    }
}







COBOL:        program-id. last-sun.
       data division.
       working-storage section.
       1 wk-date.
        2 yr pic 9999.
        2 mo pic 99 value 1.
        2 da pic 99 value 1.
       1 rd-date redefines wk-date pic 9(8).
       1 binary.
        2 int-date pic 9(8).
        2 dow pic 9(4).
        2 sunday pic 9(4) value 7.
       procedure division.
           display "Enter a calendar year (1601 thru 9999): "
               with no advancing
           accept yr
           if yr >= 1601 and <= 9999
               continue
           else
               display "Invalid year"
               stop run
           end-if
           perform 12 times
               move 1 to da
               add 1 to mo
               if mo > 12              
                   move 12 to mo
                   move 31 to da
               end-if
               compute int-date = function
                   integer-of-date (rd-date)
               if mo =12 and da = 31   
                   continue
               else
                   subtract 1 from int-date
               end-if
               compute rd-date = function
                   date-of-integer (int-date)
               compute dow = function mod
                   ((int-date - 1) 7) + 1
               compute dow = function mod ((dow - sunday) 7)
               subtract dow from da
               display yr "-" mo "-" da
               add 1 to mo
           end-perform
           stop run
           .
       end program last-sun.