C++ lecture 04

10
Arrays C++ LECTURE 04

Transcript of C++ lecture 04

Page 1: C++ lecture 04

ArraysC++ LECTURE 04

Page 2: C++ lecture 04

What is an array?•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.• A typical declaration for an array in C++ is:

◦ type name [elements];

◦ where type is a valid object type (int, float...), name is a valid variable identifier and the elements field, that is enclosed within brackets [], specifies how many of these elements the array contains.

◦ Eg ; int marks[5];

Page 3: C++ lecture 04

Initialize an Array int marks [5] = { 16, 20, 77, 40, 71 }; Int marks[ ] = {16,20,77,40,71}

Access to the values of an Array In any point of the program in which the array is visible we can access individually anyone of its values for reading or modifying as if it was a normal variable.

The format is the following: ◦ name[index]

Eg: marks[2] = 20;◦ a = marks[2]; i.e a =20;

Page 4: C++ lecture 04

Example // arrays example #include <iostream>Using namespace std;int value [] = {16, 2, 77, 40, 12071}; int n, result=0;int main () { for ( n=0 ; n<5 ; n++ ) { result += value[n]; } cout << result;Return 0; }

Page 5: C++ lecture 04
Page 6: C++ lecture 04

Example 2: C++ Program to store 5 numbers entered by user in an array and display first and last number only.

Page 7: C++ lecture 04

Multidimensional Arrays•Multidimensional arrays can be described as arrays of arrays. •For example, a bi dimensional array can be imagined as a bi dimensional table of a uniform concrete data type.

Page 8: C++ lecture 04

Arrays as parameters// arrays as parameters

#include <iostream>

Using namespace std;

void printarray (int arg[], int length) {

for (int n=0; n<length; n++)

cout << arg[n] << " ";

cout << "\n";

}

int main () {

int firstarray[] = {5, 10, 15};

int secondarray[] = {2, 4, 6, 8, 10};

printarray (firstarray,3);

printarray (secondarray,5);

return 0; }

Page 9: C++ lecture 04

Strings of Characters•strings of characters, that allow us to represent successions of characters, like words, sentences, names, texts•For example, the following array (or string of characters): •char jenny [20];

Page 10: C++ lecture 04

Initialization of strings•char mystring[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; •In this case we would have declared a string of characters (array) of 6 elements of type char initialized with the characters that compose Hello plus a null character '\0'. •char mystring [] = { 'H', 'e', 'l', 'l', 'o', '\0' }; •char mystring [] = "Hello";