This is a C Program to cyclically permutes the elements of an array.
This program first accepts an array. Assume there are 4 elements in an array. It takes 2 element as a first element in an array and so on till the last element of the given array. Now here first element of an array becomes last element in an array during cyclical permutation.
1. Create a one-dimentional array of some fixed size (lets say n), defining all its elements.
2. Reserve the first element of the array by assigning its value to the nth position of the array.
3. Now using for loop from 0 to size-1, with iterator i, each value at (i+1)th position is assigned to the ith position of array.
4. Because the nth position holds the value of 0th position, therefore the last element will have the value which was earlier the first element.
Here is source code of the C program to cyclically permutes the elements of an array. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.
/*
* C program to cyclically permute the elements of an array A.
* i.e. the content of A1 become that of A2. And A2 contains
* that of A3 & so on as An contains A1
*/
#include <stdio.h>
void main ()
{
int i, n, number[30];
printf("Enter the value of the n = ");
scanf("%d", &n);
printf("Enter the numbers\n");
for (i = 0; i < n; ++i)
{
scanf("%d", &number[i]);
}
number[n] = number[0];
for (i = 0; i < n; ++i)
{
number[i] = number[i + 1];
}
printf("Cyclically permuted numbers are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}
1. Create an array of integer of some certain maximum capacity (10, in this case).
2. From users, take a number N as input, which will indicate the number of elements in the array (N < = maximum capacity)
3. Iterating through for loops (from [0 to N) ), take integers as input from user and print them. These input are the elements of the array.
4. Now assign the value of first element of the array at 0th position to the nth position of the array.
5. Starting a for loop, with i as iterator from 0 to size-1, assigning each element at (i+1)th position to ith position, hence each element shifts left by one.
6. And value of last element at (n-1)th position would be assigned a value at nth position. Remember we stored the very first value of array at nth position.
Enter the value of the n = 4 Enter the numbers 3 40 100 68 Cyclically permuted numbers are given below 40 100 68 3
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
- Apply for C Internship
- Check C Books
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Practice Computer Science MCQs