Loop
Loops allow a block of code to run multiple times as long as a given condition is satisfied. They help reduce repetition and make programs more efficient and organized.
- Loops continue running until the condition becomes false.
- They are useful for iterating over arrays, strings, and ranges of values.
for Loop
- For Loops can execute a block of code a number of times.
- For Loops are fundamental for tasks like performing an action multiple times.
syntax
for (initialization; condition; increment/decrement)
{ // Code to execute}
Example
<!-- 1 1 1 1 1 -->
<script>
for(let a=1; a<=5; a++){
console.log(1);
}
</script>
<!-- 1 2 3 4 5 -->
<script>
for(let b=1; b<=5; b++){
console.log(b);
}
</script>
<!-- 1 3 5 7 9 -->
<script>
for(let c=1; c<10; c+=2){
console.log(c);
}
</script>
<!-- 3 6 9 12 15 -->
<script>
for(let d=1; d<=15; d++){
if(d%3==0){
console.log(d);
}
}
</script>
<!-- Multiples of 3 and 5 -->
<script>
for(let e=1; e<=50; e++){
if(e%3==0 && e%5==0){
console.log(e);
}
}
</script>
<!-- Multiples of 3 or 5 -->
<script>
for(let f=1; f<=20; f++){
if(f%3==0 || f%5==0){
console.log(f);
}
}
</script>
<!-- Divisors of given number -->
<script>
let gN=50;
for(let g=1; g<=gN; g++){
if(gN%g==0){
console.log(g);
}
}
</script>
<!--count of Divisors of given number -->
<script>
let hN=50;
let count=0;
for(let h=1; h<=hN; h++){
if(hN%h==0){
count++;
}
}
console.log("count:" +count);
</script>
<!-- prime number -->
<script>
let iN=10;
let countt=0;
for(let i=1; i<=iN; i++){
if(iN%i==0){
countt++;
}
}
if(countt==2){
console.log("prime");
}
else{
console.log("not prime");
}
</script>

Top comments (0)