Chapter-1-Overview On Functions, Arrays - Structure
Chapter-1-Overview On Functions, Arrays - Structure
return 0;
}
//Pass by reference
#.....
#.....
void Foo(int & num)
{
num = 0; int main()
cout<< “num = ” << num
{ << “
\n”; int x = 10;
} Foo(x);
cout<< “x = ”<<x<< “\n”;
getch();
return 0;
}
#.......
void order(int &, int &);
int main()
{
Factorial ( 4 )
24
4 * Factorial ( 3 )
6
3 * Factorial ( 2 )
2
2 * Factorial ( 1 )
1 1
• The stack frames for these calls appear sequentially
on the runtime stack, one after the other.
• Stack frame – The section of memory where the
local variables, arguments, return address and
other information of a function are stored, is called
stack frame or activation record.
• A recursive function must have at least one
termination condition which can be satisfied.
• Otherwise, the function will call itself indefinitely
until the runtime stack overflows.
• The three necessary components in a
recursive method are:
– A test to stop or continue the recursion
– An end case that terminates the
recursion
– A recursive call(s) that continues the
recursion
• Try to use a recursive function call to solve the
Fibonacci series. The Fibonacci series is :
– 0,1,1,2,3,5,8,13,21,…
• The recursive definition of the Fibonacci series
is as follows:
– Fibonacci (0) =0
– Fibonacci (1) =1
– Fibonacci (n) =Fibonacci (n-1) +Fibonacci (n-2);
Arrays
What is Array
• A collection of identical data objects, which are stored in consecutive
memory locations under a common heading or a variable name.
Properties of arrays:
• Arrays are zero-bounded; index of the first element is 0 and the last element
is N-1, where N is the size of the array.
Ex array[0], array[1],…array[N-1]
• It is illegal to refer to an element outside of the array bounds.
• Array can only hold values of one type
Array declaration
• Declaring the name, type and setting the number of elements in an array is
called dimensioning the array.
• The array must be declared before one uses.
• In the array declaration one must define:
– type of the array (i.e. integer, floating point, char etc.)
– Name of the array (identifier)
– number of elements in the array (total number of memory locations to
be allocated or the maximum value of each subscript)
Initializing Arrays
• Declaring an array of local scope (within a function) will not
initialize, so its content is undetermined.
• Declaring a global array (outside any function) initialize all
elements to zero.
• Ex. Global array declaration: int day [5];
• every element of day will be set initially to 0:
Accessing and processing array elements
• Any elements of array can be access individually for reading or modifying (like
variable).
• But, to access individual elements, index or subscript must be used.
• The format is the following:
name [ index ] ;
• In c++ the first element has an index of 0 and the last element has an index,
which is one less the size of the array (i.e. arraysize-1).
• Thus, day[0] is the first element and day[4] is the last element.
• Following the previous examples where day had 5 elements, we can use the
following to refer to each element:
Arrays as parameters
• At some moment we may need to pass an array to a function as a
parameter.
• In order to admit arrays as parameters the only thing that we
must do when declaring the function is to specify in the argument
the base type for the array that it contains, an identifier and a
pair of void brackets [] . For example, the following function:
void procedure (int arg[ ])
• admits a parameter of type "Array of int " called arg . In order to
pass to this function an array declared as:
int myarray [40];
• it would be enough with a call like this:
procedure (myarray);
Here you have a complete example:
// arrays as parameters
#include <iostream.h>
#include <conio.h>
void printarray (int arg[], int length)
{
for (int n=0; n<length; n++) void main ()
cout << arg[n] << " "; {
cout << "\n";
int firstarray[] = {5, 10, 15};
}
int secondarray[] = {2, 4, 6, 8, 10};
void mult(int arg[], int length)
{ printarray (firstarray,3);
for (int n=0; n<length; n++) printarray (secondarray,5);
arg[n]=2*arg[n]; mult(firstarray,3);
}
cout<<”first array after being doubled is\n”;
printarray (firstarray,3);
getch()
}
String of Characters: What is String?
• What type of variables used so far???… numerical
variables?? int, float,… char
• What if you need to represent successive
characters, like words, sentences, names, texts, etc.
• Until now we have only used them as constants, but
not variables able to contain them.
• In C++ there is no specific elementary variable type
to store string of characters.
• In order to fulfill this feature we can use arrays of
type char, which are successions of char elements.
• The maximum size of 20 characters is not
required to be always fully used.
• For example, name could store at some
moment in a program either the string of
characters "Hello" or the string "studying C++”.
• Therefore, since the array of characters can
store shorter strings than its total length, there
has been reached a convention to end the valid
content of a string with a null character, whose
constant can be written as '\0’.
•We could represent name (an array of 20 elements of type char) storing the
strings of characters "Hello" and "Studying C++" in the following way:
H e l l 0 \0
S t u d y i n g C + + \0
• It is arrays of arrays.
• Ex. a bi-dimensional array can be imagined as
a bi-dimensional table of a uniform concrete
data type
type multid_array_name[row_size][col_size];
• Matrix represents a bi-dimensional array of 3
per 5 values of type int .
• The way to declare this array would be:
int matrix [3] [5] ;
• Ex. the way to reference the second element
vertically and fourth horizontally would be:
matrix[1][3];
Structures
• A structure is a collection of one or more
variable types grouped together.
• Structure referred using a single name (group
name) and a member name.
struct [structure tag]
{
Member definition;
Member definition;
…
Member definition;
}[one or more structure variables];
//Example 1: //Example 2:
struct Student Struct Inventory{
{ char ID[8]; char description[15];
char FName[15];
char part_no[6];
char LName[15];
int quantity;
char Sex;
float cost;
int age;
}; // all structures end with semicolon
float CGPA;
};
Referencing members of a structure
• To refer to the members of a structure use dot operator (.)
• The General syntax::
VarName.Member;
• Where VarName is the varaibale name of the structure variable and
Member is varaibale name of the members of the structure
Eg:- For the above student structure:
•
struct Student Stud; //declaring Stud Student structure
strcpy(Stud.FName,”Abebe”); //assigned Abebe as First Name
Stud.CGPA=3.21; //assignes 3.21 as CGPA value of Abebe
sout<<Stud.FName; //display the name
sout<<Stud.CGPA; // display the CGPA of Abebe
Initializing Structure Data
• You can initialize members when you declare a structure, or you can
initialize a structure in the body of the program.
• Here is a complete program.
….
struct cd_collection
{
char title[25];
char artist[20];
int num_songs;
float price;
char date_purchased[9];
} cd1 = {"Red Moon","Sams and Sneeds", 12,11.95,"08/13/93"};
cout<<"\nhere is the info about cd1"<<endl;
cout<<cd1.title<<endl;
cout<<cd1.artist<<endl;
cout<<cd1.num_songs<<endl;
cout<<cd1.price<<endl;
cout<<cd1.date_purchased<<endl;
• A better approach to initialize structures is to use
the dot operator(.).
• the dot operator(.) is one way to initialize individual
members of a structure variable in the body of your
program.
• The syntax of the dot operator is :
structureVariableName.memberName;
here is an example:
#include<iostream.h> //initialize members here
.... strcpy(cd1.title,"Red Moon Men");
void main() strcpy(cd1.artist,"Sams");
{ cd1.num_songs= 12;
cd1.price = 11.95;
clrscr();
strcpy(cd1.date_purchased,"22/12/02");
struct cd_collection{ //print the data
char title[25]; cout<<"\nHere is the info"<<endl;
char artist[20]; cout<<"Title : "<<cd1.title<<endl;
int num_songs; cout<<"Artist : "<<cd1.artist<<endl;
cout<<"Songs : "<<cd1.num_songs<<endl;
float price;
cout<<"Price : "<<cd1.price<<endl;
char date_purchased[9]; cout<<"Date purchased :
}cd1; "<<cd1.date_purchased;
getch();
}
Arrays of Structures
• Arrays of structures are good for storing a complete employee file,
inventory file, or any other set of data that fits in the structure format.
• Consider the following structure declaration:
struct Company
{
int employees;
int registers;
double sales;
}store[1000];
int Numbers[20];
int * p;
• the following allocation would be valid:
p = numbers;
• At this point p and numbers are equivalent and they have the same properties, with
the only difference that we could assign another value to the pointer p whereas
numbers will always point to the first of the 20 integer numbers of type int with
which it was defined.
• Therefore, although the previous expression was valid, the following allocation is not:
numbers = p;
• N.B: An array name is just a pointer, nothing
more. The array name always points to the
first element stored in the array.
int ara[5] = {10,20,30,40,50};
cout<< *(ara + 2); //prints ara[2];
• The expression *(ara+2) is not vague at all if
you remember that an array name is just a
pointer that always points to the array’s first
element.
• Consider the following character array:
char name[] = “C++ Programming”;
• cout<<name[0]; // ____C__
• cout<<*name; // _____C__
• cout<<*(name+3); //_________
• cout<<*(name+0); //____C____
Pointer Arithmetic
• Different data type occupy different space.
• For example, in the case of integer numbers,
char occupies 1 byte, short occupies 2 bytes
and long occupies 4.
Pointer Arithmetic
• Different data type occupy different space.
• For example, char occupies 1 byte, short occupies 2 bytes and long
occupies 4.
• Let's suppose that we have 3 pointers:
char *mychar;
short *myshort;
long *mylong;
• And that we know that they point to memory locations 1000 , 2000
and 3000 respectively. So if we write:
mychar++;
myshort++;
mylong++;
• Now let us have a look at a code that shows increments through
an integer array:
void main()
{
int iara[] = {10,20,30,40,50};
int * ip = iara;
cout<<*ip<<endl;
ip++;
cout<<*ip<<endl;
ip++;
cout<<*ip<<endl;
ip++;
cout<<*ip<<endl;
}
Pointer and String
• If you declare a character table with 5 rows
and 20 columns, each row would contain the
same number of characters.
• You can define the table as:
Char names[5][20]={{“George”},{“Mesfin”},{“John”} ,
{“Kim”},{“Barbara”}};
The above statement will create the
following table in memory:
G e o r g e \0
M e s f i n \0
J o h n \0
K i m \0
B a r b a r a \
0
• Here is the definition for such an array:
char *name [5] = {{“George”},{“Mesfin”},
{“John”}, {“Kim”},{“Barbara”}};
• To print the first string, we should use:
cout<<*names; //prints George.
• To print the second use:
cout<< *(names+1); //prints Michael
Pointer to pointer:
• As the memory address where integer, float or character is stored it can
be stored into a pointer variable, the address of a pointer can also be
stored in another pointer. This pointer is said to be pointer to a pointer.
• An array of pointer is conceptually same as pointer to pointer type. The
pointer to pointer type is declared as follows:
Data_type ** pointer_name;
• Note that the asterisk is double here.
int **p; //p is a pointer which holds the address another pointer.
–E.g.:
char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b;
• supposing the randomly chosen memory
locations of 7230 , 8092 and 10502 , could be
described thus:
End!