Visual C# 2005 Guide
Functions

In the previous section we learned that we can group statements together in a reusable block of code called a procedure. The procedure can have parameters and can be called from our main program as many times as we like.

Functions differ from procedures in that they can return a value. This means that they can be used as the right hand side of a statement. Functions must include the data type of the returned value in their declaration and are exited by using the return statement. Copy and compile the following example which includes 2 functions and 2 procedures.

static int num1, answer;
static void Main(string[] args)
{
   num1 = ReadInput();
   answer = Cube(num1);
   OutputResult();
   WaitForInput();
}
static int ReadInput()
{
   Console.Write("Enter a number to be cubed: ");
   return System.Convert.ToInt32(Console.ReadLine());
}
static int Cube(int a)
{
   return a * a * a;
}
static void OutputResult()
{
   Console.Clear();
   Console.WriteLine("The cube of {0} is {1}", num1, answer);
}
static void WaitForInput()
{
   Console.WriteLine("Press enter to quit");
   Console.ReadLine();
}

Having A Go

  1. Write a program that includes a function to return the largest and smallest of 3 numbers entered at the keyboard.
  2. Write a program that includes an IsNumberPrime() function that returns true if a number is prime and false if not. Use this program to allow the user to enter a number and find out if the number is prime.
  3. Write a program to read in an integer and return the binary equivalent of that number as a string.
  4. Write a program to read in an integer and return the hexadecimal equivalent of that number as a string.