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.
#include <iostream>
usingnamespace 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;
}
#include <iostream>
usingnamespace 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 : 8060 40
output : band 3band 2 band 1
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)
#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.