Lecture 17
Lecture 17
Introduction
• break
• continue
We will study their meaning and how to use these special
statements inside the while-statement
How Break Statement works?
The break statement
• Syntax:
break;
Effect:
• When the break statement is executed inside a loop-
statement, the loop-statement is terminated immediately
• The execution of the program will continue with the statement
following the loop-statement
• The break statement is almost always used
with if...else statement inside the loop.
The break statement (cont.)
• Schematically:
Write a program to calculate the sum of
numbers (max 10 numbers) . If the user enters a
negative number loop terminates.
Example 1:
Example 1:
Output:
Example 2:
Example 2:
Write a program to determine whether a
number is prime or not. A prime number is
one, which is divisible only by 1 or itself.
Write a program to determine whether a number is prime or
not. A prime number is one, which is divisible only by 1 or itself.
• Input: x = 24 and y = 16
• Output: 8
Programming example using the break
statement: find the GCD (cont.)
• What would you do to solve this problem ?
• Suppose: x = 24 and y = 16
• The lesser of the values is 16
• Therefore, all divisors are ≤ 16
Programming example using the break
statement: find the GCD (cont.)
• Check if 16 and 24 are divisible by 16: no
• Check if 16 and 24 are divisible by 15: no
• ...
• Check if 16 and 24 are divisible by 10: no
• Check if 16 and 24 are divisible by 9: no
• Check if 16 and 24 are divisible by 8: YES
• Syntax:
continue;
The continue statement (cont.)
• As given previously:
• Schematically:
Example: Continue
Example: Continue
Example
Example
Example 2: continue statement
Example 2: continue statement
Output:
Programming example using the continue
statement: find all divisors of a number
• Problem description:
Output:
Return statement
Problem Statement
Write a program to generate all prime numbers
between 1 to 1000
Write a program to generate all prime numbers between
1 to 1000