Hi Everyone, I just started taking an Intro course to programming and I am confused. I was wondering if someone can help me with my homework? Thanks! Given the following if statements, what is the value of the variable sign and state at the end of executing all the if statements. Explain how you arrived at your answer.int state = 30; String sign = ""; if (state > 27) { if (state == 30) { sign = “blue”; } else { sign = “green”; }}else{ sign = “yellow”;}
Were you given an initial condition or just evaluating each if statement? What did you come up with?
Just go through like it's a math problem. Substitute in the variables. if (30 > 27) { // 30 is greater than 27, so continue if (30 == 30) { // 30 is 30, so continue sign = "blue"; // set sign to "blue" } else { //don't evaluate because 30 was 30 sign = "green"; } } else { //don't do it because 30 > 27 sign = "yellow"; } So sign = "blue" state was never changed, so it = 30
Let me know if you need more help
Okay thank you so much! As a beginner, I'm still trying to wrap my head around this...but thank you!
The key here is not to stuck with the specific piece of code, but to think in terms of algorithms. In each and every case you have to evaluate or generally to analyze a piece of code, pseudocode comes to the rescue. That's why we use this tool before we write an actual program (seeing the whole procedure from the reverse angle). So, you convert your statements in pseudocode doing computations in your mind e.g. this has this initial value. Add this. Assign to this variable etc., and then converting this piece of pseudocode to a real program in whatever programming language you need or you choose anyway, is a lot easier. Pseudocode is not actual code - as its name implies, it's an algorithms related tool, that is closer to human way of thinking than actual code, so it cannot be executed by a computing machine, but you write something you can evalute on paper and then if it works, converting to a programming language's real statements.
Join our real-time social learning platform and learn together with your friends!