Pages

Monday, February 15, 2016

Java : How to iterate through array with out using any loop ?
     
     OR

 How to get sum of members of array with out using any loop



Purpose : This java class to show to iterate array with out using any loop like ( for ,while etc)




public class SumArrayWithoutLoop



{



public static void main (String args[])


 {


int  a [] = {3,5,6,7,8,9,10};


System.out.println("Sum is "+ sumfunction(a,0,-1));

 }


 public static  int  sumfunction ( int arr[ ],int sum,int index)

 {
           

      if (  index  > arr.length-2  )

         {
              
         
          return sum;

         }

    else 
         {   index++;
            sum  = sum + arr[index];
             System.out.println("Index  "+index +" Sum "+sum);
            sum=sumfunction(arr,sum,index);

          }

return sum;

 }






Output :

java SumArrayWithoutLoop

Index  0 Sum 3
Index  1 Sum 8
Index  2 Sum 14
Index  3 Sum 21
Index  4 Sum 29
Index  5 Sum 38
Index  6 Sum 48
Sum is 48


No comments:

Post a Comment