'How can I skip the goto statement if the user enters marks less than 100
Note: I am a beginner. I have used goto statement to execute if the user enters marks more than 200 but if the user has entered marks less than 100 then the rest of the code should run. How can I do that ?
Here is the piece of code
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e;
float sum, perc;
int total = 500;
INPUT:
cout << "Enter marks for English" << endl;
cin >> a;
cout << "Enter marks for Urdu" << endl;
cin >> b;
cout << "Enter marks for Maths" << endl;
cin >> c;
cout << "Enter marks for Computer" << endl;
cin >> d;
cout << "Enter marks for Islamiat" << endl;
cin >> e;
if (a > 100 && b > 100 && c > 100 && d > 100 && e > 100) {
cout << "You must enter all subject marks below 100" << endl;
}
goto INPUT;
sum = a + b + c + d + e;
perc = (sum / total) * 100;
if (a <= 100 && b <= 100 && c <= 100 && d <= 100 && e <= 100) {
cout << "Percentage is = " << perc << "%" << endl;
}
else {
cout << "You must enter marks below 100" << endl;
return 0;
}
if (perc >= 50) {
cout << "Congratulations you are Passed" << endl;
}
else {
cout << "You are fail" << endl;
}
return 0;
}
Solution 1:[1]
As already pointed out in the comments section, the line
if (a > 100 && b > 100 && c > 100 && d > 100 && e > 100) {
is wrong. The entire if condition will only be true if all of the entered marks are above 100, but you want the if condition to be true if at least one of the entered marks are above 100. You can accomplish this by using || (logical OR) instead of && (logical AND).
Another issue is that using goto should generally be avoided, if you can easily accomplish the same thing using a loop. See the following question for further information: What is wrong with using goto?
The other answer avoids goto by using a do...while loop. It does this by introducing an additional variable and by checking that variable multiple times per loop iteration. However, if you use an infinite loop with an explicit break statement instead, introducing an additional variable that must be checked multiple times is not necessary:
//loop forever until input is ok
while ( true )
{
cout << "Enter marks for English: " << endl;
cin >> a;
cout << "Enter marks for Urdu: " << endl;
cin >> b;
cout << "Enter marks for Maths: " << endl;
cin >> c;
cout << "Enter marks for Computer: " << endl;
cin >> d;
cout << "Enter marks for Islamiat: " << endl;
cin >> e;
//check whether input is ok
if ( a <= 100 && b <= 100 && c <= 100 && d <= 100 && e <= 100 )
//input is ok, so we can break out of the infinite loop
break;
//input is not ok, so we must print an error message and repeat the loop
cout << "You must enter all subject marks at or below 100\n" << endl;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
