C

Write a C Program To Reverse an Array Using For Loop

In this tutorial, we are going to see how to write a C program to reverse an array using for loop. For example, if ‘arr’ is an array of integers with three elements such as:

arr[0] = 1
arr[1] = 2
arr[2] = 3

Then, by reversing the array we will have:

arr[0] = 3
arr[1] = 2
arr[2] = 1

There are four ways to reverse an array in C, by using for loop, pointers, recursion, or by creating a function.
 

 

Write a C Program To Reverse an Array Using For Loop
#include <stdio.h>

int main()
{
    int nbr, i, j;
    int arr1[100], arr2[100];
    
    printf("Enter the number of elements in the array: ");
    scanf("%d", &nbr);
    
    printf("Enter the elements of the array: ");
    for (i = 0; i < nbr ; i++)
        scanf("%d", &arr1[i]);
    
    //Copy the elements from the end of arr1 to arr2  
    for (i = nbr - 1, j = 0; i >= 0; i--, j++)
        arr2[j] = arr1[i];
    
    //Copy the reversed array 'arr2' into the original array 'arr1'
    for (i = 0; i < nbr; i++)
        arr1[i] = arr2[i];
    
    printf("The reversed array is: ");
    
    for (i = 0; i < nbr; i++)
        printf(" %d", arr1[i]);
    
    return 0;
}

Output:

Enter the number of elements in the array: 3
Enter the elements of the array: 1 2 3       
The reversed array is:  3 2 1

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *