-4

I have created an array that holds 5 numbers, and the user inputs the numbers. If the mark is less than 0 and greater than 100, I want to print out "invalid mark number". How could I do that?

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];

}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
itsTed
  • 9
  • 7

1 Answers1

1

You should use a for-loop to make the code more readable and compact. Because once you introduce if statements, the code size would grow alot. It should look like this:

#include <iostream>

using namespace std;

int mark[5];

int main () {
    for (int i = 0; i < 5; i++){
        cout << "enter mark " << i << ":  ";
        cin >> mark[i];
        if (mark[i] < 0 || mark[i] > 100){
            cout << "invalid mark number\n";
        }
    }
}

Don't use using namespace std; (read here why) and keep the int mark[5]; inside the main-function (read here why). Also to add to the logic force the user to input again:

#include <iostream>

int main () {
    int mark[5];
    for (int i = 0; i < 5; i++){
        bool valid_input = false;
        while (!valid_input){
            std::cout << "enter mark " << i << ":  ";
            std::cin >> mark[i];
            if (mark[i] < 0 || mark[i] > 100){
                std::cout << "invalid mark number\n";
            }
            else{
                valid_input = true;
            }
        }
    }
}
Stack Danny
  • 7,754
  • 2
  • 26
  • 55