CS102 Introduction to Computer Programming Chapter 6 Functions Part I.
-
Upload
tyler-kelly -
Category
Documents
-
view
267 -
download
3
Transcript of CS102 Introduction to Computer Programming Chapter 6 Functions Part I.
CS102Introduction to Computer
ProgrammingChapter 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 • Returning a value from a Function• Returning Boolean Values• Local Variables• Global Variables• Local and Global Variables with the Same Name
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
Concept - Programs may be broken up into smaller manageable functions
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";}
Return type Parameter List
BodyName
Braces
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.
Concept - A function call is a statement that causes a function to execute.
Program 6-1
#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.
632
1
5
4
Hello from the function DisplayMessage.
Program Output Hello from main..
Program 6-2#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 DisplayMessageDisplayMessage();
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-3// 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 FirstSecond(); // Call function Secondcout << "Back in function main again.\n";
}
Program Output I am starting in function main.
I am now inside the function First.I am now inside the function SecondBack in function main again.
Program 6-4/* 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 Deepercout << "Now I am back in Deep.\n";
}
void main(void){
cout << "I am starting in function main.\n";Deep(); // Call function Deepcout << "Back in function main again.\n";
}
Program Output I am starting in function main.
Back in function main again.
Now I am back in Deep..
I am now inside the function Deeper.
I am now inside the function Deep.
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();
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
Concept - A function prototype eliminates the need to place a function definition before all calls to the function
Program 6-5// This program has three functions: main,
First, and Second. #include <iostream.h> //Function Prototypesvoid first (void);void second (void);void main(void){
cout << "I am starting in function main.\n";First(); // Call function FirstSecond(); // Call function Secondcout << "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 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.
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
Concept - When a function is called, the program may send values into the function
Program 6-6 /* This program demonstrates a function
with a parameter*/#include <iostream.h> void main(void){
cout << "I am passing 5 to DisplayValue.\n";
/* Call DisplayValue 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;}
The value is 5Now I am back in main.
Program Output
I am passing 5 to DisplayValue
Program 6-7
/* This program demonstrates a function with a parameter.*/
#include <iostream.h>//fuction Prototypevoid 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 Output I am passing several values toDisplayValue.The value is 5The value is 10The value is 2The value is 16Now I am back in main
Program 6-8// This program demonstrates a function
with three parameters. #include <iostream.h>//Function Prototypevoid 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 Output Enter three integers and I will display their sum: 4 8 7 [Enter]19
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
Concept - When an argument is passed into a parameter, it is only a copy of the argument's value that is passed
Program 6-9/* 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 Prototypevoid 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 Output In main the value of Whole is 12 and the value of Real is 3.5In ChangeThem the value of I is changed to 100 and the value of F is changed to 27.5Now back in main again, the value of Whole is 12 and the value of Real is 3.5
Using Functions in a Menu Driven Program
Concept - Functions are ideal for use in menu-driven programsConcept - Functions are ideal for use in menu-driven programs
//Function Prototypesvoid 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 Choicecin >> 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)}
Checkpoint6.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 headerFunction prototype
Function call
void timesTen(int number){
cout << number * 10;}
void timesTen(int);
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.Concept - The return statement cause the function to end.
‘Return’ Example/* This program demonstrates a function with a return statement.*/#include <iostream.h>// Function prototypevoid 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";
}
Program Output In main, calling Halfway...In Halfway now.Now back in main.
Program 6-11/* 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 Output Enter two numbers and I will divide the firstnumber by the second number: 12 0 [Enter]Sorry, I cannot divide by zero
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:
Concept - A function may send a value back to the part of the program that called the function.
Concept - A function may send a value back to the part of the program that called the function.
int square(int);
void main(void){A = square(7);}
int square (int num){return num * num;}
Program 6-12/* This program uses a function that
returns a value.*/#include <iostream.h>//Function prototypeint 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 Output Enter a number and I will square it: 20 [Enter]20 squared is 400
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.Concept - Functions may return true or false values.
Program 6-14/* This program uses a function that returns true
or false. #include <iostream.h>// Function prototypebool 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; }
Enter an integer and I will tell you if it is even or odd: 5 [Enter]5 is odd.
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.
Concept - A local variable is declared inside a function, and is not accessible outside the function.
Program 6-15/* This program shows that variables
declared in a function are hidden from other functions.*/
#include <iostream.h>void Func(void); // Function prototypevoid 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 Output In main, Num is 1In Func, Num is 20Back in main, Num is still 1
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.
Concept - Global variables are declared outside all functions and are accessible to any function within their scope.
Program 6-16/* 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 prototypevoid Func(void);int Num = 2; // Global variablevoid 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 Output In main, Num is 2In Func, Num is 2But, it is now changed to 50Back in main, Num is 50
Program 6-16/* 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 prototypevoid Func(void);void main(void){
cout << "In main, Num is not visible " << endl;
Func();cout << "Back in main, Numis 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 Output In main, Num is not vissible In Func, Num is 2But, it is now changed to 50Back in main, Num is still not visible
Program 6-17
/* This program has an uninitialized global variable.*/
#include <iostream.h> /* Global variable. Automatically set
to zero.*/int GlobalNum; void main(void){
int LocalNumcout << "GlobalNum is " << GlobalNum << endl;cout << " LocalNum is " << LocalNum << endl;
}
Program Output GlobalNum is 0LocalNum is ??????
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
Concept - A local variable may have the same name as a global variable
Program 6-18/* 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 prototypesvoid 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 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.
Program 6-19/* 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 Variablesconst 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 continues
/* 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 priceThisSale = Qty * UnitPrice;
// Update global variable SaleSale += ThisSale; Tax = ThisSale * TaxRate; // Get sales tax for these itemsSubTotal = ThisSale + Tax; // Get subtotal for these itemscout << "Price for these items: " << ThisSale << endl;cout << "Tax for these items: " << Tax << endl;cout << "SubTotal for these items: " << SubTotal << endl;
}
Program Output with Example Input
Quantity: 2 [Enter]Unit Price: 20.00 [Enter]Price for these items: 40.00Tax for these items: 2.40SubTotal for these items: 42.40Is there another item to be purchased? y [Enter]Quantity: 3 [Enter]Unit Price: 12.00 [Enter]Price for these items: 36.00Tax for these items: 2.16SubTotal for these items: 38.16Is there another item to be purchased? n [Enter]The tax for this sale is 4.56The total is 80.56
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
Concept - Overuse of global variables can lead to problems as programs become larger and more complex