fork download
  1. /*Write a Program to take an integer array nums. Print an array answer such that answer[i] is equal to the product
  2. of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a
  3. 32-bit integer.*/
  4. #include <stdio.h>
  5.  
  6. int main() {
  7. int n;
  8. scanf("%d", &n);
  9.  
  10. int nums[n], answer[n];
  11.  
  12. for (int i = 0; i < n; i++)
  13. scanf("%d", &nums[i]);
  14.  
  15. // Prefix product
  16. int prefix = 1;
  17. for (int i = 0; i < n; i++) {
  18. answer[i] = prefix;
  19. prefix *= nums[i];
  20. }
  21.  
  22. // Suffix product
  23. int suffix = 1;
  24. for (int i = n - 1; i >= 0; i--) {
  25. answer[i] *= suffix;
  26. suffix *= nums[i];
  27. }
  28.  
  29. // Print result
  30. for (int i = 0; i < n; i++) {
  31. printf("%d", answer[i]);
  32. if (i != n - 1) printf(" ");
  33. }
  34.  
  35. return 0;
  36. }
  37.  
  38.  
Success #stdin #stdout 0.01s 5320KB
stdin
5
1 2 3 4 5
stdout
120 60 40 30 24