Im reading diving into c++ by alex alain. The challenge is to do an if else statement that prints out the differences in two users ages and prints a "not allowed" statement if the ages are over 100. I cant get it to seperate between the age difference and the over 100 ruloe, where am I going wrong please help. I just want it to say a is greater than b or vice versa or the ages are over 100 and the program is terminated. Thanks.
#include <iostream>
usingnamespace std;
int main()
{
int a,b;
cout << "Enter age no: 1.\n";
cin >> a;
cout << "Enter age no: 2.\n";
cin >> b;
if ( a || b < 100 && a < b )
{
cout << "Age 1 is less than age 2.\n";
goto lable;
}
elseif (a || b < 100 && b < a )
{
cout <<"Age 1 is greater than age 2.\n";
goto lable;
}
else ( a || b > 100);
{
cout << "No ages over 100 allowed\n";
goto lable;
}
lable:
{
cout << "The program has finished have a good day\n";
}
}
goto is heavily frowned upon and generally is a red flag for a design flaw/problem.
there are many other issues.
if and else statemetns are explicit. That is,
else (x || y) is not doing what you think even if it compiles.
the syntax is
if (condition)
true_code
else
if (another condition)
special false code
else
default false code
so your code
else( a || b > 100) has multiple problems
first. it should be
else if (a || b > 100)
but it is still not explicit enough, it evaluates a == 0 (false)_ else true OR b > 100, it does NOT evaluate a and b both > 100
you want
else if (a > 100 && b > 100)
and in general your needs for this program are simply (notice no gotos, notice nested condition use to do what the gotos did)
1 2 3 4 5 6 7 8 9 10 11 12
if(a > 100 && b > 100)
{
if (a > b)
cout >> a>b statement
elseif (a == b)
cout >> a == b statement
else cout >> b > a statement
}
else cout << invalid values statement
cout >> program ended statement
#include <iostream>
int main()
{
int a, b;
std::cout << "Enter age no: 1.\n";
std::cin >> a;
std::cout << "Enter age no: 2.\n";
std::cin >> b;
if (a < b && a < 100 && b < 100)
{
std::cout << "Age 1 is less than age 2.\n";
}
elseif (a > b && a < 100 && b < 100)
{
std::cout << "Age 1 is greater than age 2.\n";
}
elseif (a > 100 || b > 100)
{
std::cout << "No ages over 100 allowed\n";
}
int iTemp = 0;
std::cin >> iTemp;
return 0;
}