Top Banner
A function is a subprogram that acts on data and often returns a value . You are already familiar with the one function that every C++ program possesses: int main(void) . Ideally, your main( ) function should be very short and should consist primarily of function calls lt-in functions ld-in functions are part of the compiler package, s t(1);
35

A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

Dec 24, 2015

Download

Documents

Polly Bryan
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

A function is a subprogram that acts on data and often returns a value .

You are already familiar with the one function that every C++ program

possesses:  int main(void).  Ideally, your main( ) function should be very short and should consist primarily of function calls

Built-in functionsBuild-in functions are part of the compiler package, such asexit(1); 

Page 2: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

A function definition consists of two parts: interface and body.

The interface of a function (also called its prototype) specifies how it may be used. It consists of three entities:

The function name. This is simply a unique identifier.The function parameters (also called its signature).

This is a set of zero or more typed identifiers used for passing values to and from the function.

The function return type. This specifies the type of value the function returns. A function which returns nothing should have the return type void.

Page 3: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

•The body of a function contains the

computational steps (statements) that

comprise the function.

•Using a function involves ‘calling’ it.

• A function call consists of the function name

followed by the call operator brackets ‘()’,

inside which zero or more comma-separated

arguments appear

Page 4: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

int Power (int base, unsigned int exponent)

{

int result = 1;

for (int i = 0; i < exponent; ++i)

result *= base;

return result;

}

Function body

Note:Note:A function should be declared before its is usedA function should be declared before its is used

Page 5: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

User-defined

functions

User-defined functions

are created by you, the programmer.

Page 6: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

• Declare the function.  • The declaration, called the function

prototype, tells the computer the name, return type, and parameters of the function. 

• This statement is placed after #include<iostream.h> (and other headers) and before int main(void).

Page 7: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

FORMAT NOTE:

Please have all of your

functions end with return .

Page 8: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

•2  .Define the function  .•The function definition tells the compiler what task the

function will be performing  .•A function definition cannot be called unless the

function is declared  .•The function prototype and the function definition

must agree EXACTLY on the return type, the name, and the parameters  .

•The only difference between the function prototype and the function header is a semicolon (see diagram below) .

• The function definition is placed AFTER the end of the int main(void) function.

•The function definition consists of the function header and its body.  The header is EXACTLY like the function

prototype, EXCEPT that it contains NO terminating semicolon

Page 9: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

Local Variable

..a variable that is restricted to use

within a function of a program.

Our first style of function will simply perform an independent task. It will not send or receive any parameters and it will not return any values. The word void appears as the return type and the parameters.

Page 10: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

#include <iostream.h>

int Power (int base, unsigned int exponent); // function declaration

main (void){

cout << "2 ^ 8 = " << Power(2,8) << '\n';}int Power (int base, unsigned int exponent){

int result = 1;for (int i = 0; i < exponent; ++i)

result *= base;return result;

}

Page 11: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

• C++ supports two styles of parameters:

value and reference.

• A value parameter receives a copy of the value of

the argument passed to it

• A reference parameter, on the other hand,

receives the argument passed to it and works on it

directly

Page 12: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

#include <iostream.h> void Foo (int num)

{num = 0;cout << "num = " << num << '\n;'

} int main (void)

{int x = 10;

 Foo(x);cout << "x = " << x << '\n;'return 0;

}

Page 13: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

• variables generally denote memory locations where variable values are stored

• The storage class specifier register may be used to indicate to the compiler that the variable should be stored in a register if possible. For example:

•  for (register int i = 0; i < n; ++i)sum += i;

 

Page 14: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

•An enumeration of symbolic constants is introduced by an enum declaration.

• This is useful for declaring a set of closely-related constants .

•For example,•enum {north, south, east, west};

introduces four enumerators which have integral introduces four enumerators which have integral values starting from 0 (i.e., north is 0, south is 1, etc.) values starting from 0 (i.e., north is 0, south is 1, etc.)

enum {north = 10, south, east = 0, west};

Here, south is 11 and west is 1.

Page 15: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

However, instead of replicating this expression in many places in the program, it is better to define it as a function:

 int Abs (int n){return n > 0 ? n : -n;

}

Page 16: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

//Screen display shown at the right//Prototyping, defining and calling a function#include<iostream.h>#include<stdlib.h>void astericks(void); //function prototypeint main(void){ system("CLS"); cout<<"Heads up, function!\n"; astericks( ); //function call cout<<"Again, function!\n"; astericks( ); //function call cout<<"Job well done!\n"; return 0; //main( ) is over - ALL STOP!!}//function definitionvoid astericks(void){ int count; // declaring LOCAL variable for(count = 1; count<=10; count++) cout<<"*";     cout<<endl;     return;  //return value is VOID, no return}

SCREEN DISPLAY Heads up, function!**********Again, function!**********Job well done!

Page 17: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

• Our second style of function will take arguments (parameters) but will not return a value. 

• The argument list in the parentheses specifies the types and number of arguments that are passed to the function. 

void sum(int x, int y, int z);  //function prototypeAcceptable Prototypes

void add(int x, int y); void add(int, int); While both of these prototypes are acceptable, we will be using the first style.

Page 18: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

//Example program//Screen display shown at the right//Passing arguments to a function

#include<iostream.h>#include<stdlib.h>

void greeting(int x);   //function prototypeint main(void)

{     system("CLS");     greeting(5);  //function call- argument 5          int number;     do     {          cout<<"Please enter value(1-10):\n ";          cin>>number;     }     while ((number < 1) || (number > 10));     greeting(number); //argument is a variable     return 0;}

//function definitionvoid greeting(int x)   // formal argument is x{     int i;   // declaring LOCAL variable     for(i = 0; i < x; i++)     {          cout<<"Hi ";     }     cout<<endl;     return;  //return value is VOID, no return}

Screen Display Hi Hi Hi Hi Hi

Please enter value(1-10):4Hi Hi Hi Hi

Page 19: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

Our third style of function takes no arguments, but will return a value.  Up until now, we have been communicating information TO a called function. 

Now we will be returning information FROM the function by using the function return value. 

The return value can be a constant, a variable, or an expression.  The only requirement is that the return value be of the type specified in the function prototype. 

return_type functionName(void)   //function header{     statements;     return (value);    //value is of type return_type }

Page 20: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

• C++ compilers include built-in functions to make programming easier. 

• The number and type of functions available to you depends upon the compiler you are using. 

• These functions that come with the compiler are called "built-in" library functions.

Page 21: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

•Library functions are just like the functions that you, as the programmer, create and are used in a similar

manner  .•The only difference is that the source code

(definition) for library functions does NOT appear in your program.

•  The prototype for the library function is provided to your program using the #include compiler directive.The most common library functions.

<ctype.h>  Character classification and conversion<math.h>  Math functions

<stdlib.h>  Data conversion<time.h> Time functions

Page 22: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

•Required header :•# include <ctype.h>•C++ uses the American Standard Code for

Information Interchange (ASCII) character set  .•The CTYPE library includes character

classification functions .• A character is passed to the functions and the

functions return values that can be stored or printed.

Page 23: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

CategoryASCII Characters

Uppercase letters 'A' through 'Z'

Lowercase letters'a' through 'z'

Digits (0 through 9)'0 'through '9'

WhitespaceSpace, tab, line feed(newline), and carriage return

Punctuation ~}|{_^]\[@?>=<;:/.-,+*()'&%$#"!

Blank spaceThe blank space character

Basic ASCII Categories

Page 24: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

1 .isalnum ( ) returns a TRUE (nonzero) if the argument is digit 0-9, or an alphabetic character (alphnumeric).  Otherwise returns FALSE.

2 .isalpha ( )returns TRUE if the argument is an upper or lower case letter.

3 .isascii( )returns TRUE if the integer argument is in the ASCII range 0-127.  Treats 128-255 as non-ASCII.

4 .isdigit( )returns TRUE if the argument is a digit 0 - 9

5 .isgraph( )returns TRUE if the argument is any printable character from ASCII 32 to 127, except the space.

6 .islower( )returns TRUE if the argument is a lowercase letter.

7 .isupper( )returns TRUE if the argument is an uppercase leter.

8 .ispunct( )returns TRUE if the argument is any punctuation character (see chart above) .

9 .isspace( )returns TRUE if the argument is a whitespace (see chart above).

Page 25: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

toascii) (converts the argument )an arbitrary integer( to a valid ASCII character number 0-127.

c = toascii(500);   //c gets number 116                           // (modulus 500%128)c = toascii('d');    //c gets number 100

tolower) (converts the argument )an uppercase ASCII character( to lowercase.

c = tolower('Q');  // c becomes 'q'

toupper) (converts the argument )a lowercase ASCII character( to uppercase.

c = toupper('q');  //c becomes 'Q'

**Note:  tolower) ( and toupper) ( will actually check to see if the argument is the appropriate uppercase or lowercase before making the conversion.

Page 26: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

• Required headers:  • #include <stdlib.h>

#include <time.h>• Computers can be used to simulate the

generation of random numbers with the use of the rand( ) function. 

• This random generation is referred to as a pseudo-random generation. 

• These created values are not truly "random" because a mathematical formula is used to generate the values.

Page 27: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

•rand( )   returns a random positive integer in the range from 0 to 32,767 .

• This function can be thought of as rolling a die with 32,767 faces .

• The numbers are generated by a mathematical algorithm which when given a starting number (called the "seed"), always generates the same sequence of numbers. 

• Since the same sequence is generated each time the seed remains the same, the rand( ) function generates a pseudo-random sequence.  To prevent the same sequence from being generated each time, use srand(x) to change the seed value

Page 28: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

•srand(x)  used to set the starting value (seed) for generating a sequence of

pseudo-random integer values  .•The srand(x) function sets the seed of

the random number generator algorithm used by the function rand) ( .

• A seed value of 1 is the default setting yielding the same sequence of values as

if srand(x) were not used .• Any other value for the seed produces a

different sequence.

Page 29: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

  In order to produce random integer numbers within a specified range, you

need to manipulate the rand( ) function. 

 The formula is:int number = a + rand( ) % n;

a = the first number in your rangen = the number of terms in your range

(range computed by  largest value - smallest value + 1)

Page 30: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

Sample program:/*generate 10 random numbers between 10 and 55 inclusive,

without repetition of the sequence between program runs*/

#include <iostream.h>#include <stdlib.h>#include <time.h>

int main(void){     // to prevent sequence repetition between runs          srand(time(NULL));  

       for(int i = 1; i <=10; i++)     // looping to print 10 numbers     {           cout<< 10 + rand( ) % 46;   // formula for numbers      }

     return 0;}

Example:

*/random integers between 35 and 42 inclusive/*

int num =35+rand( )% 8;

Page 31: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

Math Functions

FunctionPrototypePurpose

abs)x(int abs)int x(;returns the absolute value of an integer.

fabs)x(double fabs)double x(;returns the absolute value of a floating point number

ceil)x(double ceil)double x(;rounds up to a whole number cout>>ceil(11.2);

      (prints 12))not normal rounding(

floor)x(double floor)double x(;rounds down to a whole numbercout>>floor(11.5);

      (prints 11))not normal rounding(

hypot)a,b(double hypot)double a,          double b(;

calculates the hypotenuse )c( of a right triangle where a and b are the legs.

pow)x,y(double pow)double x,         double y(;

calculates x to the power of y.  If x is negative, y must be an integer.  If x is zero, y must be a

positive integer.

pow10)x(double pow10)int x(;calculates 10 to the power of x.

sqrt)x(double sqrt)double x(;calculates the positive square root of x.)x is >=0(

fmod)x,y(double fmod)double x,         double y(;

returns floating point remainder of x/y with same sign as x.  Y cannot be zero.  Because the

modulus operator)%( works only with integers, this function is used to find the remainder of

floating point number division.

Page 32: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

cos)x(cosine of x

sin)x(sine of x

tan)x(tangent of x

acos)x(arc cosine x

asin)x(arc sine of x

atan)x(arc tangent x

cosh)x(hyperbolic cosine of x

sinh)x(hyperbolic sine of x

tanh)x(hyperbolic tangent of x

exp)x(exponential function

log)x(natural logarithm

log10)x(base 10 logarithm

NOTE:The trigonometric

functions work with angles in

radians rather than degrees.

All of the trigonometric functions take

double arguments and

have double return types.

Page 33: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

•   You can exchange simple if-else code for a single operator – the conditional operator. 

• The conditional operator is the only C++ ternary operator (working on three values).  Other operators you have seen are called binary operators (working on two values).

• FORMAT: conditional Expression ? expression1 : expression2;

Page 34: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

• ** if the conditional Expression is true, expression1 executes, otherwise if the conditional Expression is false, expression 2 executes. If both the true and false expressions assign values to the same variable, you can improve the efficiency by assigning the variable one time:(a>b) ? (c=25) : (c=45); can be written as:c = (a>b) ? 25 : 45;

Page 35: A function is a subprogram that acts on data and often returns a value. You are already familiar with the one function that every C++ program possesses:

if (a>b){       c=25; } else{       c=45; }can be replaced with

(a>b( ? )=25c( : )=45c ;)

The question mark helps the statement read as follows:"Is a greater than b? If so, put 25 in c. Otherwise, put 45 in c."