C Program to Generate All Combiantions of List of Numbers

«
»
This C program to generate all combination of list of numbers.

Here is the source code of the C program to display all possible combination of list of numbers. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to print all combination of list of numbers
  3.  */
  4. #include <stdio.h>
  5.  
  6. /*  Function to generate combination  */
  7. void combinationUtil(int arr[], int data[], int start, int end, int index, int r)
  8. {
  9.     int j, i;
  10.     // Current combination is ready to be printed, print it
  11.     if (index == r) {
  12.         for (j = 0; j < r; j++)
  13.             printf("%d ", data[j]);
  14.         printf("\n");
  15.         return;
  16.     }
  17.  
  18.     // replace index with all possible elements. The condition
  19.     // "end-i+1 >= r-index" makes sure that including one element
  20.     // at index will make a combination with remaining elements
  21.     // at remaining positions
  22.     for (i = start; i <= end && end - i + 1 >= r - index; i++)
  23.     {
  24.         data[index] = arr[i];
  25.         combinationUtil(arr, data, i + 1, end, index + 1, r);
  26.     }
  27. }
  28. /*  End of combinationutil()  */
  29.  
  30. /*  Function to print the combination  */ 
  31. void printCombination(int arr[], int n, int r)
  32. {
  33.     int data[r];
  34.     combinationUtil(arr, data, 0, n - 1, 0, r);
  35. }
  36. /*  End of printCombination()  */
  37.  
  38. /*  The main() begins  */
  39. int main()
  40. {
  41.     int arr[20], r, n, i;
  42.     printf("Enter the number of input : ");
  43.     scanf("%d", &n);
  44.     printf("\nEnter the integers: \n");
  45.     for (i = 0; i < n; i++)
  46.     {
  47. 	scanf("%d", &arr[i]);
  48.     }
  49.     for (r = 1; r <= 5; r++)
  50.         printCombination(arr, n, r);
  51. }

advertisement
$ gcc comb_list.c
$ a.out
Enter the number of input : 3
 
Enter the integers: 
1 2 3
1 
2 
3 
1 2 
1 3 
2 3 
1 2 3

Sanfoundry Global Education & Learning Series – 1000 C Algorithms.

advertisement
If you wish to look at all C Algorithms and Solutions, go to C Algorithms.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn