user3348229
user3348229

Reputation: 27

The maximum in each row

I have a question for you. I need to write the maximum element in each line. For example, my table :

1 2 3 4
5 6 7 8
9 10 11 12

I want to get 4,8,12 I tried but no result:

Program Lab2;
type A=array[1..5,1..5] of integer;
var x:A;
i,j,s,max:integer;
Begin
 writeln('Write date:');
 for i:=1 to 5 do
  for j:=1 to 5 do
    read(x[i,j]);

 for i:=1 to 5 do
  for j:=1 to 5 do
  begin
   max:=x[i,1];
    if (max<x[i,j]) then max:=x[i,j];
   writeln(max);
  end;
 readln;

Please help me end.

Upvotes: 1

Views: 655

Answers (1)

sir psycho sexy
sir psycho sexy

Reputation: 800

There are just three little mistakes:

1) if (max<x[i,j]) should be outside the second for loop, because you want initialize the max value only one time per row.

2) writeln(max); should be outside the second for loop, you want to print the value only one time per row.

3) read(x[i,j]); I reccomend to be readln (x[i,j]) because with read you only read one character, with readln you red characters till you find a new line character, and that will allow you to enter numbers with more than two digits.

This only make sense for strings, you can use read or readln with integers

Also I advice you to write the key word begin in the same line where you write a contol structure (for,while,if,etc), because in this way it's more similar to the C coding style convention, one of the most populars coding styles I guess. And also is better for you if you try to keep a similar coding style for any language.

so the code will be:

Program Lab2;
const SIZE=3;
type A=array [1..SIZE,1..SIZE] of integer;
var x:A;
i,j,max:integer;
Begin
  writeln('Write date:');
  for i:=1 to SIZE do begin
    for j:=1 to SIZE do begin
      readln(x[i,j]);
    end;
  end;
  for i:=1 to SIZE do begin
    max:=x[i,1];
    for j:=1 to SIZE do begin
      if (max<x[i,j]) then begin
        max:=x[i,j];
      end;
    end;
    writeln('the max value of the row ',i ,' is ',max);
end;
 readln;
 readln;
end.

Upvotes: 1

Related Questions