Stars

Descripción del contenido de la página

Conversión de Stars a varios lenguajes de programación.

Etiquetas:

Este programa ha sido convertido a 20 lenguajes de programación.

Original

Origin of diamond.bas:

Example included in Vintage BASIC 1.0.3.

http://vintage-basic.net/

10 INPUT "What is your name"; U$
20 PRINT "Hello "; U$
30 INPUT "How many stars do you want"; N
40 S$ = ""
50 FOR I = 1 TO N
60 S$ = S$ + "*"
70 NEXT I
80 PRINT S$
90 INPUT "Do you want more stars"; A$
100 IF LEN(A$) = 0 THEN 90
110 A$ = LEFT$(A$, 1)
120 IF A$ = "Y" OR A$ = "y" THEN 30
130 PRINT "Goodbye ";U$
140 END

En Arturo

; Stars

; Original version in BASIC:
;   Example included in Vintage BASIC 1.0.3.
;   http://www.vintage-basic.net

; This version in Arturo:
;   Copyright (c) 2023, Marcos Cruz (programandala.net)
;   SPDX-License-Identifier: Fair
;
; Written in 2023-10.
; 
; Last modified: 20251205T0052+0100.

name: input "What is your name? "
print render "Hello, |name|."

while [ true ] [
    until [
        numberString: input "How many stars do you want? "
        dup numeric? numberString else [ print "Number expected. Retry." ]
    ] []
    number: floor to :floating numberString

    print repeat "*" number

    answer: input "Do you want more stars? "
    if not? contains? [ "ok", "yeah", "yes", "y"] answer [ break ]
]

En C#

// Stars

// Original version in BASIC:
//  Example included in Vintage BASIC 1.0.3.
//  http://www.vintage-basic.net

// This version in C#:
//  Copyright (c) 2024, Marcos Cruz (programandala.net)
//  SPDX-License-Identifier: Fair
//
// Written on 2024-12-21.
//
// Last modified: 20251205T1549+0100.

using System;
using System.Linq;

class Stars
{
    static void Main()
    {
        Console.Write("What is your name? ");
        string name = Console.ReadLine();
        Console.WriteLine($"Hello, {name}.");

        string answer;
        string[] afirmativeAnswers = {"ok", "yeah", "yes", "y"};

        do
        {
            double number;

            while (true)
            {
                Console.Write("Enter a number: ");
                try
                {
                    number = Int64.Parse(Console.ReadLine());
                    break;
                }
                catch
                {
                    Console.WriteLine("Integer expected.");
                }
            }

            for (int i = 0; i < number; i++)
            {
                Console.Write("*");
            }
            Console.WriteLine();

            Console.Write("Do you want more stars? ");
            answer = Console.ReadLine().ToLower();
        }
        while (afirmativeAnswers.Contains(answer));
    }
}

En C3

// Stars
//
// Original version in BASIC:
//  Example included in Vintage BASIC 1.0.3.
//  http://www.vintage-basic.net
//
// This version in C3:
//  Copyright (c) 2025, Marcos Cruz (programandala.net)
//  SPDX-License-Identifier: Fair
//
// Written on 2025-03-18.
//
// Last modified: 20250731T1954+0200.

import std::io;

fn String acceptString(String prompt = "") {
    io::print(prompt);
    String! s = io::readline();
    if (catch excuse = s) {
        return "";
    } else {
        return s;
    }
}

fn int! acceptInteger(String prompt = "") {
    String s = acceptString(prompt);
    defer free(s);
    return String.to_int(s);
}

fn int acceptValidInteger(String prompt = "", String error = "Integer expected.\n") {
    while (true) {
        int! n = acceptInteger(prompt);
        if (catch excuse = n) {
            io::print(error);
        } else {
            return n;
        }
    }
}

fn bool isYes(String s) {

    String lowercase_s = String.new_ascii_to_upper(s);
    defer free(lowercase_s);
    switch(lowercase_s) {
        case "OK":
        case "Y":
        case "YEAH":
        case "YES":
            return true;
        default:
            return false;
    }

}

fn void main() {

    String name = acceptString("What is your name? ");
    defer free(name);
    io::printfn("Hello, %s.", name);

    int stars = 0;
    while (true) {
        stars = acceptValidInteger("How many stars do you want? ");
        for (int n = 0; n < stars; n += 1) {
            io::print("*");
        }
        io::print("\nDo you want more stars? ");
        String answer = acceptString();
        defer free(answer);
        if (!isYes(answer)) {
            break;
        }
    }

}

En Chapel

// Stars

// Original version in BASIC:
//     Example included in Vintage BASIC 1.0.3.
//     http://www.vintage-basic.net

// This version in Chapel:
//     Copyright (c) 2025, Marcos Cruz (programandala.net)
//     SPDX-License-Identifier: Fair
//
// Written on 2025-04-05.
//
// Last modified: 20250405T2255+0200.

import IO;

proc acceptString(prompt: string): string {
    write(prompt);
    IO.stdout.flush();
    return IO.readLine().strip();
}

proc acceptValidInteger(prompt: string): int {
    var result: int;
    while true {
        var s: string = acceptString(prompt);
        try {
            result = s: int;
            break;
        }
        catch exc {
            writeln("Integer expected.");
        }
    }
    return result;
}

proc isYes(s: string): bool {
    select(s.toLower()) {
        when "ok", "y", "yeah", "yes" do return true;
        otherwise do return false;
    }
}

proc main() {
    var name: string = acceptString("What is your name? ");
    writef("Hello, %s.\n", name);
    do {
        var number: int = acceptValidInteger("How many stars do you want? ");
        writeln("*" * number);
    } while isYes(acceptString("Do you want more stars? "));
}

En Crystal

# Stars

# Original version in BASIC:
#     Example included in Vintage BASIC 1.0.3.
#     http://www.vintage-basic.net

# This version in Crystal:
#     Copyright (c) 2023, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2023-09-30.
#
# Last modified: 20231104T0010+0100.

def getn(prompt : String) : Float64
  while true
    print prompt
    begin
      number = gets.not_nil!.to_f
      break
    rescue
      puts "Number expected."
    end
  end
  number
end

def yes_or_no(prompt : String) : String
  answer = ""
  until answer != ""
    print prompt
    answer = gets.not_nil!
  end
  answer
end

print "What is your name? "
name = gets.not_nil!
puts "Hello, #{name}."

while true
  n = getn "How many stars do you want? "
  puts "*" * n.to_i
  answer = yes_or_no("Do you want more stars? ")
  if !["ok", "yeah", "yes", "y"].any? { |yes| answer.downcase == yes }
    puts "Goodbye, #{name}."
    break
  end
end

En D

// Stars

// Original version in BASIC:
//     Example included in Vintage BASIC 1.0.3.
//     http://www.vintage-basic.net

// This version in D:
//     Copyright (c) 2025, Marcos Cruz (programandala.net)
//     SPDX-License-Identifier: Fair
//
// Written on 2025-03-22.
//
// Last modified: 20251220T0633+0100.

module stars;

string acceptString(string prompt)
{
    import std.stdio : readln;
    import std.stdio : write;
    import std.string : strip;

    write(prompt);
    return strip(readln());
}

int acceptValidInteger(string prompt)
{
    import std.conv : to;
    import std.stdio : writeln;

    int result;
    while (true)
    {
        string s = acceptString(prompt);
        try
        {
            result = to!int(s);
            break;
        }
        catch (Exception exc)
        {
            writeln("Integer expected.");
        }
    }
    return result;
}

bool isYes(string s)
{
    import std.uni : toLower;

    switch (toLower(s))
    {
        case "ok", "y", "yeah", "yes":
            return true;
        default:
            return false;
    }
}

void main()
{
    import std.range : repeat;
    import std.stdio : writef;
    import std.stdio : writeln;

    string name = acceptString("What is your name? ");
    writef("Hello, %s.\n", name);
    do
    {
        int number = acceptValidInteger("How many stars do you want? ");
        writeln(repeat('*', number));
    } while (isYes(acceptString("Do you want more stars? ")));
}

En Go

/*
Stars

Original version in BASIC:
    Example included in Vintage BASIC 1.0.3.
    http://www.vintage-basic.net

This version in Go:
    Copyright (c) 2024, Marcos Cruz (programandala.net)
    SPDX-License-Identifier: Fair

Written on 2024-12-31.

Last modified: 20241231T0125+0100.
*/

package main

import "fmt"
import "strconv"
import "strings"

func inputString(prompt string) string {

    fmt.Print(prompt)
    var s = ""
    fmt.Scanf("%s", &s)
    return s

}

func inputInt(prompt string) int {

    var number int64
    var err error
    for {
        number, err = strconv.ParseInt(inputString(prompt), 10, 0)
        if err == nil {
            break
        } else {
            fmt.Println("Integer expected.")
        }
    }
    return int(number)

}

func main() {

    var name string = inputString("What is your name? ")
    fmt.Printf("Hello, %v.\n", name)

loop:
    for {
        var number int = inputInt("How many stars do you want? ")
        var stars = strings.Repeat("*", number)
        fmt.Println(stars)

        var answer string = inputString("Do you want more stars? ")
        switch strings.ToLower(strings.TrimSpace(answer)) {
        case "ok", "yeah", "yes", "y":
        default:
            break loop
        }
    }

}

En Hare

// Stars
//
// Original version in BASIC:
//      Example included in Vintage BASIC 1.0.3.
//      http://www.vintage-basic.net
//
// This version in Hare:
//      Copyright (c) 2025, Marcos Cruz (programandala.net)
//      SPDX-License-Identifier: Fair
//
// Written in 2025-02-14/15.
//
// Last modified: 20260213T1645+0100.

// Modules {{{1
// =============================================================================

use ascii;
use bufio;
use fmt;
use os;
use strconv;
use strings;

// User input {{{1
// =============================================================================

fn print_prompt(prompt: str) void = {
        fmt::print(prompt)!;
        bufio::flush(os::stdout)!;
};

fn accept_string(prompt: str = "") str = {
        print_prompt(prompt);
        const buffer = match (bufio::read_line(os::stdin)!) {
                case let buffer: []u8 =>
                        yield buffer;
                case =>
                        return "";
                };
        defer free(buffer);
        return strings::dup(strings::fromutf8(buffer)!)!;
};

fn accept_integer() (int | ...strconv::error) = {
        const s = accept_string();
        defer free(s);
        return strconv::stoi(s);
};

fn prompted_integer(prompt: str) (int | ...strconv::error) = {
        print_prompt(prompt);
        return accept_integer();
};

fn prompted_valid_integer(prompt: str, error: str = "Integer expected.") int = {
        let result: int = 0;
        for (true) {
                match (prompted_integer(prompt)) {
                case let i: int =>
                        result = i;
                        break;
                case =>
                        fmt::println(error)!;
                };
        };
        return result;
};

// Main {{{1
// =============================================================================

fn is_yes(s: str) bool = {
        const lowercase_s = ascii::strlower(s)!;
        defer free(lowercase_s);
        return switch(lowercase_s) {
                case "ok", "y", "yeah", "yes" =>
                        yield true;
                case =>
                        yield false;
        };
};

fn repeat(s: str, n: int) str = {
        let result = "";
        for (let i: int = 0; i < n; i += 1) {
                result = strings::concat(result, s)!;
        };
        return result;
};

export fn main() void = {
        const name: str = accept_string("What is your name? ");
        defer free(name);
        fmt::printfln("Hello, {}.", name)!;

        let number: int = 0;
        for (true) {
                number = prompted_valid_integer("How many stars do you want? ");
                let stars = repeat("*", number);
                defer free(stars);
                fmt::println(stars)!;

                print_prompt("Do you want more stars? ");
                let answer: str = accept_string();
                defer free(answer);
                if (!is_yes(answer)) {
                        break;
                };
        };
};

En Janet

# Stars

# Original version in BASIC:
#  Example included in Vintage BASIC 1.0.3.
#  http://www.vintage-basic.net

# This version in Janet:
#  Copyright (c) 2025, Marcos Cruz (programandala.net)
#  SPDX-License-Identifier: Fair
#
# Written on 2025-12-24.
#
# Last modified 20251225T1946+0100.

(defn accept-string [prompt-text]
  (prin prompt-text)
  (string/trim (getline)))

(defn accept-integer [prompt-text]
  (def input (accept-string prompt-text))
  (def number (scan-number input))
  (if number
    (math/trunc number)
    (do
      (print "Number expected.")
      (accept-integer prompt-text))))

(defn yes? [question]
  (let [input (accept-string question)]
    (index-of (string/ascii-lower input) ["ok" "y" "yeah" "yes"])))

(defn main [& args]
  (def name (accept-string "What is your name? "))
  (print "Hello, " (string/trim name) ".")
  (forever
    (def number (accept-integer "How many stars do you want? "))
    (print (string/repeat "*" number))
    (if (not (yes? "Do you want more stars? "))
      (break))))

En Julia

# Stars

# Original version in BASIC:
#     Example included in Vintage BASIC 1.0.3.
#     http://www.vintage-basic.net

# This version in Julia:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-07-01.
#
# Last modified: 20240704T1050+0200.

print("What is your name? ")
name = readline()
println("Hello, $name")

n = 0

while true

    while true
        print("How many stars do you want? ")
        global n = tryparse(Int, readline())
        if isnothing(n)
            println("Number expected. Retry input line.")
        else
            break
        end
    end

    println(repeat('*', n))

    print("Do you want more stars? ")
    answer = lowercase(readline())

    if ! (answer in ["yeah", "yes", "y", "ok"])
        break
    end

end

println("Goodbye, $name")

En Kotlin

/*
Stars

Original version in BASIC:
    Example included in Vintage BASIC 1.0.3.
    http://www.vintage-basic.net

This version in Kotlin:
    Copyright (c) 2023, Marcos Cruz (programandala.net)
    SPDX-License-Identifier: Fair

Written in 2023-10.

Last modified: 20250420T0003+0200.
*/


// Print the given prompt, wait until the user enters a valid integer
// and return it.
fun getNumber(prompt: String): Int {
    var number: Int
    while (true) {
        try {
            print(prompt)
            number = readln().toInt()
            break
        }
        catch (e: Exception) { }
    }
    return number
}

fun main() {
    print("What is your name? ")
    val name = readln()
    println("Hello, $name.")
    do {
        var number = getNumber("How many stars do you want? ")
        println("*".repeat(number))
        print("Do you want more stars? ")
        val answer = readln()
    } while (
        when (answer.lowercase()) {
            "ok", "yeah", "yes", "y"  -> true
            else -> false
        }
    )
}

En Nim

#[
Stars

Original version in BASIC:
  Example included in Vintage BASIC 1.0.3.
  http://www.vintage-basic.net

This version in Nim:
  Copyright (c) 2025, Marcos Cruz (programandala.net)
  SPDX-License-Identifier: Fair

Written on 2025-01-16.

Last modified: 20250404T0159+0200.
]#

import std/strutils
import std/unicode

proc main() =

  write(stdout, "What is your name? ")
  let name = readLine(stdin)
  writeLine(stdout, "Hello, ", name, ".")

  while true:
    var number: int
    while true:
      write(stdout, "How many stars do you want? ")
      try:
        number = parseInt(readLine(stdin))
        if number >= 0:
          break
        writeLine(stdout, "Positive integer expected.")
      except:
        writeLine(stdout, "Integer expected.")
    writeLine(stdout, repeat('*', number))
    write(stdout, "Do you want more stars? ")
    case toLower(readLine(stdin)):
    of "ok", "yeah", "yes", "y":
      discard
    else:
      break

main()

En Odin

/*
Stars

Original version in BASIC:
    Example included in Vintage BASIC 1.0.3.
    http://www.vintage-basic.net

This version in Odin:
    Copyright (c) 2023, 2024, Marcos Cruz (programandala.net)
    SPDX-License-Identifier: Fair

Written in 2023-10, 2024-12, 2025-02.

Last modified: 20250226T2357+0100.
*/

package name

import "../lib/anodino/src/read"
import "core:fmt"
import "core:strings"

main :: proc() {

    fmt.print("What is your name? ")
    name, _ := read.a_string()
    defer delete(name)
    fmt.printfln("Hello, %v.", name)
    number : int
    quit := false
    for ! quit {
        for ok := false; !ok; {
            fmt.print("How many stars do you want? ")
            number, ok = read.an_int()
            if !ok do fmt.println("Integer expected.")
        }
        stars := strings.repeat("*", number)
        defer delete(stars)
        fmt.println(stars)
        fmt.print("Do you want more stars? ")
        answer, _ := read.a_string()
        defer delete(answer)
        lowercase_answer := strings.to_lower(answer)
        defer delete(lowercase_answer)
        switch answer {
            case "ok", "yeah", "yes", "y" :
            case : quit = true
        }
    }

}

En Pike

#! /usr/bin/env pike

// Stars

// Original version in BASIC:
//  Example included in Vintage BASIC 1.0.3.
//  http://www.vintage-basic.net

// This version in Pike:
//  Copyright (c) 2025, Marcos Cruz (programandala.net)
//  SPDX-License-Identifier: Fair
//
// Written on 2025-03-08.
//
// Last modified: 20250308T1701+0100.

string accept_string(string prompt) {
    write(prompt);
    return Stdio.stdin->gets();
}

int accept_integer(string prompt) {
    // NB The casting accepts any valid integer at the start of the string
    // and ignores the rest;  if no valid integer is found at the start of
    // the string, zero is returned.
    return (int) accept_string(prompt);
}

int accept_valid_integer(string prompt) {
    int n = 0;
    while (n <= 0) {
        n = accept_integer(prompt);
        if (n <= 0) {
            write("Integer greater than zero expected.\n");
        }
    }
    return n;
}

bool is_yes(string s) {
    switch(lower_case(s)) {
        case "ok":
        case "y":
        case "yeah":
        case "yes":
            return true;
        default:
            return false;
    }
}

void main() {
    string name = accept_string("What is your name? ");
    write("Hello, %s.\n", name);
    do {
        int number = accept_valid_integer("How many stars do you want? ");
        write("%s\n", "*" * number);
    } while (is_yes(accept_string("Do you want more stars? ")));
}

En Python

# Stars

# Original version in BASIC:
#     Example included in Vintage BASIC 1.0.3.
#     http://www.vintage-basic.net

# This version in Python:
#     Copyright (c) 2024, Marcos Cruz (programandala.net)
#     SPDX-License-Identifier: Fair
#
# Written on 2024-10-29.
#
# Last modified: 20241029T2037+0100.

import ast

name = input("What is your name? ")
print(f"Hello, {name}.")

n = 0

while True:

    while True:
        try:
            n = ast.literal_eval(input("How many stars do you want? "))
            break
        except:
            print("Number expected. Retry input line.")

    print("*" * n)

    answer = input("Do you want more stars? ").lower()

    if not (answer in ["yeah", "yes", "y", "ok"]):
        break

print(f"Goodbye, {name}")

En Raku

# Stars
#
# Original version in BASIC:
#   Example included in Vintage BASIC 1.0.3.
#   http://www.vintage-basic.net
#
# This version in Raku:
#   Copyright (c) 2024, Marcos Cruz (programandala.net)
#   SPDX-License-Identifier: Fair
#
# Written on 2024-12-03.
#
# Last modified: 20241203T1833+0100.

my $name = prompt 'What is your name? ';
print "Hello, $name.\n";

STARS: loop {

    my Int $number;

    loop {
        try {
            $number = +prompt 'How many stars do you want? ';
            CATCH {
                default {
                    put 'Number expected.';
                    next;
                }
            }
        }
        last;
    }
    put '*' x $number;

    my $answer = (prompt 'Do you want more stars? ').lc;
    if not $answer  ('ok', 'y', 'yeah', 'yes') {
        last STARS;
    }

}

En Ring

/*
Stars

Original version in BASIC:
    Example included in Vintage BASIC 1.0.3.
    http://www.vintage-basic.net

This version in Ring:
    Copyright (c) 2024, Marcos Cruz (programandala.net)
    SPDX-License-Identifier: Fair

Written on 2024-03-18.

Last modified: 20240318T1944+0100.
*/

load "typehints.ring"

// Display the given question, accept a Y/N answer and return a correspondent
// boolean result.
func yes(question)

    afirmativeAnswers = ["y", "yeah", "yes", "ok"]
    negativeAnswers = ["n", "no", "nope"]

    while true

        print(question)
        answer = lower(getString())

        if find(afirmativeAnswers, answer)
            return true
        elseif find(negativeAnswers, answer)
            return false
        end

    end

end

// Display the given prompt, accept a valid number and return it.
func inputNumber(prompt)

    while true
        print(prompt)
        get n
        if isDigit(n)
            break
        else
            put "Number expected. Retry." + nl
        end
    end
    return 0 + n

end

func main

    puts("What is your name? ")
    name = getString()
    print("Hello, #{name}.\n")

    while true
        n = inputNumber("How many stars do you want? ")
        put copy("*", n) + nl
        if not yes("Do you want more stars? ")
            break
        end
    end

    print("Goodbye, #{name}.\n")

end

En Scheme

; Stars

; Original version in BASIC:
;   Example included in Vintage BASIC 1.0.3.
;   http://www.vintage-basic.net

; This version in Scheme (Bigloo):
;   Copyright (c) 2025, Marcos Cruz (programandala.net)
;   SPDX-License-Identifier: Fair
;
; Written on 2025-12-04.
;
; Last modified 20251224T1231+0100.

(module stars)

(define (accept-string prompt)
    (display prompt)
    (read-line))

(define (accept-integer prompt)
    (let ((input (accept-string prompt)))
        (let ((number (string->number input)))
            (if number
                (truncate number)
                (begin
                    (display "Number expected.")
                    (newline)
                    (accept-integer prompt))))))

(define (first x) (car x))

(define (rest x) (cdr x))

(define (string-in-list-ci? a-string a-list)
    (cond
        ((null? a-list) #f)
        ((string-ci=? a-string (first a-list)) #t)
        (else (string-in-list-ci? a-string (rest a-list)))))

(define (yes? prompt)
    (let ((input (accept-string prompt)))
        (string-in-list-ci? input (list "ok" "y" "yeah" "yes"))))

(let ((name (accept-string "What is your name? ")))
    (display "Hello, ")
    (display name)
    (display ".")
    (newline))

(define (run)
    (let ((number (accept-integer "How many stars do you want? ")))
        (display (make-string number #\*))
        (newline))
    (when (yes? "Do you want more stars? ")
        (run)))

(run)

En Swift

/*
Stars

Original version in BASIC:
    Example included in Vintage BASIC 1.0.3.
    http://www.vintage-basic.net

This version in Swift:
    Copyright (c) 2025, Marcos Cruz (programandala.net)
    SPDX-License-Identifier: Fair

Written on 2025-04-23.

Last modified: 20250423T1940+0200.
*/

var name = ""
while name == "" {
    print("What is your name? ", terminator: "")
    name = readLine() ?? ""
}
print("Hello, \(name).")

var numberOfStars: Int

play: while true {

    while true {
        print("How many stars do you want? ", terminator: "")
        if let input = readLine(), let number = Int(input) {
            numberOfStars = number
            break
        } else {
            print("Integer expected.")
        }
    }

    print(String(repeating: "*", count: numberOfStars))

    print("Do you want more stars? ", terminator: "")
    let answer = (readLine() ?? "").lowercased()
    if !["ok", "yeah", "yes", "y"].contains(answer) {
        break play
    }

}

En V

/*
Stars

Original version in BASIC:
    Example included in Vintage BASIC 1.0.3.
    http://www.vintage-basic.net

This version in V:
    Copyright (c) 2025, Marcos Cruz (programandala.net)
    SPDX-License-Identifier: Fair

Written on 2025-01-03.

Last modified: 20250406T0124+0200.
*/
import os
import strconv
import strings

fn input_int(prompt string) int {
    mut n := 0
    for {
        n = strconv.atoi(os.input(prompt)) or { continue }
        break
    }
    return n
}

fn main() {
    name := os.input('What is your name? ')
    println('Hello, ${name}.')
    for {
        stars := input_int('How many stars do you want? ')
        println(strings.repeat(`*`, stars))
        answer := os.input('Do you want more stars? ').trim_space()
        if answer.to_lower() !in ['ok', 'yeah', 'yes', 'y'] {
            break
        }
    }
}

Páginas relacionadas

Basics off
Metaproyecto sobre los proyectos «Basics of…».

Enlaces externos relacionados