#include #include /*************************************************** * Printing the entries of an array * * Write a function that prints the entries of an * array, separated by commas and spaces. * * For example, the array * * { 34, 15, 65, 59, 42 } * * should be printed as * * 34, 15, 65, 59, 42 * * Follow the output by an end-of-line character. * * If there are no entries, just print the * end-of-line character. ***************************************************/ // Function declarations void print_array( int const array[], std::size_t const capacity ); int main(); // Function definitions int main() { int array1[1]{ 42 }; int array2[5]{ 34, 15, 65, 59, 42 }; int array3[27]{ 50, 65, 23, 46, 57, 3, 29, 22, 99, 73, 44, 2, 48, 88, 98, 38, 17, 46, 19, 34, 93, 88, 46, 52, 69, 38, 79 }; print_array( nullptr, 0 ); print_array( array1, 1 ); print_array( array2, 5 ); print_array( array3, 27 ); return 0; } void print_array( int const array[], std::size_t const capacity ) { std::cout << std::endl; } // Hint: // // You will need a for loop that steps through the // array, and the loop variable must have type // std::size_t. // // The difficulty is deciding when to print // // ", " // // You do not want a comma before the first entry, // nor do you want one after the final entry. // // If the array has capacity 0 or 1, no commas // should be printed. // // One approach is to treat the first entry // separately. If there is a first entry, print it // without a comma. Then use a for loop to print // each remaining entry preceded by ", ". // Here is one solution: /* void print_array( int const array[], std::size_t const capacity ) { if ( capacity > 0 ) { std::cout << array[0]; for ( std::size_t k{ 1 }; k < capacity; ++k ) { std::cout << ", " << array[k]; } } std::cout << std::endl; } */ // Another possibility: // // Instead of treating the first entry separately, // keep track of whether an entry has already been // printed. /* void print_array( int const array[], std::size_t const capacity ) { bool first_is_printed{ false }; for ( std::size_t k{ 0 }; k < capacity; ++k ) { if ( first_is_printed ) { std::cout << ", "; } else { first_is_printed = true; } std::cout << array[k]; } std::cout << std::endl; } */