Problem with if else?

Beginner programmer here. The problem says that line 27 has illegal else without matching if.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;

int main()
{
	cout << "Enter two numbers: ";
	float number1 = 0;
	float number2 = 0;
	cin >> number1;
	cin >> number2;

	cout << "Press m to multiply, d to divide: ";
	char selection = {'/0'};
	cin >> selection;

	if (selection == 'd')
		cout << "Congrats, you want division! " << endl;
	{
			if (number2 != 0)
			cout << number1 << " / " << number2 << " = " << number1 / number2 << endl;
	else 
		cout << "You cannot divide by zero! " << endl;
	}

	else
	{
		cout << number1 << " X " << number2 << " = " << number1 * number2 << endl;
	}
	return 0;
}

		
1
2
3
4
5
6
7
8
9
10
if (selection == 'd')
    { //<<<<<<<<<<<add this
		cout << "Congrats, you want division! " << endl;
    {
			if (number2 != 0)
			cout << number1 << " / " << number2 << " = " << number1 / number2 << endl;
	else
		cout << "You cannot divide by zero! " << endl;
	}
    } //<<<<<<<<<add this 
Line 17 is outside the if() "body".
Also, please invest some effort into learning an indent style, and then using it consistently.

Here is your exact code, rewritten to hopefully make the problem obvious:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
using namespace std;

int main()
{
    cout << "Enter two numbers: ";

    float number1 = 0;
    float number2 = 0;

    cin >> number1;
    cin >> number2;
    cout << "Press m to multiply, d to divide: ";

    char selection = {'/0'};

    cin >> selection;

    if (selection == 'd')
        cout << "Congrats, you want division! " << endl;

    {
        if (number2 != 0)
            cout << number1 << " / " << number2 << " = " << number1 / number2 << endl;
        else 
            cout << "You cannot divide by zero! " << endl;
    }

    else
    {
        cout << number1 << " X " << number2 << " = " << number1 * number2 << endl;
    }

    return 0;
}


Note:

1
2
3
4
5
6
7
8
// this is...
if (X)
    act1;
    act2;
    act3;
// the same as
if (X)
{
    act1;
}

act2;
act3;
Thanks. It worked.
Topic archived. No new replies allowed.