3.3. Multiple Function Definitions

Here is example program birthday3.cs where we add a function happyBirthdayAndre, and call them both. Guess what happens, and then load and try it:

using System;

class Birthday3
{
   static void Main()
   {   
       happyBirthdayEmily();
       happyBirthdayAndre();
   }

   static void happyBirthdayEmily()
   {
      Console.WriteLine ("Happy Birthday to you!");
      Console.WriteLine ("Happy Birthday to you!");
      Console.WriteLine ("Happy Birthday, dear Emily.");
      Console.WriteLine ("Happy Birthday to you!");
   }

   static void happyBirthdayAndre()
   {   
      Console.WriteLine ("Happy Birthday to you!");
      Console.WriteLine ("Happy Birthday to you!");
      Console.WriteLine ("Happy Birthday, dear Andre.");
      Console.WriteLine ("Happy Birthday to you!");
   }
}

Again, definitions are remembered and execution starts in Main. The order in which the function definitions are given does not matter to C#. It is a human choice. For variety I show Main first. This means a human reading in order gets an overview of what is happening by looking at Main, but does not know the details until reading the definitions of the birthday functions.

Detailed order of execution:

  1. Line 5: Start on Main
  2. Line 7. This location is remembered as execution jumps to happyBirthdayEmily
  3. Lines 11-17 are executed and Emily is sung to.
  4. Return to the end of Line 7: Back from happyBirthdayEmily function call
  5. Line 8: Now happyBirthdayAndre is called as this location is remembered.
  6. Lines 19-25: Sing to Andre
  7. Return to the end of line 8: Back from happyBirthdayAndre function call, done with Main; at the end of the program

The calls to the birthday functions happen to be in the same order as their definitions, but that is arbitrary. If the two lines of the body of Main were swapped, the order of operations would change.

Functions that you write can also call other functions you write. In this case Main calls each of the birthday functions.

3.3.1. Poem Function Exercise

Write a program, poem.cs, that defines a function that prints a short poem or song verse. Give a meaningful name to the function. Have the program call the function three times, so the poem or verse is repeated three times.

Table Of Contents

Previous topic

3.2. A First Function Definition

Next topic

3.4. Function Parameters

This Page