+ 1
I really don't understand "break" and "continue"
please i need an example with explanation
2 Answers
+ 3
break statement :
a break statement is used to get out from the box you're in (for loop,while loop).
continue:
its used to skip the next code and repeat again
ex:
int x;
x=5;
for(int i=0;i<x;i++)
{
if(x==3)
continue;
System.out,println("hi");
}
this code will print hi 4 times since once is skipped !
for(int i=0;i<x;i++)
{
if(x==3)
break;
System.out,println("hi");
}
this code will print hi 3 times since when x is equal to 3 we go outside the loop
+ 2
"break" is a keyword which is used to break out of loops.
For example, consider a loop where you iterate over an array and you want to find a first negative number in that array. Now ideally you would want your loop to stop as soon as you find the first negative number in that array. For that, you use break keyword. Suppose we have an array of size 5.
for(int i=0; i<5; i++)
{
if(array[i] < 0)
{
//first negative value found, now break out of the loop
break;
}
}
"continue" is a keyword that is used to skip any iteration of your loop.
For example, Consider a case where you have an array of size 5. Suppose we want to add 2 in each element of the array but if there's a 0 in the array, we don't want to add 2 in that particular number. So what we would do is skip the iteration of our loop where it finds 0 in our array.
for(int i=0; i<5; i++)
{
if(array[i] == 0)
{
//0 value found, skip this iteration and move to the next one
continue;
}
else
{
array[i] += 2;
}
}
Note: These both keywords are mostly used with "for loops" but can also be used with other loops.