ICSE Class 12 Computer Science Question 3 of 3

Solved 2017 Practical Paper ISC Computer Science — Question 3

Back to all questions
3
Question

Question 3

Caesar Cipher is an encryption technique which is implemented as ROT13 ('rotate by 13 places'). It is a simple letter substitution cipher that replaces a letter with the letter 13 places after it in the alphabets, with the other characters remaining unchanged.

ROT13

A/aB/bC/cD/dE/eF/fG/gH/hI/iJ/jK/kL/lM/m
N/nO/oP/pQ/qR/rS/sT/tU/uV/vW/wX/xY/yZ/z

Write a program to accept a plain text of length L, where L must be greater than 3 and less than 100.

Encrypt the text if valid as per the Caesar Cipher.

Test your program with the sample data and some random data.

Example 1

INPUT:
Hello! How are you?

OUTPUT:
The cipher text is:
Uryyb! Ubj ner lbh?

Example 2

INPUT:
Encryption helps to secure data.

OUTPUT:
The cipher text is:
Rapelcgvba urycf gb frpher qngn.

Example 3

INPUT:
You

OUTPUT:
INVALID LENGTH

Solution
import java.util.Scanner;

public class CaesarCipher
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter plain text:");
        String str = in.nextLine();
        int len = str.length();
        
        if (len <= 3 || len >= 100) {
            System.out.println("INVALID LENGTH");
            return;
        }
        
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if ((ch >= 'A' && ch <= 'M') || (ch >= 'a' && ch <= 'm')) {
                sb.append((char)(ch + 13));
            }
            else if ((ch >= 'N' && ch <= 'Z') || (ch >= 'n' && ch <= 'z')) {
                sb.append((char)(ch - 13));
            }
            else {
                sb.append(ch);
            }
        }
        
        String cipher = sb.toString();
        System.out.println("The cipher text is:");
        System.out.println(cipher);
    }
}
Output
BlueJ output of CaesarCipher.java
BlueJ output of CaesarCipher.java
BlueJ output of CaesarCipher.java
Answer

import
java.util.Scanner
;
public
class
CaesarCipher
{
public
static
void
main
(
String
args
[]) {
Scanner
in
=
new
Scanner
(
System
.
in);
System
.
out
.
println(
"
Enter plain text:
"
);
String
str
=
in
.
nextLine();
int
len
=
str
.
length();
if
(len
<=
3
||
len
>=
100
) {
System
.
out
.
println(
"
INVALID LENGTH
"
);
return
;
}
StringBuffer
sb
=
new
StringBuffer
();
for
(
int
i
=
0
; i
<
len; i
++
) {
char
ch
=
str
.
charAt(i);
if
((ch
>=
'
A
'
&&
ch
<=
'
M
'
)
||
(ch
>=
'
a
'
&&
ch
<=
'
m
'
)) {
sb
.
append((
char
)(ch
+
13
));
}
else
if
((ch
>=
'
N
'
&&
ch
<=
'
Z
'
)
||
(ch
>=
'
n
'
&&
ch
<=
'
z
'
)) {
sb
.
append((
char
)(ch
-
13
));
}
else
{
sb
.
append(ch);
}
}
String
cipher
=
sb
.
toString();
System
.
out
.
println(
"
The cipher text is:
"
);
System
.
out
.
println(cipher);
}
}
Output