Home > database >  nested 'while' loop not looping back to outer 'for' loop after finishing (c )
nested 'while' loop not looping back to outer 'for' loop after finishing (c )

Time:04-01

I'm needing to find how much tax $ any given number of taxpayers have to pay over any number of years. At the beginning of the program, # of taxpayers is entered, and # of years is entered. The while loop executes fine, and does what it's supposed to do the first time; however, it never loops back to the 'for' loop & asks for the next taxpayer's income. (I will note I have to do it this way as it's for a class)

for (int i = 1; i <= taxpayers; i  )
{
  while (year <= years)
    {      
     cout << "\n\nPlease enter payer " << i << "'s income for year " << year << ": $";
        cin >> income;
        
         if (income >= 0)
         {
           .......
                         
          year  ;
         }
         
         else
         {
         cout << "\n    *Error*"
         cin.clear();
         cin.ignore(INT_MAX, '\n');
         continue;
         }
    }
}

CodePudding user response:

it never loops back to the 'for' loop & asks for the next taxpayer's income

That is because after the while loop is finished the 1st time through, year has caught up to years, and so on subsequent iterations of the for loop, year <= years is always false.

You need to reset year back to its starting value on each iteration of the for loop, before entering the while loop:

for (int i = 1; i <= taxpayers; i  )
{
    year = <your 1st year>; // <-- HERE
    while (year <= years)
    {      
        ...
    }
}
  • Related