0

Can someone explain me Break & Continue with example?

19th Nov 2016, 5:20 AM
ÇhĂȘtÀñ JĂąwĂ„lĂ«
ÇhĂȘtÀñ JĂąwĂ„lĂ« - avatar
3 Answers
+ 4
Well, it's not c++ (or may be it is), but who cares. Let's say you have some array of numbers. And you need to find sum of first two numbers by looping: Int[] arr = { 2, 5, 3, 7}; // array int sum = 0; // sum counter for (int i=0; i<arr.length; i++) // loop { // check if first two elements are processed already if (i > 1) break; // so we have to exit loop with break // otherwise we didn't process first two yet sum+=arr[i]; } Now we want to sum every array elements except 5 and 42, so we have to use continue: Int[] arr = { 2, 5, 3, 7}; // array int sum = 0; // sum counter for (int i=0; i<arr.length; i++) // loop { // check if current number from array is 5 or 42 if (arr[i] == 5 || arr[i] == 42) continue; // if it is then we have to skip this element and try next // otherwise just add to sum sum+=arr[i]; }
19th Nov 2016, 5:42 AM
Ivan G
Ivan G - avatar
+ 1
let me explain with an example. consider the loop, for(int i=0; i<10;i++) { if(i==5) continue; //code } when break is encountered in a loop, that Loop is completely terminated executing. in this condition, if value of i is 5, Loop should have terminated with break. But continue just terminates Loop "execution for that iteration". that is, whatever code is written inside Loop after continue, will be skipped. and loop will continue iteration for its next value. that is 6. hope im clear to you
19th Nov 2016, 5:31 AM
P Sandesh Baliga
P Sandesh Baliga - avatar
+ 1
Oh Thanks got It...
19th Nov 2016, 5:36 AM
ÇhĂȘtÀñ JĂąwĂ„lĂ«
ÇhĂȘtÀñ JĂąwĂ„lĂ« - avatar