Write a Java Program to Search Key Elements in an Array


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.Scanner;
  2. public class Javaexcercise
  3. {
  4. public static void main(String[] args)
  5. {
  6. int num, x, flag = 0, i = 0;
  7. Scanner s = new Scanner(System.in);
  8. System.out.print("Enter no. of elements you want in array:");
  9. num = s.nextInt();
  10. int a[] = new int[num];
  11. System.out.println("Enter all the elements:");
  12. for(i = 0; i < num; i++)
  13. {
  14. a[i] = s.nextInt();
  15. }
  16. System.out.print("Enter the element you want to find:");
  17. x = s.nextInt();
  18. for(i = 0; i < num; i++)
  19. {
  20. if(a[i] == x)
  21. {
  22. flag = 1;
  23. break;
  24. }
  25. else
  26. {
  27. flag = 0;
  28. }
  29. }
  30. if(flag == 1)
  31. {
  32. System.out.println("Element found at position:"+(i + 1));
  33. }
  34. else
  35. {
  36. System.out.println("Element not found");
  37. }
  38. }
  39. }

Result

java techstudy.org

     





Related Topics




Popular Posts