An Array Reversal Program in C is a common task that involves reversing the order of elements in an array. This task helps in understanding array manipulation, looping structures, and basic input/output in C.
Example: Array Reversal Program
In this example, we will write a program that allows the user to input a specific number of integers into an array and then reverses the order of those integers.
C Program to Reverse an Array
Explanation:
Variable Declarations:
int n
: This variable holds the number of elements the user wants to input.int i
: Loop counter for iterating through the array.int arr[100]
: Declares an integer array of size 100 to store the elements.
Input for Array Size:
- The program prompts the user to enter the number of elements they want to reverse and stores this value in
n
.
- The program prompts the user to enter the number of elements they want to reverse and stores this value in
Input for Array Elements:
- A
for
loop is used to iterate from0
ton-1
, prompting the user to input each integer, which is stored in the arrayarr
.
- A
Reversing the Array:
- Two indices,
start
andend
, are initialized to point to the first and last elements of the array, respectively. - A
while
loop continues to execute as long asstart
is less thanend
. - Inside the loop:
- The elements at
start
andend
are swapped using a temporary variabletemp
. - The
start
index is incremented, and theend
index is decremented to move toward the center of the array.
- The elements at
- Two indices,
Output the Reversed Array:
- Finally, a
for
loop iterates over the array to print the elements in their new reversed order.
- Finally, a
Sample Output:
Example 1:
Example 2:
Key Points:
- Array Manipulation: The program demonstrates how to manipulate arrays through indexing and swapping.
- Looping: The use of both
for
andwhile
loops illustrates different ways to traverse an array. - Input/Output: Standard input/output functions are used for user interaction.
Variations:
You can modify the program to:
- Handle larger arrays dynamically using dynamic memory allocation (with
malloc
). - Reverse only a portion of the array based on user input.
- Implement a function for array reversal to modularize the code.
This program serves as a foundational exercise for understanding array manipulation and control structures in C programming.