Java Arrays: 25 Beginner to Advanced Questions
Each question includes a Java logic snippet.
Q1. Find the largest element in an array
Logic Code:
int max=arr[0]; for(int x:arr) if(x>max) max=x;
Q2. Find the smallest element in an array
Logic Code:
int min=arr[0]; for(int x:arr) if(x<min) min=x;
Q3. Calculate the sum of all elements
Logic Code:
int sum=0; for(int x:arr) sum+=x;
Q4. Calculate the average of elements
Logic Code:
double avg=(double)sum/[Link];
Q5. Count even and odd elements
Logic Code:
if(arr[i]%2==0) even++; else odd++;
Q6. Print array in reverse order
Logic Code:
for(int i=n-1;i>=0;i--)
Q7. Reverse an array
Logic Code:
swap(arr[i],arr[j]);
Q8. Find second largest element
Logic Code:
track largest and secondLargest;
Q9. Find second smallest element
Logic Code:
track smallest and secondSmallest;
Q10. Check if array is sorted
Logic Code:
if(arr[i]>arr[i+1]) sorted=false;
Q11. Linear Search
Logic Code:
if(arr[i]==target) found=true;
Q12. Count occurrences of an element
Logic Code:
if(arr[i]==target) count++;
Q13. Find duplicate elements
Logic Code:
compare arr[i] with arr[j];
Q14. Remove duplicates
Logic Code:
use HashSet or manual filtering;
Q15. Find frequency of each element
Logic Code:
use HashMap<Integer,Integer>;
Q16. Move all zeros to end
Logic Code:
place non-zero elements first;
Q17. Find missing number from 1 to N
Logic Code:
missing=expectedSum-actualSum;
Q18. Merge two arrays
Logic Code:
copy elements into a new array;
Q19. Find common elements in two arrays
Logic Code:
use nested loops or HashSet;
Q20. Rotate array left by one position
Logic Code:
store first, shift left, place first at end;
Q21. Rotate array right by one position
Logic Code:
store last, shift right, place last at start;
Q22. Check if two arrays are equal
Logic Code:
compare lengths and elements;
Q23. Find pair with given sum
Logic Code:
if(arr[i]+arr[j]==target)
Q24. Find majority element
Logic Code:
frequency > n/2;
Q25. Maximum subarray sum (Kadane)
Logic Code:
curr=[Link](arr[i],curr+arr[i]);