Các bài tập Pascal cơ bản đến nâng cao
Bạn có muốn phản ứng với tin nhắn này? Vui lòng đăng ký diễn đàn trong một vài cú nhấp chuột hoặc đăng nhập để tiếp tục.

Go down
ThienanAdmin
ThienanAdmin
Người điều hành
Người điều hành
Posts : 18
Join date : 30/04/2024
Age : 12
https://pascalbaitap.forumvi.com

Bài tập Mảng 6 Empty Bài tập Mảng 6

Thu Jun 27, 2024 9:08 pm
Nhập vào một mảng n các số nguyên a

a) Tìm các phần tử a[i] vừa nhập là các số có tổng các chữ số là nguyên tố

b) Xếp lại mảng đó theo thứ tự giảm dần.

c) Nhập vào một số nguyên từ bàn phím. Chèn số đó vào mảng sao cho mảng vẫn có thứ tự giảm dần. (không được xếp lại mảng).
[/i]

Code:
uses crt;
var
  n,tongchuso: integer;
  a: array[1..100] of integer;
  i, j, k: integer;
  x: integer;
  function TinhTongChuSo(n: integer): integer;
var
  tong: integer;
begin
  tong := 0;
  while n > 0 do begin
    tong := tong + n mod 10;
    n := n div 10;
  end;
  TinhTongChuSo := tong;
end;
function KiemTraNguyenTo(n: integer): boolean;
var
  i: integer;
begin
  if n < 2 then KiemTraNguyenTo := False
  else begin
    KiemTraNguyenTo := True;
    for i := 2 to n - 1 do begin
      if n mod i = 0 then begin
        KiemTraNguyenTo := False;
        Exit;
      end;
    end;
  end;
end;

procedure DoiCho(var a, b: integer);
var
  temp: integer;
begin
  temp := a;
  a := b;
  b := temp;
end;

begin
Clrscr;
  Writeln('Nhap so phan tu n: ');
  Readln(n);

  (* Nhap mang a[i] *)
  for i := 1 to n do begin
    Writeln('Nhap phan tu a[', i, ']: ');
    Readln(a[i]);
  end;
  Writeln('Cac phan tu co tong cac chu so la so nguyen to: ');
  for i := 1 to n do
  begin
    tongChuSo :=TinhTongChuSo(a[i]);
    if KiemTraNguyenTo(tongChuSo) then Write(a[i], ' ');
  end;
  for i := 1 to n - 1 do begin
    for j := i + 1 to n do begin
      if a[i] < a[j] then DoiCho(a[i], a[j]);
    end;
  end;

  Writeln;
  Writeln('Mang sau khi sap xep: ');
  for i := 1 to n do begin
    Write(a[i], ' ');
  end;
  Writeln;
  Writeln('Nhap so nguyen x: ');
  Readln(x);
  i := n;
  while (i>0) and (a[i] > x) do begin
    i := i - 1;
  end;
  if i = 0 then i := 1;
  for j := n + 1 downto i do begin
    a[j + 1] := a[j];
  end;
  a[i] := x;

  Writeln;
  Writeln('Mang sau khi chen x: ');
  for i := 1 to n -1 do
    for j := i + 1 to n do
      if a[i] < a[j] then DoiCho(a[i], a[j]);
  begin
  For i:=1 to n+1 do
    Write(a[i], ' ');
  end;
  Readln;
end.
Lưu ý* code sai tự sửa
Về Đầu Trang
Permissions in this forum:
Bạn không có quyền trả lời bài viết