选择排序
#include<stdio.h>
main()
{
int num[100];
int n,i,j,k;
printf("\n please input the number of worker:");
scanf("%d",&n);
printf("\n please input the wage of worker:");
for (i=0;i<n;i++)
scanf("%d",&num[i]);
for(i=n-1;i>=1;i--)
{
k=0;
for(j=1;j<=i;j++)
{
if (num[j]>num[k])
k=j;
}
if(k!=j)
{
int temp;
temp=num[i];
num[i]=num[k];
num[k]=temp;
}
}
printf("\n display the result of sort \n");
for (i=0;i<n;i++)
printf("%d ",num[i]);
}
(折半查找法)二分查找法
#include<stdio.h>
#define N 10
main()
{
int a[N]={12,23,45,53,58,62,68,70,80,98};
int x,low,high,mid;
printf("\n please input the code:");
scanf("%d",&x);
low=0;high=N-1;
while(low<=high)
{
mid=(low+high)/2
if (x==a[mid])
{
printf("%d\n",mid);
break;
}
else if (x>a[mid])
low=mid+1;
else
high=mid-1;
}
if(low>high)
printf("\n not found!\n");
}
五行五列矩阵,求其最大值、最小值、矩阵主对角线元素的平均值。
#include<stdio.h>
main()
{
int a[5][5],i,j,b[4],sum;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
scanf("%d",&a[i][j]);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if (a[i][j]>a[b[0]][b[1]])
{
b[0]=i;
b[1]=j;
}
if (a[i][j]<a[b[2]][b[3]])
{
b[2]=i;
b[3]=j;
}
if (i==j)
sum+=a[i][j];
}
}
printf("\n the max is %d",a[b[0]][b[1]]);
printf("\n the min is %d",a[b[2]][b[2]]);
printf("\n the average is %7.2f\n",sum/5.0);
for(i=0;i<5;i++)
{
printf("\n")
for(j=0;j<5;j++)
{
printf("%d\t",a[i][j]);
}
}
}
矩阵(三行三列)的转置
#include<stdio.h>
main()
{
int i,j,t;
int array[3][3]={{100,200,300},{400,500,600},{700,800,900}};
for (i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
printf ("%7d\t",array[i][j]);
}
for(i=0;i<3;i++)
for(j=i+1;j<3;j++)
{
t=array[i][j];
array[i][j]=array[j][i];
array[j][i]=t;
}
printf("Converted array:\n");
for (i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
printf ("%7d\t",array[i][j]);
}
}
字符串的输入
- scanf()函数。 scanf("%s",字符数组名);
- gets()函数。 gets(字符数组名);
两者略有区别:scanf()函数输入的字符串中不能含有空格(因为scanf()函数以按回车键和空格键作为字符串输入结束标志);gets()函数则没有限制(仅以按回车键作为字符串输入结束标志)。
字符串的输出
- printf()函数。 printf("%s",字符数组名);
- puts()函数。 puts(字符数组名);
两者也略有区别;printf()函数输出一个字符串后,光标不换行;而puts()函数进行输出后光标自动换行。
常用字符串操作函数(若要在程序中使用这四个函数,则需要包含头文件"string.h")
- strcpy(字符数组名,"字符串"); 将字符串复制到字符数组中且自动加'\0'。
- strcat(字符数组名1,字符数组名2); 将第二个字符串的内容连接到第一个字符串内容的后边。
- strcmp(字符串1,字符串2); 比较两个字符串。 若两个字符串相等,返回值为0;若字符串1大于字符串2,则返回值为一个正数(为串中不同字符的ASCII码差值);若字符串1小于字符串2, 则返回值为一个负整数。
- strlen(字符串); 计算以'\0'结尾的字符串的长度,并返回字符串的长度, 结尾字符'\0'不计算在内。
求符串中字符的长度
#include<stdio.h>
main()
{
char str[100];
int i=0;
gets(str);
while (str[i]!='\0')
i++;
printf ("\n rhe length of string is %d",i);
}
实现 字符串的复制
#include<string.h>
main()
{
char str1[100],str2[100];
int i=0;
gets(str1);
while(str1[i]!='\0')
{
str2[i]=str1[i];
i++;
}
str2[i]='\0';
puts(str2);
}