JavaScript 1 Write a loop that outputes the even numbers fro
JavaScript
1.) Write a loop that outputes the even numbers from 2 to x. (Assume x is larger than 2)
2.) Write code that countes the number of times a digit(i.e. one of the characters \'0\',\'1\'...\'9\' )occurs in a string named silly.(assume string exists and contains non empty string)
Solution
Question 1:
<html>
 <head>
 <title>
 Problem 3
 </title>
 <script type=\"text/javascript\">
 function calculate(){
 x = parseInt(prompt(\"Enter the number: \"));
 document.write(\"Even numbers are: \"+\"<br> \");
 for(var i=2; i<=x; i+=2){
    document.write(i+\" \");
 }
}
 </script>
 </head>
 <body onload=calculate()>
</body>
 </html>
Output:
Even numbers are:
 2 4 6 8 10 12 14 16 18 20
Question 2:
<html>
 <head>
 <title>
 Problem 3
 </title>
 <script type=\"text/javascript\">
 function calculate(){
var array = [0,0,0,0,0,0,0,0,0,0];
 var silly = prompt(\"Enter the string: \");
 for(var i=0; i<silly.length; i++){
    if(silly[i] >= \'0\' && silly[i]<=\'9\'){
    var n = parseInt(silly[i]);
    array[n]++;
    }
 }
 for(var i=0; i<array.length; i++){
    document.write(i+\": \"+array[i]+\"<br>\");
 }
 }
 </script>
 </head>
 <body onload=calculate()>
</body>
 </html>
Output:
Enter a string: sss12340890776545670122erfgg
0: 3
 1: 2
 2: 3
 3: 1
 4: 2
 5: 2
 6: 2
 7: 3
 8: 1
 9: 1


