0% found this document useful (0 votes)
59 views

C-C++-R Problem Set 2 Gopi Goswami Date Issued: June 28, 2005 Department of Statistics and IQSS Date Due: July 7, 2005 Harvard University

This document provides instructions for three problems related to functions, pointers, and memory management in C/C++. Problem 1 asks to write functions to get user input, find Pythagorean triplets, calculate means, and call these functions in main(). Problem 2 modifies the triplet function to use pointers and dynamically allocate memory as needed, growing the arrays using realloc(). Problem 3 introduces static and const variables. It asks to write functions to bootstrap memory allocation, find Fibonacci numbers storing them in a dynamically allocated array, and clean up memory. The goal is to make main() as simple as possible by outsourcing work to functions.

Uploaded by

api-19736688
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

C-C++-R Problem Set 2 Gopi Goswami Date Issued: June 28, 2005 Department of Statistics and IQSS Date Due: July 7, 2005 Harvard University

This document provides instructions for three problems related to functions, pointers, and memory management in C/C++. Problem 1 asks to write functions to get user input, find Pythagorean triplets, calculate means, and call these functions in main(). Problem 2 modifies the triplet function to use pointers and dynamically allocate memory as needed, growing the arrays using realloc(). Problem 3 introduces static and const variables. It asks to write functions to bootstrap memory allocation, find Fibonacci numbers storing them in a dynamically allocated array, and clean up memory. The goal is to make main() as simple as possible by outsourcing work to functions.

Uploaded by

api-19736688
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

C-C++-R Problem Set 2

Gopi Goswami Date Issued: June 28, 2005


Department of Statistics and IQSS Date Due: July 7, 2005
Harvard University

This problem set is a little involved because it calls for appli-


cation of a lot of concepts covered so far. The previous sentence
is here not because I want to scare you but to remind you that if
you don’t do this problem set you would be missing out on learning
a lot of really “cool stuff” ! Note if you don’t find any expla-
nation of a variable used in the following discussion, ask me to
clarify. I thought I did use pretty self explanatory names and so
skipped documentation but I might be wrong.

We are going to “function-ize”, if you will, problem set 1 in this assignment


along with some smart memory management and efficient computation thereby
improving the implementation of problem set 1 a lot.

Problem 1 Working with Functions: Here we will do almost everything with func-
tion calls.

1.a Write the following function which asks for and scans the user input,
checks for validity and returns an integer between 0 and 1000. Dump
this code in a file called pthgrn_trplts1.c.
int
get_user_input_MM (void);
1.b Now write the following function which asks for and scans the user
input (from the choices: ’y’, ’Y’, ’n’ and ’N’), checks for validity and
returns 1 or 0 depending on whether the user wants to continue or
not. Append this code to the file called pthgrn_trplts1.c.
int
get_user_input_continue (void);
1.c User of the following function provides three (pre-allocated) arrays of
length MM, namely, side1Arr, side2Arr and hypArr. This function
fills these arrays up by the Pythagorean triplets found which are less
than MM. It also, updates the pointer count to the number of such
triplets found. Note *count should be much less than MM and hence
the three arrays side1, side2 and hyp would only be partly filled.
Append this code to the file called pthgrn_trplts1.c.
void
get_pythagorean_triplet_less_than (int MM,
int *count,
int *side1Arr,

1
int *side2Arr,
int *hypArr);
1.d Now write the following mean calculator function which when given
a int array and its length computes its mean. Append this code to
the file called pthgrn_trplts1.c.
double
get_mean_of_iarray (int len, int *iarr);
1.e Now declare the following inside main( ) (where MAX_MM is 1000):
int MM, flagStop = 0, count;
int ii, side1Arr[MAX_MM], side2Arr[MAX_MM], hypArr[MAX_MM];
Now use all the above functions, call them inside main to implement
what you did in pythagorean_triplet6.c in problem set 1.

Problem 2 Working with Pointers: Here we will let the storage arrays grow as
and when needed by juggling with pointers and managing memory.

2.a Here we will modify the function get_pythagorean_triplet_less_than( )


we wrote before. The new prototype or declaration should be:
void
get_pythagorean_triplet_less_than (int MM,
int *count,
int **side1Arr,
int **side2Arr,
int **hypArr,
int *lenCurrent,
int lenIncrement);
Hold your breath, I know you haven’t seen expressions like int **side1Arr
(i.e. pointers to pointers) and such. It would be clear from the fol-
lowing code-snippet which goes inside main( ) why the suggested
prototype is as above.
int MM, flagStop = 0, count, lenCurrent = 0, increment = 20;
int *side1Arr = NULL, *side2Arr = NULL, *hypArr = NULL;

/* Some stuff */

do {
MM = get_user_input_MM( );
lenCurrent = increment;
side1Arr = (int *) malloc(lenCurrent * sizeof(int));
side2Arr = (int *) malloc(lenCurrent * sizeof(int));
hypArr = (int *) malloc(lenCurrent * sizeof(int));

2
get_pythagorean_triplet_less_than(MM,
&count,
&side1Arr,
&side2Arr,
&hypArr,
&lenCurrent,
increment);

/* Write the code to spit out the summary */

free(side1Arr);
free(side2Arr);
free(hypArr);
flagStop = 1 - get_user_input_continue( );
} while (flagStop == 0);
So, whenever the user decides to continue (and at the very first run
of the do-while loop) we allocate only enough space so that the
arrays side1Arr, side2Arr and hypArr can hold increment = 20
many ints each. What we ask of you to do is to make the function
get_pythagorean_triplet_less_than( ) call the function realloc( )
to resize (i.e. increase) the three arrays by increments of size increment = 20
(you could change 20 to whatever number you like!) as and when
needed. Note, when we return from the function get_pythagorean_triplet_less_than( )
we use free( ) to free up the memory of the arrays because we are
done with our computation for the given value of MM. We do the above
all over again upon decision to continue.
Now ask your self the following:
• Why do we need to use &sideArr1, &side2Arr and &hypArr for
calling get_pythagorean_triplet_less_than( )? If you can
answer this then you would immediately see why the prototype
of get_pythagorean_triplet_less_than( ) is done the way
you see it.
[Hint: Remember to make a permanent change in the value of a
variable inside a function we need to use call-by-reference, does
that make sense?]
Dump this code in a file called pthgrn_trplts2.c.

Problem 3 Working with Functions, static and const variables: Here we


are going to make ourself familiar with all the stuff we covered in the
previous problems as well as with static and const variables.
Fibonacci numbers are defined as the following sequence:

fn = fn−1 + fn−2 , n ≥ 3

3
with f1 = f2 = 1. The first few Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, . . ..
We are going to write a smart program to find the n-th Fibonacci number.

3.a Create a file called fib.c with the first few lines as:
#include <stdio.h>
#include <stdlib.h>

static int maxMM = 1000, increment = 50, lenCurrent = 0;


static int maxMMSoFar = 1, thisMM = 1;
static double *fibArr = NULL;

The goal here is to do a different kind of memory management than


what we did in file pthgrn_trplts2.c above. Recap from class: a
static variable declared outside of any function within a file has
a file scope i.e. only functions within that file would be able to
“see” this variable. So, with this undestanding, hopefully the above
declarations make sense.
Note, the only reason the array fibArr is declared as double as
opposed to int is because Fibonacci numbers grow big very fast!
3.b Now our goal is to make our main read like this:
int
main (int argc, char **argv)
{
usage( );
if (bootstrap()) {
printf("Error in bootstrap: bailing out...\n");
abort();
}

doIt( );
return 0;
}
i.e. as neat and small as possible. So, for the time being you can
copy-n-paste the above and append it to the file fib.c. The following
army of functions would help us achieve this goal.
3.c Write a function called bootstrap( ) which “properly” allocates and
initializes the static variables:
int
bootstrap (void);
3.d Write a function called cleanup( ) which clears all allocated mem-
ory:

4
void
cleanup (void);
3.e Now write a function called usage( ) which prints out a nice message
telling the user what the program does and what s/he supposed to
do:
void
usage (void);
Note every UNIX/Linux program has this feature, e.g. try typing
tar --help on a UNIX/Linux prompt and see what happens.
3.f Now write two functions called get_user_input_MM( ) and get_user_input_continue( )
which do exactly the same things as they did in file pthgrn_trplts1.c
above. You could just copy-n-paste, if you like!
int
get_user_input_MM (void);
int
get_user_input_continue (void);
3.g Now write the main worker function called get_fib_nums( ):
void
get_fib_nums (void);
Note it does not need any input because it can get whatever infor-
mation/variables it wants from the static variables.
3.h Now write the following mean calculator function which when given
a double array and its length computes its mean:
double
get_mean_of_darray (int len, double *darr);
3.i Now write a function called print_summary( ) which would to print
out the summary of the results.
void
print_summary (void);
The simple summary we seek here is of the following format:
Current size of internal arrays: 50
The means of the first 4 Fibonacci Numbers are: 1.75
3.j Finally lets write the driver function called doIt( ):
void
doIt (void);

5
As you might guess, this function would use get_user_input_MM( ), get_fib_nums( )
and print_summary( ).

Some things to think about or to just note. You don’t have to write anything
about the following just make yourself think for a few seconds about the different
approaches.

• Definitely the code in pthgrn_trplts2.c is better than the one ins pthgrn_trplts1.c
because it lets you allocate more memory as and when needed and you
don’t need to “hoard” a lot to being with!

• Which approach of handling memory did you like the one in pthgrn_trplts1.c
or in fib.c i.e. “pass pointers-to-pointers” or use static variables and
more importantly why?
• Is there a definite winner among the two approaches above? Try answering
the question by lising the pros and cons of the two.
• Other questions coming to your mind, come ask me.

—Happy Coding!—
6

You might also like