Functions: BIT205 - Programming in C++
Functions: BIT205 - Programming in C++
Functions
Prepared by: Ms Seetha
Functions
User-defined functions :
Functions must be defined before they are used. They are called function prototypes.
Functions
Function prototypes are typically placed near the beginning of the program file after the #include statements. Function prototypes permits type checking at compilation and linking time. 1. the return type 2. the identifier/name of the function and 3. the types of all parameters that the function expects.
Functions
parametertype defines the type of the data. E.g. char, int, float, void etc. parametername is the name by which this data is known within this function, and may be (in fact, usually is) different to its name in the calling module. functionname is a meaningful name to address the function Some examples of function prototypes :
int PromptAndRead(); float CircleArea(float radius=3); bool IsVowel(char CurrentCharacter); void Menu();
Functions
In addition default arguments may be specified when declaring C++ prototypes. Example :
float mission (int destroyers=20);
to provide destroyers with the default value of 20. The function call:
. cout<<mission(); . cout<<mission(5);
function call
function call
Functions
Function prototype
Function call will call the function and the value returned will be displayed
);
int main(){ int value; cout<<Please enter a number:<<flush; cin<<value; cout<<Square is :<<square(value)<<endl; return 0; } int square(const int num) { function definition return num *num; } The above function accepts an integer as parameter. The const modifier is used to guarantee that the function will not modify the num value i.e it will remain constant within the function.
Functions
Example 2 : Program to compute area of a user-specified circle Function definition #include <iostream.h> float CircleArea(float r){ (function prototype const float Pi=3.1415; not required as the return Pi*r*r; definition is on the } top)
int main(){ float radius; cout<<Circle radius (real number) <<flush; cin<<radius; Function call will call the float area=CircleArea(radius); cout<<Area of a circle with radius<< radius<< is <<area<<endl; return 0; }
Functions
void functions
The void data type as a return type indicates that the function does not return a value. The void data type as a parameter list indicates that the function does not take any parameters. Empty parentheses are equivalent to specifying void as the parameter. Example : void printError(void){ cout<<You have entered the wrong input data<<endl; } OR void printError(){ cout<<You have entered the wrong input data<<endl; } A call to this function is made in a block of code by .. printError(); ..
Functions
float CircleArea(float r){ return Pi*r*r; } void print(float val, int radius){ cout <<Area of a circle with radius <<radius<< is <<area<<endl; } int main(){ float radius; cout<<Circle radius (real number) <<flush; cin<<radius; float area=CircleArea(radius); print(area,radius); Function call return 0; }
Function definition (function prototype not required as the definition is on the top)
Functions
Example 1 :
#include <iostream.h> void display (int); void main ( ){ int x = 1; display (x); for (int i = 0; i < 3; i++){ int y = x + i; display (y); }//end for } void display (int num){ cout << Value in display << num <<endl; }
Functions
EXERCISES.
1. How is information supplied as input to a function? How can information be conveyed back to the calling program? 2. Write a function that accepts 2 parameters of type integer (x,y) and then prints x number of * in y rows. Example : (3,4) would produce the following results *** *** *** *** 3. Write a function that accepts an integer and determines the total number of even digits in that integer. Eg. 1334 would return 1
Functions
Note : The function call must specify the same number of parameters as the function declaration and definition. The parameters must be specified in the same order, and must be of the same type.
Functions
a b
2 3
2 3 2
Functions
one two
a b
temp
void swap (int * one, int * two) // parameters are passed by reference. { int temp; temp = *one; *one = *two; *two = temp; } Note : Pointers will be covered in the following chapters
3 2 2 3 2
Functions
Reference Parameters
A criminal who uses two names is said to have an alias. To create a second name for a variable in a program you can generate an alias. A reference variable is a variable that acts as an alias for a second variable. Syntax to declare a reference variable : datatype &varname1=varname2; Example : double somemoney=37.48; double &cash = somemoney; cash=6.58; cout<<somemoney; someymoney=1.25; cout<<cash; What is the output???
Functions
Example 2 : using reference mechanism (only avalaible in C++) #include <iostream.h> 3 2 one a void swap (int& one, int& two); two b 2 3 void main(){ int a=2,b=3; 2 temp
swap(a,b); cout<<a<<b<<endl; }
void swap (int &one, int &two) // parameters are passed by reference. { int temp; temp = one; one = two; two = temp; }
Functions
Exercise...
Write a program that converts from twenty-four hour notation to twelve-hour notation. For example, it should convert 14:25 to 2:25PM The input is given as two inetegers. There should be at least three functions; one for the input, one to do the data conversion, and one for the output. Record the AM and PM information as a value of type char, A for AM and P for PM. Thus the function for doing the conversions will have a call by reference formal parameter of type char to record whether it is AM or PM. Include a loop that lets the user repeat this computation for new input values again and again until the user says he or she wants to end the program.
Functions
You may have several functions that perform similar tasks but work with different data types, then each of the functions requires a unique name. Example :
float Mult2Float(float num1, float num2); int Mult2Ints(int num, int num2); longMult2Longs(long num1, long num2); double Mult2EDouble(double nume1, double num2); float Mult2FloatInt(float num1,int num2);
Parameter types and return types are different for each function but the function is the same i.e. multiplication. Its difficult to remember which function to call given a certain set of data.
Functions
1.Change the data types of existing function parameters 2.Change the number of function parameters 3.Change the return type
You can combine these choices in many ways If you have two or more functions for the same function name that is called overloading.
Example :
float Multiply(float num1, float num2); int Multiply(int num, int num2); longMultiply(long num1, long num2); double Multiply(double nume1, double num2);
When there is a function call, the compiler uses the function definition whose number of parameters and types of formal parameters match the arguments in the function call.
Functions
float Multiply(float a, float b) { #include <iostream.h> return a*b; } float Multiply(float num1, float num2); int Multiply(int a, int b) int Multiply(int num, int num2); { longMultiply(long num1, long num2); return a*b; double Multiply(double nume1, double num2); } void main(){ long Multiply(long a, long b) int num3=7; float fl=3.14l; double db=4.56; { cout<<Multiply(num3,num3)<<Multiply(fl,fl) return a*b; } <<Multiply(db,db)<<Multiply(num3,fl); double Multiply(double a, double b) } { return a*b; }
Example :
Functions
EXERCISES..
1. The following are the function prototypes for two versions of power function. double power (double x, int y); int power (int x, int y);
Write the function definitions for each of them. Then write the main to test your function definitions.
Functions
TUTORIAL 1
Write a function void floattopp(float q, int& L, int& P) which converts the sum of money q in RM into L RM and P cents where the cents are correctly rounded. Thus if q was RM24.5678 then L should be set to 24 and P should be set to 57. Remember that when assigning a real to an integer the real is truncated. Thus to round a real to the nearest integer add 0.5 before assigning to the integer. Write a simple driver program to test the function. Think carefully about the boundary conditions.
Functions
TUTORIAL 2
It is required to print out a table of mortgage repayments for a range of years of repayment and a range of rates of interest. Write an algorithm to produce a table of the monthly repayments on a mortgage of RM40,000 repayable over 15, 16, 17,..., 30 years with interest rates of 3, 4, 5,..., 10 per cent. Assume that the actual repayment will be produced by a function which will take as input parameters the principle P, the repayment time n in years and the rate of interest r as a percentage rate and will return the monthly repayment in RM and cents Transform your algorithm into a C++ program. Write a function prototype for the repayment calculation function and write the function itself as a function stub. That is a function that does not perform the correct calculation but delivers values that are sufficient to test the rest of the program. In this case it should return values of zero for the RM and cents of the monthly repayment. This will allow you to test that your program lays the table out properly.
Functions
Once you have the table layout working you can now write the function itself. The repayment each month on a mortgage of P RM, taken out over n years at an interest rate of r% is given by:
rPk 12n repayment 1200(k 12n 1)
where
r k 1 1200