return y; }
float f2(int m) {
int i;
float y=1;
for (i=1;i<=m;i++) {
y*=i; }
return y; }
第七章
1.从键盘上输入5个整数,保存在数组中,并输出大于0的数。 #include
for(i=0;i<5;i++) scanf(“%d”,&a[i]);
printf(“\\n”); for(i=0;i<5;i++)
if(a[i]>0) printf(“%d”,a[i]); }
2.数组初始化与未初始化的比较。 #include
void main()
{int i,a[5]={8,8,2,4,260}; int b[5];
int c[4]={1,2};
printf(“\\nArray a:”); for(i=0;i<5;i++)
printf(“m”,a[i]); for(i=0;i<5;i++)
printf(“m”,b[i]); for(i=0;i<4;i++)
printf(“m”,c[i]); }
3.从键盘上输入5个数,输出最大、最小元素的值以及它们的下标。 #define N 5 #include
{int i,j,k,max,min; static int a[5]; for(i=0;i<5;i++)
scanf(“%d”,&a[i]); max=min=a[0]; j=k=0;
for(i=0;i<5;i++)
{if(max
else if(min>a[i]) {min=a[i];k=i;} }
printf(“max:a[%d]=%d,min:a[%d]=%d”,j,max,k,min); }
4.二维数组的输入与输出。 #include
{int a[2][3],j,k;
printf(“\\nInput array a:”); for(j=0;j<2;j++) for(k=0;k<3;k++)
scanf(“%d”,&a[j][k]);
printf(“\\nOutput array a:\\n”); for(j=0;j<2;j++)
{for(k=0;k<3;k++)
printf(“%d”,a[j][k]); printf(“\\n”);
} }
5.从键盘上输入16个整数,保存在4*4的二维数组中,输出数组偶数行和偶数列中的所有元素。
include
int a[4][4];
for(i=0;i<4;i++)
for(j=0;j<4;j++)
scanf(“%d”,&a[i][j]); for(i=0;i<4;i++)
{for(j=0;j<4;j++)
if(i%2==0||j%2=0) printf(“%-4d”,a[i][j]); else printf(“%-4c”,’ ‘); printf(“\\n”);
} }
6.从键盘上输入若干学生(不超过100人)的成绩,计算平均成绩,并输出高于平均分的人
数及成绩。输入成绩为负数时结束。 #include”stdio.h” void main()
{float score[100],ave,sum=0,x; int i,n=0,count;
printf(“Input score:”); scanf(“%f”,&x); while(x>=0&&n<100) {sum+=x; score[n++]=x; scanf(“%f”,&x); }
ave=sum/n;
printf(“average=%f\\n”,ave); for(count=0,i=0;i
{printf(“%f\\n”,score[i]); count++;
if(count%5==0) printf(“\\n”); }
printf(“count=%d\\n”,count);
7.从键盘上输入10个数,用选择法将其按由大到小的顺序排列。 #define N 10
#include
for(i=0;i scanf(“%d”,&a[i]); for(i=0;i #define N 10 #include int a[N]; for(i=0;i for(j=i+1;j if(a[k] printf(“\\n); for(i=0;i } 8.假设在数组a中的数据俺有大到小的顺序排列,从键盘上输入一个数,判断该数是否在数组中,若在,输出所在序号;若不在,输出相应信息。 #define M 10 #include void main() {static int a[M]={-12,0,6,16,23,56,80,100,110,115}; int n,low,mid,high,found; low=0; high=M-1; found=0; printf(“Input a number to be searched:”); scanf(“%d”,&n); while(low<=high) {mid=(low+high)/2; if(n==a[mid])) {found=1;break;} else if(n>a[mid]) low=mid+1; else high=mid-1; } if(found==1) printf(“The index of %d is %d”,n,mid); else printf(“There is not %d”,n); } 9.初始化字符数组并输出。 #include {int k; char s[12]={‘H’,’o’,’w’,’ ‘,’r’,’e’,’’,’y’,’o’,’u’,’?’}; for(k=0;k<12;k++) putchar(s[k]); } 10.字符串输出示例。 #include {static char str[20]={“How do you do?”}; int k; printf(“%s”,str); for(k=0;str[k]!=’\\0’;k++) printf(“%c”,str[k]); } 11.字符串输入。 #include {char s[20],sl[20],end[80]; scanf(“%s”,s); printf(“%s\\n”,s); gets(end); scanf(“%s%s”,s,s1); printf(“s=%s,s1=%s”,s,s1); gets(end); puts(“\\n”); gets(s); puts(s); } 12.字符串复制。 #include { char str1[10]=”program”,str2[6]=”C++”; puts(str1); puts(str2); strcpy(str1,str2); printf(“str1:”); puts(str1); printf(“str2:”); puts(str2); } 13.连接字符串 #include {char str1[20]=”I am a”,str2[10]=”student”; strcat(str1,str2); puts(str1);