Functions Suppose we want to print out the

























- Slides: 25
Functions! Suppose we want to print out the word MISSISSIPPI in big letters. * * ** ** * * ***** * * ********* * ********* * *****
We only really need to describe how to create 4 letters -- M, I, S, P We could write a function for each letter! A function in C++ is a named chunk of statements that performs a single well-defined task. • The function’s name is a C++ identifier – Same rules as for variable names – Choose a name that reflects the task performed by the method – Function names typically sound like action verbs or phrases • print. M • Function bodies are placed in the definition of the program, right before the main function. OR • Function prototypes can be declared above the main function and function implementations can go after the main function • Variables and objects declared in a function can only be used within that function!
So now we need 4 functions: print. M print. I print. S print. P void print. M() { cout << “* *n”; cout << “** **n”; cout << “* * *n”; cout << endl; } //print. M
We call or invoke a function simply by stating its name. print. M(); tells the computer to run the function. This causes the following actions to take place: • The computer remembers the line where the call took place • Control is passed to the function (which means that the entire function is executed). • When the function is completed, control is passed back to where the call occurred. • Program execution continues there.
We would also define the other functions. The body of main will look like: void main() { print. M(); print. I(); print. S(); print. I(); print. P(); print. I(); } //main
A C++ program printing the big letter word “Simple” int main () { print. S(); print. I(); print. M(); print. P(); print. L(); print. E(); } //main void print. S() { }\print. S void print. I() {}\print. I void print. M() {}\print. M void print. P() {}\print. P void print. L() {}\print. L void print. E() {}\print. E }
Method Examples Example 1. print 5 -star method void print 5 Stars( ) { int i = 1; while(i <= 5) { cout << ‘*’; i++; } } Example 2. print 10 -star method void print 10 Stars( ) { int i = 1; while(i <= 10) { cout << ‘*’; i++; } }
Method Parameter Example. print N-star method, where N can be ANY integer greater than 1 void print. Stars(int n) { int i = 1; while(i <= n) { cout << ‘*’; i++; } }
Calling with Parameters void main() { print. Stars(5); print. Stars(10); } Tell the method how many stars you want when you call it.
void print. Stars(int n) { int i = 1; while(i <= n) { cout << ‘*’; i++; } } print. Stars(5); // the above method call specifies that n=5. print. Stars(10); // the above method call specifies that n=10. print. Stars(); // the above method call DOES NOT work. Exercise: Write a void method that will print “Simple” with N letters ‘E’ attached to it, where N>0. For example: N=1, print Simplee.
print. Max void print. Max(double x, double y) { if(x > y) cout << x << “ is bigger”; else cout << y << “ is bigger”; } Write the statement that will call the method print. Max to print out the maximum number between 76 and 100.
Most of the time, we want to give function certain values to work with. The values that functions accept are called parameters. In order to use a function with parameters, we must know the name of the function and the features of the parameters. These items describe the interface of the function. – the number, order, and data type of parameters in the parameter list must match the number and order of the values used when calling the function. – the parameters in the function header are called formal parameters – the parameters in the call are called actual parameters or arguments – we do not use the same variable names formal and actual parameters!!!!!!! – The function name and the parameter list together make up the method signature
void print. Echo(string mess, int n) { int i = 1; while(i <= n) { cout << mess << endl; i++; } } In main method: string message = "Hello"; print. Echo(message, 3); Parameters must match. None of these works: print. Echo(); print. Echo(5, “C++”); print. Echo(4. 0, “C++”); print. Echo(3, “abc”, 1);
Information Hiding • Calling or using a function only requires the caller to know the information in the “signature” or first line of a function definition. • The caller or user of a function does not need to know what goes on inside the body of the method. • A function can be viewed as a black box (Can’t see inside it) • What does this suggest about who can use variables declared inside the body of a function?
• A function may return a value. The return. Value. Type is the data type of the value the function returns. If the method does not return a value, the return. Value. Type is the keyword void. For example, the return. Value. Type in the main method is int. • A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the C++ compiler thinks it possible that this method does not return any value. int find. Sign(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return – 1; } To fix this problem, declare a local variable to hold the answer, then return that variable.
Write the function named find. Max, which accepts two integers and returns the larger value of the two integers. int find. Max(int a, int b) { int bigger; if(a >= b) bigger = a; else bigger = b; return bigger; } Write the method named find. Avg, which accepts three integers and returns the average of those three integers.
The Scope of a Variable Think of the entire program as a block. Think of functions as sub-blocks. Each (sub)block can contain a parameter list a declaration section a body (of code) Basically, you can “see” variables/constants in your block, or in any containing or surrounding block. The scope of an identifier refers to the block in which it was declared or defined. Identifiers are available only within their block; they are never available outside their block. Identifiers declared within a function are called local variables.
A local variable: a variable defined inside a function. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used. It is legal to declare a local variable with the same name multiple times in different nonnesting blocks in a function, but you cannot declare a local variable twice in nested blocks.
Example A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable.
It is fine to declare the variable i in two nonnesting blocks. // Fine with no errors public static void correct. Method() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x += i; } //for i // i is declared again for (int i = 1; i < 10; i++) { y += i; } //for i } //correct. Method
It is wrong to declare a variable in two nesting blocks. void bad. Idea() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; } //for i cout << x; } //bad. Idea void bad. Idea() { int i = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; } //for i cout << x; } //bad. Idea
• When an identifier is encountered, its scope determines its value. • We do not use the same variable names formal and actual parameters. • We can use the same variable names as the formal parameters of different methods. int max(int a, int b, int c). . . int min(int a, int b, int c). . . float avg(int a, int b, int c). . . high = max(num 1, num 2, num 3); low = min(num 1, num 2, num 3);
Chapter 5 Skip 5. 3. 1 (for now) Skip 5. 6 (for now) Skip 5. 9 -5. 11 Review Exercises 5. 1 -5. 2 5. 6 -5. 11 5. 15
The factorial of a positive integer n is defined as n! = n * (n - 1) * (n - 2) *. . . * 2 * 1 for n > 1. Write the function. int factorial(int n) { int ans=1; for (int i = n; i > 1; i--) ans = ans * i; return ans; } Suppose that n>=0. int factorial(int n) { int ans = 1; if (n > 1) for (int i=n; i>1; i--) ans*=i; return ans; }
Write a function called Arithmetic that accepts 3 parameters (2 integers and one character, which will be either ‘+’, ‘-’, ‘*’, or ‘/’). It returns the result of applying the operator to the two integers. double operate. Two. Num(int n 1, int n 2, char operator) { double ans = 1; switch (operator) { case '+': ans = n 1 + n 2; break; case '-': ans = n 1 - n 2; break; case '*': ans = n 1 * n 2; break; case '/': ans = (double) n 1 / n 2; } return ans; }