Chapter5Array and String-And CH 6pointer
Chapter5Array and String-And CH 6pointer
Chapter5Array and String-And CH 6pointer
Department of IT
Fundamental of Programming
Chapter 5
ARRAYS AND STRINGS
Lecture note
IT Dep't Fundamental of
programming
Introduction to Arrays
Consider an organization that need to store the age
of 2000 employees in their DB. For the organization
it would not be feasible to define 2000 variable,
each with a different name. because a variable is
capable to storing only one value at a time.
IT Dep't Fundamental of
programming
Why do we need Array?
• It is the method of implementing all variables of the same
data type by a single name.
• Special way of processing individuals /each of the variable.
What is the benefit or advantage of using Array?
Compare the number of instruction need to handle
individual elements
Performance of a computer is not reduced when
Fetch, decode, and execute phase
Reusability of programs-how much needs to be changed if
the number of data items changed.
IT Dep't Fundamental of
programming
Con’t
• Consider the following that displays an array score of
five elements. int Score[5]
• Score [0] Score [3]
• Score [1] Score [4]
• Score [2]
• In the above statements score is assumed to an array of
five elements. These five elements are distinguished
from one another using the subscripts 0,1,2,3 and 4.
• As a result, the first element score [0], the second
element score [1], the third element score [2], the fourth
element score [3], and the fifth element score [4].
IT Dep't Fundamental of
programming
How to Declare Arrays?
• To declare an array in C++, you should specify the
following things
– The data type of the values which will be stored in the
array
– The name of the array (i.e. a C++ identifier that will be
used to access and update the array values)
– The dimensionality of the array:
• One dimensional (i.e. list of values ),
• Two-dimension array (a matrix or a table), etc.
– The size of each dimension
syntax: type ArrayName[ArraySize];
IT Dep't Fundamental of
programming
Con’t
• Examples
– int x[10]; // An integer array named x with size 10
IT Dep't Fundamental of
programming
Declaring an Array
• An array, named score, containing five
variables of type int can be declared as
int score[ 5 ];
• This is like declaring 5 variables of type int:
score[0], score[1], … , score[4]
• The value in brackets is called
– A subscript or
– An index
IT Dep't Fundamental of
programming
Declaring arrays Con’t…
Arrays are declared like other variables, except that
the identifier is followed by brackets containing a
value specifying the size of the array.
Form/syntx:
type ArrayName[ArraySize];
Type- any data type
ArrayName – any valid identifier
ArrayValue or (ArraySize) – a constant variable,
expression,
or literal
Examples: const int N = 30;
int A[N], B[2*N], C;
The Array Variables
• The variables making up the array are referred to as:
– Indexed variables
– Subscripted variables
– Elements of the array
• The number of indexed variables in an array is the
declared size, or size, of the array
– The largest index is one less than the size
– The first index value is zero
IT Dep't Fundamental of
programming
Array Name Vs Element Name
• In array we have two types of identifiers:
– The name of the array and
– The name of each individual element
• The name of the array- is the name of the whole
structure, while ;
• The name of an element-allows us to refer to that
element.
• Example, score[5]
– where, score-is the name of the array and
– Name of each element is the name followed by the index.
• Example, score[0],score[1] and so on.
IT Dep't Fundamental of
programming
Using [ ] With Arrays
• In an array declaration, [ ]'s enclose the size
of the array such as this array of 5 integers:
int score [5];
• When referring to one of the indexed variables, the [ ]'s
enclose a number identifying one of the indexed
variables
– score[3] is one of the indexed variables
– The value in the [ ]'s can be any expression that
evaluates to one of the integers 0 to (size -1)
IT Dep't Fundamental of
programming
Indexed Variable Assignment
int n = 2;
score[n + 1] = 99;
– In this example, variable score[3] is
assigned 99
IT Dep't Fundamental of
programming
Loops And Arrays
• We can use loops to read and write the elements in an
array.
• We can also use loops to process elements.
• Now it does not matter if there are 100,1000 or 10,000
elements to be processed-loops make it easy to handle
them all.
• We can use an integer variable to control the loop and
remain in the loop as long as the value of this variable
is less than the total number of elements in the array.
IT Dep't Fundamental of
programming
Con’t
• for-loops are commonly used to step through arrays
• Example: for (i = 0; i < 5; i++)
{
cout << score[i] << " off by "
<< (max – score[i]) << endl;
}
could display the difference between each score and
the maximum score stored in an array
IT Dep't Fundamental of
programming
Constants and Arrays
• Use constants to declare the size of an array
– Using a constant allows your code to be easily
altered for use on a smaller or larger set of data
• Example:
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];
…
for (int i = 0; i < NUMBER_OF_STUDENTS; i++)
cout << score[i] << " off by "
<< (max – score[i]) << endl;
• Only the value of the constant must be changed to
make this code work for any number of students
IT Dep't Fundamental of
programming
Computer Memory
IT Dep't Fundamental of
programming
Arrays and Memory
IT Dep't Fundamental of
programming
Con’t
• Note: The array subscript numbering starts at zero.
Thus, the highest subscript for an array of N elements
would be N-1.
• Types of arrays
– You can classify arrays by name, types, and size.
– This is known as dimensioning the array.
Array can be of two types:
– Single/One-dimensional
– Multi-dimensions
IT Dep't Fundamental of
programming
Con’t
A single-dimensional array is an array with
a single row of elements.
IT Dep't Fundamental of
programming
Con’t
• A multi-dimensional array is an array with more than
one-dimension.
For example, a two-dimensional array has multiple rows
and multiple columns of elements.
• The following is a two-dimensional array with three
rows and five columns that store integer values.
Score[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
IT Dep't Fundamental of
programming
• The Subscripts of the two dimensional array
are shown below
IT Dep't Fundamental of
programming
Con’t
IT Dep't Fundamental of
programming
Con’t
• Note: - in a multi-dimensional array, each dimension is
represented by a separates square bracket. The product
of the entire dimension determines the size of such array
syntax.
• <Data_Type><variable_Name>[dimention1_size]
[dimension2_size ];
• Where: dimension1_size and dimension2_size are the
sizes of the two dimensions of the array.
IT Dep't Fundamental of
programming
One-dimensional Arrays
• We use one-dimensional (1Dim) arrays to store
and access list of data values in an easy way by
giving these values a common name,
e.g. int x[4]; // all values are named x
x[2] 20
x[2] = 20; // the 3rd value is 20
x[3] = 30; // the 4th value is 30 x[3] 30
IT Dep't Fundamental of
programming
Declaring one-dimensional Array
• Consider the following statement
• int singarray[10];
• This statement declares a single-dimensional array,
singarray of integer type.
• The number 10 in the square bracket indicates the
size of singarray. There are 10 elements in singarray.
IT Dep't Fundamental of
programming
Con’t
• Every array element is distinguished from every other
element by means of a subscript. The first element of
an array is denoted by the subscript zero, the second
by the subscript 1 and so on. The last element of an
array is denoted by a subscript which is one less than
the size of the array. So the last element of singarray
is singarray [10-1], i.e. singarray [9].
• The 10 elements of singarray can be denoted by
singarray [0], singarray [1], singarray [2], up to
singarray [9].
IT Dep't Fundamental of
programming
Con’t
• The C++ compiler allocates memory to a variable based on
its data types. Similarly, after the declaration of the array,
the compiler allocates memory to every element of that
array based on the array’s data type.
• Therefore, the declaration of singarray causes the
compiler to set aside 20 contiguous bytes of memory to
singarray (assuming that every element, an integer
variable occupies 2 bytes in memory.)
IT Dep't Fundamental of
programming
Con’t
• Following the declaration, every element of
singarray stores a garbage value in its memory
location.
• To store meaningful value in the elements of
singarray, the array can be initialized at a time of
declaration or its elements can be assigned values
later.
IT Dep't Fundamental of
programming
Accessing 1Dim Array Components
• General syntax:
IT Dep't Fundamental of
programming
Array Index Out of Bounds
IT Dep't Fundamental of
programming
Two-dimensional Arrays
• Two-dimensional array: collection of a fixed number
of components (of the same type) arranged in two
dimensions
– Sometimes called matrices or tables
• Declaration syntax:
IT Dep't Fundamental of
programming
Accessing 2D Array Components
• The syntax to access a component of a two-
dimensional array is:
arrayName[index_1][index_2]
where indexexp1 and indexexp2 are
expressions yielding nonnegative integer
values.
• Index_1 specifies the row position and
index_2 specifies the column position
IT Dep't Fundamental of
programming
Accessing 2D Array Components (cont'd.)
IT Dep't Fundamental of
programming
Processing Two-Dimensional Arrays (continued)
IT Dep't Fundamental of
programming
Two-Dimensional Array Initialization
During Declaration
• Two-dimensional arrays can be initialized when they are
declared:
int mark[4][3]={{2,3,1},{15,25,13},{20,4,7},{11,18,14}
– Elements of each row are enclosed within braces and
separated by commas
– All rows are enclosed within braces
– For number arrays, if all components of a row aren’t
specified, unspecified ones are set to 0.
IT Dep't Fundamental of
programming
2D Array cont…
• Two-dimensional arrays are stored in row order
– The first row is stored first, followed by the
second row, followed by the third row and so
on
• When declaring a two-dimensional array as a
formal parameter
– can omit size of first dimension, but not the
second
• Number of columns must be specified
IT Dep't Fundamental of
programming
Initialization
IT Dep't Fundamental of
programming
Print/display
• To output the Elements of matrix:
IT Dep't Fundamental of
programming
Input
• To input data into each component of matrix:
• Exercise 3:
• Write a program that can do matrix addition of two 3x3
matrix.
IT Dep't Fundamental of
programming
Omitting the Array Size
• If one-dimentional array is initialized, the size
can be omitted as it can be found from the
number of initializing elements:
Int []={1,2,3,4};
• This initialization creates an array of four
elements.
• Note how ever:
Int x[][]={{1,2},{3,4}}; // error is not allowed.
• And must be written
Int [2][2]={{1,2},{3,4}};
IT Dep't Fundamental of
programming
Functions and Arrays
Arrays may be passed as arguments of functions, but some
important
notes should be made:
• Function declaration - include the data type and empty
brackets
• Function call – include the array name with no brackets
• Function header – include the data type, name, and empty
brackets
String Representation and Manipulation
IT Dep't Fundamental of
programming
Character Strings cont…
A string containing a single character takes up 2
bytes of storage.
s2:
a
IT Dep't Fundamental of
programming
Reading and Writing Strings
• Most rules that apply to arrays apply to C-
strings as well
• Aggregate operations, such as assignment
and comparison, are not allowed on arrays
• Even the input/output of arrays is done
component-wise
• The one place where C++ allows aggregate
operations on arrays is the input and
output of C-strings (that is, character
arrays) IT Dep't Fundamental of
programming
Input/Output with Strings
• A common problem with reading strings from user input is that it could
contain white spaces.
• cin uses white space (e.g. space, tab, newline) as a delimiter between
inputs;
cin >> fullName;
> getName2.exe
Enter your full name: Groucho Marx
Your name is: Groucho
//Consider the following example
#include<iostream>
using name space std;
int main ( ) {
char name [16];
cout<<”enter your fulname”;
cin>>name; IT Dep't Fundamental of
programming
String Output
• cout << name; outputs the content of name
on the screen
– << continues to write the contents of name
until it finds the null character
– If name does not contain the null character,
then we will see strange/out of the ordinary
output
• << continues to output data from
memory adjacent to name until '\0' is
found
IT Dep't Fundamental of
programming
String Input
#include<iostream>
using namespace std;
int main (){
const int max=80;
char str[max];
cout<<”\n enter a sting:\n”;
cin.get(str,max,’$’); //terminates with $
cout<<”\n you entered \n”<<str;
Return 0;
}
IT Dep't Fundamental of
programming
Avoiding buffer over flow
IT Dep't Fundamental of
programming
//avoids buffer overflow with cin.width
#include<iostream.h>
usingname space std;
#include<iomanip.h> //for setw
int main()
{
const int max=20;
char str[max];
cout<<“\nenter a string:”;
cin>>setw(max)>>str;
cout<<“\n you entered:”<<str; }
IT Dep't Fundamental of
programming
Get( ) and getline( ) functions
• Use the get() and/or getline () functions to read
spaces and multiple lines in a string.
• There are situations when a user may want to store
many words in a variable.
• Consider the following codes:
//Example,Codes to enter the name of the user
#include<iostream>
using name space std
int main ( ) {
char name [16]
cout<<”enter your fulname”;
cin>>name; IT Dep't Fundamental of
programming
continued
• As seen in the output of the code the variable name,
stores only the first word. To overcome this problem
c++ provide the follow two functions.
• get () and
• getline () functions
• These are built-in functions in C++ that accept user
input at run time.
• String .h Header file
• C++ provides the string.h header file, which contains
a number of functions to manipulate strings. This
header file contains the prototypes of the string-
based functions.
IT Dep't Fundamental of
programming
The functions defined in string .h are divided in
to three categories
• str Functions: Function names that begin with str
and operate on strings that terminate with a null
character.
• Strn Functions: Function names that begin with
strn and operate on strings of specified length.
• Mem Function: Function names that begin with
mem and operate on character arrays of
specified length.
IT Dep't Fundamental of
programming
Some examples of str functions that are applied on
strings are
• Strlen( ): Returns the length of the string. The function has
only one argument, a string specified in double quotes or a
string variable. The value returned by the function does not
include the length of the null character.
//exercise on the strlen() function
# include < iostream>
using name space std
void main () {
char name [20]
int len =0;
cout << “enter your name”
cin getline (name, 20)
len= strlen (name) << name << end; IT Dep't Fundamental of
programming
• Strcat: concatenates or append a source string
to a destination string. This function takes two
arguments. The first argument is the
destination string and the second argument is
the source string. The source can be specified
in the double quotes or as a string variable.
• The value returned by the function includes the
null character.
IT Dep't Fundamental of
programming
//Example in the strcat ( ) function
IT Dep't Fundamental of
programming
//Example in the strcpy ( ) function
#include <iostream>
#include<string.h>
using namespace std
int main () {
char name [40];
char copy [40];
cout<<“ enter your name << endl;
cin.getline (name,40) ;
cout<<”name =”<< name <<endl;
strcpy (copy,name);
cout<<”copied name =”<<copy;
}
IT Dep't Fundamental of
programming
• Strcmp ( ): compares the source string with the
destination string. The function takes two arguments,
both of whichc may be strings specified in double
quotes or string variables.
• The function returns the following value based on the
results of the comparisons.
• A negative value: if the length of the first is less them
the second string
• Zero (0): it the strings are exactly the same
• A positive value: if the length of the first string is grate
than the second
IT Dep't Fundamental of
programming
//exercise on strcmp( ) function
# include <iostrem>
#include <string.h>
using name space std
int main ( ) {
char str1[40]
char str2[40]
cout<<’’enter the 1st string”<< end;
cin.getline (str1,40)
cout<< “enter the 2nd string “<< endl;
cin.getline (str2,40);
if (strcmp(str1,str2)==0);
cout<< string are same’1’;
else
cout<<’’string are not same”; IT Dep't Fundamental of
programming
C Library <strings.h> for String Operations
• char *strcpy(char *dst, char *src);
– Copies the string src to string dest
• char *strncpy(char *dst, char *src, int n);
– Copies the first n characters of src to dest
• char * strcat(*dst, char *src);
– Concatenate src to the end of dst.
• char * strcat(*dst, char *src, int n);
– Concatenate first n chars of src to end of dst.
IT Dep't Fundamental of
programming
Continued..
• int strcmp(char *str1, char *str2);
– Returns 0 if str1=str2, negative if str1<str2, positive if
str1>str2
• int strncmp(char *str1, char *str2, int n);
– Same as strcmp except it considers the first n chars of
each string
• int strlen(char *str); // returns the length of str
• char * strchr(char *str, int c);
Note.
– in strcpy, strncpy, strcat, and strncat, make sure that
the dst string has enough space to accommodate the
string copied or cancatenated to it
– If the strings are arrays, also make sure that the array
dst is large enough to accommodate the string
copied or concatenated to it
IT Dep't Fundamental of
programming
C-Strings (Character Arrays) (cont'd.)
IT Dep't Fundamental of
programming
Initialization of Array of string
• The array of string initialized like follow
• Example1. char str[2][7]=(“Sunday”,”Monday)
• Or like the following.
• Example2. char str[2][7]={{‘s’,’u,’n’,’d’,’a’,’y’},
{‘m’,’o’,’n’,’d’,’a’,’y’}}
IT Dep't Fundamental of
programming
Oromia State University
Department of IT
Fundamental of Programming
Chapter 6
Pointers
Lecture note
IT Dep't Fundamental of
programming
Pointers and dynamic objects
Topics
Pointers
Memory addresses
Declaration
Dereferencing a pointer
Reference
Computer Memory
… … a
100 … 1024 …
Variable a’s value, i.e., 100, is
stored at memory location 1024
int a = 100;
IT Dep't Fundamental of
programming
Pointers
• A pointer is a variable used to store the address of a
memory cell.
• We can use the pointer to reference this memory
cell. Is a powerful technique by which we can access
data by indirect reference.
• Pointer is a data type that stores address values.
Memory address: 1020 1024 1032
… … 100 … 1024 …
integer
pointer
IT Dep't Fundamental of
programming
Pointer Types
• Pointer
– C++ has pointer types for each type of object
• Pointers to int objects
• Pointers to char objects
• Pointers to user-defined objects
(e.g., RationalNumber)
– Even pointers to pointers
• Pointers to pointers to int objects
IT Dep't Fundamental of
programming
Why we need pointers?
• Pointers are used to:
– Access array elements
– Passing arguments to functions when the
function needs to modify the original
argument
– Passing arrays and strings to functions
– Obtaining memory from the system
– Creating data structures such as linked lists
IT Dep't Fundamental of
programming
Pointer Variables
• A pointer variable is a variable that holds address
values
• Each data type has its own pointer variable, pointer to
int, pointer to double, pointer to char, …
• C/C++ uses the address-of operator( ”&”) to get the
address of any variable
• C/C++ uses the indirection or contents-of operator(*)
to access the value of the variable pointed by.
int i=17;
int* ptr; // defines a pointer to an integer variable
ptr= &i; // assign the address of x to pointer
cout << *ptr << endl; // prints contentsprogramming
of variable i
IT Dep't Fundamental of
Pointer Variables
int i;
0x1054
17
f
int *ptr;
s so
re
a dd f
nts o
nte
co
ptr=&i;
IT Dep't Fundamental of
programming
Pointer Variables con’t
int v; // defines variable v of type int
int w; // defines variable w of type int
int *p; // defines variable p of type pointer to int
p=&v; // assigns address of v to pointer p
v=3; // assigns value 3 to v
*p=7; // assigns value 7 to v
p=&w; // assigns address of w to pointer p
*p=12; // assigns value 12 to w
• int *p;
• int x;
• P=&x;
• X=5;
• The statement p=&x; assign the address of x
to p.
• The & is a unary operator that returns the
memory address of its operand.
IT Dep't Fundamental of
programming
Declaring pointers
• The declaration of pointers follows this:
• syntax:
Data_type * Variable_name;
IT Dep't Fundamental of
programming
Continued…
• Therefore, although these three example variables
are all of them pointers, they actually have different
types: int*, char*, and double* respectively,
depending on the type they point to.
… … 100 … … …
a
int a = 100;
//get the value,
cout << a; //prints 100
//get the memory address
cout << &a; //prints 1024
IT Dep't Fundamental of
programming
Address Operator &
Memory address: 1020 1024 1032
… 88 100 … … …
a b
#include <iostream>
using namespace std;
Result is:
void main(){
The address of a is: 1020
int a, b; The address of b is: 1024
a = 88;
b = 100;
cout << "The address of a is: " << &a << endl;
cout << "The address of b is: " << &b << endl;
}
IT Dep't Fundamental of
programming
The Address-of Operator
• The address-of operator converts a name into a
pointer.
int i; // location for final value
int *p; // pointer variable
p = & i; // set p to point to i
… 88 100 … 1024 …
a p
int a = 100; Result is:
int *p = &a; 100 1024
cout << a << " " << &a <<endl; 1024 1032
cout << p << " " << &p <<endl;
IT Dep't Fundamental of
programming
Dereferencing Operator *
• We can access to the value stored in the variable pointed
to by using the dereferencing operator (*),
… 88 100 … 1024 …
a p
int a = 100;
int *p = &a; Result is:
cout << a << endl; 100
cout << &a << endl; 1024
cout << p << " " << *p << endl; 1024 100
cout << &p << endl; 1032
IT Dep't Fundamental of
programming
•
Don’t get confused
Declaring a pointer means only that it is a pointer: int *p;
• Don’t be confused with the dereferencing operator, which
is also written with an asterisk (*). They are simply two
different tasks represented with the same sign
int a = 100, b = 88, c = 8;
int *p1 = &a, *p2, *p3 = &c;
p2 = &b; // p2 points to b
p2 = p1; // p2 points to a
b = *p3; //assign c to b
*p2 = *p3; //assign c to a
cout << a << b << c; Result is:
888
IT Dep't Fundamental of
programming
A Pointer Example
Memory Layout
The code
Box diagram
void doubleIt(int x,
main
int * p)
{ p 8192
a 16
*p = 2 * x; (8200)
} doubleIt
int main(int argc, const x 9
char * argv[]) (8196)
{
int a = 16; a 16 main
doubleIt(9, &a); doubleIt (8192)
return 0;
} x 9
a gets 18 p
IT Dep't Fundamental of
programming
Another Pointer Example
#include <iostream> Let’s figure out:
using namespace std; value1==? / value2==?
int main (){ Also, p1=? p2=?
int value1 = 5, value2 = 15;
int *p1, *p2;
p1 = &value1; // p1 = address of value1
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value
// pointed to by p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
}
IT Dep't Fundamental of
programming
Pointers to Simple Values
IT Dep't Fundamental of
programming
Pointers as Function Arguments
void swap( double& x, double& y)
{
double tmp=x;
x=y; // access variable by its alias name
y=tmp; }
void swap( double* ptr1, double* ptr2)
{ double tmp=*ptr1;
*ptr1=*ptr2; // de-referencing pointer
*ptr2=tmp; }
double a=3.0;
double b=5.0
swap(a,b); // call by reference to variables a and b
swap(&a, &b); // call by pointer using the addresses of a and b
IT Dep't Fundamental of
programming
void * Pointers
void * p = dp;
A void * parameter must always be cast before
it can be used.
double * dp2;
dp2 = (double *) p; // convert p back into
pointer to double
IT Dep't Fundamental of
programming
Reference
• A reference is an alias, an alternative way to
name an existing object.
• Difference between reference and pointers
– A reference can never be null; it must
always refer to a legitimate object.
– Once established, a reference can never be
changed to make it point to a different
object.
– A reference does not require any explicit
mechanism to dereference the memory
address and access the actual data value.
– A pointer is a variable that can contain a
reference IT Dep't Fundamental of
programming
References
• A reference is declared by using the
ampersand.
int i = 7;
int & j = i; // j is an alias for i
j++; // i is now 8
i += 3; // i is now 11, as is j
• A reference can be target of an assignment.
Some functions will return a reference as a
result for precisely this reason.
int values[100];
int & index(int i) {
return values[i + 2]; }
index(27) = 12; // changes values[29];
IT Dep't Fundamental of
programming
Chapter Seven
Function
• Modular programming
– Breaking down the design of a program into individual
components (modules) that can be programmed and tested
independently
– A program divided into several smaller parts which can
interact
• Modules [functions]
– Can be written and tested separately
– Testing is easier (smaller)
– Doesn't need to be retested
– Reduces length of program
– Hides details (abstraction)
Functions in C++
Modules in C++ are called functions
Function - a subprogram that can act on data and return a value
Every C++ program has at least one function, main(), where
program execution begins
A C++ program might contain more than one function.
Functions may interact using function call
Functions in C++ come in two varieties:
– user-defined
– built-in
• E.g pow(), sqrt(), cin, etc
Declaration of Functions
Functions must be declared before use
The declaration tells the compiler
– Return type,
– Function name,
– Parameters of the function
… Declaration of Functions
The declaration of a function is called function prototype
Is a statement - it ends with a semicolon
It consists of the function's
– return type,
– name,
– parameter list
• Syntax
– return_type function_name (type [parameterName1], type
[ParameterName2] ... );
• E.g. long Area(int, int);
Or
long Area(int length, int width);
Defining a Function
The definition tells the compiler how the function
works.
Consists of :
– the function header :
• like the function prototype except that the parameters must be named
• there is no terminating semicolon
– its body
• the task of the function
Syntax
return_type function_name(parameter
declarations)
{
declarations;
statements;
}
Defining a Function
E.g.
long Area(int l, int w)
{
return l * w;
}
Calling Function
Syntax :
FunctionName (actual parameter lists);
} // end main
1 4 9 16 25 36 49 64 81 100
#include<iostream.h>
Using namespace std; Example
float RectArea(float,float);
int main()
{
float l,w;
cout<<“Enter the Length of the rectangle"<<endl;
cin>>l;
cout<<“Enter the width of the rectangle"<<endl;
cin>>w;
cout<<"The area is "<<RectArea(l,w);
return 0;
}
float RectArea(float length,float width)
{
float area=length * width;
return area;
}
Scope of identifier
Refers to where in the program an identifier is
accessible
Determines how long it is available to your program
and where it can be accessed
Two kind
– Local identifier - identifiers declared within a function (or
block)
– Global identifier – identifiers declared outside of every
function definition
Local scope
You can declare variables within the body of the
function
– local variables
– When the function returns, the local variables are no longer
available
Variables declared within a block are scoped to that
block – Local to that block
– they can be accessed only within that block and "go out of
existence" when that block ends
– E.g.
for(int i = 0;i<5; i++)
cout<<i;
i=+10; // compilation error i is inaccessible
Global Scope
Call by Value
– Value of the function argument passed to the
formal parameter of the function
– Copy of data passed to function
– Changes to copy do not change original
Call by Reference
– Address of the function argument passed to the
formal parameter of the function