Which is better practice - for loop with break or conditional loop? [closed] - loops

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm just curious what peoples' thoughts are on this topic. Let's say I have an Array of Objects, and I want to loop through them to see if the Objects contain certain values, and if so, I want to stop the loop. Which is better practice - a for loop with a break, or a conditional loop?
The pseudo-code in the example I have provided is for argument's sake only (it is also in ActionScript, since that is my primary language of late). Also, I am not looking for best practice ideas on syntax.
for loop with break:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
conditional loop:
var i:int;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
i++;
}

In short, you should go with whichever version is the easiest to read and maintain.
In slightly older times, I know breaking out of a loop was considered to be a no-no (on par with a goto statement). Loops were supposed to break on the loop condition and nowhere else. Thus, the while-loop would have been the way to go.
(This is probably a holdover from assembly, where loops are basically a block of code with a go-to-the-beginning-if-true jump statement at the end. Multiple conditional-jump statements in the block make it exceedingly hard to debug; thus they were to be avoided and combined into one at the end.)
I feel this idea seems to be changing a bit today, especially with foreach loops and the managed world; it's really a matter of style now. Break-on-found for-loops have perhaps come to be acceptable to many, save some purists of course. Note that I would still avoid using break in a while-loop, however, as this can muddle the loop condition and make it confusing.
If you'll allow me to use a foreach loop, I consider the code below to be a lot easier to read than its while-loop brother:
bool isBaxterInMilwaukee;
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
However, as the logic grows in complexity, you may want to consider a prominent comment near the break statement lest it become buried and hard to find.
Arguably, this whole thing should be refactored into its own function which doesn't break on found, but actually returns the result (feel free to use the for-loop version instead):
bool isBaxterInMilwaukee(Array myArray)
{
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
barkTwice();
return true;
}
}
return false;
}
As Esko Luontola pointed out, it would probably be best to move the call to barkTwice() outside of this function as the side-effect is not evident from the function's name, nor related to finding Baxter in every case. (Or add a boolean parameter BarkTwiceIfFound and change the line to read if(BarkTwiceIfFound) barkTwice(); to make the side-effect clear.)
For the record, you can also do the flag check in the for-loop without a break, but I feel this actually hurts readability because you don't expect an extra condition in a for-loop definition:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; !isBaxterInMilwaukee && i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
You can also simulate auto-incrementing mechanics with a while-loop. I don't like this for a few reasons - you have to initialize i to be one less than your real starting value, and depending on how your compiler short-circuits the loop-condition logic, your value of i on exiting the loop may vary. Nevertheless, it is possible and for some people, this can improve readability:
var i:int = -1;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && ++i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}

I've always disliked the use of breaks in code... In this case it doesn't seem to matter but on more involved loops, it can be awfully confusing to another coder reading it. In general, it often results in not understanding how the loop may terminate until the coder spots the nested break deep in the loop. By specifying a flag condition that's checked each iteration of the loop, it makes this much clearer.
This problem would be similar to having return statements that are deep in the body of a method where they're not easily spotted (rather than setting a retVal variable and returning at the end of the method). With a small method, this seems fine, but the bigger it gets, the more confusing this will be.
It's not an efficiency of operation thing, it's a maintainability thing.
Ask your coworkers what's readable and understandable for a particular situation... That's what really matters.

I would say it depends. In this case the loop with the break seems clearer to me.

In a for loop you can also early exit by putting the early exit criteria in the for loop declaration. So for your example you could do it this way:
var i:int;
var isBaxterInMilwaukee:Boolean;
isBaxterInMilwaukee = false;
for (i = 0; i < arrayLen && !isBaxterInMilwaukee; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
That way you don't need a break, and it's still more readable than a while loop.

There is a conceptual difference between the two. for loops are for iterating over discrete sets and while loops are for repeating statements based on a condition. Other languages add in finally clauses and looping constructs like foreach or until. They tend to have considerably fewer traditional for loops.
In any case, the rule that I use is that for loops iterate and while loops repeat. If you see something like:
while (counter <= end) {
// do really cool stuff
++counter;
}
Then you are probably better off with a for loop since you are iterating. However, loops like:
for (int tryCount=0; tryCount<2; ++tryCount) {
if (someOperation() == SUCCESS) {
break;
}
}
should be written as while loops since they are really repeating something until a condition is true.
The thought of not using break since it is just as evil as goto is pretty nonsensical. How can you justify throwing an exception then? That's just a non-local and non-deterministic goto! By the way, this isn't a rant against exception handling, just an observation.

The one that makes the most sense is going to be the one that conveys the idea to the human reading the code the best. Remember code readability first, and you'll usually make the correct choice. Usually, you do not want to use something like break unless you really need to, because it can make things hard to follow if done often or even just in a deeply-nested set of expressions. continue can serve the same purpose as a break sometimes, and the loop will then exit normally instead of because it was broken. In this case, there are a couple of different ways I might write this.
Probably the best thing you want here is a modification of your while loop:
while(!isBaxterInMilwaukee || i < arrayLen) {
if(myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") {
isBaxterInMilwaukee == true;
barkTwice()
} else {
i++;
}
}
That's clear and doesn't use break or continue, so you can tell at a glance that you'll always terminate as a result of one of the conditions specified in the while expression.
ETA: Probably should be i < arrayLen in the while loop otherwise it fails the first time through unless the input value is the same as the target value...

I see the break in both loops, is that correct?
Anyway:
I would choose FOR loop when there is known number (maximum number) of iterations before loop starts.
I would choose WHILE otherwise.
In FOR loop I use BREAK freely.
In WHILE loop I prefer to use complex condition instead of BREAK (if it is possible).

I would say break, clearer (even if you put in a comment why you break out of the loop)
Imho the while loop is not clear, i would go for break

I would definitely go with the for+break. The ‘for’ is an instantly-recognisable idiom for “iterate over sequence” and it's easier to understand “iterate over sequence; end early if value found” than the combined loop-and-stop condition.
There may be evidence for this in the way you seem to have made two mistakes in your conditional loop code!
the while condition (!isBaxterInMilwaukee || i == arrayLen) — did you mean “(!(isBaxterInMilwaukee || i == arrayLen))”?
break statement is unnecessary if you're using a terminate-loop variable.
Personally I find a simple ‘break’ much easier to read than trying to track a terminate-loop variable.

There are two aspects of the problem:
What to do (eg: find if one of the items contain the specified person in the location)
How to do it (eg: use an index, iterate etc)
Both of the examples mix the two and is hard to understand the what from the how. The best would be if we could express in code only the what part. Here is an example (c# 3.5) that does this using the specification pattern
// what we are looking for?
IsPersonInLocation condition = new IsPersonInLocation("baxter", "milwaukee");
// does the array contain what we are looking for?
bool found = myArray.Find(item => condition.IsSatifiedBy(item));
// do something if the condition is satisfied
if (found) {
barkTwice();
}
For completeness here is the class definition for the condition:
class IsPersonInLocation {
public string Person { get; set; }
public string Location { get; set; }
public IsPersonInLocation(string person, string location) {
this.Person = person;
this.Location = location;
}
bool IsSatifiedBy(item) {
return item["name"] == this.Person
&& item["location"] == this.Location;
}
}

It depends a lot on what the specific circumstances are. But in your example, you want to walk an array of bounded length, and using a for loop makes it easy to do that and guard against running off the end. In your while loop example you have to do your own incrementing--which can be problematic if you wanted to use a continue statement to skip into the next cycle--and make a more complex conditional expression (which, by the way, has a bug; I think you meant && i != arrayLen ). You're just having to do extra code to accomplish the effect that for loops help provide.
Of course, some purists will argue that break and continue should not be used and that you should use if-else and boolean variables if needed rather than continue or break out of a loop. But I think that can make the loop look much more ugly, especially if its relatively short and easy to grasp in general like this example. For a loop with much longer code where a break or continue could easily hide from notice, the purist approach might be more clear, since the loop is already complicated to grasp in that case. But you can always do this as part of the for loop, just add it as part of the conditional.
It's also better practice to test the array bound with i < arrayLen rather than for an exact equality, in case something caused i to skip over the exact value (I actually saw this happen in a Y2K bug, which could have been avoided by the better practice).

I have a C++ background and so I still have moments where I try to "think like the compiler". While loops tend to result in tighter code, and so for loops were only ever considered if you knew you were going to iterate over every element in the array, every time.
EDIT: I now believe this is overkill, if you're using .Net or whatever you aren't going to make up for the VM overhead with a couple of tight loops. I do think remembering the "why" of certain practices is a good thing though.

My theory is that there is a useful programming abstraction similar to "signal-to-noise ratio", which is "problem-to-tool ratio" - goodness can be measured in one dimension by how much time I spend thinking about the problem and its solution, compared to the time I spend thinking about how to use the tool (in this case language syntax).
By that measure, I try to use fewer constructs more frequently, because I (and hopefully those who follow) can grok the essence of my code structure more quickly and accurately. And since variations of "for loops" do a pretty good job of covering the cases where the others might be used (without distortion), I use them as a first preference, when they are interchangeable.
And it's nice to have everything you need to know (grokwise) about the loops rules in a single line at the top of the "for" loop. I also tend to put the "default" switch first in the tests for the same reason.
But consistency and clarity is the ovveriding consideration. YMMV, of course.

I guess neither is actually vary interesting. You should look for higher level constructs if it's readability you're after.
In JS:
if(myArray.some(function(o) { o.name == "baxter" && o.location == "milwaukee" }))
barkTwice();
or with some utils of your own
if(myArray.containsMatch({name:"baxter",location:"milwaukee"})
barkTwice();

Encapsulate the loop in its own method and use return to end processing when your match condition has succeeded.
Some example C# code:
class Program
{
static bool IsBaxterInMilwaukee(IList<WhoAndWhere> peopleAndPlaces)
{
foreach (WhoAndWhere personAndPlace in peopleAndPlaces)
{
if (personAndPlace.Name == "Baxter"
&& personAndPlace.Location == "Milwaukee")
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
List<WhoAndWhere> somePeopleAndPlaces = new List<WhoAndWhere>();
somePeopleAndPlaces.Add(new WhoAndWhere("Fred", "Vancouver"));
somePeopleAndPlaces.Add(new WhoAndWhere("Baxter", "Milwaukee"));
somePeopleAndPlaces.Add(new WhoAndWhere("George", "London"));
if (IsBaxterInMilwaukee(somePeopleAndPlaces))
{
// BarkTwice()
Console.WriteLine("Bark twice");
}
}
public class WhoAndWhere
{
public WhoAndWhere(string name, string location)
{
this.Name = name;
this.Location = location;
}
public string Name { get; private set; }
public string Location { get; private set; }
}
}

My general stance is:
If it has a loop counter use for() (like while while loop does).

I vote while because breaks reduce grokability.
You may not realize the loop contains a break if the loop has grown too long and you insert code you expect to run and it does not.
But I subscribe to the don't make me think model of coding.

In ES6, it has been made very easy, no need to use the break keyword, We can use the find function, once the condition satisfies, we can return true.
let barkTwice = () => {
console.log('bark twice');
}
let arr = [{
location: "waukee",
name: "ter"
}, {
location: "milwaukee",
name: "baxter"
},
{
location: "sample",
name: "sampename"
}
];
Here we matching the condition and once the condition matches, we are calling the function, as per the question and then we are returning true. So that it does not go beyond.
arr.find(item => {
if (item.location == "milwaukee" && item.name == "baxter") {
barkTwice();
return true
}
});

Related

How do I remove a single life per collision of two 2D objects?

I am programming a game for fun and to get more familiar with C and GBA mode 3. Though, I have run into an issue.
I have these two blocks on the screen, one is the good guy, the other is the bad guy. When the good guy collides with the bad guy its supposed to remove a life. That is where the problem comes in.
I have this within a while loop that runs the game:
if (plyr_row < enemy_row + enemy_size && plyr_ row
+ plyr_size > enemy_row && plyr_col < enemy_col + enemy_size
&& plyr_size + plyr_col > enemy_col)
{
lives--;
}
The lives do go down, but a lot of lives are taken away while the player is making contact with the enemy. In other words, during contact, the lives drop really fast and I just want to remove one for each time they collide, how can I accomplish that?
You have to use a flag to remember, if a collision is currently happening or not. Something like:
int in_collision = 0; // global flag, initialized to 0 once at start
...
if (plyr_row < enemy_row + enemy_size &&
plyr_row + plyr_size > enemy_row &&
plyr_col < enemy_col + enemy_size &&
plyr_size + plyr_col > enemy_col) {
if (!in_collision) {
in_collision = 1;
lives--;
}
} else {
in_collision = 0;
}
Now, the running collision must stop before another life will be removed on the following collision.
The simplest solution is to maintain a flag IN_COLLISION. You want to remove a life when there is a collision and IN_COLLISION is false.
Then it's a matter of toggling it to true at the first collision detection and then to false when you are not colliding anymore.

Translate complex conditional logic inside a loop into streams and lambdas

I'm looking for a clean way to translate complex logical conditions with if and else statements that lead to different actions, into lambdas and streams.
Suppose I have this code:
List<OuterData> result = new LinkedList<>();
for (Outer outer : getOutersFromSomewhere()) {
OuterData outerData = new OuterData();
if (outer.isImportant()) {
doImportantAction(outer, outerData);
} else if (outer.isTrivial()) {
doTrivialAction(outer, outerData);
} else {
doDefaultAction(outer, outerData);
}
for (Inner inner : outer.getInners()) {
if (inner.mustBeIncluded()) {
InnerData innerData = new InnerData();
if (inner.meetsCondition1()) {
doAction1(inner, innerData, outer, outerData);
} else if (inner.meetsCondition2()) {
doAction2(inner, innerData, outer, outerData);
} else {
doDefaultAction(inner, innerData, outer, outerData);
}
outerData.add(innerData);
}
}
result.add(outerData);
}
return result;
This is simplified from real code I have. I know it can be optimized and refactored, i.e. I could move inner for to a private method. I'd like to know how to translate the if, else if and else parts to streams and lambdas.
I know how to translate the skeleton of this example. I'd use List.stream(), Stream.map(), Stream.filter(), Stream.collect() and Stream.peek(). My problem is with conditional branches only. How can I do this translation?
One first obvious way is to stream your elements, filter them according to the needed criteria, and then applying the action on each remaining element. This also makes the code much cleaner:
List<Outer> outers = getOutersFromSomewhere();
outers.stream().filter(Outer::isImportant)
.forEach(outer -> doImportantAction(outer, outerDate));
outers.stream().filter(Outer::isTrivial)
.forEach(outer -> doTrivialAction(outer, outerDate));
// default action analog
Caution: This only works if the important, the trivial, and the default elements form a partition. Otherwise it is not equivalent to your if-else-structure. But maybe this is intended anyway ...
The main problem with this approach: It is not very good OOP. You are querying the objects in order to make a decision. But OOP should be "tell, don't ask" as much as possible.
So another solution is to provide a consuming method in your Outer class:
public class Outer {
...
public void act(OuterData data, Consumer<Outer> importantAction,
Consumer<Outer> trivialAction, Consumer<Outer> defaultAction) {
if (isImportant())
importantAction.accept(this, data);
else if (isTrivial())
trivialAction.accept(this, data);
else
defaultAction.accept(this, data);
}
}
Now you call it as simple as this:
List<Outer> outers = getOutersFromSomewhere();
outers.forEach(outer -> outer.act(...)); // place consumers here (lambdas)
This has a clear advantage: If you ever have to add a feature to your Outer class - let's say isComplex() - you have to only change the internals of that single class (and maybe resolve the compiler failure in other parts). Or maye you can add this feature in a backward compatible way.
The same rules can be applied to the Inner class and the iteration.

Single line expression to branch off of and clear a boolean flag?

The other day, a colleague noticed the common pattern he was doing of:
if (someBooleanFlag)
{
someBooleanFlag = FALSE;
...do some more stuff...
}
basically, a clear-on-read latch. And asked if I knew of a clever way to test the flag and clear it as a one-liner, so he could get rid of the boilerplate someBooleanFlag = FALSE; bit. Questions about whether this is good style or not aside, I found the best I could do for him was a something like
#define TESTANDCLEAR(var) (var ? var-- : 0)
This makes the assumption that ONLY 1 and 0 are being used, and it doesn't work on bitmasks either. I figured I'd turn to the Wizards of the Stack, to see if there was some better way and other technique that could be used.
(Again, no need to discuss whether the style of doing a TESTANDCLEAR() expression is bad or good, it was more of the academic exercise if we actually could do it, and how generally)
I don't think you need to make the 0/1 assumption, even with the approach you already have. Assignments are expressions that return a value, so you could define that macro as:
(var ? !(var = false) : false)
Or, you could use the comma operator:
(var ? ((var = false), true) : false)
Which would help if you wanted this to work with a bitfield testing for the Nth bit:
(((var & (1 << N)) ? ((var = var & ~(1 << N)), true) : false)
Ugly, but I think this should work:
if (someBooleanFlag && !(someBooleanFlag = !someBooleanFlag))
For the love of God never do this in production code.

Loops' iterating in ANTLR

I'm trying to make a Pascal interpreter using ANTLR and currently have some troubles with processing loops while walking the AST tree.
For example for loop is parsed as:
parametricLoop
: FOR IDENTIFIER ASSIGN start = integerExpression TO end = integerExpression DO
statement
-> ^( PARAMETRIC_LOOP IDENTIFIER $start $end statement )
;
(variant with DOWNTO is ignored).
In what way can I make walker to repeat the loop's execution so much times as needed? I know that I should use input.Mark() and input.Rewind() for that. But exactly where should they be put? My current wrong variant looks so (target language is C#):
parametricLoop
:
^(
PARAMETRIC_LOOP
IDENTIFIER
start = integerExpression
{
Variable parameter = Members.variable($IDENTIFIER.text);
parameter.value = $start.result;
}
end = integerExpression
{
int end_value = $end.result;
if ((int)parameter.value > end_value) goto EndLoop;
parametric_loop_start = input.Mark();
}
statement
{
parameter.value = (int)parameter.value + 1;
if ((int)parameter.value <= end_value)
input.Rewind(parametric_loop_start);
)
{
EndLoop: ;
}
;
(Hope everything is understandable). The condition of repeating should be checked before the statement's first execution.
I tried to play with placing Mark and Rewind in different code blocks including #init and #after, and even put trailing goto to loops head, but each time loop either iterated one time or threw exceptions like Unexpected token met, for example ':=' (assignement). I have no idea, how to make that work properly and can't find any working example. Can anybody suggest a solution of this problem?
I haven't used ANTLR, but it seems to me that you are trying to execute the program while you're parsing it, but that's not really what parsers are designed for (simple arithmetic expressions can be executed during parsing, but as you have discovered, loops are problematic). I strongly suggest that you use the parsing only to construct the AST. So the parser code for parametricLoop should only construct a tree node that represents the loop, with child nodes representing the variables, conditions and body. Afterwards, in a separate, regular C# class (to which you provide the AST generated by the parser), you execute the code by traversing the tree in some manner, and then you have complete freedom to jump back and forth between the nodes in order to simulate the loop execution.
I work with ANTLR 3.4 and I found a solution which works with Class CommonTreeNodeStream.
Basically I splitted off new instances of my tree parser, which in turn analyzed all subtrees. My sample code defines a while-loop:
tree grammar Interpreter;
...
#members
{
...
private Interpreter (CommonTree node, Map<String, Integer> symbolTable)
{
this (new CommonTreeNodeStream (node));
...
}
...
}
...
stmt : ...
| ^(WHILE c=. s1=.) // ^(WHILE cond stmt)
{
for (;;)
{
Interpreter condition = new Interpreter (c, this.symbolTable);
boolean result = condition.cond ();
if (! result)
break;
Interpreter statement = new Interpreter (s1, this.symbolTable);
statement.stmt ();
}
}
...
cond returns [boolean result]
: ^(LT e1=expr e2=expr) {$result = ($e1.value < $e2.value);}
| ...
Just solved a similar problem, several points:
Seems you need to use BufferedTreeNodeStream instead of CommonTreeNodeStream, CommonTreeNodeStream never works for me (struggled long time to find out)
Use seek seems to be more clear to me
Here's my code for a list command, pretty sure yours can be easily changed to this style:
list returns [Object r]
: ^(LIST ID
{int e_index = input.Index;}
exp=.
{int s_index = input.Index;}
statements=.
)
{
int next = input.Index;
input.Seek(e_index);
object list = expression();
foreach(object o in (IEnumerable<object>)list)
{
model[$ID.Text] = o;
input.Seek(s_index);
$r += optional_block().ToString();
}
input.Seek(next);
}

What are the differences between if, else, and else if? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 2 years ago.
Improve this question
I am trying to discern the difference between
if
else
else if
When do you use them and when not?
I have a homework assignment with a ton of instances and I am running into code error due to not knowing the differences between each.
Can someone please define how to use these?
An if statement follows this sort of structure:
if (condition)
{
// executed only if "condition" is true
}
else if (other condition)
{
// executed only if "condition" was false and "other condition" is true
}
else
{
// executed only if both "condition" and "other condition" were false
}
The if portion is the only block that is absolutely mandatory. else if allows you to say "ok, if the previous condition was not true, then if this condition is true...". The else says "if none of the conditions above were true..."
You can have multiple else if blocks, but only one if block and only one (or zero) else blocks.
If-elseif-else can be written as a nested if-else. These are (logically speaking) equivalent:
if (A)
{
doA();
}
else if (B)
{
doB();
}
else if (C)
{
doC();
}
else
{
doX();
}
is the same as:
if (A)
{
doA();
}
else
{
if (B)
{
doB();
}
else
{
if (C)
{
doC();
}
else
{
doX();
}
}
}
The result is that ultimately only one of doA, doB, doC, or doX will be evaluated.
**IF** you are confused
read the c# spec
**ELSE IF** you are kind of confused
read some books
**ELSE**
everything should be OK.
:)
If, else and else if are all constructs to help 'branch' code. Basically, you employ them whenever you want to make a decision.
An example would be 'if it's sunny, I'll go outside. otherwise, I'll stay inside'
In code (ignoring the extra stuff)
if (sunny) {
goOutside();
}
else {
stayInside();
}
You CAN use 'else if' statements if you want to add 'additional' conditions. Extending the previous example, "if it's sunny, I'll go outside. If it's stormy, I'll go into the basement otherwise I'll stay inside"
In code
if (sunny) {
goOutside();
}
else if (stormy) {
goDownstairs();
}
else {
stayInside();
}
EDIT section:
Here is how you can write multiple ifs as and conditions. The following example can be written in at least two ways:
'If it's sunny and warm, go outside. If it's sunny and cold, do nothing'
if (sunny) {
if (warm) {
goOutside();
}
else if (cold) {
doNothing();
}
}
OR
if (sunny && warm) {
goOutside();
}
else if (sunny && cold) {
doNothing();
}
There's no "else if". You have the following:
if (condition)
statement or block
Or:
if (condition)
statement or block
else
statement or block
In the first case, the statement or block is executed if the condition is true (different than 0). In the second case, if the condition is true, the first statement or block is executed, otherwise the second statement or block is executed.
So, when you write "else if", that's an "else statement", where the second statement is an if statement. You might have problems if you try to do this:
if (condition)
if (condition)
statement or block
else
statement or block
The problem here being you want the "else" to refer to the first "if", but you are actually referring to the second one. You fix this by doing:
if (condition)
{
if (condition)
statement or block
} else
statement or block
Dead Simple Pseudo-Code Explanation:
/* If Example */
if(condition_is_true){
do_this
}
now_do_this_regardless_of_whether_condition_was_true_or_false
/* If-Else Example */
if(condition_is_true){
do_this
}else{
do_this_if_condition_was_false
}
now_do_this_regardless_of_whether_condition_was_true_or_false
/* If-ElseIf-Else Example */
if(condition_is_true){
do_this
}else if(different_condition_is_true){
do_this_only_if_first_condition_was_false_and_different_condition_was_true
}else{
do_this_only_if_neither_condition_was_true
}
now_do_this_regardless_of_whether_condition_was_true_or_false
I think it helps to think of the "else" as the word OTHERWISE.
so you would read it like this:
if (something is true)
{
// do stuff
}
otherwise if (some other thing is true)
{
// do some stuff
}
otherwise
{
// do some other stuff :)
}
if (condition)
{
thingsToDo()..
}
else if (condition2)
{
thingsToDoInTheSecondCase()..
}
else
{
thingsToDoInOtherCase()..
}
you can think of the if and else as a pair, that satisfies two actions for one given condition.
ex: if it rains, take an umbrella else go without an umbrella.
there are two actions
go with an umbrella
go without an umbrella
and both the two actions are bound to one condition, i.e is it raining?
now, consider a scenario where there are multiple conditions and actions, bound together.
ex: if you are hungry and you are not broke, enjoy your meal at kfc, else if you are hungry but you are broke, try to compromise, else if you are not hungry, but you just want to hangout in a cafe, try startbucks, else do anything, just don't ask me about hunger or food. i have got bigger things to worry.
the else if statement to to string together all the actions that falls in between the if and the else conditions.
They mean exactly what they mean in English.
IF a condition is true, do something, ELSE (otherwise) IF another condition is true, do something, ELSE do this when all else fails.
Note that there is no else if construct specifically, just if and else, but the syntax allows you to place else and if together, and the convention is not to nest them deeper when you do. For example:
if( x )
{
...
}
else if( y )
{
...
}
else
{
...
}
Is syntactically identical to:
if( x )
{
...
}
else
{
if( y )
{
...
}
else
{
...
}
}
The syntax in both cases is:
if *<statment|statment-block>* else *<statment|statment-block>*
and if is itself a statment, so that syntax alone supports the use of else if
if (numOptions == 1)
return "if";
else if (numOptions > 2)
return "else if";
else
return "else";
The syntax of if statement is
if(condition)
something; // executed, when condition is true
else
otherthing; // otherwise this part is executed
So, basically, else is a part of if construct (something and otherthing are often compound statements enclosed in {} and else part is, in fact, optional). And else if is a combination of two ifs, where otherthing is an if itself.
if(condition1)
something;
else if(condition2)
otherthing;
else
totallydifferenthing;
The if statement uses the results of a logical expression to decide if one of two code blocks will be executed.
With this code
if (logical expression) {
code block 1;
} else {
code block 2;
}
if the logical expression is true, only the statements in code block 1 will be executed; if false, only the statements in code block 2.
In the case that there are multiple similar tests to be done (for instance if we are testing a number to be less than zero, equal to zero or more than zero) then the second test can be placed as the first statement of the else code block.
if (logical expression 1) {
code block 1;
} else {
if (logical expression 2) {
code block 2;
} else {
code block 3;
}
}
In this case, code block 1 is executed if logical expression 1 is true; code block 2 if logical expression 1 is false and logical expression 2 is true; code block 3 if both logical expressions are false.
Obviously this can be repeated with another if statement as the first statement of code block 3.
The else if statement is simply a reformatted version of this code.
if (logical expression 1) {
code block 1;
} else if (logical expression 2) {
code block 2;
} else {
code block 3;
}
The else if can be used in conjunction with 'if', and 'else' to further break down the logic
//if less than zero
if( myInt < 0){
//do something
}else if( myInt > 0 && myInt < 10){
//else if between 0 and 10
//do something
}else{
//else all others
//do something
}
Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do.
The if is telling the compiler that you have a question, and the question is the condition between parenthesis
if (condition) {
thingsToDo()..
}
the else part is an addition to this structure to tell the compiler what to do if the condition is false
if (condition) {
thingsToDo()..
} else {
thingsToDoInOtherCase()..
}
you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.
if (condition) {
thingsToDo()..
} else if (condition2) {
thingsToDoInTheSecondCase()..
}else {
thingsToDoInOtherCase()..
}
If and else if both are used to test the conditions.
I take case of If and else..
In the if case compiler check all cases Wether it is true or false.
if no one block execute then else part will be executed.
in the case of else if compiler stop the flow of program when it got false value. it does not read whole program.So better performance we use else if.
But both have their importance according to situation
i take example of foor ordering menu
if i use else if then it will suit well
because user can check only one also.
and it will give error
so i use if here..
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
now else if case
if (time < 12) {
greeting = "Good morning";
} else if (time < 22) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
here only satisfy one condition..
and in case of if multiple conditions can be satisfied...
What the if says:
Whether I'm true or not, always check other conditions too.
What the else if says:
Only check other conditions if i wasn't true.

Resources