C Program to permute the array elements cyclically


March 30, 2022, Learn eTutorial
1312

What is cyclic permutation?

Here is a c program to permute the array elements cyclically. A cyclic permutation is a permutation of the components, which maps the elements of some subset 's' of 'x' to one another in a cyclic manner. Simultaneously, settling (i.e., mapping to themselves) all different components of 'x'. for instance, the permutation of {1, 2, 3, 4} sends 1 to 3, 3 to 2, 2 to 4, and 4 to 1 is a cycle. While the permutation that sends 1 to 3, 3 to 1, 2 to 4, and 4 to 2 is not (it independently permutes the sets {1, 3} and {2, 4}).

The logic of this c program is, first read the limit of the numbers into 'n' and read the numbers into the array 'number[]' using for loop. Then change the position of each element of the array to the next place using for loop. Then display the permuted numbers as the numbers in the array number[] using for loop.

What is the syntax of for loop?. 

The syntax of For loop is:


for (initializationStatement; testExpression; updateStatement)

     {
          // codes
     }

Here the initialization statement is executed only once. Initially, we evaluate the test expression. If the test expression is false, we will terminate the loop. But if the test expression is True, we will execute the for loop statements and increment the expression. This process continues until the test expression is False. The usage of this type of loop is commonly when the number of iterations is already known.

ALGORITHM

STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare some integer variables i, n, and Array number[30].

STEP 3: Read the value of n into 'n'.

STEP 4: Read the numbers into the Array number using for loop.

STEP 5: Assign number[n]=number[0].

STEP 6: By using another for loop with the condition 'i'.

STEP 7: Increment 'i' by 1, and do step 6.

STEP 8: Display 'Cyclically permuted numbers are given below' using printf.

STEP 9: Display the numbers using for loop.

C Source Code

                                          #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]);
}
                                      

OUTPUT

Enter the value of the n = 5
Enter the numbers
10
30
20
45
18

Cyclically permuted numbers are given below
30
20
45
18
10