User:40bus/Programming languages comparison

Random choice

Java

import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class RandomChoiceExample {
    public static void main(String[] args) {
        List<String> myList = Arrays.asList("1", "2", "3");
        Random random = new Random();
        String randomChoice = myList.get(random.nextInt(myList.size()));
        System.out.println(randomChoice);
    }
}

Python

import random

mylist = ["1", "2", "3"]

print(random.choice(mylist))

Rust

use rand::seq::IteratorRandom; // Make sure to include the rand crate in your Cargo.toml

fn main() {
    let my_list = vec!["1", "2", "3"];
    
    let random_choice = my_list.iter().choose(&mut rand::thread_rng()).unwrap();
   
   println!("{}", random_choice);
}

Printing numbers

CoffeeScript

number = parseInt(prompt('Please Enter Number '))
while number > 0
    # check even and odd
    if number % 2 == 0
        console.log(number + ' is an even number')
    else
        console.log(number + ' is an odd number')
    # decrease number by 1 in each iteration
    number = number - 1

Java

import java.util.Scanner;

public class EvenOddChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please Enter Number: ");
        int number = scanner.nextInt();
        
        while (number > 0) {
            // check even and odd
            if (number % 2 == 0) {
                System.out.println(number + " is an even number");
            } else {
                System.out.println(number + " is an odd number");
            }
            // decrease number by 1 in each iteration
            number = number - 1;
        }
        
        scanner.close();
    }
}

Python

n = int(input('Please Enter Number '))
while n > 0:
    # check even and odd
    if n % 2 == 0:
        print(n, 'is a even number')
    else:
        print(n, 'is a odd number')
    # decrease number by 1 in each iteration
    n = n - 1

Rust

fn main() {
    let mut number: i32 = std::io::stdin()
        .read_line(&mut String::new())
        .unwrap()
        .trim()
        .parse()
        .unwrap();

    while number > 0 {
        // check even and odd
        if number % 2 == 0 {
            println!("{} is an even number", number);
        } else {
            println!("{} is an odd number", number);
        }
        // decrease number by 1 in each iteration
        number -= 1;
    }
}

Number range

C

#include <stdio.h>

int main(void) {
    const int start = 10;
    const int stop_exclusive = 16;   // Python's range stop is exclusive

    for (int number = start; number < stop_exclusive; ++number) {
        printf("%d ", number);
    }

    return 0;
}

CoffeeScript

# Numbers from 10 to 15
numbers = (i for i in [10..15])   # generate the sequence 10, 11, 12, 13, 14, 15
console.log numbers.join ' '      # Output: 10 11 12 13 14 15

Java

// Numbers from 10 to 15
public class Main {
    public static void main(String[] args) {
        // Print numbers 10 through 15 separated by a space
        for (int number = 10; number < 16; number++) {
            System.out.print(number);
            if (number < 15) {
                System.out.print(" ");
            }
        }
        System.out.println(); // Move to the next line after printing
    }
}

JavaScript

// Numbers from 10 to 15
let output = "";
for (let i = 10; i < 16; i++) {
    output += i + " ";
}

// Output: 10 11 12 13 14 15
process.stdout.write(output.trimEnd() + "\n");

Lua

-- Numbers from 10 to 15
for i = 10, 15 do
    io.write(i, " ")
end
io.write("\n")

PHP

<?php
// Numbers from 10 to 15

for ($i = 10; $i < 16; $i++) {
    echo $i . ' ';
}

// Output: 10 11 12 13 14 15
?>

Python

# Numbers from 10 to 15
# start = 10
# stop = 16
for i in range(10, 16):
    print(i, end=' ')

# Output 10 11 12 13 14 15

Ruby

# Numbers from 10 to 15
# start = 10
# stop = 16
(10..15).each do |i|
  print "#{i} "
end

# Output 10 11 12 13 14 15

Rust

fn main() {
    // Numbers from 10 to 15
    for i in 10..16 {
        // Print each number followed by a space, without a newline
        print!("{} ", i);
    }

    // Optional: move to the next line after the loop finishes
    println!();
}

Get current date and time

C

#include <stdio.h>
#include <time.h>

int main(void) {
    /* Get the current calendar time */
    time_t current_time = time(NULL);
    if (current_time == (time_t)-1) {
        perror("Failed to obtain current time");
        return 1;
    }

    /* Convert to local broken‑down time */
    struct tm *local_time = localtime(&current_time);
    if (local_time == NULL) {
        perror("Failed to convert time to local representation");
        return 1;
    }

    /* Build a human‑readable date‑time string */
    char datetime_str[128];
    if (strftime(datetime_str, sizeof(datetime_str),
                 "%Y-%m-%d %H:%M:%S", local_time) == 0) {
        fprintf(stderr, "strftime failed\n");
        return 1;
    }

    /* Output results */
    printf("Current DateTime: %s\n", datetime_str);
    printf("Type: struct tm*\n");

    return 0;
}

CoffeeScript

# Get the current date and time
now = new Date()

# Output the current date and time
console.log 'Current DateTime:', now

# Output the type (constructor name) of the object
console.log 'Type:', now.constructor.name

Java

import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        // Obtain the current date and time
        LocalDateTime currentDateTime = LocalDateTime.now();

        // Display the date-time value
        System.out.println("Current DateTime: " + currentDateTime);

        // Display the type (class name) of the object
        System.out.println("Type: " + currentDateTime.getClass().getName());
    }
}

JavaScript

// Get the current date and time
const currentDateTime = new Date();

// Output the current date and time
console.log('Current DateTime:', currentDateTime);

// Output the type of the variable
console.log('Type:', typeof currentDateTime);

Lua

-- Get the current timestamp
local now = os.time()

-- Print the formatted current date and time
print("Current DateTime:", os.date("%Y-%m-%d %H:%M:%S", now))

-- Print the Lua type of the timestamp variable
print("Type:", type(now))

PHP

<?php
// Create a DateTime object representing the current date and time
$currentDateTime = new DateTime();

// Output the current date and time
echo 'Current DateTime: ' . $currentDateTime->format('Y-m-d H:i:s') . PHP_EOL;

// Output the type of the variable (class name)
echo 'Type: ' . get_class($currentDateTime) . PHP_EOL;
?>

Python

from datetime import datetime

now = datetime.now()
print('Current DateTime:', now)
print('Type:', type(now))

Ruby

# Get the current date and time
current_time = Time.now

# Output the datetime and its class type
puts "Current DateTime: #{current_time}"
puts "Type: #{current_time.class}"

Rust

// Add the following dependency to your Cargo.toml:
// chrono = "0.4"

use chrono::Local;
use std::any::type_name_of_val;

fn main() {
    // Get the current local date and time
    let now = Local::now();

    // Print the datetime
    println!("Current DateTime: {}", now);

    // Print the type of the variable
    println!("Type: {}", type_name_of_val(&now));
}

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.