Multiple if statements

Im trying to create a simple age calculator that has cout of custom messages, Im trying to use multiple "if" statements. It often shows nothing in the console when i run it. why is that so? I believe i covered most of the ages, do i need an else statement?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

int main(){

int age;

cout<<"Please enter an age and press Enter";
cin>>age;

if(age>1&&age<15)
{
cout<<"You're a child!";}

if(age>15&&age<19){
	cout<<"You're a teenager!";
}
if(age>19&&age<30){
	cout<<"Youre an adult!";
}
if(age>30&&age<45){
cout<<"You're getting old!";
}
if(age>45&&age<65){
	cout<<"you're over the hill!";

}
if(age>65&&age<85){

cout<<"Holy Moly You're almost to 100!";
}

if(age>85&&age<100){
	cout<<"Keep going!";
}
if(age>100&&age<400)
{cout<<"You are Not Human!!!";
}
if(age>1&&age<-1){
cout<<"You dont exist!";}


return 0;
}
1
2
3
4
5
6
7
if(age>1&&age<15)
{
cout<<"You're a child!";}

if(age>15&&age<19){
	cout<<"You're a teenager!";
}


Where is ages of 15 and 19 for these? You are just applying lower than/higher than... Hint given
Last edited on
Your program is good.but try using a series of IF...ELSE statement instead of IF only.
e.g
if(age>1&&<15)
{cout<<"......."};
else is(...)
{"....."};
//continue using else if until the last expression then you can use single else
If you use else as Aminu Bishir suggested you can simplify the conditions. As long as the ages always increase you only need to test the upper bound.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

int main(){

    int age = 0; // generally a good idea to init varaibles

    cout<<"Please enter an age and press Enter";
    cin>>age;

    // -ve ages not handled
    if(age == 0) {
        cout<<"You dont exist!";
    } else if(age<15) { // 13 is a teenager?
        cout<<"You're a child!";
    } else if(age<19) { // no need to check lower bound as already handled
        cout<<"You're a teenager!";
    } else if(age<30){
        cout<<"You're an adult!";
    } else if(age<45){
        cout<<"You're getting old!";
    } else if(age<65){
        cout<<"you're over the hill!";
    } else if(age<85) {
        cout<<"Holy Moly You're almost to 100!";
    } else if(age<100){
        cout<<"Keep going!";
    } else if(age>100&&age<400) {
        cout<<"You are Not Human!!!";
    }
    // Jeanne Calment of France (1875–1997), died at age 122 years
    // And what about "people" 400 and older??

    return 0;
}
Last edited on
Thank you all for your insight, i made the program work thanks to your help, and @andy westken i added 400 incase someone wanted to be silly.
i added 400 incase someone wanted to be silly.

I guessed that. But what if they said they were 2000 years old?

Andy
Last edited on
Topic archived. No new replies allowed.