+ 1
If statement question in c++
can we write break in if statement like this? if(x>2){ break; } if yes, pls explain why it can, thx for answering this
19 Answers
+ 9
@gurprit...I know...this code is for logic and for understanding...
+ 9
yup..this 2 statements are only for loops(do while,while,for)..i checked..and got error with if else ladder...Thanks gurpreet
+ 8
i=0
if(i<2)
{
printf("%d ",i)
i++
continue;
}
else
{
printf("no")
break;
}
output : 0 1
note that if i take i= 5 than output will be "no"...
perhaps this will help all
+ 7
by using break statement..you can break your loop and jump outside it...
but by using continue..you can go to the loop condition again..
+ 2
@Prahar pandya thx for your answer ☺☺, but u miss your int in first line
+ 2
yes you can write like that but only when you are inside a loop...
e.g-
for(i=0;i<5;i++)
{ if(i>2)
break;
else
//something else
}
+ 2
Break can be written but it is used to break out of a nearest enclosed loop. So if the if statement is inside a loop then break is used to break out of that loop. Otherwise break would produce an error if used like you have used without any loop present.
+ 1
this if statement should be inside a loop to use break statement.
break and continue are for manipulating loop iterations
+ 1
@Gurpreet Singh means I can use break in if statement if the if statement are in a loop, and the break is use for the loop terminate like this?
for(;;){
if(x>2){
break;
}
}
+ 1
@Emi, thats correct
+ 1
@Gurpreet Singh thx 😊😊
+ 1
chk this code
https://code.sololearn.com/ct71CJU0dunX/?ref=app
+ 1
@Prahar pandya can u help explain how the continue keyword works with more details? I don't know this very well 😫😫
+ 1
break ends the loop.
continue skips the remaining statements only for that iteration
+ 1
@Gurpreet Singh thx for your answer again 😆😆
+ 1
@Prahar pandya, have you executed this?
this will give error.
+ 1
@Gurpreet Singh what's cause an error on his code? is it only miss a int? or other place? I don't know c so much 😅😅
+ 1
@Prahar pandya thx anyway 😊😊
+ 1
@Prahar pandya, just execute it and you will ger it or run my code.
Bottom line: you cant use break and continue without loop.