|
The following program reads a list of integers from the standard input until it sees integer 0. Then it writes them to the standard output backwards. It is a silly program, but it illustrates use of arrays.
#include <cstdio> using namespace std; const int maxNums = 100; // ReadNumbers(A) reads integers from the standard input // until it reads 0. It stores the first value read // into A[0], the second value into A[1], etc. // It does not store the end marker 0 into array A. // // Array A is assumed to have physical size maxNums. // // ReadNumbers returns the number of values that it read, // excluding the 0 at the end. int readNumbers(int A[]) { int i; for(i = 0; i < maxNums; i++) { scanf("%i", &(A[i])); if(A[i] == 0) { break; } } return i; } // WriteNumbers(A, howmany) writes A[howmany-1], ..., // A[0], in that order, each on a separate line, to // the standard output. void writeNumbers(const int A[], const int howmany) { for(i = howmany - 1; i >= 0; i--) { printf("%i\n", A[i]); } } int main() { int howmany; int A[maxNums]; howmany = readNumbers(A); writeNumbers(A, howmany); return 0; }
An array is not always the right tool. Show how to simplify the above program substantially by using recursion. Answer
|