90 likes | 198 Views
// This program puts values into an array, sorts the values into // ascending order, and prints the resulting array. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; void bubbleSort( int *, const int ); int main() { const int arraySize = 10;
E N D
// This program puts values into an array, sorts the values into // ascending order, and prints the resulting array. #include <iostream> using std::cout; using std::endl; #include <iomanip> using std::setw; void bubbleSort( int *, const int ); int main() { const int arraySize = 10; int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; int i; Esempi Puntatori e Stringhe
cout << "Data items in original order\n"; for ( i = 0; i < arraySize; i++ ) cout << setw( 4 ) << a[ i ]; bubbleSort( a, arraySize ); // sort the array cout << "\nData items in ascending order\n"; for ( i = 0; i < arraySize; i++ ) cout << setw( 4 ) << a[ i ]; cout << endl; return 0; } Esempi Puntatori e Stringhe
void bubbleSort( int *array, const int size ) { void swap( int * const, int * const ); for ( int pass = 0; pass < size - 1; pass++ ) for ( int j = 0; j < size - 1; j++ ) if ( array[ j ] > array[ j + 1 ] ) swap( &array[ j ], &array[ j + 1 ] ); } void swap( int * const element1Ptr, int * const element2Ptr ) { int hold = *element1Ptr; *element1Ptr = *element2Ptr; *element2Ptr = hold; } Esempi Puntatori e Stringhe
Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items in ascending order 2 4 6 8 10 12 37 45 68 89 Esempi Puntatori e Stringhe
// Using subscripting and pointer notations with arrays #include <iostream> using std::cout; using std::endl; int main() { int b[] = { 10, 20, 30, 40 }, i, offset; int *bPtr = b; // set bPtr to point to array b cout << "Array b printed with:\n" << "Array subscript notation\n"; for ( i = 0; i < 4; i++ ) cout << "b[" << i << "] = " << b[ i ] << '\n'; Esempi Puntatori e Stringhe
cout << "\nPointer/offset notation where\n" << "the pointer is the array name\n"; for ( offset = 0; offset < 4; offset++ ) cout << "*(b + " << offset << ") = " << *( b + offset ) << '\n'; cout << "\nPointer subscript notation\n"; for ( i = 0; i < 4; i++ ) cout << "bPtr[" << i << "] = " << bPtr[ i ] << '\n'; cout << "\nPointer/offset notation\n"; Esempi Puntatori e Stringhe
for ( offset = 0; offset < 4; offset++ ) cout << "*(bPtr + " << offset << ") = " << *( bPtr + offset ) << '\n'; return 0; } Esempi Puntatori e Stringhe
Array b printed with: Array subscript notation b[0] = 10 b[1] = 20 b[2] = 30 b[3] = 40 Pointer/offset notation where the pointer is the array name *(b + 0) = 10 *(b + 1) = 20 *(b + 2) = 30 *(b + 3) = 40 Esempi Puntatori e Stringhe
Pointer subscript notation bPtr[0] = 10 bPtr[1] = 20 bPtr[2] = 30 bPtr[3] = 40 Pointer/offset notation *(bPtr + 0) = 10 *(bPtr + 1) = 20 *(bPtr + 2) = 30 *(bPtr + 3) = 40 Esempi Puntatori e Stringhe