Search code examples
javaalgorithmencryptioncaesar-cipher

Ceaser's Cipher


Here's a Java Code for Ceaser's cipher

import java.util.*;

public class Main {

public static void main(String[] args) {
    Scanner stdin = new Scanner(System.in);
    int length = stdin.nextInt();
    String text = stdin.next();
    int shift = stdin.nextInt();

    for(int i = 0; i < length; i++) {
        char c = text.charAt(i);
        if(c >= 'a' && c <= 'z') {
            System.out.print((char)(((int)c - (int)'a' + shift) % 26 + (int)'a'));
        } else if(c >= 'A' && c <= 'Z') {
            System.out.print((char)(((int)c - (int)'A' + shift) % 26 + (int)'A'));
        } else {
            System.out.print(c);
        }
    }
    stdin.close();
}
}

and i cannot understand what is happening at this line of code

System.out.print((char)(((int)c - (int)'a' + shift) % 26 + (int)'a'));

why do -( int ) ' a '


Solution

  • Its the ASCII values.. letter a has ascii value of 97, A has ascii value of 65.

    I hope you understand how ceaser cipher works.

    if you have ABCD as your original text and you want to do a shift of 1 to apply ceaser cipher, it means A will be B, B will be C, C will be D and D will be E.

    length is your string length, text is your original text, shift is by how many shifts in alphabets you want to apply ceaser cipher.

    Lets take a sample text: abcd

    with shift 1

    for now lets assume c value is 'a'

    so this statement is (int)c - (int)'a' + shift) % 26 + (int)'a')

    will typically do (97-97+1)%26+97

    (1%26)+97
    1+97 
    98
    

    which is ascii equivalent of b. that is why in your code the entire operation is converted to char at the end:

    **(char)**(((int)c - (int)'a' + shift) % 26 + (int)'a')
    

    Hope it makes sense