This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array with decrement operator

 
Devaraj Rajakumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone please help me with the following issue?

I tried to process some data in an array using �for� loop and came across following problem with the condition statement.

int [] intArray = {1,5,4,6};
for(int x = intArray.length-1; x = =0; x--){
System.out.println(intArray[x]);
}

Since the condition statement should be of Boolean type I used �x= =0 � and also I tried �x<=0� but both compiles OK, not running and no run time errors.

When I changed to �x>=0� it works perfectly. I�m bit confused why this is happening.

Regards,
Devaraj
 
bart zagers
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The body of the for loop is executed as long as the conditional statement is true. So you should use x >= 0, then it will loop unitl x gets to zero, what is what you want.
 
Devaraj Rajakumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks bart zagers, I guess the condition statement should be always applied so that it does not refer to "0" initially.
 
bart zagers
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to explain it properly

for statement
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW: Did you really write x = =0? You can't have a space between the two = in an equality operator.
 
Devaraj Rajakumar
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well, I didnt have any space in between the two equal signs. (==)

thanks
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The space might have been a misprint wherever you found your example.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic