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

C++ Session 6

Intro to C++ for beginners 3

Uploaded by

CHRISTIAN ABEBI
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

C++ Session 6

Intro to C++ for beginners 3

Uploaded by

CHRISTIAN ABEBI
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Array

Dynamic Arrays will not be considered


here, we will do that later when we are
done with pointers and have time.
Arrays
• An array is a series of elements of the same
type placed in contiguous memory locations
that can be individually referenced by adding
an index to a unique identifier.
• For example, an array containing 5 integer
values called foo could be represented as:
• where each blank panel represents an element of
the array. In this case, these are values of type int.
These elements are numbered from 0 to 4, 0
being the first and 4 the last;
• In C++, the first element in an array is always
numbered with a zero (not a one), no matter its
length.
• Like a regular variable, an array must be declared
before it is used. A typical declaration for an array
in C++ is:

type name [elements];


Arrays Cont
• Where type is a valid type (such as int, float..),
• Name is a valid identifier and
• The elements field (which is always enclosed in
square brackets []), specifies the length of the
array in terms of the number of elements.

Therefore, the foo array, with five elements of


type int, can be declared as:
int foo [5];
Arrays Cont
• NOTE: The elements field within square
brackets [], representing the number of
elements in the array, must be a constant
expression, since arrays are blocks of static
memory whose size must be determined at
compile time, before the program runs.
Initializing Arrays
• By default, regular arrays of local scope are left
uninitialized. This means that none of its elements are set
to any particular value;
• Their contents are undetermined at the point the array is
declared.

But the elements in an array can be explicitly initialized to


specific values when it is declared, by enclosing those
initial values in curly braces {}. For example:
• Int foo[5] = {16, 2, 77, 40, 12071};
• Or
• Int foo[5]; foo[2] =77;
• foo[0] = 16; foo[3] = 40;
• foo[1] = 2; foo[4] = 12071;
• This statement declares an array that can be
represented like this:
• The number of values between braces {} shall
not be greater than the number of elements
in the array.
• For example, in the example above, foo was
declared having 5 elements (as specified by
the number enclosed in square brackets, []),
and the curly braces {} contained exactly 5
values, one for each element.
• If declared with less, the remaining elements
are set to their default values (which for
fundamental types, means they are filled with
zeroes).
• For example
int bar [5] = {10, 20, 30}; //less than 5

will create an array like this


• The initializer can even have no values, just
the braces:
• Int baz [5] = {};
• This creates an array of five int values, each
initialized with a value of zero:
Example Cont.
#include <iostream> dwene 1 is 0
using namespace std; dwene 2 is 0
int main() dwene 3 is 0
{ dwene 4 is 0
int dwene[5] {}; dwene 5 is 0
for (int i =1; i<6; i++) Why?
cout << "dwene "<<i<<" is "
<<dwene[i-1] << endl;
return 0;
}
• When initialization of values is provided for an
array, C++ allows the possibility of leaving the
square brackets empty [].
• In this case, the compiler will assume
automatically a size for the array that
matches the number of values included
between the braces {}:
int foo[ ] = {16,2,77,40,12071};
• After this declaration, array foo would be 5 int
long, since we have provided 5 initialization
values.
• There is no need for the equal sign between
the declaration and the initializer. The
statements below are equivalent:
int foo[] = {16,2,77,40,12071};
int foo[] {16,2,77,40,12071};
Accessing the values of an array
• The values of any of the elements in an array can
be accessed just like the value of a regular variable
of the same type. The syntax is:

• For example, the following statement stores the


value 75 in the third element of foo:
• Foo[2] = 75;
• For example, the following copies the value of the
third element of foo to a variable called x:
• X = foo[2];
• Therefore, the expression foo[2] is itself a variable
of type int.
• Notice that the third element of foo is specified
foo[2], since the first one is foo[0], the second
one is foo[1], and therefore, the third one is
foo[2].
• By this same reason, its last element is foo[4].
Therefore, if we write foo[5], we would be
accessing the sixth element of foo, and therefore
actually exceeding the size of the array.
• The main difference is that the declaration is
preceded by the type of the elements, while
the access is not.

Some other valid operations with arrays:


Example
// arrays example
#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int n, result=0; 12206
int main ()
{ for ( n=0 ; n<5 ; ++n )
{
result += foo[n];
}
cout << result;
return 0;
}
#include <iostream> #include <iostream>
using namespace std;
using namespace std; int main()
{ const int test = 3;
int main() int score[test] = {5,8,9};
{ for (int i=0;i<test;++i)
char name [] = "jeff"; { cout <<score[i]<< ‘ ‘ ;
for (int n = 0; n<4; n++) }
cout<<name[n]; return 0;
} }

jeff 589
Multidimensional Arrays

• Multidimensional arrays can be described as


"arrays of arrays". For example, a bi-dimensional
array can be imagined as a two-dimensional table
made of elements, all of them of a same uniform
data type.
Multidimensional Arrays Cont.
• jimmy is a bi-dimensional array of 3 by 5
elements of type int. The C++ syntax for this is:
int jimmy[3][5];
The way to reference the second element
horizontally and fourth vertically in an
expression would be:
Jimmy [1][3];
remember that array indices always begin with
zero
Multidimensional Array Cont.
• Multidimensional arrays are not limited to two
indices (i.e., two dimensions).
• They can contain as many indices as needed.
Although be careful.
• The amount of memory needed for an array
increases exponentially with each dimension.
For example
• char mangoes [20][5][7][6][9];
#include <iostream> for (int i=0;i<test;++i)
using namespace std; {
for(int j = 0; j<able; ++j)
int main()
cout <<score[i][j]<< ‘ ';
{
cout<<endl;
const int test = 2;
const int able = 3; }
return 0;
string score[test][able] = }
{{"Abraham","Isaac","Book"},
{"john","thoma","Brown"}};

Abraham Isaac Book


John thoma Brown
Arrays as parameters
• At some point, we may need to pass an array
to a function as a parameter.
• To accept an array as parameter for a function,
the parameters can be declared as the array
type, but with empty brackets, omitting the
actual size of the array. For example:
• void procure(int brother[])
• Would be clearer when we treat functions
#include <iostream>
using namespace std;
Example
//function Explanation may
void goArray(int trinidad[],int d)
be suspended till
{
for(int i=0; i<d; ++i)
function is
cout<<trinidad[i]<< ' '; treated
cout<<endl;
}
int main() Output
{
int tomatos[] = {5,6,8,9};
56 8 9
int barakota[] = {0,5,6,9,7,2}; 0 5 6 9 7 2
goArray(tomatos,4);
goArray(barakota,6);
}
#include<iostream>
using namespace std;
Example 2
//Function Declaration Explanation may
void goDady(int polabare[],int size)
be suspended till
{
for(int i = 0; i<size; ++i)
function is
cout<<polabare[i]<<' '; treated
cout<<endl;
}
int main()
{
6,5
int boobala[] = {6,5,8,9,7}; 1,3,2,4,81
int Rambo[] = {1,3,2,4,81,79};
goDady(boobala,2);
goDady(Rambo,5);
Assignment
• The table below are the first names of people who
went for check up the Bisi maternity home and
were attended by 3 doctors in 2 rooms. Using a
multidimensional array, write a c++ program that
displays
• the name of a patient
• the doctor that treated her
• the room where she was treated.
Doctor 1 Doctor 2 Doctor 3
Room 1 Afuah Araba Johnson
Room 2 Benjamin Koroma Chelsea
Amend the code on the next slide to request
for username and password. If any or both
are entered wrongly for 3 times the program
should terminate with message “Sorry you
don’t seem to have an account with us”
Please note
Username = ait
Password = cs103
#include <iostream> cout<<"sorry you have enterred
"<<times<<" time "
using namespace std;
<<"the program will
void printMessage(); terminate"<<endl<<endl;
static int times = 1; break;
int main() }
{ else
char choice; printMessage();
do cout<<endl<<endl;
{ }while (choice != 'Q');
cout<<"enter Q to quit, any other }
character to continue: "; void printMessage()
cin>>choice; {
cout<<"The function is called
"<<times<<" times"<<endl;
if (choice == 'Q') cout<<"The program will quit after the
cout<<"input stopped"; third call "<<endl
else if (times == 3) <<"without entering Q"<<endl;
{ times ++;

You might also like