Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please tell me why it prints 0

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);

}

}

Please tell me why it prints 0
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Karthik ,
well it prints 0 because it never enter the for loop.
this is your for statement:
for (int i = 0, j = 10; total > 30; ++i, --j)

it states that i and j should start from 0, after every iteration i should increment with 1 and j should decrement with 1
but most importantly it specifies that loop should continue to run while value of total is greater then 0 now.
before this statement you have written:
int total = 0;

as the condition is already false. it never enters the for loop.

I Hope this will help you

Sandy
[ September 16, 2005: Message edited by: Sandeep Chhabra ]
 
Kj Reddy
Ranch Hand
Posts: 1704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Karthik Rajashekaran:
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);

}

}

Please tell me why it prints 0


The for loop never be executed so the out put is
Total 0

In for loop you gave condition that total > 30, as total is initialized to 0,
total >30 is false. So it never enters into for loop.
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot

One more doubt

if i write return temp inside the code then will it execute
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thanks a lot

One more doubt

if i write return temp inside the code then will it execute


Which variable temp are you talking about? and where do you want to add this line in the code?

Sandy
 
Arvind Giri
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Karthik,
it will be better if you post the code you are asking about.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic