Question

help me with program

I have to find arithmetic mean of the positive elements of each column of the matrix A [5, 4] provided that in each column there is at least one positive element

I've already tried to do it but I cannot understand the error

program double_array;
var
  A : array [1..5, 1..4] of integer;
  B : array [1..5] of real;
  i, j, k : integer;
  s : real;
begin
  writeln('Enter your array');
  for i := 1 to 5 do
  begin 
    writeln(' ');
    for j := 1 to 4 do
      readln( A[i, j] );
  end;
  
  for i := 1 to 5 do
  begin
    s := 0;  k := 0;
    for j := 1 to 4 do
      if A[i, j] > 1 then
      begin
        s := s + A[i,j];
        k := k + 1;
      end;
      B[i] := s / k;
  end;

  writeln('Result B');
    for i := 1 to 5 do
    write ( B[i]:7:3 );
    writeln;
end.

Help me please!

Was it helpful?

Solution

A positive value is A[i, j] > 0, not A[i, j] > 1!


If you want to calculate the means of columns instead of rows, invert the indexes:

for j := 1 to 4 do begin
    s := 0;  k := 0;
    for i := 1 to 5 do
        if A[i, j] > 0 then begin
            s := s + A[i,j];
            k := k + 1;
        end;
    B[j] := s / k;
end;

You have four columns [1 .. 4]. Therefore the outer loop must range from 1 to 4. The inner loop then must iterate through the rows from 1 to 5 in order to add five numbers per column.


I also give you the advice to use constants and more speaking names for the variables, this helps to understand what the code does and to avoid errors.

const
    NumRows = 5;
    NumColumns = 4;

var
    matrix : array [1..NumRows, 1..NumColumns] of integer;
    arithmeticMean : array [1..NumColumns] of real;
    row, column : integer; { Loop variables }
    numPositive : integer;
    sum : real;

for column := 1 to NumColumns do begin
    sum := 0;   numPositive := 0;
    for row := 1 to NumRows do begin
        if matrix[row, column] > 0 then begin
            sum := sum + matrix[row, column];
            numPositive = numPositive + 1
        end
    end;
    if numPositive > 0 then begin
        arithmeticMean[column] := sum / numPositive
    end else begin
        arithmeticMean[column] := 0;
    end;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top