• Wednesday, 15 March 2017

    Generate all the sub arrays of a given array


    Question:

    Given an input array print all the subarrays of the given array.
    Also print the total number of sub arrays that can be formed with the given array.
    Exclude null set.

    Input:

    5
    1
    2
    3
    4
    5
    

    Output:

    ( 1  )
    ( 2  )
    ( 3  )
    ( 4  )
    ( 5  )
    ( 1 2  )
    ( 2 3  )
    ( 3 4  )
    ( 4 5  )
    ( 1 2 3  )
    ( 2 3 4  )
    ( 3 4 5  )
    ( 1 2 3 4  )
    ( 2 3 4 5  )
    ( 1 2 3 4 5  )
    THE TOTAL NO OF SUB ARRAYS ARE: 15
    


    Code:

    #include<stdio.h>
    int main()
    {
     int n;
     scanf("%d",&n);
     int arr[n];
     int i,j;
     for(i=0;i<n;i++)
     {
      scanf("%d",&arr[i]);
     }
     int count=0;
     int length=1;
     for(length=1;length<=n;length++)
     {
      for(i=0;i<n;i++)
      {
       
       if(i+length>n)
       {
        break;
       }
       
       printf("( ");
       for(j=i;j<i+length ;j++)
       {
        printf("%d ",arr[j]);
       }
       count++;
       printf(" )\n");
      }
     }
     printf("THE TOTAL NO OF SUB ARRAYS ARE: %d\n",count);
     return 0;
    }
    




    If you like our blog.. Please share ....

    Thanks.... :)

    No comments:

    Post a Comment

    Follow Us on Facebook: