Sample C Program

Software Development in the UNIX Environment
Sample C Program

Example C Program to Compute PI Using A Monte Carlo Method

Source code:

/* Program to compute Pi using Monte Carlo methods */
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#define SEED 35791246
main(int argc, char* argv)
{ int niter=0; double x,y; int i,count=0; /* # of points in the 1st quadrant of unit circle */ double z; double pi; printf("Enter the number of iterations used to estimate pi: "); scanf("%d",&niter); /* initialize random numbers */ srand(SEED); count=0; for ( i=0; i<niter; i++) { x = (double)rand()/RAND_MAX; y = (double)rand()/RAND_MAX; z = x*x+y*y; if (z<=1) count++; } pi=(double)count/niter*4; printf("# of trials= %d , estimate of pi is %g \n",niter,pi);
}


Monte Carlo techniques: use of random sampling techniques to solve mathematical or physical problems.

Command to compile and link : cc -o monte_pi monte_pi.c

Commands to compile and link in two steps:
1. cc -c monte_pi.c (this produces object file monte_pi.o)
2.cc -o monte_pi monte_pi.o (produces executable monte_pi)

Output of command 'ls -l monte_pi': 32 -rwxr-xr-x 1 sas user 12580 Oct 11 14:25 monte_pi

Output of command 'file monte_pi': ELF N32 MSB mips-4 dynamic executable (not stripped) MIPS - version 1

To run type: monte_pi

Results of running monte_pi:
azure 58% monte_pi
Enter the number of iterations used to estimate pi: 1000
# of trials= 1000 , estimate of pi is 3.044


Run the program using an input file:

Create a file called monte.input with the number interations (ex. 1000) on the first line.
Issue the command monte_pi < monte.input

To run the program monte_pi in the background with an input file:
monte_pi < monte.input&