1 / 39

CS102 Introduction to Computer Programming

CS102 Introduction to Computer Programming. Chapter 6 Functions Part I. Chapter 6 Topics. Breaking Up Your Programs Defining and Calling a Function Function Prototypes Sending Information to a Function Changing the value of a parameter Functions and Menus The return Statement

decker
Télécharger la présentation

CS102 Introduction to Computer Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS102Introduction to Computer Programming Chapter 6 Functions Part I

  2. Chapter 6 Topics • Breaking Up Your Programs • Defining and Calling a Function • Function Prototypes • Sending Information to a Function • Changing the value of a parameter • Functions and Menus • The return Statement • Returning a value from a Function • Returning Boolean Values • Local Variables • Global Variables • Local and Global Variables with the Same Name

  3. Breaking Up Your Programs • A function is a collection of statements that performs a specific task • Functions break programs up into small manageable units • Functions simplify programs by letting a set of statements to be used multiple times Concept - Programs may be broken up into smaller manageable functions

  4. Defining a Function • Return Type: specify the type of the data that is to be returned by the function • Name: give functions descriptive names • Parameter list: list the variables that hold the values being sent to the function • Body: statements that perform the function's operations and are enclosed in braces. void main(void) { cout << " Hello world"; } Parameter List Return type Name Body Braces

  5. Calling a Function • Function call syntax function_name(); • A function call may be placed in any flow control structure (if, switch and loops) • A program may have multiple function calls • A function may also call a function. • The compiler must know the number of parameters and their type before the function can be called Concept - A function call is a statement that causes a function to execute.

  6. #include <iostream.h> // Definition of function DisplayMessage. // This function displays a greeting. void DisplayMessage(void) { cout << "Hello from the function DisplayMessage.\n"; } void main(void) { cout << "Hello from main.\n"; DisplayMessage(); cout << "Back in function main again.\n"; } Back in function main again. Program 6-1 4 • Program Output • Hello from main. • . 5 • Hello from the function DisplayMessage. 1 2 3 6

  7. #include <iostream.h> void DisplayMessage(void) { cout << "Hello from the function DisplayMessage.\n"; } void main(void) { cout << "Hello from main.\n"; for (int Count = 0; Count < 5; Count++) // Call DisplayMessage DisplayMessage(); cout << "Back in function main again.\n"; } Program Output Hello from main. Hello from the function DisplayMessage. Hello from the function DisplayMessage. Hello from the function DisplayMessage. Hello from the function DisplayMessage. Hello from the function DisplayMessage. Back in function main again. Program 6-2

  8. // This program has three functions: main, First, and Second. #include <iostream.h> // Definition of function First. // This function displays a message. void First(void) { cout << "I am now inside the function First.\n"; } // Definition of function Second. This function displays a message. void Second(void) { cout << "I am now inside the function Second.\n"; } void main(void) { cout << "I am starting in function main.\n"; First(); // Call function First Second(); // Call function Second cout << "Back in function main again.\n"; } Program 6-3 Program Output I am starting in function main. I am now inside the function First. I am now inside the function Second Back in function main again.

  9. /* This program has three functions: main, Deep, and Deeper*/ #include <iostream.h> // Definition of function Deeper. This function displays a message.*/ void Deeper(void) { cout << "I am now inside the function Deeper.\n"; } /* Definition of function Deep. This function calls the function Deeper.*/ void Deep(void) { cout << "I am now inside the function Deep.\n"; Deeper(); // Call function Deeper cout << "Now I am back in Deep.\n"; } void main(void) { cout << "I am starting in function main.\n"; Deep(); // Call function Deep cout << "Back in function main again.\n"; } Program 6-4 Program Output I am starting in function main. I am now inside the function Deep. I am now inside the function Deeper. Now I am back in Deep.. Back in function main again.

  10. Checkpoint 6.1 Is the following a function or a function call? calcTotal(); 6.2 Is the following a function header or a function call? void showResults();

  11. Function Prototypes • The function prototype is a statement used to communicate to the compiler a functions: • return type • the number of parameters • the parameters data type • Looks similar to the function header except the parameter variables are left out. Return_type function_name (data_type, data_type,..) Concept - A function prototype eliminates the need to place a function definition before all calls to the function

  12. // This program has three functions: main, First, and Second.  #include <iostream.h>  //Function Prototypes void first (void); void second (void); void main(void) { cout << "I am starting in function main.\n"; First(); // Call function First Second(); // Call function Second cout << "Back in function main again.\n"; } /* Definition of function First. This function displays a message.*/ void First(void) { cout << "I am now inside the function First.\n"; } /* Definition of function Second. This function displays a message.*/ void Second(void) { cout << "I am now inside the function Second.\n"; } Program 6-5 Program Output I am starting in function main. I am now inside the function First. I am now inside the function Second.. Back in function main again.

  13. Sending Information to a Function • Values sent into a function are called arguments. • Arguments initialize the parameters (formal arguments) of a function. • Arguments are promoted or demoted automatically to match the data type of the corresponding parameter. Concept - When a function is called, the program may send values into the function

  14.  /* This program demonstrates a function with a parameter*/ #include <iostream.h> void main(void) { cout << "I am passing 5 to DisplayValue.\n"; /* CallDisplayValue with argument 5*/ DisplayValue(5); cout << "Now I am back in main.\n"; } /* Definition of function DisplayValue. It uses an integer parameter whose value is displayed. */ void DisplayValue(int Num) { cout << "The value is " << Num << endl; } Program 6-6 Program Output I am passing 5 to DisplayValue The value is 5 Now I am back in main.

  15. /* This program demonstrates a function with a parameter.*/ #include <iostream.h> //fuction Prototype void DisplayValue(int); void main(void) { cout << "I am passing several values to DisplayValue.\n"; DisplayValue.\n"; DisplayValue(5); DisplayValue(10); DisplayValue(2); DisplayValue(16); cout << "Now I am back in main.\n"; } /* Definition of function DisplayValue. It uses an integer parameter whose value is displayed.*/ void DisplayValue(int Num) { cout << "The value is " << Num << endl; } Program 6-7 Program Output I am passing several values toDisplayValue. The value is 5 The value is 10 The value is 2 The value is 16 Now I am back in main

  16. // This program demonstrates a function with three parameters. #include <iostream.h> //Function Prototype void ShowSum (int, int, int); void main(void) { int Value1, Value2, Value3; cout << "Enter three integers and I will display "; cout << "their sum: "; cin >> Value1 >> Value2 >> Value3; // Call ShowSum with 3 arguments ShowSum(Value1, Value2, Value3); } /* Definition of function ShowSum. It uses three integer parameters. Their sum is displayed.*/ void ShowSum(int Num1, int Num2, int Num3) { cout << (Num1 + Num2 + Num3) << endl; } Program 6-8 Program Output Enter three integers and I will display their sum: 4 8 7 [Enter] 19

  17. Changing the value of a parameter • Parameters are special-purpose variables • declared inside the parentheses of a function • initialized by the arguments from the statement that called the function. • When only a copy of an argument is passed to a function it is said to be passed by value Concept - When an argument is passed into a parameter, it is only a copy of the argument's value that is passed

  18. /* Definition of function ChangeThem. It uses I, an int parameter, and F, a float. */ void ChangeThem(int I, float F) { I = 100; F = 27.5; cout << "In ChangeThem the value of I is changed to "; cout << I << endl; cout << "and the value of F is changed to " << F << endl; } /* This program demonstrates that changes to a function parameter have no effect on the original argument. */ #include <iostream.h> //Function Prototype void ChangeThem(int , float ) void main(void) { int Whole = 12; float Real = 3.5; cout << "In main the value of Whole is " << Whole << endl; cout << "and the value of Real is " << Real << endl; ChangeThem(Whole, Real); cout << "Now back in main again, the value of "; cout << "Whole is " << Whole << endl; cout << "and the value of Real is " << Real << endl; } Program 6-9 Program Output In main the value of Whole is 12 and the value of Real is 3.5 In ChangeThem the value of I is changed to 100 and the value of F is changed to 27.5 Now back in main again, the value of Whole is 12 and the value of Real is 3.5

  19. Using Functions in a Menu Driven Program //Function Prototypes void Adult(int); void Child(int); void Senior(int); void main(void) { do { cout << "Health Club Membership Menu"; cout << "1. Standard Adult Membership"; cout << "2. Child Membership"; cout << "3. Senior Citizen Membership"; cout << "4. Quit the Program"; cout << "Enter Your Choice cin >> choice; if (choice >0 && choice <4) { cout <<"For How Many Months"; cin >> months; } • Switch (choice) • { • case 1 : Adult (months); • break; • case 2 : Child (months); • break; • case 3 : Senior (months); • break; • case 4 : exit(0); • break; • default: cout <<"Enter a number"; • cout <<" between 1 - 4"; • } • while (choice <0 || choice >4) • } Concept - Functions are ideal for use in menu-driven programs

  20. Checkpoint 6.5 Indicate which of the following is the function prototype, the function header, and the function call: void showNum(float num) void showNum(float); showNum(45,67); 6.6 Write a function named ‘timesTen’. The function should have an integer parameter named ‘number’. When ‘timesTen’ is called, it should display the product of ‘number’ times ten. (note: just write the function. Do no write a complete program.) 6.7 Write a function prototype for the ‘timesTen’ function written in 6.6. Function header Function prototype Function call void timesTen(int number) { cout << number * 10; } void timesTen(int);

  21. The return Statement • When the last line of a function is executed, program control is returned to the statement following the function call. • The return statement is used to terminate the execution of a function before all the statements have been executed. return; Concept - The return statement cause the function to end.

  22. /* This program demonstrates a function with a return statement.*/ #include <iostream.h> // Function prototype void Halfway(void); void main(void) { cout << "In main, calling Halfway...\n"; Halfway(); cout << "Now back in main.\n"; } /* Definition of function Halfway. This function has a return statement that forces it to terminate before the last statement is executed.*/ void Halfway(void) { cout << "In Halfway now.\n"; return; cout <<"Will you ever see this message?\n"; } ‘Return’ Example Program Output In main, calling Halfway... In Halfway now. Now back in main.

  23. /* This program uses a function to perform division. If division by zero is detected, the function returns.*/ #include <iostream.h> // Function prototype. void Divide(float, float); void main(void) { float Num1, Num2; cout << "Enter two numbers and I will divide the first\n"; cout << "number by the second number: "; cin >> Num1 >> Num2; Divide(Num1, Num2); } /* Definition of function Divide. Uses two parameters: Arg1 and Arg2. The function divides Arg1 by Arg2 and shows the result. If Arg2 is zero, however, the function returns.*/ void Divide(float Arg1, float Arg2) { if (Arg2 == 0.0) { cout << "Sorry, I cannot divide by zero.\n"; return; } cout << "The quotient is " << (Arg1 / Arg2) << endl; } Program 6-11 Program Output Enter two numbers and I will divide the first number by the second number: 12 0 [Enter] Sorry, I cannot divide by zero

  24. Returning a value from a Function • If a function returns a value it can be used as an expression. • Any function returning a value must contain a return statement. • Example: int square(int); void main(void) { A = square(7); } int square (int num) { return num * num; } Concept - A function may send a value back to the part of the program that called the function.

  25. /* This program uses a function that returns a value.*/ #include <iostream.h> //Function prototype int Square(int); void main(void) { int Value, Result; cout << "Enter a number and I will square it: "; cin >> Value; Result = Square(Value); cout << Value << " squared is " << Result << endl; } /* Definition of function Square.This function accepts an int argument and returns the square of the argument as an int.*/ int Square(int Number) { return Number * Number; } Program 6-12 Program Output Enter a number and I will square it: 20 [Enter] 20 squared is 400

  26. Returning Boolean Values • In C++ a value of 0 represents false and all other values are considered true. • Any C++ statement can use a function call as its relational expression if a 0 or non 0 value is returned by the function. Concept - Functions may return true or false values.

  27. /* This program uses a function that returns true or false. #include <iostream.h> // Function prototype bool IsEven(int); void main(void) { int Val; cout << "Enter an integer and I will tell you "; cout << "if it is even or odd: "; cin >> Val; if (IsEven(Val)) cout << Val << " is even.\n"; else cout << Val << " is odd.\n"; } /* Definition of function IsEven. This function accepts an integer argument and tests it to be even or odd. The function returns true if the argument is even or false if the argument is odd. The return value is bool. */ bool IsEven(int Number) { if (Number % 2) /* The number is odd if there's a remainder.*/ return false; else // Otherwise, the number is even. return true; } Program 6-14 Enter an integer and I will tell you if it is even or odd: 5 [Enter] 5 is odd.

  28. Local Variables • Very similar to block scope • Variables declared inside a function may have names identical to variables declared outside the function. Concept - A local variable is declared inside a function, and is not accessible outside the function.

  29. /* This program shows that variables declared in a function are hidden from other functions.*/ #include <iostream.h> void Func(void); // Function prototype void main(void) { int Num = 1; cout << "In main, Num is " << Num << endl; Func(); cout << "Back in main, Num is still " << Num << endl; } /* Definition of function Func. It has a local variable, Num, whose initial value, 20, is displayed.*/ void Func(void) { int Num = 20; cout << "In Func, Num is " << Num << endl; } Program 6-15 Program Output In main, Num is 1 In Func, Num is 20 Back in main, Num is still 1

  30. Global Variables • Variables that must be accessible to all functions are called a global variables. • Unless initialized in the declaration, global variables are automatically set to zero. Concept - Global variables are declared outside all functions and are accessible to any function within their scope.

  31. /* This program shows that a global variable is visible to all the functions that appear in a program after the variable's declaration. */ #include <iostream.h> // Function prototype void Func(void); int Num = 2; // Global variable void main(void) { cout << "In main, Num is " << Num << endl; Func(); cout << "Back in main, Num is " << Num << endl; } /* Definition of function Func. Func changes the value of the global variable Num. */ void Func(void) { cout << "In Func, Num is " << Num << endl; Num = 50; cout << "But, it is now changed to " << Num << endl; } Program 6-16 Program Output In main, Num is 2 In Func, Num is 2 But, it is now changed to 50 Back in main, Num is 50

  32. /* This program shows that a global variable is visible to all the functions that appear in a program after the variable's declaration. */ #include <iostream.h> // Function prototype void Func(void); void main(void) { cout << "In main, Num is not visible " << endl; Func(); cout << "Back in main, Num is still not visible" << endl; } int Num = 2; // Global variable /* Definition of function Func. Func changes the value of the global variable Num. */ void Func(void) { cout << "In Func, Num is " << Num << endl; Num = 50; cout << "But, it is now changed to " << Num << endl; } Program 6-16 Program Output In main, Num is not vissible In Func, Num is 2 But, it is now changed to 50 Back in main, Num is still not visible

  33. /* This program has an uninitialized global variable.*/ #include <iostream.h> /* Global variable. Automatically set to zero.*/ int GlobalNum; void main(void) { int LocalNum cout << "GlobalNum is " << GlobalNum << endl; cout << " LocalNum is " << LocalNum << endl; } Program Output GlobalNum is 0 LocalNum is ?????? Program 6-17

  34. Local and Global Variables with the Same Name • If a function has a local variable with the same name as a global variable only the local variable can be seen by the function Concept - A local variable may have the same name as a global variable

  35. /* This program shows that when a local variable has the same name as a global variable, the function only sees the local variable.*/ #include <iostream.h> // Function prototypes void Texas(void); void Arkansas(void); int Cows = 10; void main(void) { cout << "There are " << Cows << " cows in main.\n"; Texas(); Arkansas(); cout << "Back in main, there are " << Cows << " cows.\n"; } // The local variable Cows is set to 100. void Texas(void) { int Cows = 100; cout << "There are " << Cows << " cows in Texas.\n"; } // The local variable Cows is set to 50. void Arkansas(void) { int Cows = 50; cout << "There are " << Cows << " cows in Arkansas.\n"; } Program 6-18 Program Output There are 10 cows in main. There are 100 cows in Texas. There are 50 cows in Arkansas. Back in main, there are 10 cows.

  36. /* This program has local and global variables. In the function RingUpSale, there is a local variable named Tax. There is also a global variable with the same name. */ #include <iostream.h> // Function prototype void RingUpSale(void); // Global Variables const float TaxRate = 0.06; float Sale; void main(void) { float Tax, Total; char Again; cout.precision(2); cout.setf(ios::fixed | ios::showpoint); do { RingUpSale(); cout << "Is there another item to be purchased? "; cin >> Again; } while (Again == 'y' || Again == 'Y'); Tax = Sale * TaxRate; Total = Sale + Tax; cout << "The tax for this sale is " << Tax << endl; cout << "The total is " << Total << endl; } Program 6-19

  37. /* Definition of function RingUpSale. This function asks for the quantity and unit price of an item. It then calculates and displays the sales tax and subtotal for those items. */ void RingUpSale(void) { int Qty; float UnitPrice, Tax, ThisSale, SubTotal; cout << "Quantity: "; cin >> Qty; cout << "Unit price: "; cin >> UnitPrice; // Get the total unit price ThisSale = Qty * UnitPrice; // Update global variable Sale Sale += ThisSale; Tax = ThisSale * TaxRate; // Get sales tax for these items SubTotal = ThisSale + Tax; // Get subtotal for these items cout << "Price for these items: " << ThisSale << endl; cout << "Tax for these items: " << Tax << endl; cout << "SubTotal for these items: " << SubTotal << endl; } Program continues

  38. Program Output with Example Input Quantity: 2 [Enter] Unit Price: 20.00 [Enter] Price for these items: 40.00 Tax for these items: 2.40 SubTotal for these items: 42.40 Is there another item to be purchased? y [Enter] Quantity: 3 [Enter] Unit Price: 12.00 [Enter] Price for these items: 36.00 Tax for these items: 2.16 SubTotal for these items: 38.16 Is there another item to be purchased? n [Enter] The tax for this sale is 4.56 The total is 80.56

  39. Be Careful with Global Variables • Makes debugging difficult • Trying to find where a global variable was modified. • One function can change the correctness or accuracy of a variable used by another. • Particularly critical if more than one person is working on the same program • Requires a very disciplined approach Concept - Overuse of global variables can lead to problems as programs become larger and more complex

More Related