my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Please tell me why it prints 0 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Please tell me why it prints 0" Watch "Please tell me why it prints 0" New topic
Author

Please tell me why it prints 0

Karu Raj
Ranch Hand

Joined: Aug 31, 2005
Posts: 479
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

Joined: Aug 28, 2005
Posts: 340
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 ]

Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Kj Reddy
Ranch Hand

Joined: Sep 20, 2003
Posts: 1704
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

Joined: Aug 31, 2005
Posts: 479
Thanks a lot

One more doubt

if i write return temp inside the code then will it execute
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
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

Joined: Jun 26, 2005
Posts: 91
Hi Karthik,
it will be better if you post the code you are asking about.


Regards<br /> <br />Arvind Giri<br />MCA,SCJP 1.4,SCWCD 1.4<br />Looking for SCDJWS
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Please tell me why it prints 0