Visual C# Guide
Procedures

Copy and compile the following program. This program contains a procedure called AddUpNums. This procedure has two parameters, values that are sent to the procedure when it is called.

static void AddUpNums(int a, int b)
{
   int total = a + b;
   Console.WriteLine("The sum of the numbers is, {0}", total);
}

static void Main(string[] args)
{
   Console.Write("Enter your first number: ");
   int num1 = System.Convert.ToInt32(Console.ReadLine());
   Console.Write("Enter your second number: ");
   int num2 = System.Convert.ToInt32(Console.ReadLine());
   AddUpNums(num1, num2);
   Console.ReadLine();
}

Notice that, once defined, the procedure becomes another type of statement that can be used over and over again with different parameters.

The procedure definition begins with the words, static void. The term static is used because the procedure does not belong to a class which is instantiated (this will make some sense further down the line). The term void indicates that no value is being returned by the procedure.

Structured Programming With Procedures

Procedures can be defined for any set of statements in our program that we want to reuse. It can also be used to help us divide our program into subtasks. This allows us to keep our programming logic organised, making it easier to locate errors and expand the program. Copy and compile the example.

static double number1, number2, sum, product;
static void Main(string[] args)
{
   ReadData();
   CalculateResult();
   OutputResults();
   WaitForInput();
}
static void ReadData()
{
   Console.Write("Enter the first number: ");
   number1 = System.Convert.ToDouble(Console.ReadLine());
   Console.Write("Enter the second number: ");
   number2 = System.Convert.ToDouble(Console.ReadLine());
}
static void CalculateResult()
{
   sum = number1 + number2;
   product = number1 * number2;
}
static void OutputResults()
{
   Console.Clear();
   Console.WriteLine("{0} + {1} = {2}", number1, number2, sum);
   Console.WriteLine("{0} * {1} = {2}", number1, number2, product);
}
static void WaitForInput()
{
   Console.WriteLine("Press enter to quit");
   Console.ReadLine();
}

The Main part of this program consists of a series of procedure calls. All of our programming logic is divided into the separate stages of our problem.

Having A Go

  1. Adapt the program above to include procedures for all standard arithmetic operations. Use procedures to do this.