• Post Reply Bookmark Topic Watch Topic
  • New Topic

Traversing an integer array  RSS feed

 
Bhupinder Verma
Greenhorn
Posts: 8
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Above program runs fine.Above in each iteration we have 2 conditions, first to check if iteration number is less then array length and second is to match it with the search integer.I am required to reduce these two conditions and make it one only.Have tried it but no success.Can anyone help?
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can test the logical AND of more than one boolean condition using the "&&" operator.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bhupinder Verma wrote:Above program runs fine.

But when posting code, please UseCodeTags (←click). I've added them for you this time - see how much better it looks?

I am required to reduce these two conditions and make it one only.Have tried it but no success.

What have you tried? We're happy to help, but we don't just like to just hand out solutions.

Hint: Try and think of a loop condition that will automatically stop when a match is found. Ulf has given you a good start.

Winston
 
Bhupinder Verma
Greenhorn
Posts: 8
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried this inside my while condition as below

"while((i<arr.length)&&(arr[i++]==search))"

But in such case condition is failing first time itself and I am not able to enter while loop.


Hey Winston thanks.Will keep that in mind.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You already have a boolean variable that indicates whether the loop should be executed another time - why not use that?
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code would be a lot easier to understand with a bit more spacing.

Never write == false or == true or similar, which is bad style and error‑prone; what if you write = instead by mistake?
Not if (b == true) ... but if (b) ...
Not if (b == false) ... but if (!b) ...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!