In: Computer Science
What does break and continue mean in C++?
Break is a keyword used within a loop to abruptly exit from loop on a condition when holds true.
The condition can be anything as per the code requirement.
For example, add all the number and stop when user press -1.
So the code will be something like:
while(true)
{
cout<<"Enter a number ";
cin>>num;
if(num==-1) break; // Exit the loop
else
sum=sum+num;
}
___________________________________________________________
Continue keyword is used inside loop to go to next loop iteration if a certain condition holds true. Using continue keyword, all the statement after the keyword continue is ignored and loop goes to it's next iteration.
For example, add all positive integer entered by user.
for(int i=0; i<5;i++)
{
cout<<"Enter a number ";
cin>>num;
if(num<0) continue;
else sum+=num;
}
Now suppose user enters : 2 3 -6 1 -1
The sum will have value as : 6