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

1 Answer

0 votes
program ProductExceptSelf;

{
    Computes product of array except self.
    nums   = input array
    size   = number of elements
    returns an IntArray containing the result
}

type
    IntArray = array[1..100] of Integer;  { simple static array for Turbo Pascal }

function ProductExceptSelf(nums: IntArray; size: Integer): IntArray;
var
    answer : IntArray;
    prefix, suffix : Integer;
    i : Integer;
begin
    prefix := 1;

    { ---- Prefix products ---- }
    { answer[i] gets product of all elements before i }
    for i := 1 to size do
    begin
        answer[i] := prefix;                 { store prefix product }
        prefix := prefix * nums[i];          { update prefix }
        { Example for nums = {5,2,3,4}:
          prefix values: 1, 5, 10, 30 }
    end;

    { ---- Suffix products ---- }
    { Multiply each answer[i] by product of all elements after i }
    suffix := 1;
    for i := size downto 1 do
    begin
        answer[i] := answer[i] * suffix;     { combine prefix * suffix }
        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) }
    end;

    ProductExceptSelf := answer;             { return the array }
end;

var
    arr, result : IntArray;
    size, i : Integer;

begin
    { Input array }
    size := 4;
    arr[1] := 5;
    arr[2] := 2;
    arr[3] := 3;
    arr[4] := 4;

    { Compute product-except-self result }
    result := ProductExceptSelf(arr, size);

    { Print result }
    Write('Result: ');
    for i := 1 to size do
        Write(result[i], ' ');
end.



(*
run:

Result: 24 60 40 30 

*)


 



answered Jan 2 by avibootz
edited Jan 3 by avibootz

Related questions

...