Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

do-while input validation within array for loop

I’m currently working on an assignment where I have to ask the user to input 5 Blood Pressure readings within a certain range (>=40 and <= 100). I’m trying to create an input validation using a do-while loop within the for loop that scans those inputs to an array.

While I am getting an error message that the input is out of range and being asked to input again, The value I entered previously is still being added to the sum.

I’m not exactly sure how to go about fixing this so I would really appreciate some insight.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried moving the scan to after the if conditional but that just caused the do-while loop to break and go on infinitely. I’ve also tried changing the if into another while loop but the same thing happened (might have just done it incorrectly).

for (i = 0; i < 5; i++)
  {
    do{
      //input for 5 diastolic BP readings
    printf("Enter the Diastolic (bottom) part of your 5 blood pressure tests in the range 40-100 (in mmHg): \n");
    scanf("%f", &dia[i]);

    if(dia[i] < 40 || dia[i] > 100)
    {
      printf("Error, Please input your Diastolic blood pressure within the range 40-100. \n");
    }


      sumDia += dia[i];

  }while(dia[i] < 40 || dia[i] > 100);
  }

>Solution :

The issue you’re facing is because you’re adding the input value to the sum regardless of whether it’s within the range or not. To fix this, you can move the addition to the sum inside the if block, so that it only adds the value if it’s within the valid range. Here’s how you can modify your code:

for (i = 0; i < 5; i++)
{
  do {
    //input for 5 diastolic BP readings
    printf("Enter the Diastolic (bottom) part of your 5 blood pressure tests in the range 40-100 (in mmHg): \n");
    scanf("%f", &dia[i]);

    if(dia[i] < 40 || dia[i] > 100) {
      printf("Error, Please input your Diastolic blood pressure within the range 40-100. \n");
    } else {
      sumDia += dia[i];
    }
  } while(dia[i] < 40 || dia[i] > 100);
}

This way, if the input value is not within the valid range, the loop will continue to prompt the user for input until a valid value is entered. Once a valid value is entered, it will be added to the sum of valid values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading