Home > Back-end >  How to add a loop to this program to ensure user enters positive number, if negative make them retyp
How to add a loop to this program to ensure user enters positive number, if negative make them retyp

Time:10-18

How can I make sure the user enters a positive number, and if its negative give them an error and make them retype it?

int main()
{
    float sq, n;
    cout << "Enter any number:";
    cin >> n;
    sq = sqrt(n);
    cout << "Square root of " << n << " is " << sq;
    return 0;
}

CodePudding user response:

This can be achieved easily with a do-while loop:

int num = 0;
do {
    std::cin >> num;
} while (num < 0)

CodePudding user response:

here, you can use while loop and if-else statement within while loop.

int main()
{
    float sq;
    int n;
    
    cout << "Enter any number:\n";
    while (cin >> n) {
    
      if (n < 0)
        cout << "enter a positive number\n";
      
      else {
      sq = sqrt(n);
      cout << "Square root of " << n << " is " << sq << '\n';
      cout << "Enter any number: \n";
      } 
    }
    return 0;
}
  •  Tags:  
  • c
  • Related