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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to product of array except self (arr[i] is equal to the product of all the elements except arr[i]) in C

1 Answer

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

/*
    Computes product of array except self.
    nums   = input array
    size   = number of elements
    answer = output array (allocated by caller)
*/
void productExceptSelf(const int *nums, int size, int *answer) {
    int prefix = 1;

    // ---- Prefix products ----
    // answer[i] gets product of all elements before i
    for (int i = 0; i < size; i++) {
        answer[i] = prefix;   // store prefix product
        prefix *= nums[i];    // update prefix
        // Example for nums = {5,2,3,4}:
        // prefix values: 1, 5, 10, 30
    }

    // ---- Suffix products ----
    // Multiply each answer[i] by product of all elements after i
    int suffix = 1;
    for (int i = size - 1; i >= 0; i--) {
        answer[i] *= suffix;  // combine prefix * suffix
        suffix *= nums[i];    // update suffix
        // suffix values: 1, 4, 12, 24, 120
        // final answer: 24, 60, 40, 30
        // 24 (24*1) 60 (12*5) 40 (10*4) 30 (30*1)
    }
}

int main(void) {
    int arr[] = {5, 2, 3, 4};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Allocate output array
    int *result = malloc(size * sizeof(int));
    if (!result) {
        perror("malloc failed");
        return 1;
    }

    productExceptSelf(arr, size, result);

    printf("Result: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    free(result);
    
    return 0;
}



/*
run:

Result: 24 60 40 30 

*/

 



answered Jan 2 by avibootz

Related questions

...