



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
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
1 / 5
This page cannot be seen from the preview
Don't miss anything!




#include
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; }
Return arrays from functions
Array can NOT be returned from a
function
Array cannot be assigned
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
Bubble sort - source code // This program sorts an array’s values into ascending order #include
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?