Skip to content

Latest commit

 

History

History
151 lines (142 loc) · 2.27 KB

13. break and continue.md

File metadata and controls

151 lines (142 loc) · 2.27 KB

13. break and continue

for loop without break Example

for (let i = 1; i <= 5; i++) {
    console.log(i);
}

Output

1
2
3
4
5

for loop with break Example

for (let i = 1; i <= 5; i++) {
    console.log(i);
    break;
}

Output

1

break with specific condition

for (let i = 1; i <= 5; i++) {
    if (i == 3) {
        break;
    }
    console.log(i);
}

Output

1
2

break with while

while (true) {
    let number = parseFloat(prompt("Enter a number: "));
    if (number < 0) {
        break;
    }
    console.log(number);
}

Output

Enter a number: 5
5
Enter a number: 9
9
Enter a number: -4
-4

continue Statement

for (let i = 1; i <= 5; i++) {
 
    if (i == 3) {
        continue;
    }

    console.log(i);
}

Output

1
2
4
5

break and continue with while

while (true) {
    let number = parseFloat(prompt("Enter a number: "));
    if (number < 0) {
        break;
    }
    if (number % 2 != 0) {
      continue;
    }

    console.log(number);
}

Output

Enter a number: 4
4
Enter a number: 9
Enter a number: 28
28
Enter a number: -34

Programming Task

Can you create a program that takes the input from the user. If the user enters a prime number, print the prime number. If the user enters a negative or non-prime number, ask the user for another number. And when the user enters a number greater than 100, terminate the loop.

Solution:

while (true) {
    let number = parseFloat(prompt("Enter a number: "));
    if(number > 100) {
        break;
    }
    
    let isPrime = true;
    for (let i = 2; i < number; i++) {
        if (number % i == 0) {
            isPrime = false;
            break;
        }
    }
    
    if (number < 0 || !isPrime) {
        continue;
    }
    
    else if (isPrime) {
    	console.log(number);
    }
}

Output

Enter a number: 5
Enter a number: 8
Enter a number: 11
Enter a number: 111
5
11

Programiz Quiz

Q. Which of the following keywords is used to terminate a loop?

  1. terminate
  2. break
  3. continue
  4. loop

Answer: 2