Helllo, could you please tell me an example where break statement is used logically in a loop.
Doubt in break statement
hello @yashsharma4304
consider this code
#include <iostream>
using namespace std;
int main(){
int num =10;
while(num<=200) {
cout<<"Value of num is: "<<num<<endl;
if (num==12) {
break;
}
num++;
}
cout<<"Hey, I'm out of the loop";
return 0;
}
output:
Value of num is: 10
Value of num is: 11
Value of num is: 12
Hey, I’m out of the loop
In the above example , we have a while loop running from 10 to 200 but since we have a break statement that gets encountered when the loop counter variable value reaches 12, the loop gets terminated and the control jumps to the next statement in program after the loop body.
But why do we use it. Why someone wants to break he loop that he/ she has made. I mean what is it’s requirements or necessity.
ok so consider these examples.
this might make sense.
a)
while(t--){
int n;
cin>>n; // reading size of array
if(n<=0) // as negative size cant be possible, in such scenario we need to break otherwise our program will crash
break
int a[n];
}
b)
#include <iostream>
using namespace std;
int main(){
int num=2;
switch (num) {
case 1: cout<<"Case 1 "<<endl;
break;
case 2: cout<<"Case 2 "<<endl;
break;
case 3: cout<<"Case 3 "<<endl;
break;
default: cout<<"Default "<<endl;
}
cout<<"Hey, I'm out of the switch case";
return 0;
}
Output:
Case 2 Hey, I’m out of the switch case
In this example, we have break statement after each Case block, this is because if we don’t have it then the subsequent case block would also execute. The output of the same program without break would be:
Case 2
Case 3
Default
Hey, I’m out of the switch case
Ok so as you gave me these examples now I am able to understand the use of break statement. But in example (a) can we give stopping condition n%7==0 inside the loop itself where we have given the condition of t–. I mean the work which this break statement is doing can we do it by giving some conditions in while loop with t–.
while(t–){
int n;
cin>>n; // reading size of array
if(n<=0) // as negative size cant be possible, in such scenario we need to break otherwise our program will crash
break
int a[n];
}
@yashsharma4304
t is number of test cases u want to run
whereas n is size of array for a particular test case so how can we put n is place of t? we cant they are not related at all
Ok so we can not two different conditions inside loop. At a time only one condition can be put?
no we can put any number of condiitons inside loop but it all depends on situation.
in above example we cant put more than one condition .
when u will do some practice questions u will get more clarity
Ok. I will try more questions. Thank you for your assist.