Array Programming: Declaration, Access, Passing, and Sorting, Study notes of Electrical and Electronics Engineering

The fundamentals of arrays in programming, including declaration, accessing elements, multidimensional arrays, char arrays and strings, passing arrays to functions, returning arrays from functions, and sorting arrays using bubble sort. It includes a sample c++ code for bubble sort.

Typology: Study notes

Pre 2010

Uploaded on 09/17/2009

koofers-user-5g2
koofers-user-5g2 🇺🇸

10 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
ECE206 - Programming
Lecture 7 – Array II
09/25/07
Array Fundamentals
Declaration: specify type, name, size
(constant integer)
double myArray[10];
Accessing array elements
myArray[0], myArray[1],……
Multidimensional array
int myArray[2][3];
Char arrays and string
char myChar[] = “Hello world!”
pf3
pf4
pf5

Partial preview of the text

Download Array Programming: Declaration, Access, Passing, and Sorting and more Study notes Electrical and Electronics Engineering in PDF only on Docsity!

ECE206 - Programming

Lecture 7 – Array II

Array Fundamentals

† Declaration: specify type, name, size

(constant integer)

„ double myArray[10];

† Accessing array elements

„ myArray[0], myArray[1],……

† Multidimensional array

„ int myArray[2][3];

† Char arrays and string

„ char myChar[] = “Hello world!”

#include #include using namespace std;

void modifyArray( int [], int );

void main() { const int arraySize = 5; int i, a[arraySize] = {0, 1, 2, 3, 4};

cout << "The values of the original array are:\n"; for (i = 0; i < arraySize; i++) cout << setw(3) << a[i]; cout << endl;

modifyArray(a, arraySize);

cout << "The values of the modified array are:\n"; for ( i = 0; i < arraySize; i++ ) cout << setw(3) << a[i]; cout << endl; }

void modifyArray( int b[], int sizeOfArray ) { for (int j = 0; j < sizeOfArray; j++ ) b[j] *= 2; }

Passing array to functions

Return arrays from functions

† Array can NOT be returned from a

function

† Array cannot be assigned

int a[5] = {1, 2, 3};

int b[5];

b = a; //Wrong

Bubble sort - pseudocode

† Search for adjacent pairs that are out

of order.

† Switch the out-of-order keys.

† Repeat this n-1 times.

† After the first iteration, the last key is

guaranteed to be the largest.

† If no switches are done in an

iteration, we can stop.

Example

First pass

Second pass

Bubble sort - source code // This program sorts an array’s values into ascending order #include #include using namespace std; int main() { int arraySize = 5; int a[arraySize] = {10, 12, 8, 68, 45}; int pass, i, temp;

for (i=0; i<arraySize; i++) cout << setw(4) << a[i];

for (pass=0; pass<arraySize-1; pass++) for (i=0; i<arraySize-1; i++) { if (a[i] > a[i+1]) { temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } }

for (i=0; i<arraySize; i++) cout << setw(4) << a[i]; }

How to improve previous code?

† Reduce the number of passes?

† Reduce the comparison in each pass?