Home  • Programming • JavaScript

Loop examples in JavaScript

Code Solutions [4384]

INDEX

1. Print numbers from 1 to 50 2. Print numbers from 50 to 1 3. Print odd numbers from 1 to 20 4. Print even numbers from 1 to 20 5. Print numbers between 10 to 20 6. Print numbers between 10 to 20 except 13 and 17 7. Print numbers between 1 to 20 which are divisible by 4 8. Print 1+2+3+4+5+6+7+8+9+10 = 55 9. Print 1+3+5+7+9 = 25 10. Create a times table for 6 11. Find how many positive, negative, and zero numbers.

Problem 1: Print numbers from 1 to 50

Solution:
 for(i=1;i<=50;i++){
   document.write(i+" ");
 }

Problem 2: Print numbers from 50 to 1

Solution:
 for(i=50;i>=1;i--){
   document.write(i+" ");
 }

Problem 3: Print odd numbers from 1 to 20

Solution:
 for(i=1;i<=20;i=i+2){
   document.write(i+" ");
 }

Problem 4: Print even numbers from 1 to 20

Solution:
 for(i=2;i<=20;i=i+2){
   document.write(i+" ");
 }

Problem 5: Print numbers between 10 to 20

Solution:
 for(i=10;i<=20;i=i+1){
   document.write(i+" ");
 }

Problem 6: Print numbers between 10 to 20 except 13 and 17

Solution::
 for(i=10;i<=20;i=i+1){
   if(i==13 || i==17) continue;
   document.write(i+" ");
 }

Problem 7: Print numbers between 1 to 20 which are divisible by 4

Solution 1:
 for(i=4;i<=20;i=i+4){
   document.write(i+" ");
 }
Solution 2:
 for(i=4;i<=20;i=i+1){
    if(i%4==0)
    document.write(i+" ");
 }

Problem 8: Print numbers between 1 to 10 separated by + sign and add up the numbers as follows:

1+2+3+4+5+6+7+8+9+10 = 55 Solution:
var sum=0;
 for(i=1;i<=10;i++){
   document.write(i);
   if(i!=10)document.write("+");
   sum+=i;
 }
 document.write(" = "+sum);

Problem 9: Print odd numbers between 1 to 10 separated by + sign and add up the numbers as follows:

1+3+5+7+9 = 25 Solution:
var sum=0;
 for(i=1;i<=10;i=i+2){
   document.write(i);
   if(i!=9)document.write("+");
   sum+=i;
 }
 document.write(" = "+sum);

Problem 10: Create a times table for 6 as follows:

1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30 6 x 6 = 36 7 x 6 = 42 8 x 6 = 48 9 x 6 = 54 10 x 6 = 60 11 x 6 = 66 12 x 6 = 72 Solution:
for(i=1;i<=12;i++){
   
   document.write(i+" x 6 ="+6*i);
   document.write("<br/>");
       
 }

Problem 11: Find how many positive, how many negative and how many zero numbers from the following numbers

2,4,-9,5,-7,0,-5,0,3 Solution:
var data=[2,4,-9,5,-7,0,-5,0,3];

var p=0,n=0,z=0;
for(var d of data){
  
  if(d>0){
	 p++;  
  }else if(d<0){
	 n++;
  }else{
	 z++;  
  }//end if   	
}//end loop

document.write("Positive:"+p+"<br/>");
document.write("Negative:"+n+"<br/>");
document.write("Zero:"+z);

Comments 2


initialization  ki?
setting 1st value of any variable.

Share

Copyright © 2024. Powered by Intellect Software Ltd