3. flow of control

3. flow of control - ENGG1002 Arrays 3 The problem can be...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Applications Arrays Dr. Simon P.H. Lui Electrical & Electronic Engineering Array.doc E N G G 1 0 0 2 / A r r a y s 2 Arrays Assume that you have three variables and want to compute the sum of them: #include <iostream> // array_p1.cpp using namespace std; void main() { int i, total=0; int data0, data1, data2; data0 = 10; data1 = 12; data2 = 14; total += data0; total += data1; total += data2; cout << "Total : " << total << endl; } Obviously, it's highly inefficient if the number of variables is 1000, say. E N G G 1 0 0 2 / A r r a y s 3 The problem can be solved by using arrays. An array is a set of consecutive memory locations that have the same name and type Each item in an array is called an element The number of elements in an array is called the dimension of the array Like any other variables, you have to declare an array before using it : // an array of int int data_list[3]; This declares data_list to be an array of 3 elements : data_list[0] , data_list[1] and data_list[2] To reference an element of an array, you use a number called the index (an integer inside [ ] ) e.g. index of data_list[1] is 1 The element is also called an indexed variable C++ starts counting from 0 , not 1 . The three elements are numbered 0-2. data_list[3] is invalid. E N G G 1 0 0 2 / A r r a y s 4 Example : #include <iostream> // array_p2.cpp using namespace std; void main() { int i, total=0; int data_list[3]; data_list[0] = 10; data_list[1] = 12; data_list[2] = 14; for (i=0; i<=2; i++) { total += data_list[i]; } cout << "Total : " << total << endl; } output of program :
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/26/2011 for the course BENG 1002 taught by Professor Dr.x during the Winter '10 term at HKU.

Page1 / 4

3. flow of control - ENGG1002 Arrays 3 The problem can be...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online