0

The ages.c code doesn't seem to account for a scenario where user enters a negative integer when prompted for ages.

   {
       for (int i = 0; i < n; i++)
       {
           printf("Age of person #%i: ", i + 1);
           ages[i] = GetInt();   
       }
   }

What type of loop could one add to reprompt user for a positive integer?

2 Answers 2

1

Lots of options here. To me, the simplest would be a do-while loop.

do
{
    ages[i] = GetInt();   
    if ( ages <= 0 )
    {
        // prompt user to try again.
    }
} 
while ( ages[I] <= 0 );

It will keep looping back until you have a number greater than 0. The IF loop will prompt the user to try again only if the answer is 0 or less.

4
  • Thank you! This helped! Commented Apr 22, 2015 at 22:21
  • If you're satisfied, can you mark the question as answered? Let's keep up on forum housekeeping. ;-) thanks.
    – Cliff B
    Commented Apr 22, 2015 at 22:56
  • can I know why it is twice validating ages once using if statement, then again using do...while? can if part be skipped? Commented Jul 11, 2015 at 17:27
  • Remember that this code goes inside the outer for loop because it is collecting a series of ages and putting them in an array. You have to test twice. The IF test is to determine whether to print an error message and the second, the while condition, is to go back and get new input. Skip the if test and no error message. Skip the while test and you keep the bad data.
    – Cliff B
    Commented Jul 11, 2015 at 18:15
0

you can use do ... while to validate user input to avoid negative values.

{
       for (int i = 0; i < n; i++)
       {
           do
           {
               printf("Age of person #%i: ", i + 1);
               ages[i] = GetInt();   
            }
            while (ages[I] <= 0);
       }
   }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .