2. Introduction
Use of function
Calling a formula defined by user
Input & Output depends on type of function
Not included in main body
Can be called many times
3. Function Prototype
After #include<iostream>
Before int main()
Example 1
# include <iostream>
void FindMax(int, int); //prototype
using namespace std;
int main()
4. 4
Calling Function
Example 2
int main()
{
int num1, num2;
cout<<"Please enter a number :";
cin>> num1;
cout<<"Great!nPlease enter a second number :";
cin>> num2;
FindMax(num1, num2); //calling function
system ("PAUSE");
return 0;
}
5. Defining Function
Outside main body
Example 3
void FindMax(int x, int y){
int maxNum;
if (x>=y)
maxNum=x;
else
maxNum=y;
cout<<"Maximum number is : "<<maxNum <<endl;
}
6. Using reference variable
The Prototype:
void FindMax(double, double, double&);
The Calling:
FindMax(num1, num2, maxNum);
The Defining:
void FindMax(double x, double y, double& maxNum)
maxNum: a value edited in main function
7. • Compare Example 2
Example 4
int main()
{
double num1, num2, maxNum;
cout<<"Please enter a number :";
cin>> num1;
cout<<"Great!nPlease enter a second number :";
cin>> num2;
FindMax(num1, num2, maxNum); //calling
system ("PAUSE");
return 0;
}
Go to DevC++
8. Looping Function
Just insert function in loop to call as needed
Looping with returned value :
Declare return value
Send value to function
Write a loop
Example :
Using while loop to keep comparing numbers
9. Example 5
char next;
while(true){
cout<<"n('n' to exit')Compare with next number? :";
cin>> next;
if(next=='n')
break;
cout<<"Okay!nPlease enter the next number :";
cin>> num1;
num2 = maxNum;
FindMax(num1, num2, maxNum);
}