So I have this assignment question in C language which I have worked on for last 5 hours but can't figure out what's wrong.
Problem Statement:
Take n as number of digits from 1 to 9 and prints all the possible numbers formed without repeating digits. For E.g. If n = 3, then digits are 1,2,3 and numbers are 123, 132, 231, 213, 321, 312.
Input: 2 Output: 12, 21
Input: 3 Output: 123, 132, 231, 213, 321, 312
This is what I have done so far:
#include<stdio.h>
#include<string.h>
#include<math.h>
#define N 10
void print(int *num, int n)
{
int i;
for ( i = 0 ; i < n ; i++){
printf("%d", num[i]);
}
printf("\n");
}
int main()
{
int num[N];
int temp;
int i, n, j,k;
printf("\nNo of digits? : ");
scanf("%d", &n);
for(k=0; k<n; k++){
num[k] = k + 1;
}
for (j = 1; j <= n; j++) {
for (i = 0; i < n-1; i++) {
temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
print(num, n);
}
}
return 0;
}
I am getting expected result for digits upto 3. But from 4 it's not showing all permutations of digits.
No of digits? : 4
2134
2314
2341
3241
3421
3412
4312
4132
4123
1423
1243
1234
On setting counter to go till n! array will be out of index.
So how to correctly count all permutations ?