Computer Science, asked by harisunderrout9278, 10 months ago

Hjava program to find the given number in an array without using for/whilellop

Answers

Answered by sswaraj04
0

Answer:

import java.util.Scanner;

   public class Recursion {  

   static void p(int[] array,int a,int b,int size){  

     if(b<size)

     {

         if(array[b]==a)

         {

              System.out.println(a+" found at index "+(b+1));

         }

         else

         {

             p(array,a,b+1,size);

         }

     }

     else

     {

       System.out.println("Not found");  

     }

   }  

     

   public static void main(String[] args) {

   Scanner sc=new Scanner(System.in);

   System.out.println("Enter size of array");

   int n=sc.nextInt();

   int arr[]=new int[n];

   System.out.println("Enter array elements in consecutive lines");

   for(int i=0;i<n;i++)

   {

    arr[i]=sc.nextInt();

   }

   System.out.println("Enter element to search:");

   int key=sc.nextInt();

   int r=0;

   p(arr,key,r,n);  

   

   }  

   }  

Explanation:

I have used for loop for taking input You can remove it if you will directly feed it into program

now concept used here for searching element is called recursion.

we will pass the array and size and element to be found in function

and in the function we will search for the element in given array

and subsequently function are passed with array ,key element and index-1 each time until element is found

if found it will print the index

otherwise when element is not found till last index 'variable b'i.e index will increase more than size and as per condition it will print not found

In recursion, function is passed again and again in itself body till some false condition is reached otherwise infinitely

Try to dry run it

For better understanding

Hope it helps :-)

Similar questions