Age and gender discount – Nested if condition – CSKC
Sign In

Search

Code Learning #CPP#1937    siteicon   siteicon  

Age and gender discount – Nested if condition

Solving for more than one if conditions using nested if for conditions on age and gender of person

Learning Objectives

  • Use of nested if to check two criteria which may otherwise be unrelated.

Source Code

TC++ #1937

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

if(age>=60) 
{
  if (gender ==’F’) disc=20; 
  else disc=10;
}
Here age conditions is checked and if age condition is found true then further if condition is checked for gender. This is called nesting of if condition. This way two unrelated criteria can be checked.

cout<<“Your regular ticket amount = “<<tkt<<endl;
cout<<“Your discount “<<disc<<“%”<<endl;
cout<<“Your final ticket amount = “
        <<tkt-tkt*disc/100<<endl;
Here we print the required variables as given in input and the final ticket amount as per formula given. The formulas has been applied while cout chain itself so that additional variable for calculation is not required.

Notes

  • These types of codes can have many variation in if-else check. For e.g. the same code may be written for a variation of checking the gender first as follows.
    if(gender==’F’)
    {
      if(age>=60) disc=20;
    }
    else
    {
      if(age>=60) disc=10;
    }Difference in the above code can easily be examined for duplicacy of age check.
  • The code given here can also have “dangling else” understanding problem.  for e.g. if the code is written as follows –
    if(age>=60)
      if (gender ==’F’) disc=20;
      else disc=10;The last else can be mis-interpreted for first if condition of age also. In this case this will however work  for nearest if which is for gender check. To avoid this confusion we write the given code with clearly marked curly braces as follows.
    if(age>=60)
    {
      if (gender ==’F’) disc=20;
      else disc=10;
    }

Common Errors

  • As explained in the code notes, the programmer may write above code with dangling else problem. Use curly braces to completely avoid such problems.


Suggested Filename(s): age-gender-disc.cpp, agegend-nestedif.cpp



Share

Created: 27-Dec-2017 17:30 | Updated: 15-Sep-2018 11:51|