例7.1 数组元素的引用
#include<stdio.h>
void main()
{
int i,a[10];
for(i=0;i<=9;i++)
a[i]=i;
for(i=9;i>=0;i--)
printf("%d",a[i]);
printf("\n");
}
例7.2 用数组来处理求Fibonacci数列问题
#include<stdio.h>
void main()
{
int i;
int f[20]={1,1};
for(i=2;i<20;i++)
f[i]=f[i-1]+f[i-2];
for(i=0;i<20;i++)
{
if(i%5==0)printf("\n");
printf("%12d",f[i]);
}
}
例7.3 用气泡法对10个数排序
#include<stdio.h>
void main()
{
int a[10];
int i,j,t;
printf("input 10 numbers :\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("\n");
for(j=0;j<9;j++)
for(i=0;i<9-i;i++)
if(a[i]>a[i+1])
{
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
printf("the sorted numbers: \n");
for(i=0;i<10;i++)
printf("%d",a[i]);
printf("\n");
}
例7.4 将一个二维数组行和列互换,存到另一个二维数组中。
#include<stdio.h>
void main()
{
int a[2][3]={{1,2,3},{4,5,6}};
int b[3][2],i,j;
printf("array a:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%5d",a[i][j]);
b[j][i]=a[i][j];
}
printf("\n");
}
printf(""array b:\n"");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf("%5d",b[i][j]);
printf("\n");
}
}
例7.5 有一个3*4的矩阵,要求编程求出其中值最大的那个元素的值,以及其所在的行和列号。
#include<stdio.h>
void main()
{
int i,j,row=0,colum=0,max;
int a[3][4]={{1,2,3,4},{9,8,7,6},{-10,10,-5,2}};
max=a[0][0];
for(i=0;i<3;i++)
for(j=0;j<4;j++)
if(a[i][j]>max)
{
max=a[i][j];
row=i;
colum=j;
}
printf("max=%d,row=%d,colum=%d\n",max,row,colum);
}
例7.6 输出一个字符串
#include<stdio.h>
void main()
{
char c[10]={'I',' ','a','m',' ','a',' ','b','o','y'};
int i;
for(i=0;i<10;i++)
printf("%c",c[i]);
printf("\n");
}
例7.7 输出一个菱形图
#include<stdio.h>
void main()
{
char diamand[][5]={{' ',' ','*'}{' ','*',' ','*'}{'*',' ',' ',' ','*'}{' ','*',' ','*'}{' ',' ','*'}}
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5,j++)
printf("%c",diamand[i][j])
}
printf("\n");
}
例7.8 输入一行字符,统计其中有多少个单词,单词之间用空格分隔开。
#include<stdio.h>
void main()
{
char string[81];
int i,num=0,word=0;
char c;
gets(string);
for(i=0;(c=string[i])!='\0';i++)
if(c=' ') word=0;
else if(word==0)
{
word=1;
num++;
}
printf("There are %d words in the line,\n",num);
}
例7.9 有三个字符串,要求找出其中的最大者。
#include<stdio.h>
void main()
{
char string[20];
char str[3][20];
int i;
for(i=0;i<3;i++)
{
gets(str[i]);
}
if(strcmp(str[0],str[1])>0)
strcpy(string,str[0]);
else
strcpy(string,str[1]);
if(strcmp(string,str[2])<0)
strcpy(string,str[2]);
printf("\nthe largest string is: \n",string);
}