0
Where is the mistake?
Why does "else" work together with "if"? #include <iostream> using namespace std; int main() { string menu[4]; float total =0.0f; for (int i=0;i<4;i++) { cin >> menu[i]; if (menu[i]=="Water") {total+=4.0f;} if (menu[i]=="Coke") {total+=5.0f;} if (menu[i]=="Pizza") {total+=6.0f;} if (menu[i]=="Nachos") {total+=6.0f;} if (menu[i]=="Cheeseburger") {total+=10.0f;} else total+=5.0f; } cout<<(total*1.07f); return 0; }
3 odpowiedzi
+ 5
Azeklir
Because everytime if condition will fail untill input is not Cheeseburger but else will execute
So you have to use else if after first if condition and last will be else
if
else if
else if
else if
else if
else
+ 1
Mistake in the code
The mistake in the code is that the `else` statement is not attached to the right `if` statement in the program.
How does "else" work together with "if"?
`else` statement is used in conjunction with `if` statement to execute a block of code if the `if` condition is not met. If the condition in the `if` statement is false, the code under the `else` statement is executed. Thus, `else` statement helps to implement alternative control flow, i.e., if a certain condition is not met, then an alternate set of instructions is executed.
0
syntax for if/else statement :
1 | if
2 | else if
3 | else
example :-
//for check if a number is odd or even
#include<iostream>
using namespace std;
int main(){
int x;
cin>>x; //user input
if(x%2==0){
cout<<"even";
}
else if(x<0){
cout<<"Try again";
}
else{
cout<<"Odd";
}
}