I want to relate each if statement to the else one below it only. So when the if isn't true the else beneath it is active alone. Then the next if will be run, and the else below that one will be used if its FALSE. How can I do this?
if (.....){
}
else (....){
}
if (.....){
}
else (....){
}
if (.....){
}
else (....){
}
You could use the ternary operator in C.
The syntax is as follows
result = binaryCondition ? valueReturnedIfTrue : valueReturnedIfFalse;
The most straight-forward way of solving this would be to simply exit once you've have entered any if...else block. You can do this with either a return statement inside each conditional, or a break. As long as all of your conditionals are within a loop or outer block, this will bypass your other if...else statements.
For example:
if (a) {
return b + 1
} else {
return b + 2
}
or:
if (a) {
b += 1
break
} else {
b += 2
break
}
I am trying to refactor some code and make it easier to read. I noticed that I have some unnecessary return statements at the end of some functions. Here a conceptual example:
func someFunction(a []arr) int {
for _,v := range a {
if v == something {
// will defenitly get here at some point!
return somethingElse
}
}
return -1 // never ever happens!
}
In my opinion the return statement at the end of the function is misleading, because it suggests, that it may be reached at some point. How do I prevent it?
Please note, that I do error handling at some other point, which is why I can be sure, that someFunction will always return somethingElse.
Panic instead of returning fake value at the end of a function:
func someFunction(a []arr) int {
for _,v := range a {
if v == something {
// will defenitly get here at some point!
return somethingElse
}
}
panic("unreachable")
}
This is a common pattern in standard library.
I have a recursive function which I call acc. If a specific condition is fulfilled I call the function again. If not, I want do add a number to the variable a.
In my opinion it does not what it should. Can someone have a look on this:
double acc(v)
{
double a = 0;
for(int q=0; q<v; q++)
{
if(bf(q) < 1)
{
if(ef() == 0)
{
a += cf();
}
else
{
a += df();
}
}
else
{
return a += acc(v);
}
}
return a;
}
I tried to simplify it as good as I can. vis a variable. bf(), cf(), ef() and df() are functions which return an integer value. Now I want that a gets incremented every time a specific condition is fulfilled during the whole recursive process. Does my code what I want? I don't see it at the moment.
Your problem is that a is defined inside the recursive function. If you want to count events inside the recursion, declare a outside of acc().
How to do code something like this in groovy?
do {
x.doIt()
} while (!x.isFinished())
Because there is no do ... while syntax in groovy.
No 'do ... while()' syntax as yet.
Due to ambiguity, we've not yet added support for do .. while to Groovy
References:
groovy - dev > do while
Migration From Classic to JSR syntax
Groovy Documentation > Control Structures > Looping
Rosetta Code > Loops/Do-while Groovy
You can roll your own looping that's almost what you want.
Here's an example with loop { code } until { condition }
You can't have a corresponding loop { code } while { condition } because while is a keyword.
But you could call it something else.
Anyway here's some rough and ready code for loop until.
One gotcha is you need to use braces for the until condition to make it a closure.
There may well be other issues with it.
class Looper {
private Closure code
static Looper loop( Closure code ) {
new Looper(code:code)
}
void until( Closure test ) {
code()
while (!test()) {
code()
}
}
}
Usage:
import static Looper.*
int i = 0
loop {
println("Looping : " + i)
i += 1
} until { i == 5 }
So many answers and not a single one without a redundant call, a shame ;)
This is the closest it can get to purely language syntax based do-while in Groovy:
while ({
x.doIt()
!x.isFinished()
}()) continue
The last statement within curly braces (within closure) is evaluated as a loop exit condition.
Instead of continue keyword a semicolon can be used.
Additional nice thing about it, loop can be parametrized (kind of), like:
Closure<Boolean> somethingToDo = { foo ->
foo.doIt()
!foo.isFinished()
}
and then elsewhere:
while (somethingToDo(x)) continue
Formerly I've proposed this answer over here: How do I iterate over all bytes in an inputStream using Groovy, given that it lacks a do-while statement?
Depending on your use case, there are options like this: do .. while() in Groovy with inputStream?
Or you can do:
x.doIt()
while( !x.finished ) { x.doIt() }
Or
while( true ) {
x.doIt()
if( x.finished ) break
}
You can use a condition variable with the regular while loop:
def keepGoing = true
while( keepGoing ){
doSomething()
keepGoing = ... // evaluate the loop condition here
}
Update Groovy 2.6 has been abandoned to concentrate on 3.0.
From Groovy 2.6 on, do-while is supported when enabling the new Parrot Parser, from Groovy 3.0 on this is the default. See release notes:
// classic Java-style do..while loop
def count = 5
def fact = 1
do {
fact *= count--
} while(count > 1)
assert fact == 120
By now, Groovy has support for do/while:
do {
x.doIt()
} while (!x.isFinished())
Or you can implement it in a Groovier way :
def loop(Closure g){
def valueHolder = [:]
g.delegate = valueHolder
g.resolveStrategy = Closure.DELEGATE_FIRST
g()
[until:{Closure w ->
w.delegate = valueHolder
w.resolveStrategy = Closure.DELEGATE_FIRST
while(!w()){
g()
}
}]
}
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.