0

Receiving 5,9,7 as output.. Where as the expected should be only 9..Below is the code:

public class GreatestNoInArray {  
    public static void main(String[] args) {                
        int a[]= new int[] {1,2,5,9,7};        
        int big=a[0];        
        for (int i=1; i<a.length; i++){        
            if (big<a[i])        
                big=a[i];                   
            System.out.println(a[i]);        
        }
    }    
}

Please help

3 Answers 3

7

for expected answer you need to print big (not a[i]) out side of loop

Sign up to request clarification or add additional context in comments.

Comments

4
public class GreatestNoInArray {
  public static void main(String[] args) {
      int a[]= new int[] {1,2,5,9,7};
      int big=a[0];

      for (int i=1; i<a.length; i++){
          if (big<a[i])       
              big=a[i];
          }   
      System.out.println(big);
  }
}

1 Comment

How silly was that.. I declared a variable for the largest and m printing i instead.. Thanks a lot mate..
0

code should be like this:

public class GreatestNoInArray {  
    public static void main(String[] args) {                
        int a[] = new int[] {1,2,5,9,7};        
        int big = a[0];        
        for (int i=1; i<a.length; i++){        
            if (big < a[i])        
                big = a[i];                   
            //System.out.println(a[i]);        
        }
    System.out.println("Big: " + big);
    }    
}

This works!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.