Question- 

write a c program to print the elements of an array in reverse order.


sample input & output

enter the range - 4

2 4 6 3

After reversing the elements are

3 6 4 2


C program to print the elements of an array in reverse order


Logic to solve

  • Take an array of some integers then take a variable ( n )  for taking the input how many data the user want to enter then run a for loop to taking the inputs . 
  • Again run another for loop but this time make the condition till n/2 because we want to swap this time like from last value to first and the process continue till the half so we take n/2.
  • Take a temp variable and swap the values .
  • Then again run a for loop to displaying the array after reversing.



solve using for loop


Source Code


#include<stdio.h>

int main()

{

    int arr[10],n;


    //to taking the inputs for array

    printf("Enter the range of array :\n");

    scanf("%d",&n);

    for (int i = 0; i < n; i++)

    {

        printf("Enter the data no.  ");

        scanf("%d",&arr[i]);

    }

    

    //to reverse the array

    for (int i = 0; i < n/2; i++)

    {

        int temp;

        temp=arr[i];

        arr[i]=arr[n-1-i]; //arr[n-1-i] is for swapping from last to reverse

        arr[n-1-i]=temp;

    }

    //to show the array 


    printf("After reversing the array :\n");

    for (int i = 0; i < n; i++)

    {

        printf("%d",arr[i]);

    }

    return 0;

}




solve using functions


source code


#include<stdio.h>

//This function is to reverse the array

void reversearr(int arr[],int n)  //function definitions

{

  for (int i = 0; i < n/2; i++)

    {

        int temp;

        temp=arr[i];

        arr[i]=arr[n-1-i]; //arr[n-1-i] is for swapping from last to reverse

        arr[n-1-i]=temp;

    }

}


//this function is to display the array

void display(int arr[],int n)

{

   cout<<"After reversing the array :\n";

   for (int i = 0; i < n; i++)

    {

        printf("%d",arr[i]);

    }

}

int main()

{

    int arr[10],n;


    //to taking the inputs for array

    printf("Enter the range of array :\n");

    scanf("%d",&n);

    for (int i = 0; i < n; i++)

    {

        printf("Enter the data no.  ");

        scanf("%d",&arr[i]);

    }

    reversearr(arr,n); //function call

    display(arr,n); 

    return 0;

}



All array questions for practice in our website must visit 

Also check Out


Also check Out Projects for Resume

    click here

Projects on C++


Projects on C


Problems On C


Problems On C++




FEEDBACK

if still have you any doubts please comment below  we try to solve that