Introduction: Compare 13 programming languages through a simple little game.
The number of words in this article: 6070, the reading time is about 7 minutes
When I start learning a new programming language, I focus on defining variables, writing declarations, and evaluating expressions, and once I have a general understanding of these concepts, I can usually figure out the rest on my own. Most programming languages have similarities, so if you have mastered one programming language, the point of learning the next language is to figure out the unique concepts and distinguish the differences.
I like to write test programs to help practice new programming languages. Among them, what I often write is a small game called “guess the number”. The computer chooses any number from 1 to 100, and then I guess. The program loops until the correct number is guessed. As you can see from the pseudocode, this is a very simple program:
◈ The computer picks a random number between 1 and 100
◈ Loop until the random number is guessed
◈ The computer reads my guess
◈ Tell me if my guess is too high or too low
We published some articles writing this program in different languages. This is an interesting opportunity to compare different languages doing the same thing. Most programming languages share similarities, so when you’re learning the next new programming language, it’s mostly about its uniqueness.
Created by Dennis Ritchie at Bell Labs in 1972, C is an early general-purpose programming language. The C language was very popular and quickly became the standard programming language on Unix systems. It is because of its popularity that many other programming languages have adopted a similar programming syntax. That’s why it’s easier to learn C++, Rust, Java, Groovy, JavaScript, awk, or Lua if you already know how to program in C.
Next we look at how these different programming languages implement the main steps of the “number guessing” game. I’ll focus on the similarity or difference of the basic elements, skipping some peripheral code like assigning temporary variables.
The computer picks a random number between 1 and 100
You can see many similarities here. Most programming languages use functions like rand()
where you can set a range to generate random numbers. And some other languages use a special function to set the range to generate random numbers.
C:
-
// Using the Linux `getrandom` system call
-
getrandom(&randval, sizeof(int), GRND_NONBLOCK);
-
number = randval % maxval + 1;
-
// Using the standard C library
-
number = rand() % 100 + 1;
C++:
-
int number = rand() % 100+1;
Rust:
-
let random = rng.gen_range(1..101);
Java:
-
private static final int NUMBER = r.nextInt(100) + 1;
Groovy:
-
int randomNumber = (new Random()).nextInt(100) + 1
JavaScript:
-
const randomNumber = Math.floor(Math.random() * 100) + 1
awk:
-
randomNumber = int(rand() * 100) + 1
Lua:
-
number = math.random(1,100)
loop until I guess that random number
Loops are usually implemented with control flow, such as while
or do-while
. The implementation in JavaScript does not use a loop, but updates the HTML page “in real time” until the user guesses the correct number. Although Awk supports loops, it makes no sense to read input information through loops, because Awk is based on data pipes, so it reads input information from a file instead of directly from the user.
C:
-
do {
-
…
-
} while (guess != number);
C++:
-
do {
-
…
-
} while ( number != guess );
Rust:
-
for line in std::io::stdin().lock().lines() {
-
…
-
break;
-
}
Java:
-
while ( guess != NUMBER ) {
-
…
-
}
Groovy:
Lua:
-
while ( player.guess ~= number ) do
-
…
-
end
The computer reads my guess
Different programming languages handle input differently. For example, JavaScript reads values directly from HTML forms, while Awk reads data from data pipes.
C:
C++:
Rust:
-
let parsed = line.ok().as_deref().map(str::parse::<i64>);
-
if let Some(Ok(guess)) = parsed {
-
…
-
}
Java:
-
guess = player.nextInt();
Groovy:
-
response = reader.readLine()
-
int guess = response as Integer
JavaScript:
-
let myGuess = guess.value
Awk:
Lua:
-
player.answer = io.read()
-
player.guess = tonumber(player.answer)
Tell me to guess too high or too low
In these C-like languages, the comparison is usually done through an if
statement. There are some variations in the way each programming language prints output, but the print statements are recognizable in each sample.
C:
-
if (guess < number) {
-
puts("Too low");
-
}
-
else if (guess > number) {
-
puts("Too high");
-
}
-
…
-
puts("That's right!");
C++:
-
if ( guess > number) { cout << "Too high.\n" << endl; }
-
else if ( guess < number ) { cout << "Too low.\n" << endl; }
-
else {
-
cout << "That's right!\n" << endl;
-
exit(0);
-
}
Rust:
-
_ if guess < random => println!("Too low"),
-
_ if guess > random => println!("Too high"),
-
_ => {
-
println!("That's right");
-
break;
-
}
Java:
-
if ( guess > NUMBER ) {
-
System.out.println("Too high");
-
} else if ( guess < NUMBER ) {
-
System.out.println("Too low");
-
} else {
-
System.out.println("That's right!");
-
System.exit(0);
-
}
Groovy:
-
if (guess < randomNumber)
-
print 'too low, try again: '
-
else if (guess > randomNumber)
-
print 'too high, try again: '
-
else {
-
println "that's right"
-
break
-
}
JavaScript:
-
if (myGuess === randomNumber) {
-
feedback.textContent = "You got it right!"
-
} else if (myGuess > randomNumber) {
-
feedback.textContent = "Your guess was " + myGuess + ". That's too high. Try Again!"
-
} else if (myGuess < randomNumber) {
-
feedback.textContent = "Your guess was " + myGuess + ". That's too low. Try Again!"
-
}
Awk:
-
if (guess < randomNumber) {
-
printf "too low, try again:"
-
} else if (guess > randomNumber) {
-
printf "too high, try again:"
-
} else {
-
printf "that's right\n"
-
exit
-
}
Lua:
-
if ( player.guess > number ) then
-
print("Too high")
-
elseif ( player.guess < number) then
-
print("Too low")
-
else
-
print("That's right!")
-
os.exit()
-
end
What about non-C-like programming languages?
Non-C-like programming languages will be very different and require learning specific syntax to complete each step. Racket comes from Lisp and Scheme, so it uses Lisp prefixes and lots of parentheses. Python uses spaces instead of parentheses to denote blocks like loops. Elixir is a functional programming language with its own syntax. Bash is based on the Bourne shell in Unix systems, which itself borrows from Algol68 and supports additional shorthand characters such as &&
as a variant of and
. Fortran was created at a time when punched cards were used to enter code, so it relied on an 80-column layout for some important columns.
I will illustrate the differences between these programming languages by comparing if
statements. if
determines whether one value is less than or greater than another value and prints the appropriate information to the user.
Racket:
-
(cond [(> number guess) (displayln "Too low") (inquire-user number)]
-
[(< number guess) (displayln "Too high") (inquire-user number)]
-
[else (displayln "Correct!")]))
Python:
-
if guess < random:
-
print("Too low")
-
elif guess > random:
-
print("Too high")
-
else:
-
print("That's right!")
Elixir:
-
cond do
-
guess < num ->
-
IO.puts "Too low!"
-
guess_loop(num)
-
guess > num ->
-
IO.puts "Too high!"
-
guess_loop(num)
-
true ->
-
IO.puts "That's right!"
-
end
Bash:
-
[ "0$guess" -lt $number ] && echo "Too low"
-
[ "0$guess" -gt $number ] && echo "Too high"
Fortran:
-
IF (GUESS.LT.NUMBER) THEN
-
PRINT *, 'TOO LOW'
-
ELSE IF (GUESS.GT.NUMBER) THEN
-
PRINT *, 'TOO HIGH'
-
ENDIF
More
The “Guess the Number” game is a friendly introductory program when you’re learning a new programming language, practicing several common programming concepts in an easy way. Implementing this simple game in different programming languages allows you to understand some of the core concepts and details of each language.
Learn how to write a “number guessing” game in C and C-like languages:
◈ C
opensource.com
, Jim Hall
◈ C++
opensource.com
, Seth Kenlon
◈ Rust
opensource.com
, Moshe Zadka
◈ Java
opensource.com
, Seth Kenlon
◈ Groovy
opensource.com
, Chris Hermansen
opensource.com
, Mandy Kendall
◈ awk
opensource.com
, Chris Hermansen
◈ Lua
opensource.com
, Seth Kenlon
other languages:
◈ Racket
opensource.com
, Cristiano L. Fontana
◈ Python
opensource.com
, Moshe Zadka
◈ Elixir
opensource.com
, Moshe Zadka
◈ Bash
opensource.com
, Jim Hall
◈ Fortran
opensource.com
, Jim Hall
via: https://opensource.com/article/21/4/compare-programming-languages
Author: Jim Hall Topic: lujun9972 Translator: VeryZZJ Proofreading: wxy
This article is compiled by the original, and launched with honor
The text and pictures in this article are from Linux China
This article is reprinted from https://www.techug.com/post/how-different-programming-languages-accomplish-the-same-thing-linux-china/
This site is for inclusion only, and the copyright belongs to the original author.