Lesson 6: User-defined functions
User-defined functions are routines that can take parameters, perform calculations or other actions, and return a result.
C# Code that must be executed many times is a good candidate for functions. For Example, if you have to perform some operation that required you to cut and paste the same code over and over again can get pretty tedious. Also, C# function can provide a centralized location for common information. This way if you have to change common code you do not have to search and replace text in your code, you can just change the code in the function.
Lets see a programming example: The following example will find out which number is bigger or if the numbers are equal.
using System;
class Program
{
static void Main(string[] args)
{
int x, y;
x = 8; y = 1282;
if (x < y)
Console.WriteLine(y + " is bigger");
else if (x > y)
Console.WriteLine(x + " is bigger");
else
Console.WriteLine(x + " and " + y + " are equal");
////////////////Prints 1282 is bigger//////////////
x = 90; y = 34;
if (x < y)
Console.WriteLine(y + " is bigger");
else if (x > y)
Console.WriteLine(x + " is bigger");
else
Console.WriteLine(x + " and " + y + " are equal");
////////////////Prints 90 is bigger/////////////////
x = 1029465; y = -1283;
if (x < y)
Console.WriteLine(y + " is bigger");
else if (x > y)
Console.WriteLine(x + " is bigger");
else
Console.WriteLine(x + " and " + y + " are equal");
////////////////Prints 1029465 is bigger/////////////
x = 34; y = 34;
if (x < y)
Console.WriteLine(y + " is bigger");
else if (x > y)
Console.WriteLine(x + " is bigger");
else
Console.WriteLine(x + " and " + y + " are equal");
////////////////Prints 34 and 34 are equal///////////
Console.ReadLine();
}
}
Output:
1282 is bigger
90 is bigger
1029465 is bigger
34 and 34 are equal
As you can see the if/else if statements are copied and pasted each time x and y changed. There is a more effiecient way to do this. Just image if that common code were hundreds of lines and you had to edit some part of that common code. We will you to C# functions in the next section
C# Function Basics
To define a C# function you must declare it outside the main() block because the definition cannot be executed, it is merely a definition.
1. using System;
2. class Program
3. {
4. static void print() //Function declared outside of main block
5. {
6. Console.WriteLine("In function");
7. }
8. static void Main() //Main Block
9. {
10. print(); //Call print function
11. Console.Read();
12. }
13. }
Output:
In Function
· Static Keyword: We will not cover static in this section. We will cover it in the classes section. Just remember it must be included in your functions.
· void Keyword: void means that the function will not return a value
· Line 10: This is the syntax to run a function. Type the functions name followed by ();
Return Values in a C# Method
In a C# function you may want to return the result of an operation. You can return the value of a variable in a function by using the return keyword.
The program will simple print the value of pi: Example:
1. using System;
2. class Program
3. {
4. static double pi() //Function pi
5. {
6. return 3.14; //Return 3.14
7. }
8. static void Main()
9. {
10. Console.WriteLine(pi());// calling and showing function pi
11. Console.Read();
12. }
13. }
Output:
3.14
· double keyword Simply means that the function will return a double value
· return keyword Simply returns the value to object that called it
C# Function Parameters
C# methods can accept values when a variable calls it.
Example 1:
using System;
class Program
{
static int Multiply(int x) //accepts only a int value
{
return x * 2;
}
static void Main()
{
int z = 3;
Console.WriteLine(Multiply(z)); //Prints the returned value
Console.Read();
}
}
Output:
6
Example 2:
1. using System;
2. class Program
3. {
4. static void PrintArray(int[] x) //accepts an array value
5. {
6. foreach (int temp in x)
7. Console.WriteLine(temp);
8. }
9. static void Main()
10. {
11. int[] z = { 4, 45 };
12. double[] x = {.9, .8};
13. PrintArray(z);
14. PrintArray(x); //ERROR-- Print array only takes int values
15. Console.Read();
16. }
17. }
· Line 14: Notice this program will not compile. PrintArray only takes int arrays
C# Call by Reference
In the previous sections we have been calling functions by value. Now we will learn how to call by reference. Use call by reference any chance you get because it has tremendous performance benefits. The compiler does not have to spend the time to create a temporary variable, it uses the same variable in the calling statement. So, any changes that are made to the variable are in effect through out the whole program.
Example:
using System;
class Program
{
static void AddOne(ref int x)
{
x = x + 1;
}
static void Main()
{
int z = 8;
AddOne(ref z); //variable z will be changed in function
Console.WriteLine(z);
Console.Read();
}
}
Output
9
As you can see z is passed to the function. When you call by reference it does not send the value it sends the variables address so it knows where to find it.
AddOne(z); //call by value
AddOne(ref z); //call by reference
When you are dealing with arrays it can truelly degrade the performance of your program if you use call by value. use call by reference when passing arrays.
The C# out Parameters
The out parameter is very similar to the ref keyword. You are allowed only to return one variable from a function. The out keyword gives the ability to return multiple values. You must use out in the same way as you would the ref keyword. Except in one case:
· An out variable has to be an unassigned a variable when passed to a function
Example:
using System;
class Program
{
static int AddOne(out int x)
{
int y = 90;
x = 19; //out variable must be initialized
x = x + 1;
return y + 1;
}
static void Main()
{
int z; //out variable must be unassigned be declared
Console.WriteLine(AddOne(out z));
Console.WriteLine(z);
Console.Read();
}
}
Output:
91
20
· Tip: If you assign an out variable before it is passed to a function that value will be ignored because it must be reassigned in the function.
C# Scope
Variable scope is an crucial subject in any programming language. One of the most difficult errors to debug are runtime bugs. Compilation errors are easy to pin point because the compiler tells you were the error is. A runtime bug is a bug that produces incorrect results. The program runs fine but it gives unexpected results or behavior. Trying to track variable values is a daunting task if you have hundreds or thousands of variables. If you keep track of your variable scopes you will have less headaches in the future.
When you declare a variable inside main() it is only visible in the main() block. For example, you cannot declare a variable x in main() and then try and access it in a function.
Example 1:
using System;
class Program
{
static void printX()
{
Console.WriteLine(x); //Error--Cannot access variable x
}
static void Main()
{
int x = 78; //Declared in main()
printX();
Console.Read();
}
}
Important: This program will not compile because the function printX() is trying to access a variable that is not accessible.
If you want x to accessible in the function you must pass it by value or pass by reference. Variables only have scope in the block that they are declared in.
Example 2: using System;
class Program
{
static void Main()
{
int x = 3;
if (true) //start -- if block
{
int y = 6; //declared in if block
}
//ERROR--y is only accessible in the if block
Console.WriteLine(y);
//OK -- x is accessible
Console.WriteLine(x);
Console.Read();
}
}
Note: This program will not compile because y can ONLY be accessed in the if block Example 3:
using System;
class Program
{
static void Main()
{
int x;
if (true) //start -- if block
{
int y = 6; //declared in if block
x = y; //x is still in Main()
}
//OK -- x is accessible
Console.WriteLine(x);
Console.Read();
}
}
Output: 6
x is still accessible because it is still in the Main block. y can only be accessed only in that particular if block.
C# Global variables
Global variables are accessible through out the whole program. To declare a global variable you must use the static or const keyword. The const keyword prevents the variable from being modified.
Example: 1. using System;
2. class Program
3. {
4. static int a = 2; //Accessible in the whole program
5. static void test()
6. {
7. Console.WriteLine(a);
8. }
9. static void Main()
10. {
11. test();
12. Console.Read();
13. }
14. }
2
Line 4: Do you see the static keyword. This makes the variable accessible in the whole program.
- You cannot declare a static variable in the main block or in a function
- Global variables increase program performance
C# Main() Function
Functions are able to accept and return parameters. Main() is no different than any other function. The C# Main function is slightly different in that it is able to accept and return values to external applications. Such as MS word or any other external application. The are four versions of the Main() function:
'C# Main() Versions:
- static void Main() - accepts no parameters and returns no values
- static void Main(string[] args) - returns no parameters and accepts a string array named args
- static int Main() - returns an int value and accepts to parameters
- static int Main(string[] args) - returns an int and accepts a string array named args
Lets accept parameters from an external program like DOS. Here are the instructions to follow:
using System;
class Program
{
static void Main(string[] args)
{
foreach(string x in args)
Console.WriteLine(x);
Console.Read();
}
}
Compile and make an executable from the code above. When you finish compiling the code move the executable file to the C:\ directory and rename the file to test.exe. Then run run a DOS window and move to the c:\ directory.
C:\>test.exe it's working 1 2 3 123
Each space separates each parameter. The output should look like this:
The C# program accepted the arguments and simply displayed the arguments located in an array.
C# Function Overloading
Overloading is the idea of having multiple functons that are the same name. Each function must accept different types or amount of types. This is how the compiler differentiates from overloaded functions.
Example 1: using System;
class Program
{
static void Function(int x) //Accepts an int
{
x = 12;
Console.WriteLine(x + " is an int");
}
static void Function(long x) //Accepts a long
{
Console.WriteLine(x + " is an long");
}
static void Main()
{
int a = 12;
long b = 12;
Function(a); //passing an int value
Function(b); //passing a long value
Console.Read();
}
}
Output:
12 is an int
12 is a long
Example 2:
using System;
class Program
{
static void Function(int x) //Accepts one parameter
{
x = 12;
Console.WriteLine(x + " is an int");
}
static void Function(int x, int y) //Accepts two parameters
{
Console.WriteLine(x + " and " + y + " are int");
}
static void Main()
{
int a = 12;
int b = 12;
int c = 12;
Function(a); //passing one value
Function(b, c); //passing two values
Console.Read();
}
}
Output:
12 is an int
12 and 12 are int
The are more ways to give the compiler hints that functions are different. These are just a couple of ways I have presented. C# function overloading is a powerful tool. With overloading your code will be somewhat shorter and can decrease development time. Overloading does not have any performance benefits infact it has a minute performance hit because the compiler must choose which function to call. This decision takes a very small amount of time.
Example 3: using System;
class Example
{
private int i;
//Default constructor
//Uzing overloaded constructor
public Example():this(0)
{
}
//Overloaded constructor
public Example(int I)
{
i = I;
}
}
C# Recursion
C# recursion is the idea of a function calling itself. This may seem weird but this is a good feature to produce some elegant results. Recursion is common in advanced math and science where complicated calculations require recursion. We will provide a simple and easy example of C# recursion.The programmer must have a condition in the recursive funtion to tell it to stop, otherwise it will go forever and the program will run out of memory.
Advantages of C# Recursion
- Directory list programming
- Mathmatics and science programming
- Node programming
- Some AI programming techniques
- Forum programming
Disadvantages of C# Recursion
- Memory hog
- Can be unstable if not programmed correctly
- If recursion reaches deep levels it can have a severe performance issue when unwinding
C# Recursion Tips
- Specify a condition to end the recursion
- Do not overuse recursion
Example: This code will count from 1 to 10 using recursion
using System;
class Program
{
static void RecuriveFunction(int x)
{
if (x > 10) //Condition to stop recursion
return; //Exit out of function
else
{
Console.WriteLine(x);
RecuriveFunction(x + 1); //Call myself
}
}
static void Main()
{
RecuriveFunction(1);
Console.Read();
}
}
Output:
1
2
3
4
5
6
7
8
9
10
VARIANTS
TASK1.
Execute the problem given in the following task.
1) Write a function max3() that takes three int values as arguments and returns the value of the largest one. Add an overloaded function that does the same thing with three double values.
2) Write a driver program which uses the function to output an
m
x n
block of asterisks. m
and n
are entered by the user.3) Write a program that asks a user to type the value of N and computes N! . Use function prototype.
4) Write a C++ program employing a function int equals(int,int) which checks whether two integer numbers are equal. In this case, the return value should be 1 otherwise 0.
5) Write a program for a function that takes two parameters of the
float
type and returns true (1) if the first parameter is greater than the second one and otherwise returns false (0).6) Write a program MaxMin.cpp that reads in integers (as many as the user enters) and prints out the maximum and minimum values read in.
7) Write a program employing GeometricMean function that reads in positive real numbers and prints out their geometric mean. Find the geometric mean of N positive numbers x1, x2, ..., xN is (x1 * x2 * ... * xN)1/N.
8) Write a C++ program using a function prototype. Input data should be typed in from the keyboard.
9) Write a program employing Pnorm function that takes a command-line argument p, reads in real numbers, and prints out their p-norm. The p-norm norm of a vector (x1, ..., xN) is defined to be the pth root of (|x1|p + |x2|p + ... + |xN|p).
10) Write a program employing the HarmonicMean function that reads in positive real numbers and prints out their harmonic mean. Find the harmonic mean of N positive numbers x1, x2, ..., xN is (1/x1 + 1/x2 + ... + 1/xN) / (1 / N).
11) Write a program that calculates the mileage you travel on your car. The program should ask a user for the number of miles traveled and the number of gallons consumed. Use the function Mileage() to calculate the mileage. Mileage() should take two arguments (the number of miles traveled and the number of gallons consumed). The function should return the mileage and the program should then display it on the screen.
12) Write a program that computes the cost of a taxi ride. A taxi charges a fixed fee of $2.50 plus an additional charge of $5.50 per mile. The program should ask a user to enter the length of the trip in miles and use the function Taxi_Charge() to calculate the fare. Taxi_Charge() should have one argument, the length of the trip, and return the total fare for the ride. The program should display the total fare.
13) Write a program that asks user to input a grade that he or she received at an exam. The grade is an integer from 0 to 100 inclusive. The program should convert the numeric grade into the equivalent letter grade. Do the conversion by using a function Letter_Grade() that converts a numeric grade in the range 0100 to the equivalent letter grade. The function should have one parameter, (an integer grade). The return value of the function should be A if the grade is 90 to 100; B if the grade is 80 to 89; C if the grade is 70 to 79; D if the grade is 65 to 69; and F if the grade is 64 or lower. After converting the grade, the program should display the numeric grade and the equivalent letter grade.
14) – 16) Write a C++ program employing AREA function which will ask a user to enter coordinates and define whether they belong to the shaded area.
14 | 15 | 16 |
| | |
17) You have a,b,c numbers. Write a program employing a TRIANGLE function which will define whether you can build a triangle with a,b,c sides.
18) The factorial n! of a positive integer n is defined as
n! = 1*2*3 . . . * (n-1) * n,
where 0! = 1. Write a function to calculate the factorial of a number.
19) Write a function power (double base, int exp) to calculate integral powers of floating-point numbers. The power x0 is defined as 1.0 for a given number x. The power is defined as for a negative exponent n. The power with n > 0 will always yield 0.0 .
20) Write a program that repeatedly asks a user to enter pairs of numbers until at least one of the pair is 0. For each pair, the program should use a function to calculate the harmonic mean of the numbers. The function should return the answer to main(), which should report the result. The harmonic mean of the numbers is the inverse of the average of the inverses and can be calculated as follows:
harmonic mean = 2.0 . x . y / (x + y)
21) The trigonometry functions (sin(), cos(), and tan()) in the standard <math.h> library take arguments in radians. Write three equivalent functions, called sind(), cosd(), and tand(), which take arguments in degrees. All arguments and return values should be the double type.
22) Write a program that reads in a number (an integer) and a name (less than 15 characters) from the keyboard. Data is entered by one function, and output by another. Keep the data in the main program. The program should end when zero is entered.
23) Write a family of overloaded functions called equal(), which take two arguments of the same type, returning 1 if the arguments are equal, and 0 otherwise. Provide versions for char, int and double functions.
24) Write a program that calculates an expression , where , the maximum number between x and y. Solve this problem by using function prototype.
25) Write a C++ program by using function prototype to identify whether the entered number is odd or even. Provide versions checking also if the entered number is a total square.
26) The date consists of three numbers: y (year), m (month) and d (day). Write a program that prints out the date of the previous and the next days.
27) Write a program that displays the following on the screen:
************************** * * * I can write functions!* * * ************************** |
To accomplish the task the program should use three functions. The function Stars() should display a line of 26 asterisks. The function Bar() should display an asterisk, 24 blanks, and an asterisk. The function Message() should display the middle line. None of the functions should return a value.
28) Write a program that draws a rectangle of Xs. Ask a user to enter dimensions of a rectangle, then use the function Rectangle() to draw a rectangle of the requested size consisting of Xs. Rectangle() should have two integer arguments (the length and width of the rectangle). The function should not return a value.
29) A manufacturer needs a program to display a table of costs for certain items of her product. She wants to input the production costs for one unit, the smallest and the largest number of products produced, each in hundreds. For example, she might input 3.46 for the unit cost, and 300 and 700 as the range of numbers. The resulting table should look as shown below.
Product Cost Table:
----------------------------------------------------
Number Produced Cost
----------------------------------------------------
----------------------------------------------------
300 1038.00
400 1384.00
500 1730.00
600 2076.00
700 2422.00
Use a function Heading() to display the table headings. Heading() should receive no arguments and return no value. Use another function, Table(), to produce the table. Table() should have three arguments (the unit cost, the smallest number produced, and the largest number produced) and table() should not return a value.
30) Write a program that asks a user to enter two decimal numbers, calculates and displays the product and quotient of them. Use a function Product() to calculate the product. The function should have two arguments which are the two numbers that the user inputs. The function should return the product of the numbers. Use a function Quotient() that has two arguments, which are the numbers entered by the user. The function should return the quotient of the first number divided by the second. If the second number is zero (recall that division by zero is not allowed), display an error message and exit the program.
31) Write a program that calculates expression , where , the maximum number between x and y. Solve this problem using function prototype.
TASK2.
Note: All input values must be entered from the keyboard by the user and a sensible input prompt and informative output should be included.
1) Write a program which will ask a user to enter rectangle with m and n sides and compute how many squares with side m can be placed in it.
2) Write a program that changes an integer number of centimetres into its equivalent in kilometres, metres and centimetres. For example, 164375 centimetres is 1 kilometre , 643 metres and 75 centimetres . Include declarations of suitable variables.
3) Write a program to read in characters of different type (char, int, float, double, bool, string) and to print them out, each one in a separate line and enclosed in single quotation marks.
4) Write a program that converts a sum of money given as an integer number of pence into a floating point value representing the equivalent number of pounds. For example, 365 pence would be 3.65 pounds .
5) Write a program which prompts the user to enter two integer values, a float value and two values of bool type and then prints out all five values that are entered with a suitable message.
6) Write a program which asks user to enter the needed values and calculates the expression for the following mathematical formula:
Y=.
7) Write a program to evaluate the fuel consumption of a car. The mileage at the start and end of the journey should be read in, as well as the fuel level in the tank at the start and end of the journey. Calculate fuel used, miles traveled, and hence the overall fuel consumption in miles traveled per gallon of fuel.
8) Write a C++ program which asks a user to enter the needed values and calculates the expression for the following mathematical formula:
Y=
9) Write a program to convert currency from pounds sterling into deutsch marks. Read the quantity of money in pounds and pence, and output the resulting foreign currency in marks and pfennigs. (There are 100 pfennigs in a mark). Use a
const
to represent the conversion rate, which is 2.31DM to £1 at the time of writing. 10) Write a program which will compute the area of a square () and a triangle ().
11) A customer's gas bill is calculated by adding a standard charge of 9.02 pence per day to the charge for gas, calculated as 1.433 pence per cubic meter. The whole bill is then liable for VAT at 8%. Write a program that reads in the number of days, and the initial and final meter readings, and calculates and prints the bill. Use
const
for the various rates of charging.12) Write a program which will ask a user to enter a double figure and which will output:
– number of ten's place;
– amount of digits in it;
– summation of its digits.
Example: input: 123, output: 1) 12; 2) 3; 3) 6
13) Write a program which will calculate Surface area (S= 4 Pi2Rr) and Volume (V= 2 Pi2Rr2) of the Circular (Ring Torus).
14) Write a program which reads values of two floats and outputs their sum, product and quotient.
15) Write a program which will ask a user to enter three figures and output:
– amount of digits in it
– summation of its digits
– product of its digits
Example: input:123, output: 1) 3; 2) 6; 3) 6;
16) Write a program which will ask a user to enter three figures and output a number in which the first figure will be put after the third one. Example: input: 123, output: 231.
17) Write a program with a function which will ask a user to enter four figures and output a number in which figures will be transposed. Example: input: 1234, output: 2143 or input: 7086, output: 768.
18) Write a program which will ask a user to enter a natural number (n>9) and output an amount of ten's places.
Example: input: 123456789, output: 9.
19) Write a program that computes the hypotenuse length of four right triangles based on the lengths of the two legs. (Use the task 2 from the laboratory work 1).
20) Read in three integers of the data type
int
from the keyboard. Then add three numbers and divide received summation by the fourth number that was entered by the user.21) Write a program that is capable of displaying the distances from the sun to four planets closest to it in centimeters and inches. (Use the task 8 from the laboratory work 1).
22) Write a program that prints out all six permutations of the three lines typed into the screen. Declare a named constant for each line and write an output statement for each permutation. (Use the task 10 from the laboratory work 1).
23) Write a program that prints out a business card. A card should include your name, street address, phone number(s), and email address. Also make up a company name and put it on the card. Print the complited card to the screen.
24) Write a program that takes an integer as the number of minutes and outputs the total hours and minutes.
25) Write a program to calculate the volume of a sphere . Print the result to the screen in the following manner:
The volume of a sphere | |
r | V |
2 3.5 1.07 | ? ? ? |
26) Write a program that converts Celsius into Fahrenheit. The formula is . Print the result to the screen in the following manner:
Celsius to Fahrenheit | |
Celsius | Fahrenheit |
-17.8 -10 10 | ? ? ? |
27) Write a program to print out the perimeter of a rectangle given its height and width. The formula is perimeter = 2 · (width + height). Print the result to the screen in the following manner:
The perimeter of a rectangle | ||
Width | Height | Perimeter |
3.04 2.9 11 | 10 7.6 3.4 | ? ? ? |
28) Write a program which asks a user to enter the needed values and calculates the expression for the following mathematical formula:
Y=
29) Write a program that does the following: given as input three integers representing a date as day, month, year, print out the number day, month and year for the following day's date.
Typical input: 28 2 1992
Typical output: Date following 28:02:1992 is 29:02:1992.
30) Write a program creating a table of Olympic running distances in meters, kilometers, yards, and miles. Use the pattern exhibited in these distances to write your program: 1m = 0.001 km = 1.094 yd = 0.0006215 mi . All distances are real numbers. Print the result to the screen in the following manner:
Table of Olympic running distances | |||
Meters | Kilometers | Yards | Miles |
100 200 300 400 | ____ ____ ____ ____ | ____ ____ ____ ____ | ____ ____ ____ ____ |
No comments:
Post a Comment