Home
>>    




HW4 - C Functions

CS 241 (HD)

A. Function Specifications

  1. func

    Additional problems (PDF)
    spec -- Function specifications. A function specification is a structured description of the behavior of a function, in terms of arguments, return values, etc. For example, the mean function defined by
    double mean(double num1, double num2) {
      return (num1 + num2)/2;
    }
    
    satisfies the following specification:

    mean

    2 arguments: double (double-precision floating-point numbers
    Return: A double, the average value of arg1 and arg2.
    This spec describes the function mean() unambiguously.
    • The number of arguments for that function are indicated, and their types are identified.

    • The return value is described in terms of the argument(s).

    • The spec uses arg1 and arg2 to refer to the individual arguments for that function.

    • The type of the return value is also indicated.

    A spec is often accompanied by one or more example calls, such as
        mean(5, 8) --> 6.5
    
    For another example of a spec, consider the function sum_input() defined by
    int sum_input() {
      int val;  /* holds next integer value from standard input */
      int sum = 0;  /* sum of input integers so far */
      while (scanf("%d", &val) != EOF) 
        sum = sum + val;
      return sum;  
    }
    
    This function has no arguments, but reads values from standard input. Here is a spec:

    sum_input

    No arguments
    State change:
    Integer values are read from standard input, which is assumed to consist only of a series of integer values.
    Return: A long, the sum of those input integers.
    Example call:
    sum_input()
    
    If the standard input contains
    16 40 20
    82
    
    then the return value will be 158
    • A state change is an effect of a function other than a return value. Input and output (as in sum_input()) are examples of state changes.

    DO THIS:

    Write a program specs.c that

    • includes the two function definitions mean() and sum_input() (these should be entered
      after #include <stdio.h> and before main() );

    • calls mean() with arguments 5 and 8, and prints the return value along with a descriptive label (e.g.,

      The call mean(5, 8) returns 6.5
      

    • Prompts for the user to enter input integers, followed by CTRL/D; and

    • calls sum_input() with standard input

      16 40 20
      82
      
      and prints the return value with a descriptive label (e.g.,
      The return value from calling sum_input() is 158
      

    Note:

    The function sum_input() will read input integers until the end of standard input is detected.

    • When running your program in the usual way at the command line, enter CTRL/D (hold down control key and press D) at the beginning of an input line in order to end standard input for your program ./specs

      ./specs
      16 40 20
      82
      CTRL/D
      

    • Alternatively, you can enter your input integers in a file specs.in, and run your program using this command:

      ./specs < specs.in
      
      In this case, the end of that file specs.in constitutes the end of standard input for that program ./specs .

    To submit your work on this problem, enter these commands:

    git add specs.c
    git add specs.in   # only if you used a file specs.in as described above
    git commit -m "hw4:  problem 1"
    git pull origin master
    git push origin master
    



  2. For the problems below:
    Write C function definitions for each of the following specs, together with main() programs that test that function. For each of these problems marked [HC],
    • Write out your function definition and main() on a piece of paper as correctly as possible -- so correct, if possible, that someone else who didn't know C could type it in exactly and produce a correct C computation. If you are uncertain about anything as you write, look it up.

    • Then, enter your program, compile, and verify that it runs correctly

    • Finally submit your program to stogit using the commit message

      "hw4: problem n"
      
      with the appropriate problem number n.

    (Note: Writing out your work by hand precisely beforehand is the most direct way to master the details of C programming. If there are no errors, your understanding of C is confirmed. If there turns out to be an error in your code, that error indicates exactly what you still need to learn about C. Writing out by hand also prepares you for taking quizzes.)
  3. areaCircle -- [HC] Area of a circle. In Mathematics, the area of a circle with radius r is .

    Use this formula to implement the following C function.

    area

    One argument: A non-negative float value, representing the radius of a circle
    Return: A non-negative float value, the area of a circle of radius arg1
    Example call:
    area(3) --> 28.274333882308138
    
    Hint:
    • You can define a value for π in C as follows:

      const double pi = 3.1415926;  
      
      Here, the type const double means that the variable pi holds a double value and may not be assigned a new value.



  4. moInterest -- [HC] Monthly interest. In Economics, the amount of monthly interest owed on a loan depends on the principal (or amount of money still owed on the loan) and the interest rate. The interest rate r is often expressed as a percentage per year. Thus, the formula for a monthly interest charge on a loan with current principal P is

    Use this formula to implement the following C function.

    moInterest

    2 arguments: Non-negative float numbers, a principal amount (of money) and an interest rate (expressed in percent per year)
    Return: A non-negative float number, the amount of one month's interest on a loan with current principal arg1 at interest rate arg2. .
    Example:
        moInterest(10000, 6) --> 50.0
    

B. Accumulator variables

acc -- Accumulator variables. A variable is a named location in main memory. For example, the assignment
    x = 7
stores the value 7 in a location in main memory named x. We can visualize the results of this assignment in a diagram as follows:

Here, we write the type int above the box representing the memory location to indicate what can be stored there, and we write the C language name of the variable next to the box.

An accumulator is a variable that is used to build up an answer over time. For example, consider the code for the sum_input() function

int sum_input() {
  int val;  /* holds next integer value from standard input */
  int sum = 0;  /* sum of input integers so far */
  while (scanf("%d", &val) != EOF) 
    sum = sum + val;
  return sum;  
}
The variable sum is an accumulator that holds the sum of all input integers already read at the beginning of each iteration of the while loop. Note: The comment
/* sum of input integers so far */
is called an invariant assertion (or more simply, an invariant). It is intended for a human reader, not a C processor (which ignores that comment). An invariant describes the state of a computation at the beginning and end of each iteration of a loop.

Here are details of how this function uses the variable sum to compute the desired return value. Suppose we call the function

sum_input()
with standard input
16 40 20
82

  1. The variable sum is initialized at the value 0:

  2. After reading the first input integer 16, that value is added to sum, which replaces the value 0 by 16

  3. After reading the second input integer 20, the accumulator variable sum is updated to hold 36.

  4. Likewise for the remaining two input integers. Notice how the invariant remains true at the beginning and end of each repetition: it always holds the number of invititations printed at those points in the computation.

DO THIS: Write C function definitions for each of the following specs, using accumulator variables within those definitions to compute the desired return values. As before, write out precise and correct code for each of these [HC] problems on paper first, then test each on the computer. (It's ideal to write out an answer to one problem, then test that code using C, then write out an answer to the next problem, etc., so that any errors you catch on one problem can be avoided in the next.)

  1. mean_input -- [HC] Mean of input integers.

    Write a function that computes the mean of integers in standard input.

    mean_input

    No arguments
    State change:
    Integer values are read from standard input, which is assumed to consist only of a series of integer values.
    Return: A float number, the mean (average) value of those input integers.

    Example call

    mean_input() 
    
    If the standard input contains
    16 40 20
    82
    
    then the return value will be 39.5

    Notes:
    • You will need two accumulators in order to compute the mean: one to keep track of the sum, and the other to accumulate the count of integers read.

    • Include an invariant that describes both accumulators. For example, if your accumulator variables are named count and sum, your invariant might have the form "count holds ..., and sum holds ...".

    • To test your program, enter your test input as described above