构造素数表
#include<stdio.h>
#define number 100
int isprime(int x,int knownprimes[],int numberofknownprimes) {
int ret = 1;
int i;
for(i=0; i<numberofknownprimes; i++) {
if(x%knownprimes[i]==0) {
ret = 0;
break;
}
}
return ret;
}
int main()
{
int prime[number] = {2};
int count = 1;
int i = 3;
while (count < number) {
if (isprime(i,prime,count)) {
prime[count++] = i;
}
i++;
}
for(i=0; i<number; i++) {
printf("%d",prime[i]);
if( (i+1)%5 ) printf("\t");
else printf("\n");
}
return 0;
}
利用指针进行数据交换
#include<stdio.h>
void swap(int *pa,int *pb) {
int t;
t=*pa;
*pa=*pb;
*pb=t;
}
int main()
{
int a=5;
int b=6;
printf("a = %d,b = %d\n",a,b);
swap(&a,&b);
printf("a = %d,b = %d\n",a,b);
return 0;
}
冒泡排序
#include<stdio.h>
void swap(int *pa,int *pb) {
int t;
t=*pa;
*pa=*pb;
*pb=t;
}
int main()
{
int n=10;
int a[10]= {1,3,1,2,7,5,3,4,3,9};
int i=0;
for(i; i<n-1; i++) {
int j=0;
for(j; j<n-1-i; j++) {
if(a[j]>a[j+1]) {
swap(&a[j],&a[j+1]);
}
}
}
for(i=0; i<n; i++) {
printf("%d ",a[i]);
if((i+1)%n) printf(" ");
else printf("\n");
}
return 0;
}