I am having problem with this statement please help.thanks for your time
#include <iostream>
using namespace std;
int main()
{
int a=10,b;
cout << "Please enter any value (1 or 2) : ";
cin>>a;
if (a==1) {cout << "\nOrange";
cout << "\nOranges are orange";}
if (a==2) { cout << "\nApple";
cout << "\nApples are red";}
else {cout << "\nWrong selection";}
cout << endl;
one way to fix it is to add an else to the first if:
if (a==1)
{
cout << "\nOrange";
cout << "\nOranges are orange";
}
else
if (a==2)
{
cout << "\nApple";
cout << "\nApples are red";
}
else
{
cout << "\nWrong selection";
}
-----------------
the program that you posted does this:
is a 1? yes, print orange stuff.
stop. reset. moving to a new code block that is unrelated in every way to the above block.
begin new block.
is a 2? if yes, print apple stuff.
if not (include, a may be 1 here)
print wrong stuff.
therefore if a is 1,
it prints orange stuff, correctly.
then it checks if 1 is 2, it isnt, so WRONG is printed.
the else I offered ties the 2 if statements together:
is a 1? no.
ok, is it 2? no.
ok its wrong.
or
is a 1? Yes
else//skipped
if//part of skipped else
//else part of skipped if that is part of skipped else above..
the end.
Which is what he said ^^^ But much more explicitly.
You have to be careful with this stuff ... the computer needs everything explicitly stated, whereas a human reading your code understands what you meant, the compiler just does what you said literally.