0
#include <iostream>

int main()
{
  int number;
  using namespace std;

  cout<<"write number between 1 and 10:"<<endl;
  cin>>number;

  if (number<=10 && number>=1)
    cout<<"correct!"<< endl;
  else
    do{
      cout<<"wrong! new number:"<<endl;
      cin>>number;
    }
    while(number>10 && number<1);
}

The loop only goes once and ends directly :( i want it to go endlessly until condition is met. Im very new to c++ so any help is appreciated :)

1
  • 5
    number>10 && number<1 This condition can never possibly be true. There is no number that is simultaneously greater than 10 and less than 1. Commented Nov 9, 2016 at 14:27

3 Answers 3

1

Your while condition is wrong, it should be or instead of and there ( || instead of && in your case). To avoid such errors and make code cleaner try to avoid repeating code, ie code that literally or logically does the same. In your code you input from cin twice and you check for condition twice as well:

int number = 0;
while( true ) {
    cout << "Enter number between 1 and 10:";
    cin >> number;
    if( number >= 1 && number <= 10 )
        break;
    cout << "invalid number, try again" << endl;
}
Sign up to request clarification or add additional context in comments.

Comments

0

The while condition is clearly not correct. A variable that is>10 and <1 does not exists. Try to put a || instead of the && in the condition first.

Comments

0
#include <iostream> int main() { int number; using namespace std; cout<<"write number between 1 and 10:"<<endl; cin>>number; if (number<=10 && number>=1) cout<<"correct!"<< endl; else do{ cout<<"wrong! new number:"<<endl; cin>>number; } while(number<10 && number>1); }

Your while condition isn't right and I've fixed that. Your condition isn't met even once Due to do while task is done before checking condition.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.