/********************************************************* * From C PROGRAMMING: A MODERN APPROACH, Second Edition * * By K. N. King * * Copyright (c) 2008, 1996 W. W. Norton & Company, Inc. * * All rights reserved. * * This program may be freely distributed for class use, * * provided that this copyright notice is retained. * *********************************************************/ /* reverse.c (Chapter 8, page 164) */ /* Reverses a series of numbers */ #include /* This program demonstrates how useful macros can be. If we later decide to work with an array of different size, e.g., 7 element array, or 58 element array, then all we have to do is to replace one number in macro defining N. Otherwise, we would have to change several numbers in the program. */ #define N 4 int main(void) { int a[N], i; printf("Enter %d numbers: ", N); for (i = 0; i < N; i++) { scanf("%d", &a[i]); printf("On iteration %d, you entered the number %d\n", i, a[i]); } /* The following is to demonstrate that a[N] can have a meaningless run-time dependent value. Recall that N-element array stores values only in cells a[0], a[1], ... , a[N-1] , but a[N] is beyond the bounds of array with size N. */ printf("\nUpon exit from for-loop, iteration is %d, and the number a[N]=%d\n\n", i,a[i]); printf("Now we print all enetered numbers in reverse order:"); /* Since the last element of N-sized array has index (N-1) our for-loop should start from a[N-1] and go down to a[0]. This is why we decrement index i on each iteration. */ for (i = N - 1; i >= 0; i--) printf(" %d", a[i]); printf("\n"); return 0; }