Examples of code for the top 10 programming languages:

Contents:
Introduction | Text Examples Input/Output (I/O): C, C++, Java | Python, PHP | Perl, Ruby, Shell | Basic | SmartPhones |
Code to run in/from Web browsers: Javascript | CGI (run on server)
Calculation: Determine Greatest Common Divisor (GCD)
Other: AJAX | Open a File | Class def | R statistical language


All of these languages except C# come with the Mac OS X system, so I don't talk about how to get and install them.

Introduction:
I finally did my own web pages on languages after the annual programming language shootout at ACGNJ didn't really compare languages.

I coded several examples and ran them on my Mac with the top 10 top languages except C# where you need a windows environment.
My copy of win 7 required you to download the C# development environment.

The examples I used are:
1. Text (String) Input/Output with a modified version of "Hello World" where I added input and variable storage.
Print "Hello World" is commonly used to make sure your software is set up to work with a new language.
I modified it to prompt "What is your name:", save it and then output "Hello <NAME>"
I created examples for the more popular languages, C, C++, Java, Python, PHP, Perl, Ruby, UNIX/Linux shell, BASIC, Visual Basic, Visual Basic .NET below.
See: Computer Programming/Hello world - Wikibooks - Print "Hello World" in 220 languages for others.

2. Numeric computation: The standard example used in academics to compare languages, Euclid's algorithm to determine the Greatest Common Divisor (GCD) of two numbers.
See GCD below for examples in C, Java, Javascript, Python,

3. Web browser interface
The above methods were for running the program stand alone.
It is common now for programs to be initiated from a web browser. This can be done with javascript within the browser or with an interface to a program run on a server that returns results to the browser.
See Code to run in/from Web browsers below.

4. I have a 4th example for database access in unix/linux shell (a flat file in this case). It includes more error checking (important) than the other examples.


Development - Run Environment:
They were developed on a Macintosh. Mac OS X 10.11 (El Capitan) which includes C, C++, Objective-C, Java, Ruby, Python, PHP, and Perl, compilers/interpreters as well as UNIX/Linux shell scripting and a Java Virtual Machine (JVM) (The Java Runtime Environment (JRE) contains the JVM).
The compiled object code for C and C++ runs on BSD UNIX, the underlying operating system for Mac OS X available thru the terminal application.
The Mac OS X runs on top of BSD UNIX and the terminal app which runs a shell in UNIX is used in some of the examples.
The interpreted languages, PHP, Perl, Python, and Ruby run on any computer with the interpreters for these.
The Python example shows how to download a Python interpreter for Android.
The Common Gateway Interface (CGI) examples run on a server and are initiated in browsers with forms, so can run almost anywhere.
The Java .class files will run on a Java Virtual Machine (JVM), which is included in most operating systems.
JavaScript is supported in most browsers (Internet Explorer, Edge, Chrome, Safari, Firefox, ...).


Text Examples - Modified Hello World examples:
Prompt for name and read it.
Print out "Hello name"
See programming environments below for Windows, Linux, ....

See Compiling and Running C, C++, Java, Python, ... on the Mac
 

in C (GCC 5.2.0)


/* Hello example in C */
#include <stdio.h>
int main(void) {
    char name[40];
    printf("Enter your name: ");
    scanf("%s", &name);
    printf("Hello %s \n", name);
    return 0;
}

Run it
In C++ (LLVM version 7.0.2)
// C++ example
#include <iostream>
#include <string>
int main()
{
 std::cout << "Please enter your name: ";
 std::string name;
 std::cin >> name;
 std::cout << "Hello" << name << std::endl;
return 0;
}

Run it
in Java [Version 8 (Update 73)]

Hello.class is bytecode.

import java.util.Scanner;
 class Hello {
     String name;
     
      Scanner in = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = in.nextLine();
            
          System.out.println("Hello " + name);
     }

Run it
See below for a Java Servlet
  
in Python (2.7.10)

# Hello example in Python
name = raw_input('Please enter your name: ')
print("Hello " + name)

# Simple python program for Android QPython3

import sl4a
droid = sl4a.Android()
name = droid.dialogGetInput('TTS' 'Please enter your name: ').result
print("Hello " + name)

Run it

In PHP (5.5.30)

<?php
/* Hello example in PHP */
$name = readline("Plese enter your name: ");
print("hello $name \n");
?>

Run it
See PHP: readline - Manual

In Perl 

print "Please enter your name:";
$name = <>;
print "Hello $name";

Run it

In Ruby

#!/usr/bin/ruby
print "Please enter your name: "
name = gets
puts "Hello #{name}"

Run it
See Input & output in Ruby

In UNIX/Linux shell

# - Comment line
#!/bin/bash 
echo -n "Please enter your name: "
read name
echo "Hello $name"

Run it
BASIC, developed at Dartmouth, is the old language I used in 1968 on a teletype terminal connected to a GE timesharing service.
Visual Basic, developed by Microsoft, was first released in 1991 and declared legacy in 2008. 
Visual Basic .NET was introduced in 2002.  Many people stuck with Visual Basic 6
 because Visual Basic .NET was a vastly different paradigm.
See Comparison of Visual Basic and Visual Basic .NET - Wikipedia
Visual basic is part of Microsofts Visual Studio 2015 
Stand alone Visual basic for Windows is available at microsoft-visual-basic.en.softonic.com/
Excel VBA (Visual Basic for Applications) is what is used to create macros in Excel.

In BASIC

10 REM Hello example in BASIC 
20 INPUT "Please enter your name: "; P$  
30 PRINT "Hello "; P$;
40 END

Run it - Go to Quite BASIC and
 Paste the above into 
 the BASIC Program window.
Then click the run button  

In Visual Basic

Module hello
 Sub Main()
  Dim name as String = Nothing
  Console.WriteLine ("Please enter your name:")
  name = Console.ReadLine()
  Console.WriteLine ("Hello " & name)
 End Sub
End Module
 

In Visual Basic .NET

Module hello
 Public Sub Main()
   Dim name As String
    Console.WriteLine("Please enter your name: ")
    name = Console.ReadLine()
    Console.WriteLine ("Hello " & name)
   End Sub
End Module

Note: In this simple example .NET
 is the same VB6
Code to Run in Web Browsers
JavaScript is designed to run in browsers.
JavaScript and Java are not related except for the name. JavaScript was developed by Netscape (now Mozilla), the browser developer; The Java programming language was developed by Sun Microsystems (now Oracle).
See Javascript and Java here.
AJAX uses JavaScript's XMLHttpRequest object to get data from the server.
Java applets were the old way to run java in a browser, but they are not implemented on mobile devices and other platfroms.
Note: Java developed by Sun Microsystems and JavaScript developed at Netscape have little in common accept the similar names.
CGI (Common Gateway Interface) is a way for web browsers to run programs like Perl, PHP and Python on a server. See CGI below.

Java Servlets or Server Side Java (SSJ) often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

  • Performance is significantly better.
  • Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.
  • Servlets are platform-independent because they are written in Java.
  • Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.
  • The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.
See Java servlet below.


in Javascript

<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Start</button>
<p id="demo"></p>

<script language="JavaScript">
function myFunction() {
    var person = prompt("Please enter your name", "");
    if (person != null) {
        document.getElementById("demo").innerHTML =
        "Hello " + person;
    }
}
</script>
</body>
</html>

Try it. | Another version | About javascript
Javascript with jQuery Library
The jQuery Library is a
 popular set of utilities to make coding in javaScipt easier.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Hello " + $("#name").val());
    });
});
</script>
</head>
<body>
<p>Please enter your name: <input type="text" id="name" value="" size="30"></p>
<button>Go</button>
</body>
</html>

Run it

jQuery and Angular are popular tool used with cJavascript
See Javascript tools.
 

A Java  Servlet or Server-side Java (SSJ) to display in a browser

See example
Also called server-side applets (SSA). SSJ is a powerful hybrid of the Common Gateway Interface (CGI) and lower-level server API programming.

See java web applications
How to get started with server-side Java | JavaWorld

Some more advanced programming can be done in HTML 5
CGI (Common Gateway Interface) CGI (Common Gateway Interface) is a standard way for web servers to interface with executable programs installed on a server that generate web pages dynamically or execute other code when called as http from your web browser.

On GoDaddy Perl (.cgi or .pl), PHP (.php) and Python (.cgi) are supported for cgi. Some platforms support Ruby also.
See Change file extension handlers/languages (Linux) | GoDaddy Help

Some hosting systems also support Ruby.
There are several ways to pass arguments from a web page to a cgi program.
1. QueryStrings following the url. e.g. https://donsnotes.com/pgms/hello-py.py?name=Don&age=over+the+hill
2. Forms with a POST or GET method.
   e.g. <FORM ACTION="https://donsnotes.com/pgms/hello-perl.cgi" METHOD="POST">
   Note: GET passes arguments as QueryStrings as in 1 above.
   POST sends data (name/value pairs)  in the HTTP message body
 See HTTP Methods GET vs POST | w3schools.com
 
The cgi file must be readable and executable by everyone. mode=755 (see chmod) This is typically done with the chmod (change mode) command available with ftp programs such as FileZilla on Windows or fetch on a Mac.
Some hosting systems require cgi programs to be in a cgi-bin directory/folder. They can be anywhere on GoDaddy.
See PHP vs Python
In Perl as a .CGI file

cgi program to read variable passed
via an html form with a POST method

#!/usr/bin/perl -w
use CGI qw(:standard);
use strict;
my $query = new CGI;
my $name = $query->param("name");
print $query->header("text/plain");
print "Hello $name \n";

Run it

In PHP 

<?php
 echo "Hello ". $_POST['person']. "<br>";
?>

Run it
In Python 

cgi program to read variable passed
via an html form with a POST method
Note: We could have skipped all the html code
and printed hello <person> as in the perl example

Simple version - print Hello person:
 
#!/usr/bin/python
# Import modules for CGI handling 
import cgi, cgitb 
# Create instance of FieldStorage 
form = cgi.FieldStorage() 
# Get data from fields
person = form.getvalue('person')
print "Content-type:text/html\r\n\r\n"
print "hello %s" % (person)

Fancy version # Send html back for a new web page so you can try it again. #!/usr/bin/python import cgi, cgitb form = cgi.FieldStorage() person = form.getvalue('person') print "Content-type:text/html\r\n\r\n" print """ <html> <head> <title>Hello - CGI Program</title> </head> <body> <P> <form action="/cgi-bin/hello-python1.cgi" method="post"> <label><b>Please enter your name</b></label> <input type="text" name="person" SIZE=30> <input type="submit" value="Submit" /> </form> <h2>Hello %s </h2> </body> </html>""" % (person) Run it See Other python cgi examples
AJAX (Asynchronous JavaScript and XML)
AJAX is a technology or technique for web browsers to communicate with servers not a programming language.
It refers to JavaScript's capability to use a built-in object, XMLHttpRequest, to communicate with a server without submitting a form or loading a page.
The name is a missnomer because XML is not required. AJAX can retrieve test, HTML, XML and JSON (Java Object Notation) files and can communicate with server-side scripts/programs like CGI, but without refreshing the web page.
Google, Amazon, Facebook and many social networking sites use AJAX.
See more about AJAX

Let AJAX change this text

This would not work in Chrome or Firefox on Mac OS X or Firefox on Win 7 use IE, Edge or the Safari browser.


An example with xml
The code

<!DOCTYPE html>
<html>
<body>

<div id="demo"><b>Let AJAX change this text</b></div>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}
</script>

</body>
</html>

ajax-demo.txt on the server contains:
<p><b>This text comes from the file ajax-demo.txt on the server</b></p>
Source: w3schools
Code for iPhones, iPad, Apple watch, Apple TV Code for Android phones and tablets
Objective-C  

import Foundation

var fh = NSFileHandle.fileHandleWithStandardInput()

println("What is your name?")
if let data = fh.availableData {
  var name = NSString(data: data, encoding: NSUTF8StringEncoding)
  println("Hello \(name)")
}
Swift 

//: Example in swift - Note I don't have Xcode,
 Apple’s integrated development environment (IDE), so haven't tried this

import Cocoa
import Foundation

func input() -> String {
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding: NSUTF8StringEncoding) as! String
} 

println("Please enter your name: ")
var Name = input()

func printPersonalGreeting(name: String){
    print("Hello \(name)")
  }
  
printPersonalGreeting(Name)
}

See: Start Developing iOS Apps (Swift): developer.apple.com
Adroid Studio
(This is incomplete)
<?xml version="1.0" encoding="utf-8" ?>
<resources>
   <string name="app_name">HelloWorld</string>
   <string name="hello_world">Hello world!</string>
   <string name="menu_settings">Settings</string>
   <string name="title_activity_main">MainActivity</string>
</resources>

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:padding="@dimen/padding_medium"
      android:text="@string/hello_world"
      tools:context=".MainActivity" />
</RelativeLayout>

EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();

Intent result = newIntent();
result.putExtra(EXTRA_MESSAGE, message);



See examples for Fortran and COBOL at Computer Programming | Victor Fay-Wolfe - Univ. of Rhode Island

Numeric calculation - Determine the Greatest Common Divisor (GCD) of two numbers.
Euclid's algorithm for GCD computation is not intuitive but it is frequently used to demonstrates a variety of operators in a language.
There are many other ways to do this computation.
see Greatest common divisor code in a bunch of languages- Rosetta Code
% is the remainder (modulus) operator,   e.g.12%5=2 i.e. 5x2=10 12-10=2
See Operators for others like ?, !=, +=, ++, ...
Iterative Algorithm - Uses looping statements such as for loop, while loop or do-while loop to repeat the same steps.
Recursive Algorithm - Will call itself with "smaller (or simpler)" input values.
in C
Iterative Euclid algorithm

int
gcd_iter(int u, int v) {
  int t;
  while (v) {
    t = u; 
    u = v; 
    v = t % v;
  }
  return u < 0 ? -u : u; /* abs(u) */
}

Recursive Euclid algorithm

int gcd(int u, int v) {
return (v != 0) ? gcd(v, u%v):u;
}
in Python
Iterative Euclid algorithm

def gcd_iter(u, v):
    while v:
        u, v = v, u % v
    return abs(u)
    
Recursive Euclid algorithm

def gcd(u, v):
    return gcd(v, u % v) if v else abs(u)
    
Run it
in Java
Iterative Euclid's Algorithm
//valid for positive integers.
public static int gcd(int a, int b) 
{
	while(b > 0)
	{
		int c = a % b;
		a = b;
		b = c;
	}
	return a;
}

Recursive
  private static int GCD(int number1, int number2) {
    if(number2 == 0){
     return number1;
     }
     return GCD(number2, number1%number2);
   }
Run it
  
Javascript:

Iterative implementation 

function gcd(x, y) {
	while (y != 0) {
		var z = x % y;
		x = y;
		y = z;
	}
	return x;
}

Recursive

function gcd_rec(a, b) {
  return b ? gcd_rec(b, a % b) : Math.abs(a);
}


Run it

Many of these operators were introduced with the C Language and exist in many other languages.

JavaScript Arithmetic Operators
   +, -, *, /  standard arithmetic operators
   %    Modulus (Remainder) 
  ++   Increment
  --   Decrement
  
JavaScript Assignment Operators
 Example    Same As
  x += y    x = x + y
  x -= y    x = x - y
  x *= y    x = x * y
  x /= y    x = x / y
  x %= y    x = x % y  modulo/remainder 

JavaScript Comparison
 and Logical Operators
Operator  Description
  ==     equal to
  ===    equal value and equal type
  !=     not equal
  !==    not equal value or not equal type
  
  ?   Ternary operator
  variable = condition ? value_if_true : value_if_false
  See JavaScript Operators at w3schools.com

Open a file
Examples from Python & Java: A Side-by-Side Comparison | Python Conquers The Universe

in Python

# open an input file
myFile = open(argFilename)
in Java

import java.io.*;
...

BufferedReader myFile =
    new BufferedReader(
        new FileReader(argFilename));

Define a class:
Your application has an Employee class. When an instance of Employee is created, the constructor may be passed one, two, or three arguments.

If you are programming in Java, this means that you write three constructors, with three different signatures. If you are programming in Python, you write only a single constructor, with default values for the optional arguments.

in Python

class Employee():

  def __init__(self,
    employeeName
    , taxDeductions=1
    , maritalStatus="single"
    ):

    self.employeeName  = employeeName
    self.taxDeductions = taxDeductions
    self.maritalStatus = maritalStatus
...
in Java

public class Employee
{
    private String myEmployeeName;
    private int    myTaxDeductions = 1;
    private String myMaritalStatus = "single";
    public Employee(String EmployeName)
    {
        this(employeeName, 1);
    }
    public Employee(String EmployeName, int taxDeductions)
    {
       this(employeeName, taxDeductions, "single");
    }
    public Employee(String EmployeName,
           int taxDeductions,
           String maritalStatus)
    {
       this.employeeName    = employeeName;
       this.taxDeductions   = taxDeductions;
       this.maritalStatus   = maritalStatus;
    }
...

UNIX/Linux Shell example for database lookup:

More complex example with I/O and file lookup:
It includes:
- logic (if-then)
- user interface - input output
- database (a flat file) query
It does not demonstrate advanced features necessary for producton commercial code.

I tried to get my C and Java friends to code a version of this in C and Java but no luck.

UNIX shell Is a command-line interpreter or shell that provides a traditional user interface for the Unix operating system and for Unix-like systems (e.g. linux).
Originally used with printing terminals, it now typically accessed by a terminal emulator on a graphical OS, using a command line interface (CLI) where users type commands and responds to querys, one line at a time.
Bash is a Unix shell written for the GNU Project to replace the Bourne shell (sh). The C Shell is another popular version.


# - Comment line
# - program to lookup email or phone in a flat file database
#!/bin/bash 
# This command has 1 argument, the file name ($1) for a flat file containing
# Name:Phone:Email:twitter
#
# check that file is specified and that it exists and is a regular file
if [ -z "$1" ] # Is 1st argument is null?
  then
    echo "Filename required"
    exit
elif [ -f "$1" ] # Does the file exist and is it a regular file
 then 
   echo "Lookup example"
 else
   echo "$1 does not exist or is not a regular file"
   exit
fi
# Get query type
echo -n "Lookup email or phone? Enter em or ph: "
read type
case $type in
   em* )
     field=3 ;;
   ph* )
     field=4 ;;
     * )
      echo "Got $type . expected em or ph."
      exit ;;
esac
# Get query name
echo -n "Enter Name:"
read name
# lookup name
if grep -i "^$name" $1 >/dev/null;  # Can you find the name 
then
  grep -i "^$name" $1 | awk -F':'  "{print \$1,"\t",\$$field;}" 
# Note: There are numerous way to perform the functions in the above line.
# The whole thing could be done in awk.  Sed could be used instead of awk. ...
# The above example demonstrates the pipe "|" sending the output of one command
#  to the input of another and regular expressions (^ = beginning of line)
else
   echo "$name not found"
   exit
fi
# grep - global regular expression parser
# awk -  Aho-Weinberger-Kernighan (The authors) A data extraction and reporting tool.
# -i = ignore case, ^ = beginning of line -F = field delimiter, \t = tab character
Notice that almost half the code is error checking. This is something sloppy programmers frequently forget. (In a production system the file name would be fixed, so would be checked in system testing not interactively.)
Commenting (#) is also something sloppy programmers forget.
Test file - contacts.txt
Name:Company:email:phone:twitter
Larry Page:Google:CEO@google.com:650 253-0000:
Larry Ellison:Oracle:CEO@oracle.com:800-633-0738:larryellison
Tim Cook:Apple:tcook@apple.com:408 974-2042:tim_cook
Mark Zuckerberg:Facebook:CEO@facebook.com:650-308-7300:finkd


A typical interaction is a follows:

Home$ lookup-ex contacts.txt (the name of the shell program and data file)
Lookup email
Lookup email or phone? Enter em or ph: ph
Enter Name: Larry Page
Larry Page  650 253 0000



PHP - originally stood for Personal Home Page, it now stands for PHP: Hypertext Preprocessor, PHP is a server-side scripting language designed for web development but, also used as a general-purpose programming language. A typical interface is with a form on a web page where the user enters information. The input data is sent to the php program on the server which returns some result. HTML for web page: Lookup Email or Phone<BR> <form action="" method="post"> Email <Input type = 'Radio' Name ='type' required value= 'email'>   Phone <Input type = 'Radio' Name ='type' required value= 'phone'> <BR> Name: <input type="text" name="name" size="40" maxlength="40" required value=""><BR> <input type="submit" value="submit"> </form>
What it looks like:
Lookup Email or Phone
Email   Phone
Name:

Programming Environments.
The examples here were developed on a Mac and some run on Godaddy's (where this site is hosted) linux host environment.

Microsoft Visual Studio 2015 which runs on Windows, includes Visual C#, Visual C++, Visual Basic, Node.js and Visual F#
See Windows Programming

See InstallingCompilers on Ubuntu Linux

Install Android Studio | Android Developers

Swift - Overview - Apple Developer (iPhone, iPad, Apple Watch,OS X,)

Links:
Stack Overflow - Help on programming
Programmers Stack Exchange - Help
Computer Programming/Hello world - Wikibooks print "Hello World" in 220 languages
PHP vs Python

last updated 15 Apr 2016