Search code examples
c++functionmedian

How to loop if input number is negative


Input Validation:

The program should output an error and let the user retry if any if the numbers are negative. Only one iteration is required (i.e. you program does not need to prompt for another three numbers, it can exit after printing the result).

So I have the homework completed and the only thing im missing is this input validation as stated above. In other words (from my understating), I should be implementing a loop in my code where the user has to input another 3 set of numbers if they previously entered a negative number.

#include <iostream>
#include <iomanip>
using namespace std;

double getAverage (double num1, double num2, double num3){

    double averageAmount;

    averageAmount = (num1 + num2 + num3)/ 3;

    return averageAmount;
}
double getMedian (int num1, int num2, int num3){

       int x = num1-num2;
       int y = num2-num3;
       int z = num1-num3;
       if(x*y > 0) return num2;
       if(x*z > 0) return num3;
       return num1;
}
double countDigits( int num1){

    int digits = 0;

    while (num1){

        num1 = num1/10;
        digits++;
    }

    return (digits);
}

int main() {

    double num1 = 0;
    double num2 = 0;
    double num3 = 0;

    cout << "Enter 3 integers" << endl;
    cin >> num1;
    cin >> num2;
    cin >> num3;

    cout << "The average is " << fixed << setprecision(2) << getAverage(num1, num2, num3) << endl;
    cout << "The median is " << fixed << setprecision(2) << getMedian(num1, num2, num3) << endl;
    cout << "There are " << countDigits(num1) << " digits in the number " << num1 << endl;

    return 0;
}

If user enters an negative number I expect the output to be "Enter 3 integers" //since we want only positive numbers


Solution

  • you can write the code using a do-while loop:

    do {
       cout << "Enter 3 integers" << endl;
       cin >> num1;
       cin >> num2;
       cin >> num3;
    } while ((num1 < 0) || (num2 < 0) || (num3 < 0));
    

    otherwise with just a while loop as:

    while (true) {
       cout << "Enter 3 integers" << endl;
       cin >> num1;
       // if any number is -ve, continue the whole loop
       if (num1 < 0) continue;
       cin >> num2;
       if (num2 < 0) continue;
       cin >> num3;
       if (num3 < 0) continue;
       // if every number is positive, just break out of the loop
       break; 
    }
    

    Hope this helps, Thanks - Rajkumar