nested if else

hello. I'm confuse with these two program.
why there is difference when put the braces in nested if else statement?
Output for program A is difference from program B.


programA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main() {
	int marks, band;

	cout << "Enter your marks: ";
	cin >> marks;

band = 1;
if (marks > 50) 
{
if (marks < 75)
band = 2;	
} 
else
band = 3;

	cout << "You are in band " << band << endl;

    system("PAUSE");  // for Dev C++ 
	return 0;
}



sample input: 80 60 40
output : band 1 band 2 band 3




programB


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main() {
	int marks, band;

	cout << "Enter your marks: ";
	cin >> marks;

	band = 1;
if (marks > 50) 
    if (marks < 75)
	band = 2;	
else
band = 3;

	cout << "You are in band " << band << endl;

    system("PAUSE");  // for Dev C++ 
	return 0;
}


sample input : 80 60 40
output : band 3 band 2 band 1
Last edited on
Format your code properly and everything will be clear:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
band = 1;
if (marks > 50) 
{
    if (marks < 75)
        band = 2;	
} 
else
    band = 3;

//VS

band = 1;
if (marks > 50) 
    if (marks < 75)
        band = 2;	
    else
        band = 3;
If first case else is grouped with first if and is executed when it is false (marks <= 50)
In second case it is grouped with second if and executed when it is false (marks >= 75)
Last edited on
Because in the second case the else is 'paired' with your second if. Not the first. Your indentation is confusing you.
Thanks MiiNiPaa and mutexe.
i understood now.

MiiNiPaa is this more proper format than before?
Thanks for telling about the format.
Last edited on
Basic rule of indent: lines belonging to the same "level of execution" should be lined vertically. Lines of nested code blocks should be deeper.

As for style of formatting, pick whichever you like: http://en.wikipedia.org/wiki/Indent_style
I prefer K&R and would write your code as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main() {
    int marks;
    std::cout << "Enter your marks: ";
    std::cin >> marks;

    int band = 1;
    if (marks > 50) {
        if (marks < 75)
            band = 2;	
    } else
        band = 3;
    std::cout << "You are in band " << band << '\n';
}


Check if you IDE provide autoindent feature (and tell it to replce tabs with spaces: do not mix tabs and spaces as indent). Most modern ones do.
Last edited on
Topic archived. No new replies allowed.