473,473 Members | 1,933 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to create a Factorials Table with JavaScript, HTML5 and CSS

94 New Member
Hello, everyone. In this article, I'll show you a way to print a table of the factorials of the integers in the range 0-20. Please note there is no warranty when it comes to using the code here presented. We'll be using JavaScript, HTML5 and CSS. To learn more about factorials, check this link: http://en.wikipedia.org/wiki/Factorial.

The factorial of a positive integer n (n >= 1) is given by the product n * ( n - 1 ) * ( n - 2 ) * ... * 1, where the multiplication by 1 can be omitted because it won't make a difference in our implementation. Also, the factorial of 0 is defined to be 1. The whole code will be shown first, and then we'll walk through it:

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html>
  2.  
  3. <html lang="en">
  4.     <head>
  5.         <title>Factorials Table</title>
  6.         <meta charset="utf-8">
  7.         <!-- CSS styling: -->
  8.         <style type="text/css">
  9.             table
  10.             {
  11.                 border-spacing: 0;
  12.                 font-family: Consolas;
  13.                 font-size: 1.2em;
  14.                 text-align: right;
  15.             }
  16.         </style>
  17.         <!-- JavaScript code: -->
  18.         <script>
  19.             var n;
  20.  
  21.             /* Starts table: */
  22.             document.writeln( "<table>" );
  23.  
  24.             /* Table's head section: */
  25.             document.writeln( "<thead style='background-color: red; color: yellow'>" );
  26.             document.writeln( "<tr>" );
  27.             document.writeln( "<th>n</th>" );
  28.             document.writeln( "<th>n!</th>" );
  29.             document.writeln( "</tr>" );
  30.             document.writeln( "</thead>" );
  31.  
  32.             /* Table's body section: */
  33.             document.writeln( "<tbody>" );
  34.             for ( n = 0 ; n <= 20 ; ++n )
  35.             {
  36.                 if ( n % 2 == 0 ) /* Starts new row with black background and white font: */
  37.                 {
  38.                     document.writeln( "<tr style='background-color: black; color: white;'>" );
  39.                 }
  40.                 else /* Starts new row with blue background and yellow font: */
  41.                 {
  42.                     document.writeln( "<tr style='background-color: blue; color: yellow;'>" );
  43.                 }
  44.  
  45.                 /* First column of the current row: */
  46.                 document.writeln( "<td>" + n + "</td>" );
  47.  
  48.                 /* Second column of the current row: */
  49.                 document.writeln( "<td>" + factorial( n ) + "</td>" );
  50.  
  51.                 /* Finishes current row: */
  52.                 document.writeln( "</tr>" );
  53.             }
  54.             document.writeln( "</tbody>" );
  55.  
  56.             /* Finishes table: */
  57.             document.writeln( "</table>" );
  58.  
  59.             /* Calculates n!: */
  60.             function factorial( n )
  61.             {
  62.                 var counter;
  63.                 var fact = 1;
  64.  
  65.                 if ( n < 0 ) /* Invalid argument to function factorial. */
  66.                 {
  67.                     return -1;
  68.                 }
  69.                 else
  70.                 {
  71.                     if ( n >= 1 )
  72.                     {
  73.                         for ( counter = 2 ; counter <= n ; ++counter )
  74.                         {
  75.                             fact *= counter;
  76.                         }
  77.                     }
  78.  
  79.                     return fact;
  80.                 }
  81.             }
  82.         </script>
  83.     </head>
  84.  
  85.     <body></body>
  86. </html>
Line 1 specifies the !DOCTYPE of the page; in this case, we specify html, which means the page is (supposed to be) HTML5.
<!DOCTYPE html>


Line 3 starts the html tag,
<html lang="en">


Line 86 closes the HTML tag
</html>


Lines 4 through 83 specify the head element of the page.
<head>
. . . . .
</head>


Line 5 specifies the title of the page.
<title>Factorials Table</title>


Line 6 specifies the character encoding used.
<meta charset="utf-8">

Lines 8-16 specify the styling of the page. In this page, we only style the table element as follows: the spacing in the border is chosen to be 0; the font-family is Consolas, but we could have specified more fonts in case the user doesn't have such font; the font-size is chosen to be 1.2em; and, finally, the text is chosen to be aligned to the right inside each cell of the table. More characteristics of the style are specified with inline styles through the JavaScript code, as we'll see soon.
Expand|Select|Wrap|Line Numbers
  1. <style type="text/css">
  2.             table
  3.             {
  4.                 border-spacing: 0;
  5.                 font-family: Consolas;
  6.                 font-size: 1.2em;
  7.                 text-align: right;
  8.             }
  9.         </style>
  10.  
Lines 18-82 contain the JavaScript code to perform the calculations and output of the table. Let's start with the factorial function, defined in lines 60-81. This function starts by declaring variables counter and fact; fact is initialized with the value 1, and counter will vary from 2 to n (the function's only parameter whose factorial is desired to be calculated) in case fact needs to change (it won't if n<= 0). Lines 65-68 check whether n is negative, and, if so, make the function return -1 to indicate that it received an invalid, nonpositive integer as argument. This won't happen on our page, but it is importante to have error-checking in industrial-strength code. Lines 69-80 are used if n >= 0. If n is 0, then fact should remain 1, and no calculations are performed. Otherwise, lines 73-76 calculate the factorial of n. Notice that counter starts at 2 - it would be unnecessary for us to multiply fact by 1. Line 79 returns the result.

As for the rest of the code, we have as follows. Line 19 contains the declaration of n - the variable whose factorial will be calculated. It will vary from 0 to 20. Line 21 output the markup for the beginning of the table, finished in line 57. Lines 25-30 output the table's head section, 33-53 output the table's body, calling function factorial for each value of n.
May 8 '14 #1
0 9075

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Swartz | last post by:
Hi all. I'm building a development webserver (redhat-based). I'm trying to compile PHP (v4.3.4 if anyone cares) with all the features I might require in the near future. I've ran into a problem...
9
by: Phil Powell | last post by:
I am producing a form using PHP on the back end and Javascript on the front end. The resulting script will come to the browser as follows: <script> <!-- function selectAll() { moveElement =...
6
by: Liza | last post by:
Dear all, can you please tell me how i can get information from a form filled in by a user at my website to my e-mail inbox? are there alternative ways of retrieving information enter by users...
54
by: tshad | last post by:
I have a function: function SalaryDisplay(me) { var salaryMinLabel = document.getElementById("SalaryMin"); salaryMinLabel.value = 200; alert("after setting salaryMinLabel = " +...
11
by: surya | last post by:
hello sir, i have a table emp ,it has three fields one is empno int ,second is ename varchar(20). and last is salary , emp empno ename salary ----------- ------------...
21
by: petermichaux | last post by:
Hi, I've been asking questions about library design over the last week and would like to get feedback on my overall idea for a JavaScript GUI library. I need a nice GUI library so there is a...
3
by: Kirk | last post by:
Let me start by saying that I am a complete idiot when it comes to JS. However, I need help with something that apparently can only be done this way. I am using an ASP.NET AJAX control...
11
by: priyapratheep | last post by:
Hi friends, I am strugging with this problem.I don't know much javascript. Please you gurus can help me. My problem is I cloned the frist row in a table.after cloning i want to change the names...
15
by: Sampat | last post by:
Hi, I wanted to know the performance of calling a function pointer v/s a normal function call in javascript in a scenario where there are multiple calls in the js to the same function. Please...
8
by: falconsx23 | last post by:
Hi,I want to create a coke machine that distributes cans with the cost of one token. All the cans in the coke machine coast the same. When a token is inserted, one can drops out. The coke machine...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.