Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to print all possible ways to write a number (N) as a sum of two or more positive integers in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

void print_array(int* arr, int size) {
    if (size != 1) {
        for (int i = 0; i < size; i++) {
            if (i < size - 1) {
                printf("%d + ", arr[i]);
            } else {
                printf("%d", arr[i]);
            }
        }
    }
     
    printf("\n");
}

void all_ways_to_write_a_number_as_sum_of_two_or_more_ints(int* arr, int* index, int i, int n) {
    if (n == 0) {
        print_array(arr, *index);
    }

    for (int j = i; j <= n; j++) {
        arr[(*index)++] = j;

        all_ways_to_write_a_number_as_sum_of_two_or_more_ints(arr, index, j, n - j);

        (*index)--;
    }
}

int main() {
    int n = 5; // The number
    int* arr = (int*)malloc(n * sizeof(int));
    int index = 0;

    all_ways_to_write_a_number_as_sum_of_two_or_more_ints(arr, &index, 1, n);

    free(arr);
    
    return 0;
}



/*
run:

1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 2
1 + 1 + 3
1 + 2 + 2
1 + 4
2 + 3

*/

 



answered Aug 3, 2024 by avibootz
...