IF Else Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{
    int a;
    cout<<"Enter a:";
    cin>>a;
    if(a>10)
        cout<<a;
    else
        cout<<"Wrong input. Enter again: ";
    return 0;
}


H everyone. I'm a newbie so I have a basic question for my code above. If I enter a value for a < 10. What should I do to enter the value again instead of exit the program?
Last edited on
You probably haven't learned about while or do/while loops yet, but one method for repeatedly asking for input until you get an acceptable value is (rewriting the if/else):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{

   std::cout << "Enter a: ";
   int a;

   do
   {
      std::cin >> a;

      if (a <= 10)
      {
         std::cout << "Wrong input. Enter again: ";
      }
   }
   while (a <= 10);

   std::cout << a << '\n';
}
Enter a: 5
Wrong input. Enter again: 12
12

https://www.learncpp.com/cpp-tutorial/55-while-statements/
https://www.learncpp.com/cpp-tutorial/56-do-while-statements/

goto could also be used, but using it is frowned upon and not recommended:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
   int a;

begin_loop:
   std::cout << "Enter a: ";
   std::cin >> a;

   if (a > 10)
   {
      std::cout << a << '\n';
   }
   else
   {
      std::cout << "Wrong input. Enter again: ";
      goto begin_loop;
   }
}

https://www.learncpp.com/cpp-tutorial/54-goto-statements/
thanhquan1704 wrote:
If I enter a value for a < 10

Your if statement actually checks for a value greater than 10, so 10 and below is rejected. If you want a value to be 10 or greater the if should be if (a >= 10).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

int main()
{
   int a;
   cout<<"Enter a: ";
   while ( true )
   {
      cin >> a;
      if ( a > 10 ) break;
      cout << "Wrong input. Enter again: ";
   }
   cout << a;
}
Topic archived. No new replies allowed.