0% found this document useful (0 votes)
6 views

Lec Functions and Pointers

The document provides an overview of functions in C++, covering their definitions, declarations, and calling methods, including call by value and call by pointer. It also discusses random number generation and recursion, explaining how recursive functions work with examples such as calculating factorials and summing numbers. Additionally, the document introduces pointers, their declaration, initialization, and arithmetic, as well as their relationship with arrays.

Uploaded by

ahmedbedawy65
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)
6 views

Lec Functions and Pointers

The document provides an overview of functions in C++, covering their definitions, declarations, and calling methods, including call by value and call by pointer. It also discusses random number generation and recursion, explaining how recursive functions work with examples such as calculating factorials and summing numbers. Additionally, the document introduces pointers, their declaration, initialization, and arithmetic, as well as their relationship with arrays.

Uploaded by

ahmedbedawy65
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/ 47

1

Functions

Dr. Hadeer A. Hosny


2 Points to be covered:
 Function definition
 Function declaration
 Calling function
 Random Number generator
 Recursive function
Function definition
3  A function in C++ works like a mathematical function.
 Experience has shown that the best way to develop and
maintain large programs is to construct it from smaller
pieces(Modules)
 This technique Called “Divide and Conquer”
Function definition
4  Boss To Worker Analogy
 A Boss (the calling/caller function) asks a worker (the
called function) to perform a task and return result when it
is done.
5 Function definition
Function definition
6  The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}
 A C++ function definition consists of a function header and a function
body. Here are all the parts of a function:
 Return Type − A function may return a value. The return_type is the
data type of the value the function returns. Some functions perform the
desired operations without returning a value. In this case, the
return_type is the keyword void.
 Function Name − This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
 Parameters − The parameter list refers to the type, order, and number
of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
 Function Body − The function body contains a collection of statements
that define what the function does.
 Functions cannot be defined inside other functions.
Function declaration (prototype)
7  A function declaration tells the compiler about a function
name and how to call the function. The actual body of
the function can be defined separately.
 A function declaration has the following parts −
return_type function_name( parameter list );
 For the function max(), following is the function
declaration
int max(int num1, int num2);
 Parameter names are not important in function
declaration only their type is required, so following is also
valid declaration
int max(int, int);
 Function declaration is required when you define a
function in one source file and you call that function in
another file. In such case, you should declare the function
at the top of the file calling the function.
Function declaration
8
Calling function
9 There are two types to call function:

 1) Call by value.
The call by value method of passing arguments to a function copies
the actual value of an argument into the formal parameter of the
function. In this case, changes made to the parameter inside the
function have no effect on the argument.

 2) Call by pointer (reference).


The call by pointer method of passing arguments to a function
copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the passed argument.
Example on call by value
10
#include <iostream>
using namespace std;

// function declaration
void swap(int x, int y);

int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

// calling a function to swap the values.


swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}
// function definition to swap the values.
void swap(int x, int y) {
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */
}
Remarks on function
11  Local variables
 Known only in the function in which they are defined
 All variables declared inside a function are local variables
 Parameters
 Local variables passed to function when called (passing-
parameters)
 Global variables
 Variables defined outside and before function main.
 Can be accessible and used anywhere in the entire program

 If a Global variable defined again as a local variable in a


function, then the Local-definition overrides the Global defining
 Function declaration, function definition, and function call must
be consistent in:
1-Number of arguments
2-Type of those arguments
3-Order of those arguments
Random function generator
12
 rand function generates an integer between 0 and RAND-
MAX(~32767) a symbolic constant defined in <stdlib.h>
 You may use modulus operator (%) to generate numbers within a
specifically range with rand.
 //generate 10 random numbers open-range
int x;
for( int i=0; i<=10; i++){
x=rand();
cout<<x<<“ “;
}

 //generate 10 integers between 0……..49


int x;
for( int i=0; i<10; i++){
x=rand()%50;
cout<<x<<“ “;
}
Random function generator
13
 //generate 10 integers between 5…15
int x;
for ( int i=1; i<=10; i++){
x= rand()%11 + 5;
cout<<x<<“ “;
}

 //generate 100 number as simulation of rolling a dice


int x;
for (int i=1; i<=100; i++){
x= rand%6 + 1;
cout<<x<<“ “;
}

 The rand( ) function will generate the same set of random numbers each
time you run the program .
 To force NEW set of random numbers with each new run use the
randomizing process.
 Randomizing is accomplished with the standard library function
srand(unsigned integer);which needs a header file <stdlib.h>
Example on Random function
14 generator num entered
by user

#include<iostream >
#include<stdlib.h>
using namespace std;
int main()
{
int i;
int num ;
// we will enter a different number each time run
cin >> num;
srand (num);
for( i=1; i<=5; i++)
cout << 1+rand()%6;
return 0;
}
Recursive (Recursion function)
15
 Recursion and Recursive Functions
 The main() can call another function…..normal
 A function calls another function2….normal
 A function calls itself ?! Possible?? YES
 A recursive function is one that call itself.
16 Recursive (Ex. factorial)

#include<iostream >
using namespace std;
int factorial( int n );
void main()
{ int n;
cout<<"\nEnter the Value of n \n";
cin>>n;
cout<<"\nFactorial => "<<factorial (n);
}

int factorial( int n )


{ int fact =1, i;
for(i=n ; i>=1 ; i--)
fact = fact *i;
return fact;} int Factorial (int n)
> {
if( n == 0)
return 1;
return n*Factorial (n -1);
}
17
Recursive (Ex. factorial)
18 Recursive (Ex. factorial)
19 Recursive (Ex. factorial)
Recursive (Ex. Adding numbers)
20

 Consider the problem of computing the sum of all the


numbers between 1 and any positive integer N
 This problem can be recursively defined as:
Recursive (Ex. Adding numbers)
21

#include <iostream>
using namespace std;

int sum (int num )


{ Recursive function
int result;
if (num == 1)
result = 1;
else
result = num + sum(num-1) ;
return result; }

int main(){

cout<<sum(3);

return 0;
}
Recursive (Ex. Adding numbers)
22

#include <iostream>
using namespace std;

int sum (int num )


{
int result;
if (num == 1)
result = 1;
else
result = num + sum(num-1) ;
return result; }

int main(){

cout<<sum(3);

return 0;
}
23

Pointers
24 Points to be covered:
 Why pointers?
 What is a pointer?
 Pointer variable initialization and declaration.
 Pointers operators.
 Pointers and arrays.
25
Why pointers?
 Why we need Pointers?

 Pointes enable programs to create dynamic memory,


which can grow at runtime.

 More flexible pass-by-reference.

 Manipulate complex data structures efficiently, even if


their data is scattered in different memory locations.
26
What is a pointer?
 The main difference between normal variables and pointers
is that, variables contain a value, while pointers contain a
memory address.
What is a pointer?
27
 Pointer Variables and Addresses
 Pointer variable: is variable that contains the address of a
variable that has a specific value ( indirect reference).

 Addresses are numbers, written in base-16 (digits 0-9, A-F)


Example : 0010 means 16
0009 means 9
000A means 10
 Pointers provide an alternate way to access memory
locations
Example on pointers
28
 Consider the following which will print the address of the
variables

#include <iostream>
using namespace std;

int main () {
int var1;
char var2[10];

cout << "Address of var1 variable: ";


cout << &var1 << endl;

cout << "Address of var2 variable: ";


cout << &var2 << endl;

return 0;
}
Pointer variable initialization
29 and declaration
 A pointer is a variable whose value is the address of
another variable. Like any variable or constant, you must
declare a pointer before you can work with it. The general
form of a pointer variable declaration is :
type *var-name; or type* var-name; or type*var_name;
(space in definition doesn’t matter)

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

 Pointers initialization
 Initialized to 0, NULL, or an address.
 0 or NULL points to nothing.
Pointer operators
30  & (address operator)
 returns the address of variable stored in memory.
 Example
Pointer operators
31
 * (indirection/dereferencing operator)
 Returns the value of what its operand points
 *yPtr returns value of variable y
(because yPtr points to y).
 * can be used to assign a value location in memory
*yPtr = 7; // changes y to 7
 * and & are inverses
 Cancel each other out
*&myVar == myVar
&*yPtr == yPtr
Pointer variable initialization
32 and declaration
 int x, num = 25; int *ptr ; // declaration of variable x , num ,
and pointer ptr
 ptr = & num ; // ptr holds address and points to
value stored in num
 *ptr = 44; // Store 44 into the memory cell
pointed by ptr
 x = * ptr ; // Store the value pointed by ptr to variable x

 cout<< ptr; // Display the address stored in ptr

 cin >> * ptr; // Store value into the memory cell that
ptr points to
Pointer variable initialization
33 and declaration
 There are important operations, which is done with the pointers
very frequently:

 (a) Define a pointer variable. (Ex: int *ptr;)

 (b) Assign the address of a variable to a pointer. (Ex: ptr=&x;)

 (c) Access the value at the address available in the pointer


variable. (Ex: cout<<*ptr;)
Example on Pointer
34  Following example makes use of these operations

#include <iostream>
using namespace std;

int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}
35
Pointer variable assignment
36
Pointers Arithmetic
Some arithmetic operators can be used with pointers

 Increment and decrement operators ++ , --

 Integers can be added to or subtracted from pointers


using the operators +, -, += , and -=

 One pointer can be subtracted from another by using the


subtraction operator
Example on pointers arithmetic
37  The following program increments the variable pointer to
access each succeeding element of the array

#include <iostream>

using namespace std;


const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have array address in pointer.
ptr = var;
for (int i = 0; i < MAX; i++) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


ptr++;
}
return 0;
}
38
Pointers and arrays
 Pointers and arrays are strongly related.

 A pointer that points to the beginning of an array can


access that array by using either pointer arithmetic or
array-style indexing.

 Also from main uses of pointers with arrays is Dynamic


array.
Example on using pointers with
39 arrays
 It is perfectly acceptable to apply the pointer operator *
to var but it is illegal to modify var value. The reason for
this is that var is a constant that points to the beginning of
an array and can not be used as a value.

#include <iostream>

using namespace std;


const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};

for (int i = 0; i < MAX; i++) {


*var = i; // This is a correct syntax
var++; // This is incorrect.
}

return 0;
}
40
Pointers and arrays
 Array of pointers: there may be a situation, when we want to
maintain an array, which can store pointers to an int or char or
any other data type available. Following is the declaration of
an array of pointers to an integer

 int *ptr[MAX];

 This declares ptr as an array of MAX integer pointers. Thus,


each element in ptr, now holds a pointer to an int value.
Example on using array of
41 pointers
 Following example makes use of three integers which will
be stored in an array of pointers as follows
#include <iostream>

using namespace std;


const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr[MAX];

for (int i = 0; i < MAX; i++) {


ptr[i] = &var[i]; // assign the address of
integer.
}

for (int i = 0; i < MAX; i++) {


cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
}

return 0;
}
Dynamic array (Dynamic
42
memory allocation)

 Why dynamic array


 Array limitations
 Must specify size first
 May not know until program runs!
 Must "estimate" maximum size needed
 Sometimes OK, sometimes not
 "Wastes" memory
 Dynamic arrays
 Can grow and shrink as needed
Dynamic array (Dynamic
43
memory allocation)
 Creating Dynamic Arrays
 Very simple!
 Use new operator
 Dynamically allocate with pointer variable
 Treat like standard arrays

 Example: double *d; d = new double[10]; //Size in


brackets

 Creates dynamically allocated array variable d, with ten


elements, base type double
Dynamic array (Dynamic
44
memory allocation)
 Operator new creates variables
 No identifiers to refer to them
 Just a pointer!
 Example: p1 =new int;
 Creates new "nameless" variable, and assigns p1 to "point to" it
 Can access with *p1
 Use just like ordinary variable
 If new operation fails:
 Program terminates automatically
 Produces error message
Dynamic array (Dynamic
memory allocation)
45
46
Outline of course
 Contents going to be covered during the course:
 Problem Solving
 Flow chart, pseudo code, and Algorithm
 Starting writing first C++ program
 Input and Output
 Conditions
 Loops
 Array
 Function
 Pointers
 String
 Class
47

You might also like