0% found this document useful (0 votes)
8 views27 pages

CS503 Lec7

The document discusses void functions in programming, explaining their characteristics, how to define and call them, and the differences between value and reference parameters. It includes examples of function definitions, memory allocation for parameters, and the use of static variables. Additionally, it provides self-study examples and questions to reinforce understanding of the concepts presented.

Uploaded by

id oualid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views27 pages

CS503 Lec7

The document discusses void functions in programming, explaining their characteristics, how to define and call them, and the differences between value and reference parameters. It includes examples of function definitions, memory allocation for parameters, and the use of static variables. Additionally, it provides self-study examples and questions to reinforce understanding of the concepts presented.

Uploaded by

id oualid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Lecture 7

Functions (Cont.)
Void functions (do not have a data type)

- You can place void functions either before or after the function main (like
value-returning functions).
If you put it after the function main, place its prototype before the function main.

- Because void functions do not have a data type, they are not called in an
expression.

A call to a void function is a stand-alone statement.

Thus, to call a void function, use the function name together with the actual
parameters (if any) in a stand-alone statement.
void Function Definition
void is a reserved word.

The formal parameter list may be empty but the empty parentheses are still needed.
Summary
// demonstrates function definition preceding function calls
#include <iostream>
using namespace std; //there’s no function declaration as its definition is written before the main function
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

// starline() //function definition


void starline() {
for (int j = 0; j < 45; j++) cout << '*' ;
cout << endl; }
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

int main() { //the main() follows the definition of the function


starline(); //call to function
cout << "Data type Range" << endl;
starline(); //call to function
cout << "char -128to127 \n" << "int System dependent \n"
<< "long - 2,147,483,648to2,147,483,647 \n";
starline(); //call to function
return 0; }
This approach(removing the declaration)is simpler for short programs but it’s less flexible.
When there are more than a few functions, the programmer must give considerable thought
to arranging the functions so that each one appears before it’s called by any other function.
void functions examples
EX1:
#include <iostream>
using namespace std;
void print(){cout<<"//////////////////////////////////// \n";} //print isn’t a reserved word in C++
int main(){
print();
return 0; }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

EX2:
#include <iostream>
using namespace std;

void print( int n); //prototype


int main() {
print(20);
return 0; }
void print( int n) { for (int i =1; i <= n; i++) cout << "/"<< " " ; }
More about the parameters

They enable functions to manipulate different data each time they are called.

Value parameter: A formal parameter that receives a copy of the content of


the corresponding actual parameter.

Reference parameter: A formal parameter that receives the location


(memory address) of the corresponding actual parameter.

If a formal parameter needs to change the value of an actual


parameter, you must declare this formal parameter as a
reference parameter in the function heading.
Value and Reference Parameters and Memory Allocation
When a function is called, memory for its formal parameters and variables
declared in the body of the function (called local variables) is allocated
in the function data area.

In the case of a value parameter, the value of the actual parameter is copied
into the memory cell of its corresponding formal parameter.

In the case of a reference parameter, the address of the actual parameter


passes to the formal parameter. That is, the content of the formal
parameter is an address. During data manipulation, the content of the
formal parameter directs the computer to manipulate the data of the
memory cell indicated by its content.
Thus, in the case of a reference parameter, both the actual and formal
parameters refer to the same memory location. Consequently, during the
program execution, changes made by the formal parameter permanently
change the value of the actual parameter.
Value Parameters

When a function is called, the value of the actual parameter is copied into
the corresponding formal parameter.

If the formal parameter is a value parameter, then after copying the value
of the actual parameter, there is no connection between the formal
parameter and actual parameter; that is, the formal parameter has its
own copy of the data.
Therefore, during program execution, the formal parameter manipulates
the data stored in its own memory space.

The following program further illustrates how a value parameter works.


//A program illustrates how a value parameter works.
#include <iostream>
using namespace std;
void funcValueParam (int num); //function prototype
int main() {
int number = 6;
funcValueParam (number);
cout <<"After calling the function funcValueParam, number = " << number << endl;
//int a=number +100; cout<<"its value in an expression +100 is "<< a<<endl; //106
return 0; }
void funcValueParam (int num) {
cout<<"In the function funcValueParam, before changing, num = " << num << endl;
num = 15;
cout<< "In the function funcValueParam, after changing, num = " << num <<endl; }
Sample Run:
In the function funcValueParam, before changing, num = 6
In the function funcValueParam, after changing, num = 15
After calling the function funcValueParam, number = 6
Reference parameters
Because a reference parameter receives the address (memory location) of the
actual parameter, reference parameters can pass one or more values from a
function and can change the value of the actual parameter.

Reference parameters are useful in three situations:


• When the value of the actual parameter needs to be changed.
• When you want to return more than one value from a function.
• When passing the address would save memory space and time relative to
copying a large amount of data.

By writing & after the dataType in the formal parameter list of a function,
the variable following that dataType becomes a reference parameter.
//EX1: A program illustrates how a reference parameter works.
#include <iostream>
using namespace std;
void funcRefParam (int& num);
int main() {
int number = 6;
funcRefParam(number);
cout << "After calling the function, funcRefParam, number = " << number << endl;
//int a=number +100; cout<<"its value in an expression +100 is "<<a<<endl; //115
return 0; }
void funcRefParam (int& num) {
cout<<"In the function funcRefParam, before changing, num = " <<num << endl;
num = 15;
cout << "In the function funcRefParam, after changing, num = " << num << endl; }
Sample Run:
In the function funcRefParam, before changing, num = 6
In the function funcRefParam, after changing, num = 15
After calling the function funcRefParam, number = 15
EX2: Program takes a course score and determines its grade. 3 functions: main, getScore, printGrade
#include <iostream>
using namespace std;
void getScore (int& score);
void printGrade (int cScore);
int main(){ int courseScore;
getScore (courseScore);
printGrade (courseScore);
return 0;}
void getScore (int& score) { cout<<"Enter course score: "; cin>>score;
cout << "\n The course score is" << score << endl;}
void printGrade (int cScore) {
cout << "Your grade for the course is ";
if (cScore >= 90) cout << "A." << endl;
else if (cScore >= 80) cout << "B." << endl;
else if (cScore >= 70) cout << "C." << endl;
else if (cScore >= 60) cout << "D." << endl;
else cout << "F." << endl; }
EX2 (Cont.)
The formal parameter score of the function getScore is a reference parameter, the
address (that is, the memory location of the variable courseScore) passes to
score. Thus, both score and courseScore refer to the same memory location
(which is courseScore)

Any changes made to score immediately change the value of courseScore.


Control is then transferred to the function getScore printing the second line of
output. This statement prompts the user to enter the course score. Then reads
and stores the value entered by the user (85 in the sample run) in score,
which is actually courseScore (because score is a reference parameter).
Thus, at this point, the value of the variables score and courseScore is 85
Self study example 1:
#include <iostream>
using namespace std;

void funOne (int a, int& b, char v);


void funTwo (int& x, int y, char& w);
int main() {
int num1, num2; char ch ;
num1 = 10;
num2 = 15;
ch = 'A';
cout<<"Inside main: num1 = "<<num1<<", num2 = "<<num2<<", and ch = "<<ch<<endl;

funOne(num1, num2, ch);


cout<<"After funOne: num1 = "<<num1<<", num2 = "<<num2<<", and ch = "<<ch<<endl;

funTwo(num2, 25, ch);


cout<<"After funTwo: num1 = "<<num1<<", num2 = "<<num2<<", and ch = "<<ch<<endl;
return 0; }
Self study example 1: (Cont.)
void funOne (int a, int& b, char v) {
int one;
one = a;
a++;
b = b * 2;
v = 'B';
cout<<"Inside funOne: a="<<a<<", b="<<b<<", v="<<v<<", and one="<<one<<endl;}
void funTwo (int& x, int y, char& w) {
x++;
y = y * 2;
w = 'G';
cout<<"Inside funTwo: x = "<<x<<", y = "<<y<<", and w = " <<w<<endl; }
Sample Run:
Inside main: num1 = 10, num2 = 15, and ch = A
Inside funOne: a = 11, b = 30, v = B, and one = 10
After funOne: num1 = 10, num2 = 30, and ch = A
Inside funTwo: x = 31, y = 50, and w = G
After funTwo: num1 = 10, num2 = 31, and ch = G
self study example 2: Reference and value parameters

#include <iostream>
using namespace std;
void addFirst (int& first, int& second);
void doubleFirst (int one, int two);
void squareFirst (int& ref, int val);
int main() {
int num = 5;
cout << "Inside main: num = " << num<< endl;
addFirst (num, num);
cout << "Inside main after addFirst:"<< " num = " << num << endl;

doubleFirst (num, num);


cout << "Inside main after "<< "doubleFirst: num = " << num << endl;
squareFirst (num, num);
cout << "Inside main after "<< "squareFirst: num = " << num << endl;
return 0; }
self study example 2: Reference and value parameters (Cont.)
void addFirst (int& first, int& second){
cout << "Inside addFirst: first = "<< first << ", second = " << second << endl;
first = first + 2;
cout << "Inside addFirst: first = "<< first << ", second = " << second << endl;
second = second * 2;
cout << "Inside addFirst: first = "<< first << ", second = " << second << endl; }
void doubleFirst (int one, int two) {
cout << "Inside doubleFirst: one = "<< one << ", two = " << two << endl;
one = one * 2;
cout << "Inside doubleFirst: one = "<< one << ", two = " << two << endl;
two = two + 2;
cout << "Inside doubleFirst: one = "<< one << ", two = " << two << endl; }
void squareFirst (int& ref, int val){
cout << "Inside squareFirst: ref = "<< ref << ", val = " << val << endl;
ref = ref * ref;
cout << "Inside squareFirst: ref = "<< ref << ", val = " << val << endl;
val = val + 2;
cout << "Inside squareFirst: ref = "<< ref << ", val = " << val << endl; }
self study example 2: Reference and value parameters (Cont.)

Inside main: num = 5


Inside addFirst: first = 5, second = 5
Inside addFirst: first = 7, second = 7
Inside addFirst: first = 14, second = 14
Inside main after addFirst: num = 14
Inside doubleFirst: one = 14, two = 14
Inside doubleFirst: one = 28, two = 14
Inside doubleFirst: one = 28, two = 16
Inside main after doubleFirst: num = 14
Inside squareFirst: ref = 14, val = 14
Inside squareFirst: ref = 196, val = 14
Inside squareFirst: ref = 196, val = 16
Inside main after squareFirst: num = 196
Static and Automatic Variables
Memory for the formal parameters and local variables of a function is
allocated when the function is called and de-allocated when
the function exits.

A static variable
A variable for which the memory remains allocated as long as the program
executes.
The syntax for declaring a static variable is:

static is a reserved word.

EX:
static int x; //declares x to be a static variable of type int.
EX:
Sample run:
#include <iostream>
using namespace std;

void test();
int main() {
int count;
for (count = 1; count <= 5; count++) test() ;
return 0; }
void test()
{
static int x = 0;
int y = 10;
x = x + 2;
y = y + 1;
cout << "Inside the function test, x = " << x << " and y = "<< y << endl;
EX (Cont.)

Memory for the variable y is allocated every time the function test is called
and deallocated when the function exits. Thus, every time the function
test is called, it prints the same value for y.

However, because x is a static variable, memory for x remains allocated as


long as the program executes. The variable x is initialized once to 0.

The subsequent ‫التالية‬calls of the function test use the current value of x.
Questions Samples:
1. Consider the following program:
#include <iostream>
using namespace std;
void func1();
void func2();
int main(){ int num;
cout << "Enter 1 or 2: "; cin >> num;
cout << " \n Take ";
if (num == 1) func1();
else if (num == 2) func2();
else cout<<"Invalid input. You must enter1or2 \n"; return 0; }

void func1() { cout << "Programming I." <<endl; }

void func2() { cout << "Programming II." << endl; }


a. What is the output if the input is 1?
b. What is the output if the input is 2?
c. What is the output if the input is 3?
d. What is the output if the input is -1?
Questions Samples:

2. Write the definition of a void function that takes as input a decimal


number and outputs 3 times the value of the decimal number.

3. Write the definition of a void function that takes as input two decimal
numbers. If the first number is nonzero, it outputs second number
divided by the first number; otherwise, it outputs a message
indicating that the second number cannot be divided by the first no.
cause the first number is 0

4. Write the definition of a void function that takes as input two


parameters of type int, say sum and testScore. The function updates
the value of sum by adding the value of testScore. The new value of
sum is reflected in the calling environment.
.
5.What is the output of the following program?
#include <iostream>
using namespace std;
void tryMe (int& v);
int main() {
int x = 8;
for (int count = 1; count < 5; count++)
tryMe(x);
return 0; }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

void tryMe (int& v) {


static int num = 2;
if (v % 2 == 0)
{ num++; v = v + 3; }
else
{ num--; v = v + 5; }
cout << v << ", " << num << endl; }

You might also like