C++ program to detect a negative input (logic explained)

Here is the C++ code to detect a negative input . It takes input from user until a negative number is entered and it shows the message for negative number.. You all should have in mind how it works exactly. Here is the algorithm.

  Steps
User side
1: User asked to enter a number
2: If the number is negative, screen displays a message that the number is negative.
3: Otherwise user again asked to enter a number.
Developer side
1: Declare variables that are going to be used in program .
2: Start a do while loop.
3: In the loop input a number from user
4: In the while statement place a condition (n>=0) that is number should be positive.
5: Program ends here.

Code:

#include<iostream>
using namespace std;

int main(){
       //declaraton of varables
       int n;
       do
       {
              cout<<"Enter a positve number = ";
              cin>>n;
       }
       while(n>=0);
       cout<<"You entered a negatve number so program is ended"<<endl;
    system("pause");
    return 0;

}

Output:


Comments