Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Flow Control

 
Deepak Jindal
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q. Examine the following code. It says the answer to be c). Please explain it to me. Thanx.
public class Calc {
public static void main (String args []) {
int total = 0;
for (int i = 0, j = 10; total > 30; ++i, --j) {
System.out.println(" i = " + i + " : j = " + j);
total += (i + j);
}
System.out.println("Total " + total);
}
}
Does this code:
A. Produce a runtime error
B. Produce a compile time error
C. Print out "Total 0"
D. Generate the following as output:
i = 0 : j = 10
i = 1 : j = 9
i = 2 : j = 8
Total 30
Please select the most appropriate answer.
 
natchit
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
C
 
Sivalingam Sivasuthan
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Deepak Jindal:
That for loop never get execute as the codition is not getting evaluated to true(total>30). so the answer will be c.
Siva.

 
Priya Kannan
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Deepak,
Answer is "Total 0" b'cos the condition "total > 30" in the if statement fails the first time itself.Hey...you gotta read the Qns properly man!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic