C Program to Cyclically Permute the Elements of an Array

Here, we are implementing a C program, which will cyclically permute the elements of an array.
Submitted by Radib Kar, on December 12, 2018

Problem statement

Write a c program to cyclically permute the element of an array. (In right to left direction). Array should be taken as input from the user.

Explanation with example

Let the user input for the array be: 4 5 6 7 8 10 11 34 56 1

The cyclic permutation operation on the array results in rotation of the array by one position in right to left direction.

Thus the array becomes: 5 6 7 8 10 11 34 56 1 4

i.e. the first element becomes the last element & the rest of the elements are shifted by one position.

Algorithm

    To shift the (i+1)th element to the left 
    can be easily done only by:
    A[i] =A[i+1]; // A is the input array

    So it may seem that the entire shifting can be done by
    For i =0:n-1
        A[i] =A[(i+1)%n];
    End For
    
    But this will lead to wrong solution since for i=n-1
    A[n-1]=A[0] which is correct statement but A[0] has been 
    updated already. This code snippet will result in 
    A[0] & A[n-1] to be same which is actually wrong. 

    So what we need to do is to store A[0] ( staring element) 
    and assign this value to A[n-1]

    Thus, a little modification can lead to correct solution:
    1.  Set temp to A[0]
    2.  For i=0:n-1
            If i==n-1
                A[i]=temp; //actually it means A[n-1]=A[0]
            Else
                A[i]=A[i+1];
            End If
        End For

    3.  Print the updated array.

C Implementation for Cyclically Permute the Elements of an Array

#include <stdio.h>
#include <stdlib.h>

//function to print the array
void print(int* a,int n){
	printf("printing ........\n");
	for(int i=0;i<n;i++)
		printf("%d ",a[i]);
	printf("\n");
}

int* cyclicallyPermute(int* a,int n){
	int temp=a[0];//store a[0]

	for(int i=0;i<n;i++){
		//for the last element in the modified array 
		//it will be starting elemnt    
		if(i==n-1) 
			a[i]=temp;
		//for other element shift left    
		else
			a[i]=a[i+1];
	}

	return a;    
}

int main()
{   
	int n;
	
	printf("enter array length,n: ");
	scanf("%d",&n);
	
	//allocating array dynamically
	int* a=(int*)(malloc(sizeof(int)*n));

	printf("enter elements: \n");
	//taking input
	for(int i=0;i<n;i++)
		scanf("%d",&a[i]);

	printf("array before permutation\n");
	print(a,n);
	
	//function to permute cyclically
	//returning base adress of modified array
	a=cyclicallyPermute(a,n);

	printf("array after permutation\n");
	print(a,n);

	return 0;
}

Output

enter array length,n: 10
enter elements:
4 5 6 7 8 10 11 34 56 1
array before permutation
printing ........
4 5 6 7 8 10 11 34 56 1
array after permutation
printing ........
5 6 7 8 10 11 34 56 1 4 

C One-Dimensional Array Programs »

Related Programs



Comments and Discussions!

Load comments ↻





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