Example:
If the elements of the array are: 10, 5, 16, 35, 500
Then its reverse would be: 500, 35, 16, 5, 10
That is if
array[0] = 10
array[1] = 5
array[2] = 16
array[3] = 35
array[4] = 500
Then after reversing array elements should be
array[0] = 500
array[1] = 35
array[2] = 16
array[3] = 5
array[4] = 10
Required knowledge:
Basic C programming, For Loop, ArrayAlgorithm:
Basic algorithm for reversing any array.Step 1: Take two array say A and B. A will hold the original values and B will hold the reversed values.
Step 2: Read elements in array A.
Step 3: Set i=size - 1, j=0 (Where size is the size of array).
Step 4: Set B[j] = A[i]
Step 5: Set j = j + 1 and i = i - 1.
Step 6: Repeat Step 4-5 till i>=0.
Step 7: Print the reversed array in B.
Program:
/** * C program to find reverse of an array */ #include <stdio.h> int main() { int arr[100], reverse[100]; int size, i, j; /* * Reads the size of array and elements in array */ printf("Enter size of the array: "); scanf("%d", &size); printf("Enter elements in array: "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); } /* * Reverse the array */ j=0; for(i=size-1; i>=0; i--) { reverse[j] = arr[i]; j++; } /* * Prints the reversed array */ printf("\nReversed array : "); for(i=0; i<size; i++) { printf("%d\t", reverse[i]); } return 0; }
Output
Enter size of the array: 5
Enter elements in array: 10 5 16 35 500
Reversed array : 500 35 16 5 10
Enter elements in array: 10 5 16 35 500
Reversed array : 500 35 16 5 10
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to find reverse of any number.
- C program to check whether a number is Palindrome or not.
- C program to find factors of a number.
- C program to find Prime factors of any number.
- C program to find factorial of any number.
- C program to find maximum and minimum element in an array.
- C program to insert an element in an array.
- C program to delete an element from array at specified position.
- C program to delete all duplicate elements from array.
- C program to count frequency of each element of an array.
- C program to sort elements of array in ascending order.
- C program to multiply two matrices.
- C program to check whether two matrices are equal or not.
- C program to find transpose of a matrix.
- C program to print Pascal triangle up to n rows.