Download programming function topic and more Schemes and Mind Maps C programming in PDF only on Docsity!
FUNCTIONS
Contents
- What is a C++ Function?
- <math.h> Library Functions
- Function Prototype - 1
- Function Definition - 2
- Function Call -
- Function Call by Value
- Function Call by Reference
- Taking input from user : Example
- Prime Number Function : Example
- Output Function : Example
- Function Over Loading
- Function Over Loading : sum Examples
- Function with Default Argument
- Scope of Variable Department of Computer Sciences Bahria University, Islamabad
CSC 113 – Computer Programming
- Functions Slide: 2
Functions in C++
Experience has shown that the best way to develop and maintain large programs is to construct it from
smaller pieces (modules)
This technique Called “ Divide and Conquer ”
Bad Development
Approach
Easier To
Design
Build
Debug
Extend
Modify
Understan
d
Reuse
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 3 function f2() {
} function f1() {
} main() {
}
Wise Development
Approach
main() {
. . .
return 0; } Functions in C++(Cont.) In C++ modules Known as Functions & Classes Programs may use new and “prepackaged” or built-in modules New: programmer-defined functions and classes Prepackaged: from the standard library Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 4
Math Library Functions
Function arguments can be
Constants
sqrt( 4 );
Variables
sqrt( x );
Expressions
sqrt( 6x + 10 );
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 7
Calling Functions
Examples (built-in, and user-defined functions)
int n = getPIValue( ) ; //Takes no argument
A user-defined function
cout << sqrt(9); //Takes one argument, returns square-root
cout<<pow(2,3); //Calculates 2 power
cout<<SumValues(myArray); //Returns sum of the
array
A user-defined
Department of Computer^ function
Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 8
Math Library Functions Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 9 Method Description Example ceil( x ) rounds x to the smallest integer not less than x (^) ceil( 9.2 ) is 10. ceil( -9.8 ) is -9. cos( x ) trigonometric cosine of x ( x in radians) cos( 0.0 ) is 1. exp( x ) exponential function ex^ exp( 1.0 ) is 2. exp( 2.0 ) is 7. fabs( x ) absolute value of x fabs( 5.1 ) is 5. fabs( 0.0 ) is 0. fabs( -8.76 ) is 8. floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9. floor( -9.8 ) is -10. fmod( x, y ) remainder of x/y as a floating-point number fmod( 13.657, 2.333 ) is 1. log( x ) natural logarithm of x (base e ) log( 2.718282 ) is 1. log( 7.389056 ) is 2. log10( x ) logarithm of x (base 10) (^) log10( 10.0 ) is 1. log10( 100.0 ) is 2. pow( x, y ) x raised to power y ( xy ) pow( 2 , 7 ) is 128 pow( 9 , .5 ) is 3 sin( x ) trigonometric sine of x ( x in radians) sin( 0.0 ) is 0 sqrt( x ) square root of x sqrt( 900.0 ) is 30. sqrt( 9.0 ) is 3. tan( x ) (^) trigonometric tangent of x ( x in radians) tan( 0.0 ) is 0
Functions
A function groups a number of program statements into a unit and gives it a name.
This unit can then be invoked from other parts of the program.
The most important reason to use functions is to help in the conceptual organization of a program.
Another reason to use functions is to reduce program size.
Any sequence of instructions that appears in a program more than once is a candidate for being
made into a function.
The function’s code is stored in only one place in memory, even though the function is executed
many times in the course of the program.
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 10
Output Guess its instructions Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 13 Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 14
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 15 Explanation
The program consists of two functions: main() and starline().
What other components are necessary to add a function to the program?
There are three: the function declaration , the calls to the function, and the
function definition.
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 16
Function Definitions Example function int square( int y ) { return y * y; } return keyword Returns data, and control goes to function’s caller
If no data to return, use return;
Function ends when reaches right brace
Control goes to caller
Functions cannot be defined inside other functions Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 19 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // Creating and using a programmer-defined function. #include <iostream.h> int square( int ); // function prototype void main() { // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call cout << endl; } // end main // square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { return y * y; // returns square of y as an int } // end function square
Example Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 20
// max_func.cpp // Finding the maximum of three floating-point numbers. #include 9 double maximum( double, double, double ); // function prototype 10 11 void main() 12 { 13 14 15 16 17 18 19 20 21 22 23 24 double number1; double number2; double number3;^ cout >> number1^ <<^ "Enter three floating-point numbers: "; cin >> number2 >> number3; // number1, number2 and number3 are arguments to // the maximum function call cout << "Maximum is: " << maximum( number1, number2, number3 ) << endl; Example Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 21 26 27 } // end main 28 // function maximum definition; // x, y and z are parameters double maximum( double x, double y, double z ) 32 { 33 34 35 36 37 38 39 40 41 42 double max = x; // assume x is largest if ( y > max ) max = y; // if y is larger, // assign y to max if ( z > max ) max = z; // if z is larger, // assign z to max return max; // max is largest value 43 } // end function maximum Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 22 Enter three floating-point numbers: 99.32 37.3 27. Maximum is: 99. Enter three floating-point numbers: 1.1 3.333 2. Maximum is: 3. Enter three floating-point numbers: 27.9 14.31 88. Maximum is: 88. Comma separated list for multiple parameters.
Header Files
Header files contain
Function prototypes Definitions of data types and constants
Header files ending with .h
Programmer-defined header files
#include “myheader.h”
Library header files
#include <math.h>
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 25 Comparison with Library Functions
Where are the declaration and definition for the library function?
E.g..
Where are the declaration and definition for this library function?
The declaration is in the header file specified at the beginning of the program (CONIO.H, for getche()). The
definition (compiled into executable code) is in a library file that’s linked automatically to your program when
you build it.
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 26
Eliminating the Declaration Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 27 Passing Arguments to Functions An argument is a piece of data (an int value, for example) passed from a program to the function. Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it. Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 28
Passing by Value
In previous example, the particular values possessed by chin and nin when the function call is executed will
be passed to the function.
As it did when constants were passed to it, the function creates new variables to hold the values of these
variable arguments.
The function gives these new variables the names and data types of the parameters specified in the declarator:
ch of type char and n of type int.
It initializes these parameters to the values passed.
They are then accessed like other variables by statements in the function body.
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 31 Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 32
Functions
Call By Value
Copy of data passed to function Changes to copy do not change original Prevent unwanted side effects Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 33 Functions
#include <iostream.h> void funct(int);
void main(void)
int x = 10; funct(x);
cout << “ In main X : “ <<x;
void funct(int x)
x = 5;
cout << “ In the Function X : “<< x <<endl;
Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 34
Functions #include <iostream.h> void swap(int &, int &); void main() { int x = 10; int y = 15; cout << “X : “ << x << “ Y: “ << y << endl; swap(x,y); cout << “X : “ << x << “ Y: “ << y << } endl; void swap(int &x,int &y) { int temp = x; x = y; y = temp; } Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 37 //^^^^^^^^^^^^^^^^^^^^^1^^^^^^^^^^^^^^^^^^^^^^^^ //1. get a positive number from user //2. check if number is prime or not //3. print the result ... yes if prime, no otherwise int getPositiveNumberFromUser(); bool checkPrime(int); void printResultOfPrime(bool); void printPrimeTillALimit(int); void printFactorial(int); // { int valueForPrime = getPositiveNumberFromUser(); bool primeResult = int main() checkPrime(valueForPrime); printResultOfPrime(primeResult); // //printResultOfPrime(checkPrime(getPositiveNumberFromUser())); // // printFactorial(getPositiveNumberFromUser()); // int limit = getPositiveNumberFromUser(); printPrimeTillALimit(limit); _getch(); } //^^^^^^^^^^^^^^^^^^^^^2^^^^^^^^^^^^^^^^^^^^^^^^ // { int number=0; int getPositiveNumberFromUser() while (number <= 0) { cout << "Enter a Positive Number : "; cin >> number; } return number; } // { int sq = sqrt( bool checkPrime(intvalue) + 1; value) bool prime = true; for (int loop = 2; loop < sq; loop++) { if (value % loop == 0) { prime = } false; break; } return prime; } // { if ( void printResultOfPrime(boolprime) prime) cout cout } <<<< "The value is a Prime Number""The value is NOT a Prime Number" << endl; << endl; else // { for (int loop = 1; loop <= void printPrimeTillALimit(int value; loop++) value) { if (checkPrime(loop)) cout } << " " << loop; } // { void printFactorial(int number) int factorial = 1; for (int loop = number; loop > 1; loop--) factorial *= loop; cout endl; } <<endl<< "The factorial of value " << number << " is " << factorial << Department of Computer Sciences Bahria University, Islamabad CSC 113 – Computer Programming
- Functions Slide: 38