Function
Introduction Use of function   Calling a formula defined by user   Input & Output depends on type of function Not incl...
Function Prototype After #include<iostream> Before int main()    Example 1    # include <iostream>    void FindMax(int, ...
4Calling FunctionExample 2int main(){    int num1, num2;    cout<<"Please enter a number :";    cin>> num1;    cout<<"Grea...
Defining Function Outside main body Example 3 void FindMax(int x, int y){      int maxNum;      if (x>=y)      maxNum=x; ...
Using reference variable The Prototype:    void FindMax(double, double, double&); The Calling:    FindMax(num1, num2, ...
•   Compare Example 2Example 4int main(){    double num1, num2, maxNum;    cout<<"Please enter a number :";    cin>> num1;...
Looping Function Just insert function in loop to call as needed Looping with returned value :    Declare return value  ...
Example 5char next;while(true){   cout<<"n(n to exit)Compare with next number? :";   cin>> next;   if(next==n)   break;   ...
END
Upcoming SlideShare
Loading in …5
×

C++ programming function

1,833 views

Published on

summary

  • Be the first to comment

C++ programming function

  1. 1. Function
  2. 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. 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. 4Calling FunctionExample 2int 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. 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. 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. 7. • Compare Example 2Example 4int 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. 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. 9. Example 5char 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); }
  10. 10. END

×