You are on page 1of 26

Arrays

An array is like a large data variable that can store multiple data items of the same type. Arrays are a series of elements (variables) of the same type placed consecutively in memory that can be individually referenced by adding an index to a unique name. X
X[0]

Each individual element is referred to by the array name and the subscript (or index)

The ith element is referred to by X[i-1]

Arrays
We can store 5 values of type int without having to declare 5 different variables each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with an unique identifier. Example: Use an array called billy to contain 5 integer values of type int.
0 1 2 3 4

billy
int The cells are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length .

Declaration of Array variables


A typical array declaration in C++ is as follows: type name [elements]; Example: int X[10]; // Array X will contain 10 elements of integer type. The elements will be X[0] to X[9]

We can have arrays of any type and dimension: Example: char X[20] float Y[50] double Z[10] NOTE: The elements field within brackets [] when declaring an array must be a constant value, since arrays are blocks of static memory of a given size and the compiler must be able to determine exactly how much memory must assign to the array before any instruction is considered.
3

Initialising Arrays (1)


When declaring an array of local scope (within a function), if we do not specify otherwise, it will not be initialized. So, its content is undetermined until we store some values in it. If we declare a global array (outside any function) its content will be initialized with all its elements filled with zeros. Thus, if in the global scope we declare int billy [5] : 0 0 int 1 0 2 0 3 0 4 0

billy

But additionally, when we declare an Array, we have the possibility to assign initial values to each one of its elements using curly brackets { }. Example: int billy [5] = { 16, 2, 77, 40, 12071 }; 4

Initialising Arrays (2)


The number of elements in the array that we initialized within curly brackets { } must match the length in elements that we declared for the array enclosed within square brackets [ ]. Example: int billy [5] = { 16, 2, 77, 40, 12071 }; Because this can be considered an useless repetition, C++ includes the possibility of leaving empty the brackets [ ], being the size of the Array defined by the number of values included between curly brackets { }: Example: int billy [] = { 16, 2, 77, 40, 12071 };

Input/Output of array elements (1)


Exercise: Write a program to input values into all elements of an integer array A of size 10 and display back the values.
void main()
{ int A[10]; int i; cout<<Enter 10 integer values; for (i=0;i<10;i++) cin>>A[i]; /*Displaying back the values *./ for (i=0;i<10;i++) cout<<A[i];
6

To read and write in an array, we make use of a loop

Input/Output of array elements (2)


Exercise: Write a program to input values into all elements of an integer array A of size 10 and display back the values in reverse order.
void main() {int A[10]; int i;

cout<<Enter 10 integer values);


for (i=0;i<10;i++) cin>>A[i];

/*Displaying back the values */


for (i=0;i<10;i++) cout<<A[9-i];} OR for (i=9;i>=0;i--) cout<<A[i];
7

Exercise: Write a program to input an integer n (n<=10) value followed by n real-numbers into an array A of size 10 and display the maximum value stored as well as the position where it is stored in the array .
#include <iostream.h> void main() {int i,n; float A[10]; int maxposn; float max; cout<<Input value for n; cin>>n; cout<<Input<<n<<integer numbers; maxposn=0;
for (i=0;i<=n;i++) { cin>>A[i]; if (i= =0) max=A[i]; else if (A[i]>max) {max=A[i]; maxposn=i;} } cout<<largest is <<max<< at posn << maxposn; }

Input/Output of array elements (3)

Strings/Array of characters (1)


Character arrays can be treated in a similar way to arrays of integers and real numbers. Example: char x[20] Each element can be accessed separately: for (i=0; i < 20;i++) cout<<x[i]; However, since a whole array of characters may be required to store a useful information like a name or an address, the type string is used to refer to an array of characters. With the declaration char x[20], the array x can contain a string of characters. Displaying the value of x: cout<<x;
9

Exercise - Write a program to input the name of a person and display the number of vowels in the name.
void main() { char name[20]; char ch; int i,count; count = 0; cout<<Input name; cin>>name; i=0; while ((name[i]!=\0) && (i<20)) { ch=name[i]; if ((ch==A) || (ch==E)|| (ch==I) ||(ch==O)|| (ch==U)) count++; i++; } 10 cout<<No. of vowels is << count<<endl; }

Strings/Array of characters (2)


Initialization of strings: char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; The above example shows a string of characters (array) of 6 elements of type char initialized with the characters that compose Hello plus a null character '\0'. Nevertheless, string of characters have an additional way to initialize its values: using constant strings: Example: char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' }; char mystring [] = "Hello"; In both cases the Array or string of characters mystring is declared with a size of 6 characters (elements of type char): the 5 characters that compose Hello plus a final null character ('\0') which specifies the end of the string. However, in the second case, when using double quotes ("), the null character it is automatically appended.

11

Strings/Array of characters (3)


Note: We can "assign" a multiple constant to an Array only at the moment of initializing it, that is, at the moment it is being declared. The following examples are invalid: mystring = "Hello"; mystring[] = "Hello"; mystring = { 'H', 'e', 'l', 'l', 'o', '\0' }; However, the following is valid: mystring[0] = 'H'; mystring[1] = 'e'; mystring[2] = 'l'; mystring[3] = 'l'; mystring[4] = 'o'; mystring[5] = '\0';

12

Strings/Array of characters (4)


One method to assign values to an array is by using directly the input stream (cin). In this case the value of the string is assigned by the user during program execution. With cin, we can actually use its getline method, that can be called following this prototype:

cin.getline (char buffer[], int length, char delimiter = ' \n');


where buffer is the address where to store the input (like an array, for example) length is the maximum length of the buffer (the size of the array) delimiter is the character used to determine the end of the user input, which by default - if we do not include that parameter - will 13 be the newline character ('\n').

Strings/Array of characters (5)


// Example of using cin with strings #include <iostream.h> int main () { char mybuffer [100]; cout << "What's your name? "; cin.getline (mybuffer,100); cout << "Hello " << mybuffer << ".\n"; cout << "Which is your favourite team? "; cin.getline (mybuffer,100); cout << "I like " << mybuffer << " too.\n"; return 0; } Note: Notice how in both calls to cin.getline, the same string identifier (mybuffer) is used. What the program does in the second call is simply step on the previous content of buffer by the 14 new one that is introduced.

Strings/Array of characters (6)


Advantages of using cin.getline over cin only: cin can only receive single words (no complete sentences) since this method uses as delimiter any occurrence of a blank character, including spaces, tabulators, newlines and carriage returns.

It is not allowed to specify a size for the buffer using cin. What makes your program unstable in case that the user input is longer than the array that will host it.

15

Exercise: Write a program to store your name first name and surname and your address #include<iostream.h> #include<conio.h> void main() { char x[100], y[50]; clrscr(); cout<<"Please enter your name:"; cin.getline(x,50,'\n'); cout<<"Please enter your address:"; cin.getline(y,50,'\n'); cout<<"You entered the following values:"<<endl; cout<<"Name:"<<x<<" Address:"<<y; getch(); }

Strings (ctnd.)

16

Exercise: Write a program which makes use of two functions enter - to store your name first name and surname and your address and display to display back the values entered.
#include<iostream.h> #include<conio.h> //Function Prototypes void enter(char a[], char b[]); void display(char a[], char b[]); void main() { char x[100], y[50]; enter(x,y); display(x,y); } } void display(char a[], char b[]) { cout<<"You entered the following values:"<<endl; void enter(char a[], char b[]) { cout<<"Please enter your name:"; cin.getline(a,50,'\n'); cout<<"Please enter your address:"; cin.getline(b,50,'\n');

Strings (ctnd.)

cout<<"Name:"<<a<<" Address:"<<b;
}
17

Two-Dimensional arrays (1)


Multidimensional arrays can be described as arrays of arrays. For example, a bidimensional array or 2-D array can be imagined as a bidimensional table of a uniform concrete data type.

jimmy represents a bidimensional array of 3 per 5 values of type int. (3x5 means 3 rows by 5 columns) The way to declare this array would be: int jimmy [3][5];
18

Two-Dimensional arrays (2)


The way to reference the second element vertically and fourth horizontally in an expression would be: jimmy[1][3]

jimmy[1][3]

Note: Multidimensional arrays are not limited to two indices (two dimensions)
19

Two-Dimensional arrays (3)


For a two-dimensional array, we need two subscripts to reference an element. For example, X[1][2]. Declaration of a two-dimensional array: type Arrayname[Dimension1][Dimension2]; Eg. int X[10][20]; In the above declaration X can store up to 200 values at a time. The elements are X[0][0], X[0][[1]X[0][19] X[1][0], X[1],[1]X[1][19] .etc.

20

Two-Dimensional arrays (4)


Exercise: Create a 2-D array to store the Multiplication Table 1 1 1 .. 2 11 12 12 #define WIDTH 12 #define HEIGHT 3 int jimmy[HEIGHT][WIDTH]; int n,m; int main () { for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n][m]=(n+1)*(m+1); } }
21

. 9 18

99 108

10 10 20

110 120

Storing Matrices
A 2-D Array can be viewed as a table consisting of rows and columns. Hence it can be used to store matrices. Exercise: Write a program to input two 3x3 matrices A and B, of integers, and output their sums.
#include <iostream.h> void main() { int A[3][3],B[3][3],C[3][3]; int i,j; cout<<Input the nine elements of A; for (i=0;i<3;i++) for (j=0;j<3;j++) cin>>A[i][j]; cout<<Input the nine elements of B; for (i=0;i<3;i++) for (j=0;j<3;j++) cin>>B[i][j];

for (i=0;i<3;i++) for (j=0;j<3;j++) C[i][j] =A[i][j]+B[i][j]; for (i=0;i<3;i++) { for (j=0;j<3;j++) cout<<C[i][j]; cout<<endl;} }
22

Storing Matrices of Varying Sizes


Exercise: Write a program to input two integer values m,n (m,n <=10) followed by mxn matrices A and B, of integers, and output their sums.
void main() { int A[10][10],B[10][10],C[10][10]; int m,n,i,j; cout<<Input values for m and n; cin>>m>>n; cout<<input the <<m*n<<elements of A; for (i=0;i<m;i++) for (i=0;i<m;i++) for (j=0;j<n;j++) cin>>B[i][j]; for (i=0;i<m;i++) for (j=0;j<n;j++) C[i][j] =A[i][j]+B[i][j]; for (i=0;i<m;i++) { for (j=0;j<n;j++) cout<<C[i][j]<<\t; cout<<endl;}//for }//main
23

for (j=0;j<n;j++) cin>>A[i][j];


cout <<input the <<m*n<<elements of B;

Storing students Names and Marks


Exercise: Write a program to input the names of 10 students as well as their marks in 4 modules, calculate their overall percentage and display the names and percentages, one line per student.
#include <stdio.h> void main() {char names[10][20]; float marks[10][4]; float sum,percentage[10]; int i,j; /*Input of Information*/ cout<<enter the names and marks of each student); for (i=0; i<10;i++) {cin>>names[i]; for (j=0;j<4;j++) cin>>marks[i][j]; } /*calculate percentages*/ for (i=0; i<10;i++) {sum=0; for (j=0;j<4;j++)

sum=sum+marks[i][j];
percentage[i] = sum/4;} for (i=0; i<10;i++)

{cout<<names[i];
for (j=0;j<4;j++) cout<<marks[i][j]<< percentage[i]<<endl;} }
24

2-D Arrays as Parameters (1)


In a function declaration, it is also possible to include multidimensional arrays. Its format for a bidimensional one is:

base_type[][depth] For Example, a function with a multidimensional array as argument could be: void procedure (int myarray[][3]) Notice that the first bracket [] is void and the following one not. This must always be thus because the compiler must be able to determine within the function which is the depth of each additional dimension.

25

2-D Arrays as Parameters (2)


Exercise: Use a function to pass the multiplication table as parameter
#include<iostream.h> #include<conio.h> #define WIDTH 12 #define HEIGHT 3 int jimmy[HEIGHT][WIDTH]; int n,m; void display(int jimmy[][WIDTH]) { for (int i=0; i<HEIGHT; i++) for (int j=0; j<WIDTH; j++) cout<<jimmy[i][j]<<'\t'; }
26

void main () { for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++) { jimmy[n][m]=(n+1)*(m+1); }

display(jimmy);

You might also like