Complementary task for topic: 3
M Nemeth · 2023-08-29 15:21:04.616219'
Arrays: Array Reversal
Arrays: Array Reversal
Write a C program that prompts the user to enter an integer array of size 5 and then reverses the order of the array elements.
Hint: Watch out for the indices! In the second loop you can use one index to traverse (and back traverse), but as in the example, you can use two in one loop!
Solution
#include
#define SIZE 5
int main() {
int numbers[SIZE];
printf("Enter %d integers:\n", SIZE);
for (int i = 0; i < SIZE; i++) {
scanf("%d", &numbers[i]);
}
printf("Original array: ");
for (int i = 0; i < SIZE; i++) {
printf("%d ", numbers[i]);
}
// Reversing the array elements
for (int i = 0, j = SIZE - 1; i < j; i++, j--) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
printf("\nReversed array: ");
for (int i = 0; i < SIZE; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Explanation
n this example, the program declares an integer array numbers of size SIZE, which is set to 5 using the #define directive. The program prompts the user to enter SIZE number of integers using scanf() within a for loop. Each input is stored in the corresponding index of the numbers array. After taking the input, the program displays the original array using printf() and a for loop. Next, the program reverses the order of the array elements using a for loop with two variables i and j. The i variable starts from the first element (index 0), and the j variable starts from the last element (index SIZE-1). The loop iterates until i is less than j. Within the loop, the elements at indices i and j are swapped.