Presentation is loading. Please wait.

Presentation is loading. Please wait.

Suppose we want to print out the word MISSISSIPPI in big letters.

Similar presentations


Presentation on theme: "Suppose we want to print out the word MISSISSIPPI in big letters."— Presentation transcript:

1 Suppose we want to print out the word MISSISSIPPI in big letters.
Functions! Suppose we want to print out the word MISSISSIPPI in big letters. * * ** ** * * * * * * * * * * * ********* *

2 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 printM 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!

3 So now we need 4 functions:
printM printI printS printP void printM() { cout << “* *\n”; cout << “** **\n”; cout << “* * * *\n”; cout << “* * * *\n”; cout << “* * *\n”; cout << endl; } //printM

4 We call or invoke a function simply by stating its name.
printM(); 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.

5 We would also define the other functions.
The body of main will look like: void main() { printM(); printI(); printS(); printP(); } //main

6 A C++ program printing the big letter word “Simple”
int main () { printS(); printI(); printM(); printP(); printL(); printE(); } //main void printS() { }\\printS void printI() {}\\printI void printM() {}\\printM void printP() {}\\printP void printL() {}\\printL void printE() {}\\printE }

7 Method Examples Example 1. print 5-star method void print5Stars( ) {
int i = 1; while(i <= 5) cout << ‘*’; i++; } Example 2. print 10-star method void print10Stars( ) while(i <= 10)

8 Method Parameter Example. print N-star method, where N can be ANY integer greater than 1 void printStars(int n) { int i = 1; while(i <= n) cout << ‘*’; i++; }

9 Calling with Parameters
void main() { printStars(5); printStars(10); } Tell the method how many stars you want when you call it.

10 void printStars(int n)
{ int i = 1; while(i <= n) cout << ‘*’; i++; } printStars(5); // the above method call specifies that n=5. printStars(10); // the above method call specifies that n=10. printStars(); // 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.

11 printMax void printMax(double x, double y) { if(x > y) cout << x << “ is bigger”; else cout << y << “ is bigger”; } Write the statement that will call the method printMax to print out the maximum number between 76 and 100.

12 Most of the time, we want to give function certain values to work with
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 for formal and actual parameters!!!!!!! The function name and the parameter list together make up the method signature

13 void printEcho(string mess, int n)
{ int i = 1; while(i <= n) cout << mess << endl; i++; } In main method: string message = "Hello"; printEcho(message, 3); Parameters must match. None of these works: printEcho(); printEcho(5, “C++”); printEcho(“C++”); printEcho(4.0, “C++”); printEcho(3, “abc”, 1);

14 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?

15 A return statement is required for a nonvoid method.
A function may return a value. The returnValueType is the data type of the value the function returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType 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 findSign(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.

16 Write the function named findMax, which accepts two integers and returns the larger value of the two integers. int findMax(int a, int b) { int bigger; if(a >= b) bigger = a; else bigger = b; return bigger; } Write the method named findAvg, which accepts three integers and returns the average of those three integers.

17 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.

18 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 non-nesting blocks in a function, but you cannot declare a local variable twice in nested blocks.

19 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.

20 It is fine to declare the variable i in two non-nesting blocks.
// Fine with no errors public static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) x += i; } //for i // i is declared again y += i; } //correctMethod

21 It is wrong to declare a variable in two nesting blocks.
void badIdea() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) int x = 0; x += i; } //for i cout << x; } //badIdea int i = 1;

22 When an identifier is encountered, its scope determines its value.
We do not use the same variable names for 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(num1, num2, num3); low = min(num1, num2, num3);

23 Chapter 5 Skip (for now) Skip 5.6 (for now) Skip Review Exercises

24 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 ans = 1; if (n > 1) for (int i=n; i>1; i--) ans*=i;

25 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 operateTwoNum(int n1, int n2, char operator) { double ans = 1; switch (operator) case '+': ans = n1 + n2; break; case '-': ans = n1 - n2; case '*': ans = n1 * n2; case '/': ans = (double) n1 / n2; } return ans;


Download ppt "Suppose we want to print out the word MISSISSIPPI in big letters."

Similar presentations


Ads by Google