Skip this Video
Download Presentation

Loading in 2 Seconds...

play fullscreen
1 / 23

Arrays - PowerPoint PPT Presentation

  • Uploaded on

Arrays. ARRAYS. Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef. Motivation. Suppose we want to compute the average of 20 marks. Do we need to declare 20 variables mark1, mark2, …, mark20 ? Do we need to write 20 cout s and 20 cin s ?

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about ' Arrays' - azizi

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Computer programming

  • Motivation
  • Introduction to Arrays
  • Static arrays
  • Arrays and Functions
  • Arrays, Classes, and typedef

Computer programming

  • Suppose we want to compute the average of 20 marks. Do we need to declare 20 variables mark1, mark2, …, mark20? Do we need to write 20 couts and 20 cins?
  • How about sorting a large number of ints?
  • This is where arrays come in!

Computer programming

introduction to arrays
Introduction to Arrays
  • An array is a fundamental data structure used to store objects of a particular type in contiguous memory locations.
  • Arrays allow us to randomly access this contiguous memory via indexing.
  • There are essentially two ways to declare arrays in C++: statically and dynamically (until pointers are covered).

Computer programming

static arrays
Static Arrays
  • Static array declaration

typeName arrayName[sizeOfTheArray]

  • typeName is the base type of the particular type of the elements of the array. Can be any type (primitive or user-defined)
  • arrayName is the name of the array. Any valid C++ identifier
  • sizeOfTheArray is the size or the capacity of the array
  • The above declaration is equivalent to declaring sizeOfTheArray variables. Each variable is an indexed variable, a variable referenced using an index between 0 and sizeOfTheArray

arrayName[0] is an indexed variable at the index 0

arrayName[1] is an indexed variable at the index 1

arrayName[sizeOfTheArray-1] is an indexed variable at

the index sizeOfTheArray-1

Computer programming

static arrays declaration
Static arrays - Declaration
  • An array consisting of 5 variables of type int is declared:

int score[5];

  • Such a declaration creates 5 int type variables which are accessed as

score[0], score[1], score[2], score[3], score[4]

  • These are called indexed variables, also called subscripted variables.
  • The number in the brackets is called an index or subscript.
  • Array subscripts start at 0 and run to one less than sizeof the array, which is 4.
  • Be careful not to confuse the size in a declaration of an array with the index value in an array reference.

int score[size];

score[index]; // 0 <= index < size

  • It is possible to declare arrays along with ordinary variables:
  • int next, score[5], max;

Computer programming

static arrays initialization
Static arrays - Initialization
  • You may initialize specific index variables

int score[5];

//actually the indexed variables are initialized to the default

//value (usually 0 of int)

score[4] = 10; //this can also be read from cin

  • You can use for statement to initialized the values of an array

for (int i=0;i<5;i++)


  • The size of an array can be omitted as shown in the following definition

int score[]={2, 1, 5, 4, 6};

  • The following definition is also possible

int score[5]={2, 1, 5, 4, 6};

  • Initialization may cover only the first few elements

int marks[10]={1,2};

//the first two elements are initialized to 1 and 2. The others //to the default value.

Computer programming

referencing and using arrays
Referencing and using arrays
  • Array references may be used anywhere an ordinary variable is used.

cin >> score[4] >> score[2];

cout << score[2] << “ “ << score[4];

score[0] = 32;

score[3] = score[0]++;

  • Another way of accessing/referencing the elements of an array is discussed later
  • The forstatement is a good way to go through the elements of an array
  • Arrays are used in several occasions such as:
    • Searching
    • Sorting

Computer programming

problem 1
Problem 1
  • A set of positive data values (200) are available. It is required to find the average value of these values and to count the number of values that are more than 10% above the average value.

The solution will be provided in class

Computer programming

problem search
Problem: search
  • Given an arrayaofnintegers and a valueval, find the index of the scripted variable that has the valueval?
    • Linear search
    • Binary search

Solution will be provided in class

Computer programming

memory allocation
Memory allocation
  • Recall that a computer’s memory is like a long list of numbered locations.
  • The numbers are called addresses, and the information written there is either some program’s instructions or data.
  • Recall that good programmers make efficient use of memory.
  • Suite to a running program, a memory is organized into segments
    • Text segment: where the program instructions reside
    • BSS segment: where static and global variables that are uninitialized
    • Data segment: where static and global variables that are initialized go
    • Stack segment: where local variables reside
    • Heap segment: where dynamically allocated variables reside
  • Every variable has an address and a number of bytes necessary to hold the variable value
    • This number of bytes is determined by the type of the variable.

Computer programming

memory allocation1
Memory allocation

int size=100;  Data

int glb;  BSS

int func() {

int tmp = 10;  stack

int* dyn = new int(200); heap

return …;


Computer programming


Arrays in memory

  • Consider:

int a[6];

  • The namea is the address of the element a[0]
    • So, to access an element we could use *(a + index) instead of a[index]
  • Here the compiler decides where in memory to put the array, and the size of the array is 6 * the size of an int.
  • In general, the size of an array is

size * sizeof(Array_Type)

  • So, an array has three things:
  • 1) an address of the start of the array in memory
  • 2) a type, which tells how big each indexed variable is
  • 3) the array size, which tells number of indexed variables.

Computer programming

indexed variables as function arguments
Indexed Variables as Function Arguments
  • An indexed variable is just a variable whose type is the base type of the array, and may be used anywhere any other variable whose type is the base type of the array might be used.

void my_function (int x) {

cout << x*x <<endl;


int i, n, a[10];



Computer programming

entire arrays as function arguments
Entire Arrays as Function Arguments
  • It is possible to use an entire array as a parameter for a function.
  • This is a new parameter type called an array parameter.
  • Declaration

void fillUp(int array[], int nbrOfElts);

or void fillUp(int [], int);

  • Definition

void fillUp(int array[],int nbrOfElts) {

for (int i=0; i < nbrOfElts; i++)



  • Calling the function

int score[100];

fillUp(score, 10);

How come we are able to change the array without using references?

Computer programming


Entire Arrays as Function Arguments

  • Passing an array is not by value because we can change the array when passed this way.
  • It is by reference because we cannot change the complete array by a single assignment when passed this way.
  • The behavior, however, is like call-by-reference since we can change individual array elements.
  • The array argument tells the caller only the address and type, but not the size of the array.

Computer programming

the const parameter modifier
The const Parameter Modifier
  • Array parameters allow the function to change any value stored in the array.
  • Frequently, this is the intent of the function.
  • Sometimes, however, we want to avoid changing an array parameter.
    • Use theconstkeyword

void printArray( const int a[ ], int size_of_a) {

cout << "Array values are:\n";

for ( int i = 0; i < size_of_a; i++)

cout << a[i]++ << " ";

cout << endl;


Computer programming

  • Do not consider the name of the array as a variable.
    • We cannot increment or decrement an array
  • Do not forget that arrays are not passed by value
  • Array Index Out of Range
    • The most common programming error when using arrays is the attempt to reference a non-existent array index.
    • The statement

int a[6];

declares ONLY the indexed variables a[0] through a[5].

    • An index value outside 0 to 5 is anout of range error, i.e.,illegal

a[7] = 248;

C++ treats 7 as if it were legal subscript, and attempts to write to memory where a[7] would be.

Computer programming

problem sorting
Problem: Sorting
  • To know
    • Sorting an array means putting data in a certain order. An array that contains objects that can be compared is sorted in a non-decreasing order if

for every pair of indices i and j, if i < j then a[i] <= a[j]. This gives:

a[0] <= a[1] <= a[2] <= . . . <= a[number_used - 1]

    • Note that the array is partially filled so we must pass an additional array parameter that specifies how many array elements are used.
    • Algorithms: Bubble sort, Selection sort,Insertion sort, Shell sort, Merge sort, Heapsort, Quicksort, Bucket sort, and Radix sort.
  • Write a program that sorts in a non-decreasing order the elements of an array. The base type can be int, char, float, or double.

Computer programming


Selection sort

Computer programming

arrays classes typedef
Arrays, Classes, typedef
  • You can use arrays as attributes in a class
  • You can have an array of classes

Person students[1000];

  • You can use typedef with arrays as follows

typedef int ScoreType[100];

ScoreType score; //int score[100];

Computer programming