≈ the.bay.news

Nested statements versus statements with logical operators

programming.dev
Nested statements versus statements with logical operators
I’m studying nested statements, but realized that there - of course - is a way to get the same results without nesting. I’m not trying to avoid nesting, it’s just fun to try to achieve the same result with different methods. Next, I’m trying the ternary operator, for instance. Is either one of these preferred over the other? Is either more computationally heavy than the other? I realize that the latter one tests age two times, but other than that. Or is it a matter of style? // with nested statements if (age >= 18) { printf("You are old enough to vote "); if (isCitizen == 'Y') { printf("and you are a citizen, so you can vote.\n"); } else if (isCitizen == 'N') { printf("but you are not a citizen, so you cannot vote.\n"); } } else if (age < 18) { printf("You are not old enough to vote "); if (isCitizen == 'Y') { printf("but you are a citizen. Come back when you are old enough!\n"); } else if (isCitizen == 'N') { printf("and you are not a citizen, so you cannot vote.\n"); } } else { printf("Incorrect input.\n"); } // with logical operators if (age >= 18 && isCitizen == 'Y') { printf("You are old enough to vote and you are a citizen, so you can vote.\n"); } else if (age >= 18 && isCitizen == 'N') { printf("You are old enough to vote but you are not a citizen, so you cannot vote.\n"); } else if (age < 18 && isCitizen == 'Y') { printf("You are not old enough to vote but you are a citizen. Come back when you are old enough!\n"); } else if (age < 18 && isCitizen == 'N') { printf("You are not old enough to vote and you are not a citizen, so you cannot vote.\n"); } else { printf("Incorrect input.\n"); } return 0; }

0 comments

Sign in to join the discussion — your thebay.events account works here.

No comments yet.