Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display each set of 3 numbers on a new line separated by commas

Tags:

javascript

I need a JavaScript code that generates 3 numbers between 1 and 10 one hundred times.It should display each set of 3 numbers on a new line separated by commas, and also display the total number of times the generated numbers were equal to 7 (also on a separate line). An example output should be formatted as follows: Number set 1 is: 10,7,8 Number set 2 is: 5,1,7 The code I have for some reason is not working

<html>
<head>
  <title>Day 3 - Example 7</title>
</head
<body>

 <script language="javascript">
   // count number of times seven was generated
   var i,num,n,num1,num2,cnt=0;
   n=100;
   for( i=1; i<=n; i++){
       num = Math.floor(Math.random()*10+1);
       num1 = Math.floor(Math.random()*10+1);
       num2 = Math.floor(Math.random()*10+1);
       document.write("Number Set " +i+ is + num,+ num1, +num2);

       if (num == 7) {
           cnt++;
      > }
   }
   document.write("<br>Total number of Sevens: " + cnt);

 </script>
</body>
</html 
like image 889
Carlos Avatar asked Apr 08 '17 00:04

Carlos


1 Answers

The code you posted seems right based on your description save for a couple of minor errors. I have cleaned it up and made it runnable right here in Stack Overflow.

var i, num, n, num1, num2, cnt = 0;
n = 100;
for (i = 1; i <= n; i++) {
  num = Math.floor(Math.random() * 10 + 1);
  num1 = Math.floor(Math.random() * 10 + 1);
  num2 = Math.floor(Math.random() * 10 + 1);
  console.log("Number Set", i, "is", num, num1, num2);
  if (num == 7) {
    cnt++;
  }
}
console.log("<br>Total number of Sevens: " + cnt);

Note: When you use + between a string and a number as you have done, the number will be converted into a string and then the two strings will be appended. Comma (,) will append the values separated by spaces. I used commas throughout to make it clear and consistent. I also spaced things out a bit for readability and used console.log so we can see the result of the formatting changes.

like image 174
jakeehoffmann Avatar answered Sep 30 '22 17:09

jakeehoffmann