Monday, July 8, 2013

Encrypt a 4 digit number by adding 7 to each digit and swapping first with third & 2nd with 4rth digit & Decrypt to original again

Encrypt a 4 digit number in such a way that ,later on Decrypt the number to original number :

1)Your program should read a four-digit integer in such a way that it replaces each digit by(sum of that digit + 7)
2)Swap 2nd digit with 4rth
3)Swap 1st digit with 3rd
4)Print the encrypted number

#include <stdio.h>
int main(void)
{
    int num,dig,mod,total = 0,div = 1000,base = 1000,dig1,dig2,dig3,dig4;
    printf("Enter a 4 digit +ve number to be Encrypted : ");
    scanf("%d",&num);
 
    if ( num > 999 && num <= 9999)
    {
        while ( num != 0)
        {
            dig = num / div + 7;
            total = total * 10 + dig ;
            num = num % base;
            div = div / 10;
            base = base / 10;
         
        }
        printf("Total encrypted number is %d",total);
     
            dig1 = (total/1000);
            dig2 = (total % 1000 / 100);
            dig3 = (total % 100 / 10);
            dig4 = (total % 10);
            printf("\nNew Encrypted number is %d%d%d%d",dig3,dig4,dig1,dig2);
    }
    else
        printf("Please Enter a 4 digit +ve number : ");
 
 
    return 0;
}


Part 2 : Decryption to original number :

#include <stdio.h>
int main(void)
{
    int num,dig1,dig2,dig3,dig4,base = 1000,div = 1000,mod,total = 0;
    printf("\nEnter an Encrypted four digit number : ");
    scanf("%d",&num);


    if ( num > 999 && num <= 9999)
    {
        
        dig1 = num / base ;
        dig2 = (num % base)/100 ;
        dig3 = (num % 100)/10 ;
        dig4 = (num % 10);


        num = dig3*1000+dig4*100+dig1*10+dig2;


        while( num != 0)
        {
            mod = num / base - 7;
            total = total + mod * base;
            base = base / 10;
            num = num % div;
            div = div / 10;
        }
        printf("\nDecrypted number is %d",total);
    }
    else
        printf("\nPlease enter a +ve 4 digit number & try again ");
    return 0;
    

}