IF statement to control value range

How would I control the data range to ensure a mark entered was between 0 and 100, if it is less than 0 and greater than 100 it is invalid. I know this can be done using IF statements but I'm not sure how to go about it. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  using namespace std; 

int mark[5];

int main () 
{
	cout << "enter mark 0:  ";
	cin >> mark[0];

	
	cout << "enter mark 1:  ";
	cin >> mark[1];

	cout << "enter mark 2:  ";
	cin >> mark[2];

	cout << "enter mark 3:  ";
	cin >> mark[3];

	cout << "enter mark 4:  ";
	cin >> mark[4];

}
Last edited on
Something like this should do. It uses a while loop + if statements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main () 
{
    using namespace std; 
    int mark[5];

    for (int i = 0; i < 5; i++)
    {
        do
        {
            cout << "enter mark " << i << ":  ";
            cin >> mark[i];
        }
        while (mark[i] < 0 || mark[i] > 100);
    }
}
I'd create a function to do it:
1
2
// Prompt the user with "prompt" and then read an int from cin.  Repeat if they enter a non-integer, or an int outside the range [low, high). Returns the valid int.
int getInt(const char *prompt, int low, int high)
Topic archived. No new replies allowed.