You are on page 1of 40

Functions Part1

• Introduction
• Function Prototype
• Function call
• Function Definition
• Passing variables to function
• Returning variable from function
• Scope Of variables
• Global variables
• Static variable
1 (C) Copyright 2020 by Dr.Abeer El_korany
Introduction
Modular Programming
• Modular programming:
– breaking a program up into smaller, manageable
functions or modules

• Motivation for modular programming:


– Improves maintainability of programs
– Simplifies the process of writing programs

2 (C) Copyright 2020 by Dr.Abeer El_korany


Introduction
• A function is a block of instructions that is executed
when it is called from some other point of the program

• Each block (piece of program) more manageable than


the original program.

• Using functions we can structure our programs in a more


modular way (smaller pieces or components)

• Software reusability
– Call function multiple times

• Two function types:


• Library Functions
3 • User Defined Functions (C) Copyright 2020 by Dr.Abeer El_ko
Function
• Three things are needed in order to build a function:
• Function Declaration (Prototype)
– Before a function can appear in an invocation its interface
must be specified

• Functions call
• Invoke the function
• Function name and information (arguments) it needs

• Function definition
– Only written once
– Hidden from other functions

4 (C) Copyright 2020 by Dr.Abeer El_ko


Function Example
#include <iostream>
using namespace std;
Function prototype
int addition (int , int );
int main ()
{
int z; Function call
z = addition (5,3);
cout << "The result is " << z <<endl;
return 0;
}
int addition (int a, int b)
{
int r; Function definition
r=a+b;
return (r);
} (C) Copyright 2020 by Dr.Abeer El_korany
5
Function Prototype
• Ways to notify the compiler about a function before
a call to the function:

• Place function definition before calling function’s


definition
• Function prototype contains
– Function name
– Parameters (number and data type)
• Names in prototype optional (Compiler ignores)
– Return type (void if returns nothing)

• Only needed if function definition after function call

• Prototype must match function definition


6 (C) Copyright 2020 by Dr.Abeer El_ko
Function Definition(cont.)

Return type Function name parameter

float CircleArea (float r)


{
Function body const float Pi = 3.1415;
return Pi * r * r;
}
Return statement

7 (C) Copyright 2020 by Dr.Abeer El_ko


Function Definition
return-value-type function-name( parameter-list )
{ declarations and statements;
return;
}
•Definition includes:
–return type: data type of the value that function returns to the part
of the program that called it
–name: name of the function. Function names follow same rules
as variables
–parameter list: variables containing values passed to the function
–body: statements that perform the function’s task, enclosed in {}

8 (C) Copyright 2020 by Dr.Abeer El_ko


Function Definition(cont.)
return-value-type function-name( parameter-list )
{
declarations and statements;
return;
}
– Return-value-type is the type of data returned by the
function (use void if nothing returned)
– Function-name is the name by which it will be possible to
call the function.
– Parameter list
• Comma separated list of arguments
– Data type needed for each argument
• If no arguments, leave blank
– Declarations and statements
• Statement list with curly braces that comprises its actions
9 • Return statement to indicate value of
(C)invocation
Copyright 2020 by Dr.Abeer El_ko
Function call
➢ When called, program executes the body of the called
function

➢ After the function terminates, execution resumes in the


calling function at point of call.

➢ The Flow of control is temporarily transferred to the


invoked function

➢ A function call produces a return value


◼ The return value is the value of the function call
◼y = f(a);

10 (C) Copyright 2020 by Dr.Abeer El_korany


Function call (cont.)
• main can call any number of functions
• Functions can call other functions
• Compiler must know the following about a
function before it is called:
– name
– return type
– number of parameters
– data type of each parameter

11 (C) Copyright 2020 by Dr.Abeer El_ko


Function call (cont.)
➢ A function call specifies
◼ The function name
The name indicates what function is to be called
y = f(a);
◼The actual parameters to be used in the invocation
The values are the information that the called
function requires from the invoking function (main
or others) to do its task

12 (C) Copyright 2020 by Dr.Abeer El_korany


Function Prototype & Definition
Method1
#include <iostream >
void myfunction();
int main()
{
myfunction();
return 0;
}
void myfunction()
{
Here-Is-The-Body-Of-My-Function;
}

13 (C) Copyright 2020 by Dr.Abeer El_korany


Function Prototype & Definition (cont.)

Method2
#include <library>
void myfunction()
{
Here-Is-The-Body-Of-My-Function;
}
void main()
{
myfunction();
}

14 (C) Copyright 2020 by Dr.Abeer El_korany


Function call (1. Invocation Process)
• Flow of control is temporarily transferred to the invoked
function
✓ Correspondence established between actual parameters of the
invocation with the formal parameters of the definition

✓ Next statement executed is the first one in the invoked function

✓ Function body of invoked function is executed

✓ Flow of control then returns to the invocation statement

✓ The return value of the invoked function is used as the value of the
invocation expression

✓ After function completes its action, flow of control is returned to the


invocation statement and the return value is used as value of
invocation

15 (C) Copyright 2020 by Dr.Abeer El_korany


Function call (1. Empty Parameter Lists)
#include <iostream>
Using namespace std;
void starline();
int main()
{
starline();
cout << “Table input Table output” <<endl;
starline();
cout << “Number1 1 2 10” <<endl;
cout << “Number2 3 4 20” <<endl;
cout << “Number3 4 6 30” <<endl;
cout << “Number4 7 8 40” <<endl;
starline();
return 0;
}
void starline()
{
for (int j=0; j<50; j++)
cout<< ‘*’;
cout << endl; (C) Copyright 2020 by Dr.Abeer El_korany
16
Sending Data into a Function
• Can pass values into a function at time of call:
c = pow(a, b);

• Values passed to function are arguments

• Variables in a function that hold the values passed as


arguments are parameters

• Homogeneity should be maintained between number


and types of argument
– void evenOrOdd(int); //prototype
– void evenOrOdd(int num) //header
– evenOrOdd(val); //call

17 (C) Copyright 2020 by Dr.Abeer El_korany


Function Parameter Rules
• Formal parameter is created on function invocation
and it is initialized with the value of the actual
parameter

Changes to formal parameter do not affect actual parameter

New activation record for every function invocation

Formal parameter name is only known within its function

Activation record memory is automatically released at function


completion

Reference to a formal parameter produces the value for it in the current


activation record
18 (C) Copyright 2020 by Dr.Abeer El_korany
Function call (2. Passing parameters to function)
#include <iostream>

void repchar(char, int);


int main()
{
int in;
char ch;
cout << “Enter the character” <<endl;
cin >> ch;
cout <<“Enter number of repeated times”<<endl;
cin >> in;
repchar(ch, in);
return 0;
}
void repchar(char cha, int n)
{
for (int j=0; j<n; j++)
cout<< cha;
cout << endl;
} (C) Copyright 2020 by Dr.Abeer El_korany
19
#include <iostream>
using namespace std;
void showSum(int, int, int); // Function Prototype
int main()
{
int value1, value2, value3;
cout << "Enter three integers and I will display ";
cout << "their sum: ";
cin >> value1 >> value2 >> value3;
showSum(value1, value2, value3);
return 0;
}
//*************** Definition of function showSum. ************************//
void showSum(int num1, int num2, int num3)
{
int total = num1 + num2 + num3;
cout << total<< endl;
} 20 (C) Copyright 2020 by Dr.Abeer El_korany
3. returning value from function

#include <iostream>
using namespace std;
int subtraction (int a, int b)
{
int r;
r=a-b;
return (r);
}
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << "\n ";
cout << "The second result is " << subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The third result is " << z << "\n ";
return 0;
}
21 (C) Copyright 2020 by Dr.Abeer El_korany
#include <iostream>
using namespace std; Void Function
void divide(double, double);
int main()
{
double 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);
return 0;
}
/*************************Definition of function divide*****************/
void divide(double arg1, double arg2)
{ if (arg2 == 0.0)
cout << "Sorry, I cannot divide by zero.\n";
else
cout << "The result is " << (arg1 / arg2) << endl;
}

22 (C) Copyright 2020 by Dr.Abeer El_korany


A Value-Returning Function
Return Type

int sum(int num1, int num2)


{
int result;
result = num1 + num2;
return result;
}
Value Being Returned

23 (C) Copyright 2020 by Dr.Abeer El_korany


#include <iostream> Returning value from
using namespace std; function(cont.)
bool isEven(int);
int main()
{ 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";
return 0;
}
bool isEven (int number)
{ bool status;
if (number % 2 == 0)
status = true;
else status = false;
24 return status; (C) Copyright 2020 by Dr.Abeer El_korany
#include <iostream> Returning value from
#include <cstdlib> function(cont.)
using namespace std;
int Random(int X)
{
int Result;
Result = rand() % X ;
return (Result);
}
int main()
{
int Count, RandNumbers;
cout << "How many numbers? \n";
cin >> Count;
cout << "Enter the maximum number: \n";
cin >> RandNumbers;
cout << "\n";
for( int i = 1; i <= Count; i++ )
cout << Random(RandNumbers) << endl;
cout << "\n\n";
return 0;
} 25 (C) Copyright 2020 by Dr.Abeer El_korany
Example
• Definition
– Input two numbers that represent a range of
integers and display the sum of the integers
that lie in that range
• Design
– Prompt user and read the first number
– Prompt user and read the second number
– Calculate the sum of integers in the range
smaller...larger by adding in turn each integer
in that range
– Display the sum
26 (C) Copyright 2020 by Dr.Abeer El_korany
Range.cpp
#include <iostream.h>
using namespace std;
int PromptAndRead();
int Sum(int, int );
int main() {
int FirstNumber = PromptAndRead();
int SecondNumber = PromptAndRead();
int RangeSum = Sum(FirstNumber , SecondNumber);
cout << "The sum from " << FirstNumber << " to " << SecondNumber
<< " is " << RangeSum << endl;
return 0;
}

27 (C) Copyright 2020 by Dr.Abeer El_korany


Range.cpp
// PromptAndRead(): prompt & extract next integer
int PromptAndRead() {
cout << "Enter number (integer): ";
int Response;
cin >> Response;
return Response;
}

// Sum(): compute sum of integers in a ... b


int Sum(int a, int b) {
int Total = 0;
for (int i = a; i <= b; ++i) {
Total += i;
}
return Total;
}
28 (C) Copyright 2020 by Dr.Abeer El_korany
Scope Of variables
• Scope
• Portion of program where identifier can be used

• File scope
• Defined outside a function, known in all functions
• Global variables, function definitions and prototypes

• Function scope
• Can only be referenced inside defining function.
• Local variables, known only in the function in which
they are defined

• Block scope
• A block is a list of statements within left curly braces{
begins at declaration, ends at right brace }
29 (C) Copyright 2020 by Dr.Abeer El_korany
Local and Global Variables

• Variables defined inside a function are local to that


function. They are hidden from the statements in
other functions, which normally cannot access
them.
• Because the variables defined in a function are
hidden, other functions may have separate, distinct
variables with the same name.

(C) Copyright 2020 by Dr.Abeer El_korany


30
Local Variable Lifetime
• A function’s local variables exist only while the
function is executing. This is known as the lifetime of
a local variable.
• When the function begins, its local variables and its
parameter variables are created in memory, and when
the function ends, the local variables and parameter
variables are destroyed.
• This means that any value stored in a local variable is
lost between calls to the function in which the
variable is declared.

31 (C) Copyright 2020 by Dr.Abeer El_ko


#include <iostream> Scope of the variables
#include <math> 1- Block variable manipulation
using namespace std;
main()
{
int x;
cout<< " Please enter a number ";
cin>>x;
for (int i=0;i<5;i++)
{
int result = pow(x,2) ;
cout<< " i is " << i << " x is " << x << " square
of x is " << result<<endl;
x++;
}
cout <<result; //Error, undefined variable result
return 0;
}

32 (C) Copyright 2020 by Dr.Abeer El_ko


#include <iostream> Scope of variable
using namespace std; 2. Function local variable
void funcB(int b)
{ int y = 100;
cout<<"In funcb b is " << b <<"\n y is "<< y <<endl;
}
void funcA(int a)
{ int x = 1, y = 2;
cout<<"In funcA a is " <<a<<" \n x is " <<x<<"\n y is " <<y;
cout << "\nCalling funcB from funcA\n";
x++;
funcB(x);
}
int main()
{ int y=10;
cout<<"In main y is " << y <<endl;
y++;
funcA(y);
return 0;
}
33 (C) Copyright 2020 by Dr.Abeer El_korany
Global Scope
A global variable can be used by any function in the file that is
defined after the global variable

Global variable, meaning the entire program knows each


variable and has the capability to change any of them.

It is best to avoid programmer-defined global variable


 Exceptions tend to be important constants

34 (C) Copyright 2020 by Dr.Abeer El_ko


#include <iostream>
using namespace std;
void funagain(); // Prototype

int i ; // Global variable because it’s defined outside

int main()
{
float p ; // Local to main() only.

p = 9.0; // Puts value in global variable.

cout << i << ", " << p << " \n "; // Prints global I and local p.

i++;
funagain(); // Calls next function.
cout << i << ", " << p << " \n "; // Prints global I and local p.
return 0;
}
float z = 10.0; // Global variable because it’s defined before a function.
void funagain()
{
int j = 5; // Local to only pr_again().
cout << j << ", " << z; // This can’t print p!.
cout << ", " << i << " \n ";
35 i++; (C) Copyright 2020 by Dr.Abeer El_ko
Static variables
• By default, all local variables are automatic, meaning
that they are erased when their function ends.

• static variable: retains its value when its function ends


in case the function is called a second time.

• All global variables are static

• To declare a variable as static, place the static


keyword in front of the variable when you define it.
static int i = 0;
36 (C) Copyright 2020 by Dr.Abeer El_ko
Static Local Variables

• Local variables only exist while the function is


executing. When the function terminates, the
contents of local variables are lost.

• static local variables retain their contents


between function calls.

• static local variables are defined and initialized


only the first time the function is executed. 0 is
the default initialization value.

37 (C) Copyright 2020 by Dr.Abeer El_ko


Using
#include <iostream>
a Static Variable
using namespace std;
void showStatic(); // Function prototype

int main()
{
for (int count = 0; count < 5; count++)
showStatic();
return 0;
}
void showStatic()
{
static int statNum;
cout << "statNum is " << statNum << endl;
statNum++;
} (C) Copyright 2020 by Dr.Abeer El_korany
38
Static variables (cont.)
#include <iostream>
using namespace std;
void stat();
int main()
{ int i;
for (i=0;i<5; ++i)
stat();
return 0;
}
void stat()
{
int autovar = 0;
static int stvar ;
cout<< \n auto = ”<< autovar << “ static = “<< stvar <<endl;
autovar ++;
stvar++;
(C) Copyright 2020 by Dr.Abeer El_korany
} 39
Using of Static Variable (cont.)
#include <iostream>
using namespace std;
void showStatic(); void shownum();
int main()
{
for (int count = 0; count < 5; count++)
{ showStatic();
shownum();}
return 0;
}
void shownum()
{ int Num =1;
cout << "Num is " << Num << endl;
Num++;
}
void showStatic()
{ static int statNum=1;
cout << "statNum is " << statNum << endl;
statNum++;
} (C) Copyright 2020 by Dr.Abeer El_korany
40

You might also like