-4
public class Main{
    public static void main(String[] args){

        int[] a = {2,7,3,4,5,6,7,8};
        int merker = a[0];
        int i =4;
        int n = a.length;
        while(i<n){
            if(a[i] < merker)
                merker = a[i];
            i = i + 1;
        }
        System.out.print(merker);
    }
}

I don't understand why the while loop does not start at the 5th number of the array as i made int i = 4;.

azro
  • 53,056
  • 7
  • 34
  • 70
Laffa Yett
  • 17
  • 3
  • 1
    Why do you think your loop does not start at the 5th element? – melpomene Jun 11 '19 at 21:08
  • Since the loop looks for the smallest value, and the smallest value is in `a[0]`, and you initialize `merker` with that smallest value, it doesn't matter where in the loop you start, the result will always be `2`. So how do you even "know" it does not start at the 5th number? --- Did you perhaps intend to initialize `merker` with `a[i]` instead of `a[0]`? – Andreas Jun 11 '19 at 21:11

2 Answers2

0

Your process :

  • your merker values 2,
  • you look for a value smaller than it, starting at the 5th value,
  • there is no smaller value,
  • result is 2

To get the smallest value, starting at 5th value, uou need to init merker at a high value like Integer.MAX_VALUE, i refactor a bit to use a for loop, it's easier to understand :

int min = Integer.MAX_VALUE;;
int startindice = 4;            >> a[4] is 5th value : {2,7,3,4,>>5<<,6,7,8}
for(int i = startindice; i < a.length; i++)
    if(a[i] < min)
        min = a[i];

To check wether a value is present or not, with a simple for loop

boolean isPresent(int[]array, int value){
    for(int i=0; i<array.length; i++)
        if(a[i] == value)
            return true;
    return false;
}

For Java 8 ways : How do I determine whether an array contains a particular value in Java?

azro
  • 53,056
  • 7
  • 34
  • 70
0

It does. To verify you can add a println statement:

$ cat Main.java
public class Main{
    public static void main(String[] args){

        int[] a = {2,7,3,4,5,6,7,8};
        int merker = a[0];
        int i =4;
        int n = a.length;
        while(i<n){
            System.out.println("Is " + a[i] + " < " + merker + "? "+ (a[i] < merker) );
            if(a[i] < merker)
                merker = a[i];
            i = i + 1;
        }
        System.out.print("merker = " + merker);
    }
}

$ java Main
Is 5 < 2? false
Is 6 < 2? false
Is 7 < 2? false
Is 8 < 2? false
merker = 2⏎
OscarRyz
  • 196,001
  • 113
  • 385
  • 569