1

Take following code as base:

for (int i = 0; i < 26; i++)
{   
    alphabet[i] = (char) ('A'+  i );
}

My question is: -

If 'A' Changes to 'X' how can we achieve the alphabet to reset from the start?

For example XYZABC

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
user1805445
  • 159
  • 1
  • 10
  • Possible hint: http://stackoverflow.com/questions/8981296/rot-13-function-in-java –  Dec 05 '14 at 10:36

2 Answers2

2

You can just insert an if statement:

char startChar = 'X';

for (int i = 0; i < 26; i++) {
    char ch = (char) (startChar + i);
    if (ch > 'Z') {
        ch -= 26;
    }
    alphabet[i] = ch;
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
2

Whenever you have something that should "wrap around", have a look at the modulo operator. The basic idea is: you don't want to count from i=0 to 26, but e.g. from i=23 to 49, but only add the modulo-26 value to it.

Instead of starting to count at 23 (which would be kind of 'X' - 'A'), you can directly integrate this offset into your loop:

for (int i = 0; i < 26; i++)
{   
    alphabet[i] = (char) ('A' + ('X' - 'A' +  i) % 26);
}

'A' is the base, 'X' - 'A' builds that offset where you add i to, and then take the modulo of 26 (as the alphabet has 26 characters), and then add that to your 'A' again.

cello
  • 5,356
  • 3
  • 23
  • 28