Search code examples
cfunctioncodeblocksswapdigits

how to change postition of digits in an integer in c


The problem is as follows: I need to write a function that takes a four digit integer and then encrypts the number in this manner: take each digit and replace it by (c + 7)% 10; and then swap the first digit with the third and the second with the last digit; and then returns the encrypted integer. I have managed to write this much of code thus far:

#include<stdio.h>
#include <stdlib.h>
#define N 100


int encrypt(int a){
  int n=0,i;
  for (i=0;i<4;i++){
    n = a%10;
    a = a/10;
    n = (n+7)%10;
  }
}


void main()
{
  int a;
  printf("Enter the four digit integer: ");
  scanf("%d",&a);
  encrypt(a);
}

I am getting correct output for the conversion but I have no idea how to swap the position of digits.


Solution

  • The easiest solution would be:

    int encrypt(int value) {
    
        int first = value / 1000;
        int second = (value / 100) % 10;
        int third = (value / 10) % 10;
        int fourth = value % 10;
    
        first = (first + 7) % 10;
        second = (second + 7) % 10;
        third = (third + 7) % 10;
        fourth = (fourth + 7) % 10;
    
        return third * 1000 + fourth * 100 + first * 10 + second;
    }