
Andy R. answered 12/14/18
Computer Engineer/CS Instructor with 10+ Years of Teaching Experience
Hey Sara,
It's probably long after you needed it, but I am submitting an answer in case someone else has similar issues with nested-if statements. Your code is equivalent to this:
#include <iostream>
#include <string>
using namespace std;
int main() {
int x = 8, y = 5;
if (x > y) {
if (y <= 2) {
cout << "Hi-4\n";
cout << "Hi-5\n";
}
}
else {
cout << "Hi-8\n";
}
cout << "Hi-6\n";
}
As you can see, x will always be greater than y, therefore, the cout << "Hi-8\n"; command inside the else statement will not be executed as it refers to the outer if-statement, not the inner one.
Quick tip: use indents; they will help you recognize the blocks of commands better when using nested-if statements.