J Examples





Generated by AI, corrected by PeatSoft

  1. Basic Arithmetic Operations
    
    x =: 5 + 3  NB. Addition
    y =: 10 - 4 NB. Subtraction
    z =: 6 * 7  NB. Multiplication
    w =: 8 % 2  NB. Division
    
    echo x, y, z, w  NB. Output all results
    
    
  2. Creating and Accessing Arrays
    
    arr =: 1 2 3 4 5          NB. Create a simple array
    secondElement =: 2 { arr  NB. Access the second element (indexing starts at 0)
    
    echo arr, secondElement   NB. Output the array and the accessed element
    
    
  3. Functions
    
    double =: * & 2     NB. Define a function to double its input
    result =: double 5  NB. Call the function
    echo result         NB. Output the result
    
    
  4. Control Structures (if-then-else)
    
    num =: 3 : 0
    if. y > 5 do. 'Greater'
    else. 'Not Greater'
    end.
    )
    result =: num 10
    echo result  NB. Output the result
    
    
  5. Loops (Using a For Loop)
    
    List =: 3 : 0
    for_i. y do.
        echo i   NB. Output each value from 0 to 4
    end.
    )
    List 0 1 2 3 4
    
    
  6. Defining and Using a Simple Matrix
    
    matrix =: 3 3 $ 1 2 3 4 5 6 7 8 9  NB. Create a 3x3 matrix
    echo matrix  NB. Output the matrix
    
    
  7. Conditional Logic
    
    result =: (>: & 3)   NB. Use conditional logic. Results in 1 if true, 0 if false.
    echo result 3
    
    
  8. Date and Time
    
    current_date =: 6!:0 ''  NB. Get the current date
    echo current_date        NB. Output the current date
    
    
  9. Reading Input from User
    
    echo 'Enter your name: ' 
    read =: 1!:1  NB. read becomes a verb to read from file
    name =: read 1
    
    
  10. Generating Random Numbers
    
    randomNumbers =: ?. 5$10    NB. Generate 5 random numbers between 0 and 9, including 0 and 9
    echo randomNumbers          NB. Output the random numbers
    
    
  11. Working with Lists
    
    list =: 10 20 30 40 50              NB. Create a list
    sumList =: +/ list                  NB. Sum of the list elements
    echo sumList                        NB. Output the sum