Due: Mon, Sep 30th, 2024 by 10:00 am; No late exercises will be accepted.
Goals: Write a C program from scratch including a function
declaration, learn how to process command-line arguments, and explore
some basic C libraries for handling I/O, strings, and numeric
conversions.
Description: One way to estimate π is to use the following infinite series, which was discovered by Nilakantha in the 15th century:
π = 3 + (4 / (2 x 3 x 4)) - (4 / (4 x 5 x 6)) + (4 / (6 x 7 x 8)) - ...
Breaking the series down:
Write a C program that estimates π by adding together terms 0 through n, inclusive, in the Nilakantha series, and prints out that estimate to 20 decimal places. "n" is provided to your program as a command-line argument. Your program, when compiled, should be called "ex0" and an example of how the user should invoke it, and the resulting output, which you should match, is:
bash$ gcc -Wall -g -std=c17 -o ex0 ex0.c bash$ ls ex0 ex0.c bash$ ./ex0 100 Our estimate of Pi is 3.14159241097198238535 bash$
You should use C's double
type for the floating-point
arithmetic and you should add the terms in increasing order (ie, add the
1st term to the 0th term, then the 2nd term to the previous sum).
Different floating-point types or adding up the terms in a different order
may yield different results. Since the point of this exercise is to
create and run a simple C program, not to explore the nuances of
floating-point arithmetic, please use double
and add the terms
in increasing order.
As part of this exercise, you will need to explore the standard C
libraries and conventions for accessing the command line argument (ie, the
string of digit characters), converting that digit string to a binary
int
value, and printing the result. The course
Resources page contains a link to
cplusplus.com,
which is a good source for information about the C and C++ libraries; ignore
the C++ information for now. In particular, you will find it useful to
look at the stdio.h
library for basic input and output,
string.h
for handling C strings (null-terminated arrays of
characters), and stdlib.h
for assorted functions (including
multiple options for parsing (converting) strings of digit characters to
int
values.
Your code must:
gcc -Wall -g -std=c17 -o ex0 ex0.c
-- do not
submit a Makefile
.
<math.h>
requires the addition of
the -lm
option to the compilation command, so you may
not use this library.
valgrind
)cpplint --clint
.
You should submit your exercise to the course Gradescope.