When will the ‘break’ and ‘continue’ statements be used in programme? Mention the scenario and write the programme to demonstrate this.
#include<iostream>
using namespace std;
/*Break and continue are known as jump statements because they are generally used
to change or manipulate the regular flow of the program, loops, etc. when a particular
condition is met.
The break statement is used to terminate the execution of the current loop.
Whenever there is a need to end the loop, you need to add the break statement.
Once the break statement is met, all the iterations are stopped, and the control
is shifted outside the loop.
The continue statement is used to move to the next iteration, it is also used for
termination, but unlike break, it is not used to terminate the entire execution of
the loop but only the current iteration of the loop.*/
int main()
{
//Make a program, that ask user to enter a value and count sum
//of all even numbers from 0 to value
int value;
cout<<"Please, enter a value: ";
cin>>value;
double sum=0;
for(int i=value;;i--)
{
if(i==0)
break;//break from loop
else if(i%2==1)
continue;//jump to the next iteration
else
sum+=i;
}
cout<<"Summ of all even numbers from 0 to "<<value<<" is "<<sum;
}
Comments
Leave a comment