Hello I have the understanding on how to fill an array with loop iterations. But to understand and bridge the gap to complexity I would like to know how to solve this problem recursively.
The problem is let 'n' be an index for array 'nums'. nums will store all the previous numbers in it's array. For example, n=6; nums = [0=6],[1=5],[2=4],[3=3],[4=2],[5=1].
static void Main(string[] args)
{
int n = 6;
int[] nums = new int[n];
for(int i = 0;i < nums.Length; i )
{
Console.WriteLine(fillArray(nums, n)[i]); //expected output 6,5,4,3,2,1
}
}
static int[] fillArray(int[] nums, n)
{
for(int i = 0; i< nums.Length; i )
{
nums[i] = n--;
}
return nums;
}
Much appreciated, thank you all for your responses!
CodePudding user response:
You can try this:
static void fillArray(int[] nums, int index, int n)
{
if(index == nums.Length)
{
return;
}else
{
nums[index] = n;
fillArray(nums, index 1, n - 1);
}
}
static void Main(string[] args)
{
int n = 6;
int[] nums = new int[n];
fillArray(nums, 0, n);
for(int i = 0;i < nums.Length; i )
{
Console.WriteLine(nums[i]); //expected output 6,5,4,3,2,1
}
}