In C

Two standard libraries are imported. Inside the main() function the printf() function is run, calling the rand() function, which is given as the string to print. A return value of 0 tells the program to exit.

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
printf(" %d ", rand());
return 0;
}


In C++

Two standard libraries are imported, and a namespace is established. Inside the main() method, an integer variable is given the value of a random number between 1 and 100. This is then sent to the standard output stream. A return value of 0 tells the program to exit.

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
int r = (rand() % 100) + 1;
cout << r << " ";
return 0;
}


In Java

A class is named, and designated available in any scope. Inside it is the main() method, which contains a call to println().

This code would be saved as a .java file, and run in a console environment.

public class RandomNumber {
public static void main(String[] args) {
System.out.println((int) (Math.random() * 100));
}
}


In JavaScript

The browser, running the JavaScript, will run the randomNumber() method once the button is clicked. That method selects the element with the id jsTest (which is the <p>) and initializes a variable with its (empty) value. A random number between 1 and 100 is then assigned to its innerHTML property. This changes the content of that element.

<html>
<head>
<title>JavaScript Test</title>
</head>
<body>
<button onclick="randomNumber()">Go</button>
<p id="jsTest"></p>
<script>
function randomNumber() {
    var x = document.getElementById("jsTest")
    x.innerHTML = Math.floor((Math.random() * 100) + 1);
}
</script>
</body>
</html>


In PHP

Before the HTML is processed, the server processes the PHP. It does this because the .php file extension is used. The echo() function prints a random number between 1 and 100 in the body of the (blank) HTML document.

<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo rand(1, 100); ?>
</body>
</html>


In Python

The code is saved as a text file with a .py extension, then run in a console environment.

import random
print random.randint(1,101)
There are no comments on this page.
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki