350 likes | 480 Views
Functions. Ideally, your main( ) function should be very short and should consist primarily of function calls. 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).
E N D
Functions Ideally, your main( ) function should be very short and should consist primarily of function calls 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). Built-in functions Build-in functions are part of the compiler package, such asexit(1);
Functions • A function definition consists of two parts: interface and body. • The interfaceof 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.
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
Simple Function int Power (int base, unsigned int exponent) { int result = 1; for (int i = 0; i < exponent; ++i) result *= base; return result; } Function body Note:A function should be declared before its is used
User-defined functionsUser-defined functions are created by you, the programmer. • 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).
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
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.
#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; }
Parameters and Arguments • 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
Parameters and Arguments #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; }
Register Variables • 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 inti = 0; i < n; ++i) sum += i;
Enumerations • 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 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.
Inline Functions 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; }
//Screen display shown at the right//Prototyping, defining and calling a function #include<iostream.h>#include<stdlib.h> void astericks(void); //function prototype int main(void){ system("CLS");cout<<"Heads up, function!\n";astericks( ); //function callcout<<"Again, function!\n";astericks( ); //function callcout<<"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!
Style 2: void functionName(argument(s)) • 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 prototype Acceptable 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.
//Example program//Screen display shown at the right//Passing arguments to a function • #include<iostream.h>#include<stdlib.h> • void greeting(int x); //function prototype • int 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{inti; // 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 HiPlease enter value(1-10):4Hi Hi Hi Hi
Style 3: non-void functionName(void) • 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_typefunctionName(void) //function header{ statements; return (value); //value is of type return_type}
Library Functions • 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.
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
Character Functions Built-in Library Functions for Character Classifications and Conversion • 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.
Random Number Generator • 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.
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
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.
Generating random numbers within a specified range: 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)
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;}
All of the trigonometric functions take double arguments and have double return types.
Conditional Operator • 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;
conditional Expression ? expression1 : expression2; • ** 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;
if (a>b){ c=25; } else{ c=45; } can be replaced with (a>b) ? (c=25) : (c=45); 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."