0

this a program that work based on a specific algorithm. it works perfectly in java but whenever I run the html code i dont get error but it show me only the first three number while in java code the for loop continues until to show the whole numbers

Java code

 package test1;

  public class Test1
  {
  public static void main(String arg[])
   {
    int num = 1;
    counterA(num);
  }

  public static void counterA(int num)
   {       
     for (int i = num; i <= 24; i += 5)
     {
        System.out.println(i);
        counterB(i);
     }
 }

 public static void counterB(int i)
 {
    counterA(i * 3);
 }

}

HTML code

<script>

    var num1 ;
    counterA(num1);
    var total=0;
    var counterA=function(num11)
    {
        for (num1 = num11; num1 <= 24; num1 += 5)
        {
            console.log(num1);
            counterB(num1);
        }

    }

    var counterB =function (num11)
    {
        counterA(num11 * 3);
    }
 </script>

 <body>

<button onclick="counterA(1)">Try it</button>

 </body>

</html>
4
  • It returns 1, 3, 9. What is the expected output? Commented Feb 22, 2014 at 11:44
  • @krnk num1 is already declared Commented Feb 22, 2014 at 11:46
  • I've executed the Java code and this returns: 1 3 9 14 19 24 8 24 13 18 23 6 18 23 11 16 21 Commented Feb 22, 2014 at 11:49
  • I've created a working JSFiddle: jsfiddle.net/jEEL4 Commented Feb 22, 2014 at 11:53

3 Answers 3

1

You've a few mistakes in your code:

  1. You're calling a function before it is defined. Calling counterA before it's defined.
  2. You've to reset the counter num1 in the for loop

Possible option to make your code to work:

  1. Remove var num1 ; counterA(num1); var total=0;
  2. Replace for (num1 = num11; ... with for(var num1 = num11; ...
Sign up to request clarification or add additional context in comments.

Comments

1

Try this,

<!DOCTYPE html>
<html>

<script>

function counterA(num11)
{
   var num1;
    for (num1 = num11; num1 <= 24; num1 += 5)
    {
        alert(num1);
        counterB(num1);
    }
}

function counterB(num11)
{
    counterA(num11 * 3);
}
</script>

<body>

<button onclick="counterA(1)">Try it</button>

</body>

</html>

This is giving me output as 1, 3, 9, 14, 19, 24, 8, 24, 13, 18, 23, 6, 18, 23, 11, 16 and 21.

1 Comment

Great. You can accept my answer if it helped you and you find the solution. :)
0

You can do

<html>
<script type="text/javascript">
    function counterA(num11){
        for (var num1 = num11; num1 <= 24; num1 += 5) {
            alert(num1);
            counterA(num1*3);
        }
    }
</script>

<body>
    <button onclick="counterA(1)">Try me</button>
</body>

</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.