Find all sub-array from array

Question:

Find all possible subarray from given array

Given an array of positive integers,  Write an C# Program to find all sub arrays from an array.

int [] a = {5, 4, 9};

Output:

{4}, {9}, {1}, {5, 4} , {4, 9}, {5, 4, 9}

Answer:

Subarray of an array a is a[i..j] where 0 <= i <= j < n where n is length of array.

using System;

namespace SubArray
{
    class Program
    {
        static void Main()
        {
            var a = new[] { 5, 4, 9, 1, 7, 8, 3 }; 

            for (var i = 0; i < a.Length; i++)
            for (var j = i; j < a.Length; j++)
            {
                for (var k = i; k <= j; k++) Console.Write($"{a[k]} ");
                Console.WriteLine("");
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *