C program to create array with reverse elements of one dimensional array

In this C program, we are going to learn how to create an array with reverse elements of given array? Here, we have an array with some integer elements and we have to create another array by assigning elements of first array in reverse order.
Submitted by IncludeHelp, on March 10, 2018

Given an array with N integer elements, and we have to reverse all elements of given array using C program.

Example:

    Input array elements:
    10, 10, 20, 30, 10

    Output:
    Reversed array is:
    10, 30, 20, 10, 10

Program to create an array with reverse elements of another array in C

/*C program to create array with reverse elements 
of one dimensional array.*/

#include <stdio.h>

//defining -  MAX to declare array
//for maximum of 100 elements
#define MAX 100

int main()
{
	//declaring arrays 'arr' for input array
	//and 'revArr' for output array with reverse elements
	int arr[MAX],revArr[MAX];
	//loop counters
	int i,j
	
	//'n' as number of array elements
	int n;
	
	//read total number of elements
	printf("Enter total number of elements: ");
	scanf("%d",&n);
	
	//read array elements
	printf("Enter array elements:\n");
	for(i=0;i< n;i++)
	{
		printf("Enter element %d: ",i+1);
		scanf("%d",&arr[i]);
	}
	
	//store reverse values of arr into revArr
	for(i=(n-1),j=0; i>=0; i--,j++)
	{
		revArr[j]=arr[i];
	}
	
	printf("\nArray elements after reverse:\n");
	for(i=0;i< n;i++)
	{
		printf("%d\n",revArr[i]);
	}
	
	return 0;
}

Logic:

Consider the given code snippets:

//store reverse values of arr into revArr
for(i=(n-1),j=0; i>=0; i--,j++)
{
	revArr[j]=arr[i];
}

Here, in this loop:

  • There are two loop counters i and j, they are initialised with (n-1) and 0 respectively.
  • Assigning elements from last positions of first array (arr) using arr[i] to the starting of second array (revArr) using revArr[j].
  • Since, i is initialised by (n-1) which is pointing to the last element of the first array and j is initialised by 0 which will point first element/memory block of the second array. And, i is decreasing by 1, j is increasing by 1.
  • By using this logic - second array will be filled by the elements of first array in reverse order.

Output

    Enter total number of elements: 5
    Enter array elements:
    Enter element 1: 10
    Enter element 2: 20
    Enter element 3: 30
    Enter element 4: 40
    Enter element 5: 50

    Array elements after reverse:
    50
    40
    30
    20
    10

C One-Dimensional Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.