The Basics of Programming

Subroutines

Programs can get very big as more and more lines of instructions are added. Also, in some cases you may need to re-use bits of code over and over again. This is where subroutines and functions come in.

A subroutine is a set of instructions that does a specific task, for example, you could have a subroutine that calculates the average of an array of numbers and displays the result. A subroutine will always have a name, and sometimes provided with a list of values (known as parameters) that it can use, in this case an array and the number of items in the array (called num). A subroutine never returns a value, so we use the word void to say 'no value is returned'. We will use a counted loop, called a for loop, which will count through the array from 1 to num and use a variable called sum to store the sum of the values, and another variable called avg to store the average. The Console.Writeline command will display the result on the Output window.

E.g.

public void average (Int16 numbers[],Int16 num)
{
  Int16 sum, n; /* Define variables here */
  float avg;
  sum = 0; /* Set sum of numbers to zero */

  for (n=1; n<=num; n++) { /* Count from 1 to num, and increase count by 1 */
    sum = sum + numbers[n];
  }
  avg = sum / num;
  
Console.Writeline( "The average is" + avg.ToString()); /* Display string 'The average is ' and convert avg to string and append it. */

}
To use this subroutine, you can call it from the main program or even other subroutines, using its name and pass it the variables or values that it needs.

e.g.

Int16 numbers[5+1]; /* Define array of five integers, including one for index 0 */
numbers[1] = 456;
numbers[2] = 172;
numbers[3] = 78;
numbers[4] = 102;
numbers[5] = 321;
average( numbers[], 5);

and it should display the following result:

The average is 225.8

Functions

A function is very similar to a subroutine, it is still a set of instructions that does a specific task, but this time it will return a value, the type of value is specified by the variable type e.g. int, char, float, long etc. To return a value, you use the return statement and give it a value. Then the function also can be used in expressions, so if you have a complex calculation to perform regularly, you can create a function and and use it in expressions and assignments.

e.g.

float average (Int16 numbers[], Int16 num) /* Function is called average and returns a floating point number */
{
  Int16 sum, n; /* Define variables here */
  float avg;

  sum = 0; /* Set sum of numbers to zero */
  for (n=1; n<=num; n++) { /* Count from 1 to num */
    sum = sum + numbers[n];
  }
  avg = sum / num;
  return (avg);
}

Now you can use it in expressions or assignments from the main program, subroutines or even other functions.
e.g.

float MyAverage = average(numbers[], 5);
Console.Writeline("The average is " + MyAverage.ToString());

Many programming languages have built in libraries of functions which you can use in your programs. There are functions that do complex arithmatic such as square root, sines, cosines, tangents, minimum, maximum values. There are functions that are performed on strings such as length of a string, substrings, concatenate strings and so on.

Mathematical Functions

C has a number of built in functions you can use. By including the Math class, you have access to a range of useful functions for your programs.

Standard functions

Function Description Example
Abs Absolute value r = Math.Abs(n)
Exp Exponential r = Math.Exp(n)
Log Natural logarithm r = Math.Log(n)
Log10 Base 10 logarithm r = Math.Log10(n)
Max Max value from 2 possible values r = Math.Max(n, p)
Min Min value from 2 possible values r = Math.Min(n, p)
Pow Raise number to power of value r = Math.Pow(n, p)
Round Rounds a value to nearest integer r = Math.Round(n)
Sqrt Square root r = Math.Sqrt(n)
Sign Return integer indicating sign of value r = Math.Sign(n)

 

Trigonometry functions

NB: These use 'double' variables or values. See this basic information on using these functions when working with triangles.

Function Description Example
acos Arcosine r = Math.Acos( n);
asin Arcsine r = Math.Asin(n)
atan Arctangent r = Math.Atan(n)
atan2 Arctangent of x/y r = Math.Atan2(x, y)
cos Cosine r = Math.Cos(n)
sin Sine r = Math.Sin(n)
tan Tangent r = Math.Tan(n)
cosh Cosine Hyperbolic r = Math.Cosh(n)
sinh Sine Hyperbolic r = Math.Sinh(n)
tanh Tangent Hyperbolic r = Math.Tanh(n)

Character and String functions

Programs can do a lot with characters, strings and numbers.

Character functions

Function Description Example
ToString convert value to a string a = c.ToString()
Convert.ToChar convert number to a ascii character c = Convert. ToChar(n)
ToLower convert to a lower case a = s.ToLower()
ToUpper covert to upper case a = s.ToUpper()

String functions

Function Description Example
Clone Clone a string as a reference dest = s.Clone()
Length Length of a string n = str.Length()
IndexOf Find character in string n = str.IndexOf(c)
Concat Concatenate/combine strings s = string.Concat(c1, c2)
Compare Compare strings Compare(str1, str2)

Conversion functions

Function Description Example
ToSingle Expression to floating point number f = Convert.ToSingle(s)
ToDouble Expression to double precision number d = Convert.ToDouble(s)
ToInt16 Expression to 16 bit integer i = Convert.ToInt16(s)
ToInt32 Expression to integer i = Convert.ToInt32(s)
ToInt64 Expression to long l = Convert.ToInt64(s)
ToBoolean Expression to boolean b = Convert.ToBoolean(s)
ToDateTime Expression to date time d = Convert.ToDateTime(s)


Go to C# Input and Output