Q:

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

0

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

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to count total number of elements divisi... >>
<< C program to check prime numbers in an array...