Maths and Computing
Home
Books
Mathematics
Binary
Computing
Coding
Information
Maths and Computing JavaScript Examples
This tool will run small JavaScript programs. It is essentially intended for use with the book "An Introduction to Mathematics for Computing and IT Practitioners". Click an entry on the right to select one of the book's code examples.
1.3.2: Working out the triangular numbers
2.3.1: Storing a vector in an array
2.3.2: Storing a matrix in an array
3.2.3: Multiplying two 2 by 2 matrices
5.3.2: Solving a simultaneous equation
6.4.2: Finding the minimum spanning tree
7.5.1: Calculating the nth term of a given sequence V1
7.5.2: Calculating the nth term of a given sequence V2
8.2.2: Quick Sort
9.6.3: Simulation Scenario 1
9.6.4: Simulation Scenario 2
11.1.5: Converting a decimal number to binary
11.5.3: Converting binary numbers to Gray code
13.4.3: Converting an 8-bit character to MIME Base 64
15.1.2: Calculating a sequence of prime numbers
15.2.3: Euclids Algorithm
15.3.2: Calculating the square root of a binary number
15.5.2: Working out the day of the week
<html>
<body>
<script type ="text/javascript"> <title>
Converting binary numbers to Gray code
</title>
</head>
<body>
<script type ="text/javascript">
var n = new Array(8); // Used for the binary number var g = new Array(8); // Used for the Gray code var p; // Digit Position var whole_num; // Current number for(val=0;val<255;val++) { // Set the values of the array n to 0 for(i=0; i<8; i++) { n[i] = 0; } p = 7; dec_num = val; // Convert the number to binary while(dec_num>0) { whole_num = Math.floor(dec_num/2); n[p--] = dec_num - whole_num*2; dec_num = whole_num; } // Calculate and display the Gray code value g[0] = n[0]; document.write(g[0]); for(i=1; i<8; i++) { if(n[i] != n[i-1]) g[i] = 1; else g[i] = 0; document.write(g[i]); } document.writeln("
"); }
</script>
</body>
</html>