so here the if inside the loop is it possible to write the if statement in an optimized way or should I just split the two conditions?
#include <iostream>
using namespace std;
int main()
{
int grade, counter = 1, total = 0, average;
while (counter <= 10)
{
cout << "Enter grade /100: ";
cin >> grade;
if (grade < 0 && grade > 100) //HERE PLEASE
{
cout << "invalid grade value." << endl;
cout << "Reenter grade value */100*: ";
cin >> grade;
}
total = total grade;
counter ;
}
average = total / 10;
cout << "\nThe class average is: " << average << endl;
return 0;
}
CodePudding user response:
if (grade < 0 && grade > 100)
There is no number that is lower than 1
and bigger than 100
, so that conditions will return false
every time.
If you want lower than 1
or bigger than 100
, try:
if (grade < 0 || grade > 100)
Overall, your code should be:
#include <iostream>
// using namespace std; is bad practice, so don't use it
int main()
{
int grade = 0, counter = 1, total = 0, average = 0;
while (counter <= 10)
{
std::cout << "Enter grade /100: ";
std::cin >> grade;
if (grade < 0 || grade > 100)
{
// use newline character instead of std::endl
std::cout << "invalid grade value." << '\n';
std::cout << "Reenter grade value */100*: ";
std::cin >> grade;
}
// a = a b is equal to a = b
total = grade;
counter;
}
average = total / 10;
std::cout << "\nThe class average is: " << average << '\n';
return 0;
}