473,396 Members | 1,833 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,396 developers and data experts.

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

94 64KB
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 9068

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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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,...

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.