C Program to Generate All Possible Combinations of a Given List of Numbers

«
»
This C program generates all possible combinations of a given list of Numbers.

Here is the source code of the C program to print all combinations for list of N numbers. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include<stdio.h>
  2. #include<string.h>
  3. #define N 10
  4.  
  5. void print(int *num, int n)
  6. {
  7.     int i;
  8.     for ( i = 0 ; i < n ; i++)
  9.         printf("%d ", num[i]);
  10.     printf("\n");
  11. }
  12. int main()
  13. {
  14.     int num[N];
  15.     int *ptr;
  16.     int temp;
  17.     int i, n, j;
  18.     printf("\nHow many number you want to enter: ");
  19.         scanf("%d", &n);
  20.     printf("\nEnter a list of numbers to see all combinations:\n");
  21.     for (i = 0 ; i < n; i++)
  22.         scanf("%d", &num[i]);
  23.     for (j = 1; j <= n; j++) {
  24.         for (i = 0; i < n-1; i++) {
  25.             temp = num[i];
  26.             num[i] = num[i+1];
  27.             num[i+1] = temp;
  28.             print(num, n);
  29. 	}
  30.     }
  31.     return 0;
  32. }

$ gcc combination.c -o combination
$ ./combination
How many number you want to enter: 4
Enter a list of numbers to see all combinations: 1 2 3 4
2 1 3 4 
2 3 1 4 
2 3 4 1 
3 2 4 1 
3 4 2 1 
3 4 1 2 
4 3 1 2 
4 1 3 2 
4 1 2 3 
1 4 2 3 
1 2 4 3 
1 2 3 4

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.