# logic problem

Bhargav Patel
Greenhorn
Posts: 1
hii..i am totally new to java when i compile this code it's run successful..but not get desired code...whts problem with it?
it's simple program to find largest among arrays..

nir sharma
Ranch Hand
Posts: 72

you need to understand what is happening in this loop.
you are only checking values at j and j+1 position in the array, and replacing the previous value of k with the new value.
you need to check whether the new value the you get from the max function is greater than the value of k or not, if not then you should not replace it.
you need to write the code on your own.

Lexington Smith
Ranch Hand
Posts: 67

Run this code and see the output.

nir sharma
Ranch Hand
Posts: 72
@Lexington Smith
can you tell me what different you are doing in your code , because I am unable to find the difference and hence the same result.

Campbell Ritchie
Sheriff
Posts: 50671
83
Welcome to the Ranch
What did you expect to happen and what actually happened? You need to tell us that if we are to help. Also, I have added code tags, which you should always use, and you can see how much better the code looks.

Campbell Ritchie
Sheriff
Posts: 50671
83
Lexington Smith wrote: . . .
. . . .
Not convinced. I think that line you have added will produce interesting results. What do you think the output will be from {12, 54, 44, 34}?

Swathi Kodeboyina
Greenhorn
Posts: 9
@ Bhargav Patel.

The value of k is replaced every time in the loop. The value of k should be changed only if Math.max(i[j],i[j+1]) is greater than k.

i hope this solves your problem according to what i assume your problem is. If not, tell what is the output you need?

Lexington Smith
Ranch Hand
Posts: 67
Campbell Ritchie wrote:
Lexington Smith wrote: . . .
. . . .
Not convinced. I think that line you have added will produce interesting results. What do you think the output will be from {12, 54, 44, 34}?

Yes, I made a mistake. Corrected the code -

There is a bug though - if all numbers in array are negative, then your code will give 0 as the result.

Gaurangkumar Khalasi
Ranch Hand
Posts: 187
Bhargav Patel wrote:...whts problem with it?

fred rosenberger
lowercase baba
Bartender
Posts: 12228
36
Bhargav,

A couple of suggestions..

First, I would use more descriptive variable names. "k" doesn't tell me anything. however, "maxFound" tells me EXACTLY what it means...

If you want to see why your code doesn't work, put a bunch of System.out.println() statements in it to see what it is REALLY doing. something like this:

>