Converting if-else statement to if-else if-else statement - if-statement

How do I convert this nested if-else statement into a non-nested if-else if-else statement? You may need to add some boolean operators to make this completely non-nested:
if (ball > 0) {
if (cup > 0) {
console.log(“I have a ball and cup.”);
} else {
console.log(“I have a ball.”);
}
} else {
if (cup > 0) {
console.log(“I have a cup”);
} else {
console.log(“I have nothing”);
}
}

If I understand what you are trying to do, then maybe this can help:
if (ball > 0 && cup > 0) {
console.log(“I have a ball and cup.”);
} else if (ball > 0) {
console.log(“I have a ball.”);
}
if (ball <= 0 && cup > 0) {
console.log(“I have a cup”);
} else if (ball <= 0) {
console.log(“I have nothing”);
}
Instead of nesting if-else statements, you can just check for multiple conditions in each if statement.

Related

Can somebody tell me how this code working with no curly braces between two if?

If I am enclosing the code after first if upto second return in curly braces it is not giving me desired output.
static int comparator(Player a, Player b) {
if(a.score == b.score)
if(a.name == b.name)
return 0;
else
return (a.name > b.name)? -1:1;
return (a.score < b.score)? -1:1;
}
Your code has if() and else statements. Each will execute one line of code that comes after them. This means that it will only execute a single statement and end after the first ; that it finds.
for() loops, while() loops, if-else blocks can be used without curly braces if the statement you want to execute consists of only one line of code following them.
Your code works as -
static int comparator(Player a, Player b) {
// if statement without braces- means just one statement executes
if(a.score == b.score)
// Remember if-else will be considered as a single code block so both will run
if(a.name == b.name)
return 0;
else
return (a.name > b.name)? -1:1;
// This statement will run only when the above if condition is not satisfied
return (a.score < b.score)? -1:1;
}
This can be considered to be same as -
static int comparator(Player a, Player b) {
if(a.score == b.score) {
if(a.name == b.name) {
return 0;
} else {
return (a.name > b.name) ? -1 : 1;
}
}
return (a.score < b.score) ? -1 : 1;
}
NOTE : It is generally better if you use the braces as it will be good for readability as well as maintainability of the code. There can actually be two way of parsing it - Dangling else(though most compiler will associate the else with closest if).
In this coding style, there's no way to differentiate between below two code -
if(condition1)
if(condition2)
foo1();
else
foo2();
and,
if(condition1)
if(condition2)
foo1();
else
foo2();
Since, in C/C++, it doesn't consider the indentation in code, so it might create ambiguity while reading the code. So its always better to use curly braces instead of doing it like above. Drop them only when you have a single line and it won't create any confusion reading the code later on...
Hope this helps !
Without curly braces, only the next statement is executed. With proper indentation it becomes easier to see what's going on:
static int comparator(Player a, Player b) {
if(a.score == b.score)
if(a.name == b.name)
return 0;
else
return (a.name > b.name) ? -1 : 1;
return (a.score < b.score) ? -1 : 1;
}
This is actually the same as:
static int comparator(Player a, Player b) {
if(a.score == b.score) {
if(a.name == b.name) {
return 0;
} else {
return (a.name > b.name) ? -1 : 1;
}
}
return (a.score < b.score) ? -1 : 1;
}
You have maybe used the braceless else variant without noticing it when writing something like:
if(condition) {
//
} else if(another_condition) {
//
} else {
//
}
Which is actually the same as
if(condition) {
//
} else {
if(another_condition) {
//
} else {
//
}
}
Without curly braces, the if guard only applies to the immediate next statement.
It's just how the language works. :/

If and If statement / using { }

I have a simple question . Why the first program don't work and return me 0 but the second where if go into another if works ? It wont go down and check the next if ?
#include <stdio.h>
int main ()
{
int m,n,tmp,i;
int nnumber=0,numbermin=9999999;
scanf("%d %d",&m,&n);
for(i=m;i<=n;i++)
{
tmp=i;
while (tmp > 0 && (tmp % 10) % 2 == 0)
{
tmp/=10;
}
if (tmp == 0){ // This don't work i as want from this if to go down
// there and check the next if
// i only got 0 at the printf("%d" , numbermin);
nnumber=i;
}
if(nnumber<numbermin)
{
numbermin=nnumber;
}
}
if(nnumber==0)
printf("NO");
else
printf("%d",numbermin);
}
And the code that runs good .
#include <stdio.h>
int main ()
{
int m,n,tmp,i;
int nnumber=0,numbermin=9999999;
scanf("%d %d",&m,&n);
for(i=m;i<=n;i++)
{
tmp=i;
while (tmp > 0 && (tmp % 10) % 2 == 0)
{
tmp/=10;
}
if (tmp == 0) {
nnumber=i;
if(nnumber<numbermin)
{
numbermin=nnumber; // But this work perfect i want to know why the first ex didn't work ?
}
}
}
if(nnumber==0)
printf("NO");
else
printf("%d",numbermin);
}
Why only the second one work good but the first don't ?
This is caused by the fact that in the first example, if tmp isn't equal to 0, then the second if statement can still be evaluated as true while the first does not.
if (tmp == 0){
nnumber=i;
}
if(nnumber<numbermin)
{
numbermin=nnumber;
}
While in the second example, if tmp is equal to 0, then the first if statement is evaluated as false and disallows anything within it from affecting the program.
if (tmp == 0){
nnumber=i;
if(nnumber<numbermin){
numbermin=nnumber;
}
}
This would explain the difference in results when running these two versions of the code.

Arduino Autonmous car if statements (ultrasonic)

I have run into a problem while creating the if statements for the autonomous car. The car skips most of the if statements and immeaditly goes to the else statement. The sensors give of the right values. Is it because i use "else if" statements or something else? The car is supposed to react to its surroundings, so i had to give it many if statements as possible. But instead it just does the last bit where it goes backwards waits goes backwards left and backwards right. So my question is do i have to add more if statements so it reacts better to its surroundings or is there more to it? Here is the code of the if statements:
if (sensors[0] >= 50 ) { //if the distance of the front sensor is greater than 50cm, than set Fwd true. Otherwise its false.
Fwd = true;
} else {
Fwd = false;
}
delay(50);
if ((Fwd == true) && (sensors[1] > 50) && (sensors[2] > 50)) {
fwd();
} else if ((Fwd == true) && (sensors[1] < 50)) {
fwdRight();
} else if ((Fwd == true) && (sensors[2] < 50)) {
fwdLeft();
} else if ((Fwd == false) && (sensors[1] < 50) && (sensors[2] < 50)) {
Stp();
} else if ((Fwd == false) && (sensors[1] < 50)) {
bwdRight();
} else if ((Fwd == false) && sensors[2] < 50) {
bwdRight();
} else {
Stp();
delay(1000);
bwd();
delay(500);
bwdLeft();
delay(500);
bwdRight();
}
Start by tidying up your code, and it may be obvious where things may be going wrong. For example, you are calling multiple checks to Fwd by doing:
if ((Fwd == true) && ... ) {
...
} else if ((Fwd == true) && ... ) {
...
} else if ((Fwd == true) && ... ) {
...
} else if ((Fwd == false) && ... ) {
...
} else if ((Fwd == false) && ... ) {
...
}
This uses up valuable resources in your program memory. It would be much more efficient to do a single check, and evaluate from there:
if (Fwd){
// Check sensor conditions here
} else {
// Check more sensor conditions here
}
In fact, you could probably omit the Fwd variable (unless you are using it elsewhere) altogether, saving you more memory space:
// Check whether to go forward or backwards.
// >= 50 - forward
// < 50 - backward
if (sensors[0] >= 50) {
// Check sensor conditions here
} else {
// Check more sensor conditions here
}
Overall, you could end up with something like:
// Check whether to go forward or backwards.
// >= 50 - forward
// < 50 - backward
if (sensors[0] >= 50) {
// Going forward, but which direction?
if (sensors[1] < 50) {
fwdRight();
} else if (sensors[2] < 50) {
fwdLeft();
} else {
// sensors[1] >= 50 AND sensors[2] >= 50
// Going straight forward
fwd();
}
} else {
// Check backward sensor conditions here
}
This answer might not directly answer your question, but it should help you diagnose better what is going on.

Out of range vector subscript C++

I have this method in one of my cpp files where I have navigated my failure to be. I have also added cout statements and checked that there is content in both foo and mainWord. I think my problem has to do with how I've added elements to foo or how I am trying to re-add them. The size mainWord is 88 and the size of foo is more than 1000. Here is where I add elements to foo:
while (myfile>>magic)//store the colours in an array
{
foo.push_back(magic);
}
and here is where I try and change them and add them back in.
void Penguin::addWord(std::vector<int> foo)
{
unsigned fooCounter=0;
int temp;
for (int i=0;i<88;i+2)
{
if(foo.at(fooCounter) == 11111111 && foo.at(fooCounter) != NULL)
{
if(mainWord[i]==1 && mainWord[i+1]==1)
{
foo.at(fooCounter) = 11111111;
}
else if(mainWord[i]== 1 && mainWord[i+1] == 0)
{
foo.at(fooCounter) = 11111110;
}
else if(mainWord[i]== 0 && mainWord[i+1] == 1)
{
foo.at(fooCounter) = 11111101;
}
else
{
foo.at(fooCounter) = 11111100;
}
}
else if (foo.at(fooCounter) == 11111111 && foo.at(fooCounter) != NULL)
{
if(mainWord[i]== 1 && mainWord[i+1] == 1)
{
foo.at(fooCounter) = 00000011;
}
else if(mainWord[i]== 1 && mainWord[i+1] == 0)
{
foo.at(fooCounter) = 00000010;
}
else if(mainWord[i]== 0 && mainWord[i+1] == 1)
{
foo.at(fooCounter) = 00000001;
}
else
{
foo.at(fooCounter) = 00000000;
}
}
fooCounter++;
}
}
I keep getting an error that says: "Debug Assertion Failed. Vector subscript out of range"
...Please help
You have an infinite loop because i is never updated in the for loop. You need to fix the typo:
for (int i=0;i<88;i+=2)
^
^

Why am I getting an 'Else without previous if' error within a for loop?

I'm new to C++ and have been staring at my (probably abysmal) code for a while and can't figure out what's off about it.
I'm trying to loop through a few iterations of if and else statements and must be doing something grammatically incorrect - as it shows compiler errors of 'else without a previous if'
This is for a class and I'm trying to work it out, but if you see something obvious that I am overlooking I would love to know.
Thank you!
for (i = 0; i < iterationsNum; i++){
if (charlieAlive == 0) // Aarron's shot
{
if (aaronShot() == 1)
charlieAlive = 1;
}
else (charlieAlive == 1 && bobAlive == 0);{
if (aaronShot() == 1)
bobAlive = 1;
}
else (charlieAlive == 1 && bobAlive == 1 && aaronAlive == 0);{
cout << "Aaron is the Winner!\n";
totalShot++;
aaronCounter++;
}
continue;
if (charlieAlive == 0 && aaronAlive ==0) // Bob's shot
{
if (bobShot() == 1)
charlieAlive = 1;
}
else (charlieAlive == 1 && aaronAlive == 0);{
if (bobShot() == 1)
aaronAlive = 1;
}
else (charlieAlive == 1 && aaronAlive == 1 && bobAlive == 0);{
cout << "Bob is the Winner!\n";
bobCounter++;
totalShot++;
}
continue;
if (charlieAlive == 0 && bobAlive == 0) // Charlie's shot
{
bobAlive = 1;
}
else (charlieAlive == 0 && bobAlive == 1 && aaronAlive == 0);{
aaronAlive = 1;
totalShot++;
}
else (charlieAlive == 0 && bobAlive == 1 && aaronAlive == 1);{
cout << "Charlie is the Winner!\n";
}
continue;
else doesn' take any condition, but you've written this:
else (charlieAlive == 1 && bobAlive == 0); //else : (notice semicolon)
which doesn't do what you intend it to do.
You want to do thos:
else if (charlieAlive == 1 && bobAlive == 0) //else if : (semicolon removed)
Notice the difference.
Also, there can be at most one else block, associated with an if block Or a chain of if, else-if, else-if blocks. That is, you can write this:
if (condition) {}
else {}
Or,
if (condition0) {}
else if (condition1) {}
else if (condition2) {}
else if (condition3) {}
else if (condition4) {}
else {}
In any case, else block is always the last block. After that if you write another else block, that would be an error.
Apart from that you also have a semicolon at wrong place. Fixed that also:
else (charlieAlive == 1 && bobAlive == 0); <---- remove this semicolon!
Hope that helps.
Pick a good Introductory C++ Book. Here are few recommendations for all levels.
The Definitive C++ Book Guide and List
There are several problems I see here:
There are semicolons in your else statements - these aren't supposed to be there
You have multiple else clauses for a single if. Use 'else if' when you are evaluating another condition - else is the catch-all for when no conditions are met
I highly recommend proper indenting and consistent brace usage - not doing this isn't necessarily an error, but it will make it much easier to notice errors.
you cant put condition statement in else statement
correct for all else statements
like in else (charlieAlive == 1 && bobAlive == 0);
else is simply the alternative flow of if - i.e.
if(condition) // if this fails go to else part
{
--- // if condition true execute this
}
else{
--- // will run when condition in if fails
}
so you don't have to put condition for else statement
Edit
where as else if takes condition as well
seems you wanted to do this
else if(your condition statements) // Note: no semicolon at the end