Prev Main Next

Creating Functions That Act Like Expressions: One Argument

To define a new function with one argument, you can use the form

  public static return-type function-name(argument-type argument-name)
  {
    statements
  }
The return-type tells the type of thing that the function produces as its result. The argument-type tells the type of argument that the function takes.

The statements inside the function, called the function body, tell what the function does when it is run. When the function has determined what its result vshould be, it performs statement

  return v;

(When you define a function, the arguments are usually called parameters. When you use the function, they are called arguments.)


Example

Here is a function called grok that takes one number and doubles it and adds 1. For example, grok(3) = 7 and grok(10) = 21.

  public static int grok(int n)
  {
    return 2*n + 1;
  }

Things to remember

  1. A class contains a collection of function definitions, one after another.

  2. You cannot put one function definition inside another function definition.

  3. Every function definition must be in a class.

  4. You can call the parameters anything that you like. The names that you choose have nothing to do with how the function is used. For example grok has a parameter called n. You can use it in any of the following ways.

        int snore = grok(32);
        int sleep = grok(snore + 1);
        int snooze = sleep*grok(snore + sleep + 1);
      

  5. When you define a function, you write the type of the parameter. When you use a function, you do not write the type of the parameter.

Question. What are the values of snore, sleep and snooze? Answer[30]


The body can do anything

Here is a function that tells you whether a number is prime. It returns true if the number is prime, false if not.

  public static boolean isprime(int num)
  {
    if(num < 2) return false;
    int k;
    for(k = 2; k < num; k++)
    {
      if(num % k == 0) return false;
    }
    return true;
  }


Example

The following function returns the absolute value of a real number. For example, absolute(5.1) = 5.1, and absolute(-5.1) = 5.1.

  public static double absolute(double x)
  {
    if(x < 0) return -x;
    else return x;
  }

Questions.

  1. What is wrong with the following definition?

        public static int foo(int r)
        {
          if(r > 0) return r;
          else return "r is negative"
        }
      
    Answer[31]

  2. What is wrong with the following use of a function?

       int x = 40;
       int n = jump(int x);
      
    Answer[32]


Prev Main Next