Search code examples
c++classif-statementinstance

if statement is not executing correctly


When i make the initial input age = 10, then the if-else statement should print out first "You are young" and then after age is incremented by 3, it should print out "You are teenager".However, it prints out "You are old" executing the wrong if-else statement.There would be a problem with my amIOld() function.The ranges or conditions are (age>=13 and age<18) (age<13) and (age>=18) for the statements remaining the same.

using namespace std;
#include <iostream>

class Person{
    public:
        int age;
        Person(int initialAge);
        void amIOld();
        void yearPasses();

        private :

    };

    Person::Person(int initialAge){

        age=initialAge;

            if(age<0){
              cout << " Age is not valid, setting age to 0." << endl;
              age=0;
            }
    }

    void Person::amIOld(){         //Check if-else statements of this function// 

        if(age>=13 && age<18){

            cout << "You are teenager." << endl;
        }
                                  
      else{
          if (age<13){

           cout << "You are a young." << endl;
          }
    
        if(age>=18){ 
            cout << "You are old." << endl;
        }
      }
      
    }
    

    void Person::yearPasses(){
        
           age = age+3;                
    }

int main(){
    int t;
    int age;
    cin >> t;
    for(int i=0; i < t; i++) {
        cin >> age;
        Person p(age);
        p.amIOld();
        for(int j=0; j < 3; j++) {
            p.yearPasses(); 
        }
        p.amIOld();
      
        cout << '\n';
    }

    return 0;
}

Solution

  • The j loop runs three times. Each time through, it calls p.yearPasses(), which adds 3 to age. So the end age is 10 + 3 + 3 + 3 = 19, which is "old" according to p.amIOld().