For Loops and stopping conditions

人走茶凉 提交于 2021-02-05 12:32:29

问题


Can anyone explain why the answers are what they are please? The first one i guess its because the stopping condition is already reached so it skips the statement but question 13 why would it not print 4321?

12.What output is produced by the following code:

int n;
for (n = 1; n > 4; n++)
    System.out.print(n); 

a) 12345

b) 1234

c) 0 ---> for loop never runs because stopping condition already met.

d) It produces no output*

13.What output is produced by the following code:

int n;
for (n = 4; n > 0; n--);  
    System.out.print(n); 

a) 43210

b) 4321

c) 0* ---> semi colon after for loop, causing print statement to run after loop is finished

d) It produces no output


回答1:


Regarding question 13: there's a semicolon behind the for-loop. Because of that, the loop will first be execuetd until n no longer is > 0 => it is zero then. Then, the print will show a zero.




回答2:


The first will produce no output as the for loop body is never run (assuming that the print line is within the for loop). The second appears to do nothing in the for loop and just prints the value of n after the loop. Which would be 0 as it has just failed a test for being greater than 0.




回答3:


In Question 13 :

for (n = 4; n > 0; n--);

the loop executes directly. So, It just decreases the value of n, and didnot enter to the next statement until it completes its execution. So, here it won't come to statement until it completes its execution. At the End of execution value of n is 0. So, when it comes to statement

System.out.print(n);

value of n is 0 , so the output of the program is 0




回答4:


In question 13) there's a ; after the for-loop, it means that the program do nothing but (n--) 4 times. It results that the value of n become 0.



来源:https://stackoverflow.com/questions/10293711/for-loops-and-stopping-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!