Task

Write a program to find the sum of squares of a numeric vector.

The program should work on a zero-length vector (with an answer of   0).



Related task

   Mean


include "cowgol.coh";
include "argv.coh";
 
# Sum of squares
sub sumsquare(vec: [int32], len: intptr): (out: uint32) is  
    out := 0;    
    while len > 0 loop
        var cur := [vec];
        # make positive first so we can use extra range of uint32
        if cur < 0 then cur := -cur; end if;
        out := out + cur as uint32 * cur as uint32;
        vec := @next vec;
        len := len - 1;
    end loop;
end sub;
 
 
# Read array from command line, allowing empty line (giving 0)
var nums: int32[128];
var len: @indexof nums := 0;
 
ArgvInit();
loop
    var argmt := ArgvNext(); # read number
    if argmt == (0 as [uint8]) then
        break; # stop when no more numbers
    end if;
 
    var dummy: [uint8];
    (nums[len], dummy) := AToI(argmt);
    len := len + 1;
end loop;
 
# Print sum of squares of numbers
print_i32(sumsquare(&nums[0], len as intptr));
print_nl();