If/else question

This is a homework question...

I have completed it and worked out everything but this:

I am a nested if to determine the smallest number. If the numbers are equal there should only be one message displayed. ("The numbers are equal.")

I am getting two messages. The one above and ("The smallest number is 0.")

Can you tell me where I need to look to correct my mistake?



if (num1 == num2)
cout << "The two numbers are equal." << endl;
else if (num1 > num2)
smallNum = num2;
else smallNum = num1;
cout << " The smallest number is " << smallNum << "." << endl;


Thanks for reading! :)
1
2
3
4
5
6
7
8
9
10
11
if (num1 == num2)
   cout << "The two numbers are equal." << endl;
else 
{ 
   if (num1 > num2)
      smallNum = num2;
   else 
      smallNum = num1;

   cout << " The smallest number is " << smallNum << "." << endl;
}
Last edited on
The last row does not belong to any of the if/else statements so it will always run. What you can do is use curly braces to tell that it should be part of the first else.

1
2
3
4
5
6
7
8
9
10
if (num1 == num2)
	cout << "The two numbers are equal." << endl;
else 
{
	if (num1 > num2)
		smallNum = num2;
	else 
		smallNum = num1;
	cout << " The smallest number is " << smallNum << "." << endl;
}
Last edited on
Thanks! That solved it :)

I didn't know I could put {} within another set of {}.
you can also do {{{}{{}{}}}{}} etc...
as long as the number of { is equal to the number of } and everything makes sense there is no problem
Last edited on
You can write these if-else statements without {} and intermediate variable smallNum. For example

1
2
if (num1 == num2 ) cout << "The two numbers are equal." << endl;
else cout << " The smallest number is " << ( num1 < num2 ? num1 : num2 ) << "." << endl;
Last edited on
only problem is that nesting stuff can get hard to understand after a while
only problem is that nesting stuff can get hard to understand after a while

That's why it's usual to indent the source code to correspond with the degree of nesting. That in itself, at least with practice, renders the meaning more obvious. The compiler doesn't care about the whitespace used, but to the human reader it is very important.

For example in the code posted above by Peter87, it is clear from the indentation where the cout at line 9 belongs in the control structures.

It's often useful to insert a blank line before and after some blocks of code, to indicate whether they do or do not belong together logically.
Last edited on
Topic archived. No new replies allowed.