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:
intSwap
Function:- This function swaps the values of two integer variables, facilitating the reversal of array elements.
printIntArray
Function:- Prints the elements of an array in a user-friendly format, with a specified number of elements per line.
getIntArray
Function:- Reads integers from the user until a sentinel value (in this case, 0) is entered or the array is full.
- Provides basic input validation and handles the array size limit.
reverseIntArray
Function:- Reverses the order of the first
n
elements in the array by using theintSwap
function.
- Reverses the order of the first
Source Code of the C Program
#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