What is wrong with this?

So I am a beginner to C++..I was doing this algorithm when some errors occurred
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream.h>
using namespace std;
int main ()
{
	int a,b,x;
	cout<<"a=";cin>>a;
	cout<<"b=";cin>>b;
	if (a!=0) x=(-b/a);cout<<"x="<<x;
		else 
			if (b!=0) cout<<"Infinity of solutions";
				else cout<<"no solution";
	return 0;
	
	
}

What is wrong with this???? The errors i get are :
expected primary-expression before "else"
expected `;' before "else"
expected primary-expression before "else"
expected `;' before "else"
This goes for both "else" I must mention that I use MinGW developer studio.And one last question,Should I use visual studio ? If so what is the difference between a custom C++ dev. program and visual studio?
Thank you for your adivse.



Use curly brackets to group multiple statements

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,b,x;
	cout<<"a=";cin>>a;
	cout<<"b=";cin>>b;
	if (a!=0)
	{
		x=(-b/a);
		cout<<"x="<<x;
	}
	else if (b!=0)
		cout<<"Infinity of solutions";
	else 
		cout<<"no solution";
	return 0;
}
Always play safe and use curlies for control statement bodies:
1
2
3
4
5
6
if(condition) { 
// BODY
}
else {
// BODY
}

For example, your line 8 already has a body of two statements. Curly-less bodies only allow a single statement. Now, it says this:
1
2
3
4
5
6
if (a!=0) {
    x = (-b/a);
}
cout << "x="<<x;
else { 
...

As an else must directly follow an if, this throws an error due to the cout in between.
Last edited on
You need curly braces if you want more than 1 statement after if():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream.h>
using namespace std;
int main ()
{
	int a,b,x;
	cout<<"a=";cin>>a;
	cout<<"b=";cin>>b;
	if (a!=0) { x=(-b/a);cout<<"x="<<x; } // Note
		else 
			if (b!=0) cout<<"Infinity of solutions";
				else cout<<"no solution";
	return 0;
	
	
}
Thank you everyone,it really really helped me,Thank you a lot ,now i can continue my studying in C++. Again Thank you!
Topic archived. No new replies allowed.