Arrays
Sieve of Erathostenes
/* Sieve of Erathostenes */
#include <stdio.h>
#define TRUE 1
#define FALSE 0
#define MAX 1000
int erath[MAX];
int main() {
int i, j, k;
for (i=0 ; i < MAX ; i++) /* initialize array*/
erath[i] = FALSE;
for (j=2 ; j*j < MAX ; j++ ) /* do sieve */
if (erath[j-1] == FALSE) /* j is not a composite */
for (k=2 ; j*k <= MAX; k++ )
erath[k*j-1] = TRUE; /* multiples of j are composites */
for (i = 1 ; i < MAX ; i++)
if (erath[i] == FALSE)
printf("%d is a prime \n", i+1);
}
Distance
/* Distance between points in 3-space */
#include <stdio.h>
#include <math.h>
int main(){
int i;
double x[3], y[3], sum, dist;
printf("The coordinates of the first point: ");
for ( i = 0 ; i < 3 ; i++ )
scanf("%lf",&x[i]);
printf("\nThe coordinates of the second point: ");
for ( i = 0 ; i < 3 ; i++ )
scanf("%lf",&y[i]);
sum = 0;
for( i = 0 ; i < 3 ; i++)
sum = sum + (x[i] - y[i])*(x[i] - y[i]);
dist = sqrt(sum);
printf("\nThe distance is %lf.\n",dist);
}
Structures
In next examples we discuss the notion of a
structure. The example is a structure called point in
the plane. The program we use as an example calculates the distance
between two given points.
/* point1.c */
#include <stdio.h>
#include <math.h>
int main() {
float d;
struct {
float x;
float y;
} A, B;
printf("The coordinates of the point A are: ");
scanf("%f %f",&A.x,&A.y);
printf("\nThe coordinates of the point B are: ");
scanf("%f %f",&B.x,&B.y);
d = sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y));
printf("\nThe distance between A and B is %f\n",d);
}
In the second example we use a label point.
/* point2.c */
#include <stdio.h>
#include <math.h>
struct point {
float x;
float y;
};
int main(){
float d;
struct point A, B;
printf("The coordinates of the point A are: ");
scanf("%f %f",&A.x,&A.y);
printf("\nThe coordinates of the point B are: ");
scanf("%f %f",&B.x,&B.y);
d = sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y));
printf("\nThe distance between A and B is %f\n",d);
}
Finally, the third example we define a new type point. This is the most flexible use of structures.
/* point3.c */
#include <stdio.h>
#include <math.h>
typedef struct {
float x;
float y;
} point ;
float dist( point A, point B) {
return(sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y)));
}
int main(){
float d;
point A, B;
printf("The coordinates of the point A are: ");
scanf("%f %f",&A.x,&A.y);
printf("\nThe coordinates of the point B are: ");
scanf("%f %f",&B.x,&B.y);
printf("\nThe distance between A and B is %f\n", dist(A,B));
}