0% found this document useful (0 votes)
89 views17 pages

Chapter 7 Arrays: Int Marks

An array is a collection of consecutive storage locations of the same type. Arrays allow storing multiple values of the same type using a single name. When declaring a one-dimensional array, the size must be specified. Each element has an index that starts from 0. Arrays can be initialized with values at declaration. Memory is allocated for the entire array as a block, with each element having a unique address that can be accessed using pointers or indexes. Arrays can be passed as function parameters by specifying the array name without indexes.

Uploaded by

LEOW CHIA WAY
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views17 pages

Chapter 7 Arrays: Int Marks

An array is a collection of consecutive storage locations of the same type. Arrays allow storing multiple values of the same type using a single name. When declaring a one-dimensional array, the size must be specified. Each element has an index that starts from 0. Arrays can be initialized with values at declaration. Memory is allocated for the entire array as a block, with each element having a unique address that can be accessed using pointers or indexes. Arrays can be passed as function parameters by specifying the array name without indexes.

Uploaded by

LEOW CHIA WAY
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER 7

ARRAYS

An array is a collection of consecutive storage locations which has the same name and the same type. To refer to a location or a specific element from a certain array, we have to specify the name of the array together with its position (index or subscript). An array has elements with subscripts starting with 0. Simple Arrays (One Dimensional Arrays) Array Declaration data_type identifier[size_of_array]; Example
int marks[285];

This declaration tells the compiler to allocate 285 consecutive storage locations, each of type int. The first element has subscript 0 and the 285th element has the subscript 284. Contents Subscript Variable name or index marks[0] 0 marks[1] 1 marks[2] 2 : : : : : : : : : : : : marks[283] 283 marks[284] 284 An array may be declared in several ways
int marks[285];

or

const int size = 285; int marks[size];

or
#define size 285 : int marks[size];

You have to be careful when referring to elements in an array so that reference to elements which are out of bound does not happen, e.g. element marks[285] does not exist. You must always remember that an array starts with subscript/index 0, i.e. marks[0]. The compiler does not have the facility to check the array bounds. Subscripts may be constants, variables or expressions which are of integer values. Example,
marks[35] marks[j]

(here j has been assigned an integer value before this) marks[3*k+2] (here k has been assigned an integer value before this) Array Initialization An array needs to be initialized after declaration to start computation. Example of array initialization, Example 1
int result[5] = {3, 56, 39, 13, 52};

will produce Array result[0] result[1]

Value 3 56

result[2] 39 result[3] 13 result[4] 52 This is known as compile-time initialization. Example 2


int result[] = {3, 56, 39, 13, 52};

will declare the array with variable name result and size 5. The subscript will be in the order from 0 to 4. The values produced in the array result are as follows, Array Value result[0] 3 result[1] 56 result[2] 39 result[3] 13 result[4] 52 Example 3 If the dimension size is greater than the number of listed elements, the array elements not explicitly initialized are set to 0.
int result[5] = {3, 56};

will produce Array result[0] result[1] result[2] result[3] result[4]

Value 3 56 0 0 0

Warning The following declaration/initialization

int result[5] = {3, 56, 39, 13, 52, 72};

is illegal because it allocates more values than what was permitted.

Memory Allocation for Arrays When an array is declared, the compiler allocates a series of available memory spaces consecutively equivalent to the size of the array. For example, when variable result is declared as an integer array with 5 elements, int a1[5]; The following memory spaces are allocated,
00000000
num a1[0] res int int int 2 5

00000004
avg a1[1] float int 4.5 1.2

00000008
char Y

00000009
cost a1[3] 38 int int 123

0000000A 00000020
90 1.2 a1[4] int 8

00000010 00000020 00000030

00000014 00000024 00000034


4

00000018
a1[2] int

0000001C 00000028 0000003A


8 2

00000026 00000036

0000002B 0000003C

Exercise What is the memory allocation for declaration of int marks[285] ? Array processing with loops Use loops to monitor the subscripts : float number[100]; : for (int i = 0; i < 100; i++) number[i] = 0.0; :

Array Operations The elements in an array can be manipulated the same way as ordinary variables, in arithmetic operations, as input, output, etc. Duplicating Array To copy one array into another, each element must be copied in turn. For example,
const int arraySize = 7; void main() { int ia1[] = {0, 1, 2, 3, 4, 5, 6}; int ia2[arraySize]; for (int ix = 0; ix < arraySize; ++ix) ia2[ix] = ia1[ix];

// continue with array operations


: : }

From the above program, arrays ia1 and ia2 are two different arrays, i.e. changing of value in ia1 does not change the value in ia2, after the duplication of array. Consider the below program.
const int arraySize = 7; void main() { int ia3[] = {0, 1, 2, 3, 4, 5, 6}; int ia4[arraySize]; ia3 = ia4; //different meaning }

The above program sets the memory address of array ia3 to the same as memory address of array ia4, i.e. arrays ia3 and ia4 are pointing to the same memory location. In other words, arrays ia3 and ia4 are the same, changing of value in ia3 will change the value in ia4. Example #include <iostream> #include <iomanip> using namespace std; const int SIZE = 5; void main() { int number[SIZE], i; // read in 5 numbers and assign to the array number[] cout << "\nEnter " << SIZE << " numbers: "; for (i = 0; i < SIZE; ++i) cin >> number[i]; // displays the 5 numbers read by cout the array number[] for (i = 0; i < SIZE; ++i) cout << setw(5) << number[i]; cout << endl << endl; // add 10 to each array element then assign back to array //number[] for (i = 0; i < SIZE; ++i) number[i] = number[i] + 10; // display the array number[] with new values for (i = 0; i < SIZE; ++i) cout << setw(5) << number[i]; }

IMPORTANT If an array is referred using only the name without the subscripts, the address of the first element of the array is actually being referred, not the element. For example, : int marks[10]; : cout << marks; will print the address of the memory location for marks[0]. In other words, marks = &(marks[0]) Whereas, cout << marks[0]; will print the value marks[0]. Memory Address of Array Each non-array variable is assigned a unique memory address upon declaration. The memory address of a variable can be view by adding ampersand (&) symbol in front of the variable, e.g. &a.
#include <iostream> using namespace std; void main() { int a = 3; cout << "The value for variable a is " << a << endl; cout << "The memory address for variable a is " << &a; cout << endl;}

Conclusion: if a is a variable name, then &a is the memory address of variable a.

Similarly, each element in an array is also assigned unique memory address. For example, if an array integer arr has been declared with 5 elements and initialized as below,
int arr[5] = { 2, 3, 5, 6, 8 };

The following figure shows the memory addresses and values assigned to arr when arr is declared and initialized. Con tents 2 3 5 6 8 Index 0 1 2 3 4 Variable name arr[0] arr[1] arr[2] arr[3] arr[4] Memory address for each element is denoted by (arr + 0) or &arr[0] (arr + 1) or &arr[1] (arr + 2) or &arr[2] (arr + 3) or &arr[3] (arr + 4) or &arr[4]

Example The example below shows the values represented by a[i], &(a[i]) and a+i.
#include <iostream> using namespace std; #define SIZE 5 void main() { int a[] = {0, 1, 2, 3, 4}, i;

// printing the value of a[i] -> integer value


for (i = 0; i < SIZE; i++)

cout << "a[" << i << "] = " << a[i] << endl; cout << endl;

// printing the value of &a[i] -> memory address


for (i = 0; i < SIZE; i++) cout << "&(a[" << i << "]) = " << &(a[i]) << endl; cout << endl;

// printing the value of a+i -> memory address


for (i = 0; i < SIZE; i++) cout << "a + " << i << " = " << a+i << endl; cout << endl; }

Sample Output
a[0] = 0 a[1] = 1 a[2] = 2 a[3] = 3 a[4] = 4 &(a[0]) = 0xaea72408 &(a[1]) = 0xaea7240c &(a[2]) = 0xaea72410 &(a[3]) = 0xaea72414

&(a[4]) = 0xaea72418 a + 0 = 0xaea72408 a + 1 = 0xaea7240c a + 2 = 0xaea72410 a + 3 = 0xaea72414 a + 4 = 0xaea72418

More Examples on Arrays Example 1 The below program generates the Fibonacci numbers by using an array.
#include <iostream> #include <iomanip> using namespace std;

// required for setw()

//---- void main()


void main() { int i,n; unsigned int fibonacci[26]; char next; fibonacci[1]=0; fibonacci[2]=1; next = 'y'; while (next == 'y') { cout << "\nEnter the number of terms in ";

cout << "Fibonacci sequence (<= 25): "; cin >> n; for (i = 3; i <= n; i++) fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];

for (i = 1; i <= n; i++) { cout << setw(12) << fibonacci[i]; if (i%5 == 0) cout << endl; } cout << "\nType \'y\' if you want to continue: "; cin >> next; } // end while }

// end main() Why is the number of terms in this program limited to not more than 25? Example 2 The example below asks for user input for marks (in array), then displays the average marks and percentage of the students who have passed the test, among all the marks input (assuming there are less than 50 marks to be input).
#include <iostream> using namespace std; #include <iomanip> void main() {

// required for setw()

// variable declarations and initialization

const int size = 50; int marks[size], i = 0, count = 0, num_pass = 0; float sum = 0.0, average, pass_percentage; cout << "\nEnter marks of students:\n(Assume there are "; cout << "less than 50 students in the class). "; cout << "\nPress <Ctrl-z> when you have finished "; cout << "entering the marks:"; while (cin >> marks[i]) { count++; sum += marks[i]; if (marks[i] >= 40) num_pass++; ++i; } average = sum/count; pass_percentage = num_pass * 100 / count; for (i = 0; i < count; i++) cout << setw(3) << (i+1) << setw(4) << marks[i] << endl; cout << "\nAverage marks = " << average << endl; cout << "\nThe passing percentage is " << pass_percentage; }

Arrays As Function Parameters In order to use arrays as function parameters, the required changes are pointed out in the below program segment.
: void main() { void change1(int[]); : int x[10]; : change1(x); : } : void change1 (int a[]) { : } :

The symbol [] should be used in the parameter. Size of the array is optional. Declare the array in main program Use only the name of array, i.e. exclude symbol [], to pass in the address of the array.

Example 1 The below example shows how to use array as function parameters. Note the difference of parameters between void change1(int a[]) and void change2(int b).
#include <iostream> using namespace std; #define SIZE 5

//-------------------------------------------------------// void main() //-------------------------------------------------------void main

void change1(int[]); void change2(int);

// function prototype

// variable declaration & initialization


int x[SIZE] = {0, 2, 4, 6, 8}; int i;

// main function body


cout << "main(): Values for array x before change1(x) "; cout << "function executed:\n"; for (i = 0; i < SIZE; i++) cout << x[i] << " "; cout << endl;

// calling change1() function


change1(x); cout << "main(): Values for array x after change1(x) "; cout << "function executed:\n"; for (i = 0; i < SIZE; i++) cout << x[i] << " "; cout << endl;

// calling change2() function


for (i = 0; i < SIZE; i++) change2(x[i]); cout << "\nmain(): The value for array x after "; cout << "change2(x[i]) function executed:\n"; for (i = 0; i < SIZE; i++) cout << x[i] << " "; cout << endl; }

// end void main() //-------------------------------------------------------// void change1(int[]) //-------------------------------------------------------void change1 (int a[])

{ int j; for (j = 0; j < SIZE; j++) a[j] *= 3; }

// end void change1(int[]) //-------------------------------------------------------// void change2(int) //-------------------------------------------------------void change2 (int b) { b = 2*b; }

// end change2(int) Sample output


main(): Values for array x before change1(x) function executed: 0 2 4 6 8 main(): Values for array x after change1(x) function executed: 0 6 12 18 24 main(): The value for array x after change2(x[i]) function executed: 0 6 12 18 24

//Example of program with functions //parameters using arrays modification //previous min-max program #include<iostream> using namespace std; #include<conio.h> #define size 10 void main() { void read_input(int []); void max(int [], int &); void min(int [], int &); void print_out(int [], int, int); int x[size], Maximum, Minimum; read_input(x); max(x, Maximum); min(x, Minimum); print_out(x, Maximum, Minimum); getch();

passing of our

} //-------------------------------------------void read_input(int a[]) { int i; cout << "Enter " << size << " integers: "; for (i=0; i < size; i++) cin >> a[i]; } //---------------------------------------------void max(int a[], int &maximum) { int i; maximum = a[0]; for (i = 1; i < size; i++) if (a[i] > maximum) maximum = a[i];

} //--------------------------------------------void min(int a[], int &minimum) { int i; minimum = a[0]; for (i = 1; i < size; i++) if (a[i] < minimum) minimum = a[i]; } //---------------------------------------------void print_out(int a[], int Max, int Min) { int i; cout << "\nThe maximum between "; for (i=0; i < size; i++) cout << a[i] << " "; cout << "is " << Max; cout << "\nThe minimum between "; for (i=0; i < size; i++) cout << a[i] << " "; cout << "is " << Min << endl; }
//----------------------------------------------------------------------

Note: The output of this program is similar with the max-min problem before this. But please note the difference when passing parameters using arrays (function declaration/prototype, actual parameters, etc.)

You might also like