Reputation: 79
In my opinion I feel like many people are confused about this question. What I want to do is ask the user for a number and if it is between 0 - 17, the output I would want it to be is:
Too Young
And if it is 18 - 42, the output should be:
Adult
And if it's 43 and over to be:
Senior
All while using the switch statement
Here is the code I used:
#include <iostream>
using namespace std;
int main()
{
int age;
cin >> age;
if (age <= 16) {
cout <<"Too young";
}
if (age <= 42) {
cout << "Adult";
}
if (age <= 70) {
cout << "Senior";
}
return 0;
}
The output of my code is:
Too YoungAdultSenior
Please help me out.
Upvotes: 2
Views: 3292
Reputation: 12866
Replace your code with:
#include <iostream>
using namespace std;
int main()
{
int age;
cin >> age;
if (age <= 17) {
cout <<"Too young";
} else if (age <= 42) {
cout << "Adult";
} else {
cout << "Senior";
}
return 0;
}
Upvotes: 6
Reputation: 3526
The perfect way:-
#include <iostream>
using namespace std;
int main()
{
int age;
cin >> age;
if (age < 18 && age >=0) {
cout <<"Too young";
} else if (age >= 18 && age <= 42) {
cout << "Adult";
} else if(age > 42)
cout << "Senior";
}
return 0;
}
Upvotes: 1
Reputation: 12866
This is how you would do it with a switch
statement btw:
#include <iostream>
using namespace std;
int main(){
int age;
cin >> age;
switch (age) {
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17:
cout << "Too young\n";
break;
case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40:
cout << "Adult\n";
break;
default:
cout << "Senior\n";
}
return 0;
}
Upvotes: 1
Reputation: 1934
In the above answer, if you wish to use using namespace std;
, simply use this piece of code:
#include <iostream>
using namespace std;
int main()
{
int age;
cin >> age;
if ((age>=44) && (age <= 56))
{
cout << "YAY!!!\n";
}
return 0;
}
Upvotes: 1
Reputation: 11789
To check if something is 2 conditions at the same time, use the &&
operator, which means and
and checks for two conditions being true either side. Example for age between 44 and 56
:
#include <iostream>
int main()
{
int age=55;
if ((age>=44) && (age <= 56))
{
std::cout << "YAY!!!\n";
}
return 0;
}
In C++11 - instead of &&
, you can use and
keyword.
Upvotes: 1