数组练习题
一、数组的输入输出
1、计算并输出s=错误!未找到引用源。,其中xi的值为1,3,5,7,……17,19,yi的为
21,22,23,……29,30。
2、总务室在商店购买了八种文具用品,其数量及单价如下表:编程计算各物品计价及总
计价。
3、读入10个数,输出偶数项及它们的和,输出奇数项及它们的平均数。
4、读入N个数,打印其中的最大数及其位置号。
5、用筛法求出100以内的全部素数,并按每行五个数显示。
解:⑴把2到100的自然数放入a[2]到a[100]中(所放入的数与下标号相同);
⑵在数组元素中,以下标为序,按顺序找到未曾找过的最小素数minp,和它的位
置p(即下标号);
⑶从p+1开始,把凡是能被minp整除的各元素值从a数组中划去(筛掉),也
就是给该元素值置0;
⑷让p=p+1,重复执行第②、③步骤,直到minp>Trunc(sqrt(N)) 为止;
⑸打印输出a数组中留下来、未被筛掉的各元素值,并按每行五个数显示。
Program Exam53;
const N=100;
Var a: array[1..n] of boolean; t,i,j: integer;
Begin
Fillchar(a,sizeof(a),true);
a[1] := False;
for i:=2 to Trunc(sqrt(N)) do
if a[I] then
for j := 2 to N div I do
a[I*j]:= False;
t:=0;
for i:=2 to N do
if a[i] then
Begin
write( i:5); inc(t);
if t mod 5=0 then writeln
end;
End.
二、数组元素的移动
1、将A数组中的第一个元素移到最后数组末尾,其余数据依次往前平移一个位置。
2、将a数组中的元素实现逆序交换
program exa2;
Const n=10;
var a:array[1..n] of integer;
i,temp:integer;
begin
writeln(‘read’,n,’datas’);
for i:=1 to n do read(a[i]);
for i:=1 to n div 2 do
begin
temp:=a[i] ;
a[i]:=a[n+1-i];
a[n+1-i]:=temp;
end;
for i:=1 to n do write(a[i],’‘);
3、有一组数(设有N个)其排列顺序如下:3,6,11,45,23,70,67,34,26,89,90,
15,56,50,20,10。编一程序交换这组数中任意指定的两段不重合数据
program a1;
const n=16;
const a:array[1..n] of integer =(3,6,11,45,23,70,67,26,89,90,15,56,50,20,10,34);
var i,k,b1,e1,b2,e2:integer;
var b:array[1..n] of integer;
begin
writeln('please read data:');
write('begin 1=');read(b1);
write('end 1=');read(e1);
write('begin 2=');read(b2);
write('end 2=');read(e2);
if b1 begin i:=b1;b1:=b2;b2:=i; i:=e1;e1:=e2;e2:=i; end; for i:=1 to b1-1 do b[i]:=a[i]; for k:=0 to e2 -b2 do b[b1+k]:=a[b2+k]; for k:=1 to b2 -e1-1 do b[b1+e2-b2+k]:=a[e1+k]; for k:=0 to e1-b1 do b[e2-e1+b1+k]:=a[b1+k]; for i:=e2+1 to n do b[i]:=a[i]; writeln('number:':7,'begin:':7,'end:':7); for i:=1 to n do writeln(i:7,a[i]:7,b[i]:7); end. 三、数组元素的查找、插入、删除 1、对于数组A,输入一个测试数据X,如果X存在于数组A,则把X元素删除,否则将X 插在相应的位置,要求数组仍然有序(假设数组递增) Program exa3; Const n=10; Var a:array[1..n+1] of integer x, i, j :integer; Begin writeln(‘ read array a:’); for i:=1 to n do read(a[i]); write(‘ x=’); readln(x); a[n+1]:=x; i:=1; while a[i] if i=n+1 then write(‘Not found and no place to insert.’) else if a[i] = x then begin writeln(‘Found and deleted.Result:’); for j:=i to n-1 do a[j]:=a[j+1]; for j:=1 to n-1 do write(a[j]:3); end else begin writeln(‘Not found and insert. Result:’); for j:=n downto i do a[j+1]:=a[j]; a[i]:=x; for j:=1 to n+1 do write(a[j],3); end; readln; end. 2、从键盘输入若干个数,将它们按从小到大的顺序输出。 3、给定一串整数数列,求出所有的递增和递减子序列的数目。如数列7,2,6,9,8,3, 5,2,1可分为(7,2),(2,6,9),(9,8,3),(3,5),(5,2,1)5个子序列,答案就是5,我们称2,9,3,5为转折元素。 program aaa; const n=9; var a:array[1..n] of integer; i,dz,dj:integer; begin for i:=1 to n do read(a[i]); dz:=0;dj:=0; if a[2]>a[1] then dz:=1 else dj:=1; for i:=2 to n-1 do begin if(a[i]-a[i-1])*(a[i+1]-a[i])<0 then begin