﻿ C# Sharp Exercises: Generate all possible permutations of an array - w3resource

# C# Sharp Exercises: Generate all possible permutations of an array

## C# Sharp Recursion : Exercise-11 with Solution

Write a program in C# Sharp to generate all possible permutations of an array using recursion.

Pictorial Presentation:

Sample Solution:

C# Sharp Code:

``````using System;

class formPermut
{
public void swapTwoNumber (ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
public void prnPermut (int []list, int k, int m)
{
int i;
if (k == m)
{
for (i = 0; i <= m; i++)
Console.Write ("{0}",list [i]);
Console.Write (" ");
}
else
for (i = k; i <= m; i++)
{
swapTwoNumber (ref list [k], ref list [i]);
prnPermut (list, k+1, m);
swapTwoNumber (ref list [k], ref list [i]);
}
}
}
class RecExercise11
{
public static void Main()
{
int n,i;
formPermut test = new formPermut();
int[] arr1 = new int[5];

Console.WriteLine("\n\n Recursion : Generate all possible permutations of an array :");
Console.WriteLine("------------------------------------------------------------------");

Console.Write(" Input the number of elements to store in the array [maximum 5 digits ] :");
Console.Write(" Input {0} number of elements in the array :\n",n);
for(i=0;i<n;i++)
{
Console.Write(" element - {0} : ",i);
}

Console.Write ("\n The Permutations with a combination of {0} digits are : \n",n);
test.prnPermut(arr1, 0, n-1);
Console.Write ("\n\n");
}
}
```
```

Sample Output:

```Recursion : Generate all possible permutations of an array :
------------------------------------------------------------------
Input the number of elements to store in the array [maximum 5 digits ] :3
Input 3 number of elements in the array :
element - 0 : 1
element - 1 : 2
element - 2 : 3

The Permutations with a combination of 3 digits are :
123 132 213 231 321 312
```

Flowchart :

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

﻿

New Content: Composer: Dependency manager for PHP, R Programming