This program serves as a practical example for beginners to understand array manipulation, function usage, and basic input/output operations in the C programming language. It also introduces concepts like function prototypes and error handling.
The main objective of the program is to read integers into an array, print the array, reverse its order, and print the reversed array.
Note: You can read more about Arrays in this article: Arrays in C
Main Functions of the Program
Key Features:
intSwapFunction:printIntArrayFunction:getIntArrayFunction:reverseIntArrayFunction:
Source Code of the C Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | #include <stdio.h> #include <stdlib.h> // For exit() #define NMAX 5 #define ELEMENTS_PER_LINE 5 // Function prototypes void intSwap(int* x, int* y); int getIntArray(int a[], int nmax, int sentinel); void printIntArray(int a[], int n); void reverseIntArray(int a[], int n); int main(void) { int x[NMAX]; int hmny; // Read integers into the array hmny = getIntArray(x, NMAX, 0); printf("The array was: \n"); printIntArray(x, hmny); // Reverse the array reverseIntArray(x, hmny); printf("After reversing, it is:\n"); printIntArray(x, hmny); return 0; } void intSwap(int* x, int* y) { // Swap the content of x and y int temp = *x; *x = *y; *y = temp; } void printIntArray(int a[], int n) { // Print values, ELEMENTS_PER_LINE per line for (size_t i = 0; i < n; ) { printf("\t%d ", a[i++]); if (i % ELEMENTS_PER_LINE == 0) printf("\n"); } printf("\n"); } int getIntArray(int a[], int nmax, int sentinel) { // Read up to nmax integers and store them in a; sentinel terminates input int n = 0; int temp; do { printf("Enter integer [%d to terminate] : ", sentinel); // Check for valid input if (scanf("%d", &temp) != 1) { printf("Invalid input. Exiting.\n"); exit(EXIT_FAILURE); } if (temp == sentinel) break; if (n == nmax) { printf("Array is full\n"); } else { a[n++] = temp; } } while (1); return n; } void reverseIntArray(int a[], int n) { // Reverse the order of the first n elements of a for (size_t i = 0; i < n / 2; i++) { intSwap(&a[i], &a[n - i - 1]); } } |
Output of this C program is:
Enter integer [0 to terminate] : 5
Enter integer [0 to terminate] : 4
Enter integer [0 to terminate] : 3
Enter integer [0 to terminate] : 2
Enter integer [0 to terminate] : 1
Enter integer [0 to terminate] : 0
The array was:
5 4 3 2 1
After reversing, it is:
1 2 3 4 5
