need help on my homework.

i need the message to show up only once for example i input 80 it only shows the 2nd message.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
  int main()
{
	int a;
	cout<<"Enter Grade = ";
	cin>>a;
	cin.ignore();
	if (a >=75)
		cout<<"You are passed!" << endl;
	if (a >=80)
		cout<<"You have an average level of ability!" << endl;
	if (a >=90)
		cout<<"You are outstanding student!" << endl;
	if (a <=74)
		cout<<"You are failed!" << endl;	
return 0;		
}
Last edited on
1
2
if (a >=75   && 
    a <  80 )


Similarly for other if statements.
Reorganize your if's a bit and use else:
1
2
3
4
5
	if (a <75)
		cout<<"You are failed!" << endl;	
	else if (a <80)
		cout<<"You are passed!" << endl;
...
i did as you guys said and it works now thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;
int main()
{
	int a;
	cout<<"Enter Grade = ";
	cin>>a;
	cin.ignore();
	if (a >=75 && a<=79)
		cout<<"You are passed!" << endl;
	else if (a >=80 && a<=89)
		cout<<"You have an average level of ability!" << endl;
	else if (a >=90 && a<=100)
		cout<<"You are outstanding student!" << endl;
	else if (a >=50 && a<=74)
		cout<<"You are failed!" << endl;	
return 0;		
}
Last edited on
One can use the opposite direction too:
1
2
3
if ( a >= 90 ) cout << "A\n";
else if ( a >= 80 ) cout << "B\n";
...

However, a foo >= bar is essentially (bar < foo) || (bar == foo) and also !(foo < bar).
The < is simpler to read and compute than the >=.

The real point of else is mutual exclusiveness:
1
2
3
4
5
6
7
8
if ( cond )
{
  // have a cake
}
else
{
  // eat a cake
}

The cond is either true or false, never both.
You will either have the cake or eat it, but never both.

The further benefit in if .. else if is that when a condition is true, all the following else branches will be skipped. If we know that a is less than 75, there is no need to compute the a<80 and the a<90.


The Repeater's style of independent if-statements with complex conditions does have two issues:
* Every condition has to be evaluated, even when logic tells that they must false.
* Complex conditions are harder to write and maintain.
Registered users can post here. Sign in or register to post.