ISC Important Programs Questions 2021
ISC Important Programs Questions 2021
Design a program to accept a day number (between 1 and 366), year (in 4 digits) from the user to generate and display the
corresponding date. Also, accept ‘N’ (1 <= N <= 100) from the user to compute and display the future date corresponding to ‘N’
days after the generated date. Display an error message if the value of the day number, year and N are not within the limit or
not according to the condition specified.
Test your program with the following data and some random data:
Example 1
INPUT:
DAY NUMBER: 255
YEAR: 2018
DATE AFTER (N DAYS): 22
OUTPUT:
DATE: 12 TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4 TH OCTOBER, 2018
Example 2
INPUT:
DAY NUMBER: 360
YEAR: 2018
DATE AFTER (N DAYS): 45
OUTPUT:
DATE: 26 TH DECEMBER, 2018
DATE AFTER 45 DAYS: 9 TH FEBRUARY, 2019
Example 3
INPUT:
DAY NUMBER: 500
YEAR: 2018
DATE AFTER (N DAYS): 33
OUTPUT:
DAY NUMBER OUT OF RANGE.
Example 4
INPUT:
DAY NUMBER: 150
YEAR: 2018
DATE AFTER (N DAYS): 330
OUTPUT:
DATE AFTER (N DAYS) OUT OF RANGE.
Programming Code:
1 /**
* The class ISC2019_Q1 inputs a day number, year and number of days after
2
* and prints the current date and the future date
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2019 Question 1
6 */
import java.util.*;
7 class ISC2019_Q1
8 {
9 int isLeap(int y) //function to check for leap year and return max days
10 {
11 if((y%400 == 0) || (y%100 != 0 && y%4 == 0))
return 366;
12 else
13 return 365;
14 }
15
16 String postfix(int n) //function to find postfix of the number
{
17
int r = n%10;
18 if(r == 1 && n != 11)
19 return "ST";
20 else if(r == 2 && n != 12)
21 return "ND";
else if(r == 3 && n != 13)
22 return "RD";
23 else
24 return "TH";
25 }
26
27 void findDate(int d, int y) //function to find the date from day number
{
28 int D[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
29 String MO[] = {"", "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
30 "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"};
31 if(isLeap(y)==366)
{
32 D[2] = 29;
33 }
34 int m = 1;
35 while(d > D[m])
36 {
d = d - D[m];
37 m++;
38 }
39 System.out.println(d+postfix(d)+" "+MO[m]+", "+y);
40 }
41
42 void future(int d, int y, int n) //function to find future date
{
43 int max = isLeap(y);
44 d = d + n;
45 if(d>max)
46 {
d = d - max;
47 y++;
48 }
49 findDate(d,y);
50 }
51
52 public static void main(String args[])
{
53 ISC2019_Q1 ob = new ISC2019_Q1();
54 Scanner sc = new Scanner(System.in);
55 System.out.print("Enter the day number : ");
56 int day = sc.nextInt();
57 System.out.print("Enter the year : ");
int year = sc.nextInt();
58 int max = ob.isLeap(year);
59 if(day > max)
60 {
61 System.out.println("DAY NUMBER OUT OF RANGE");
}
62
else if(year<1000 || year>9999)
63 {
64 System.out.println("YEAR OUT OF RANGE");
65
66
67
68
69
70
71
72
73 }
74 else
{
75
System.out.print("Enter the number of days after : ");
76 int n = sc.nextInt();
77 if(n<1 || n>100)
78 {
79 System.out.println("DATE AFTER (N DAYS) OUT OF RANGE");
}
80 else
81 {
82 System.out.print("DATE :\t\t\t");
83 ob.findDate(day,year);
84 System.out.print("DATE AFTER "+n+" DAYS :\t");
ob.future(day,year,n);
85 }
86 }
87 }
88 }
89
90
91
92
93
94
95
96
Output:
Enter the day number : 360
Enter the year : 2019
Enter the number of days after : 80
DATE : 26TH DECEMBER, 2019
DATE AFTER 80 DAYS : 15TH MARCH, 2020
Question:2
A Prime-Adam integer is a positive integer (without leading zeros) which is a prirne as well as an Adam number.
Prime number : A number which has only two factors, i.e. 1 and the number itself.
Example: 2, 3, 5, 7 …etc.
Adam number: The square of a number and the square of its reverse are reverse to each other.
Exarnple: If n=13 and reverse of ‘n’ =31, then,
(13)2 = 169
(31)2 = 961 which is reverse of 169
thus 13, is an Adam number.
Accept two positive integers m and n, where m is less than n as user input. Display all Prime-Adam integers that are in the
range between m and n (both inclusive) and output them along with the frequency, in the format given below:
Test your program with the following data and some random data:
Example 1
INPUT:
m=5
n=100
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
11 13 31
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3
Example 2
INPUT:
m=100
n=200
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
101 103 113
FREQUENCY OF PRIME-ADAM INTEGERS IS: 3
Example 3
INPUT:
m=50
n=70
OUTPUT:
THE PRIME-ADAM INTEGERS ARE:
NIL
FREQUENCY OF PRIME-ADAM INTEGERS IS: 0
Example 4
INPUT:
m=700
n=450
OUTPUT: INVALID INPUT.
Programming Code:
1 /**
* The class ISC2020_Q1 inputs a lower and an upper range
2 * and prints all the Prime-Adam numbers within that range
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2020 Question 1
6 */
import java.util.*;
7 class ISC2020_Q1 //the main class
8 {
9 boolean isPrime(int n) //to check for prime number
10 {
11 int c = 0;
for(int i=1; i<=n; i++)
12 {
13 if(n%i == 0)
14 {
15 c++;
}
16 }
17 if(c == 2)
18 return true;
19 else
20 return false;
}
21
22
23 int reverseNum(int n) //to reverse a number
24 {
int r = 0, d = 0;
25 while(n > 0)
26 {
27 d = n%10;
28 r = r*10 + d;
n = n/10;
29 }
30 return r;
31 }
32
33 boolean isAdam(int n) //to check for Adam number
34 {
int rev = reverseNum(n);
35 int sqn = n*n;
36 int sqr = rev * rev; //square of reverse
37 int rsqn = reverseNum(sqn); //reverse of square
38 if(rsqn == sqr)
39 return true;
else
40 return false;
41 }
42
43 public static void main(String args[]) //the main method
44 {
Scanner sc = new Scanner(System.in);
45
System.out.print("Enter the lower limit : ");
46 int m = sc.nextInt();
47 System.out.print("Enter the upper limit : ");
48 int n = sc.nextInt();
49
50 ISC2020_Q1 ob = new ISC2020_Q1();
51
if(m<1 || n<1 || m>n) //checking for invalid input
52 {
53 System.out.println("INVALID INPUT");
54 }
55 else
56 {
int c = 0;
57 System.out.println("THE PRIME-ADAM INTEGERS ARE:");
58 for(int i=m; i<=n; i++)
59 {
60 if(ob.isPrime(i) && ob.isAdam(i)) //checking for prime-adam number
{
61 c++;
62 System.out.print(i + "\t");
63 }
64 }
65 if(c == 0)
System.out.print("NIL");
66 System.out.println("\nFREQUENCY OF PRIME-ADAM INTEGERS IS:" + c);
67 }
68 }
69 }
70
71
72
73
74
75
76
77
78
79
80
81
82
Output:
Enter the lower limit : 100
Enter the upper limit : 200
THE PRIME-ADAM INTEGERS ARE:
101 103 113
FREQUENCY OF PRIME-ADAM INTEGERS IS:3
Question:3
The result of a quiz competition is to be prepared as follows:
The quiz has five questions with four multiple choices (A, B, C, D), with each question carrying 1 mark for the correct answer.
Design a program to accept the number of participants N such that N must be greater than 3 and less than 11. Create a double
dimensional array of size (Nx5) to store the answers of each participant row-wise.
Calculate the marks for each participant by matching the correct answer stored in a single dimensional array of size 5. Display
the scores for each participant and also the participant(s) having the highest score.
Note: Array entries are line fed (i.e. one entry per line)
Test your program with the sample data and some random data:
Example 1
INPUT : N = 5
Participant 1 D A B C C
Participant 2 A A D C B
Participant 3 B A C D B
Participant 4 D A D C B
Participant 5 B C A D D
Key: B C D A A
OUTPUT : Scores :
Participant 1 D A B C C
Participant 1 = 0
Participant 2 = 1
Participant 3 = 1
Participant 4 = 1
Participant 5 = 2
Highest score: Participant 5
Example 2
INPUT : N = 4
Participant 1 A C C B D
Participant 2 B C A A C
Participant 3 B C B A A
Participant 4 C C D D B
Key: A C D B B
OUTPUT : Scores :
Participant 1 = 3
Participant 2 = 1
Participant 3 = 1
Participant 4 = 3
Highest score:
Participant 1
Participant 4
Example 3
INPUT : N = 12
OUTPUT : INPUT SIZE OUT OF RANGE.
Programming Code:
1 /**
* The class QuizResult_ISC2017 inputs the answers of each participant row-wise
2 * and calculates the marks for each participant
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2017 Question 2
6 */
7
import java.util.*;
8 class QuizResult_ISC2017
9 {
10 char A[][],K[];
11 int S[],n;
12
13 void input()
{
14 Scanner sc = new Scanner(System.in);
15 System.out.print("Enter number of participants : ");
16 n = sc.nextInt();
17 if(n<4 || n>10)
{
18
System.out.println("INPUT SIZE OUT OF RANGE");
19 System.exit(0);
20 }
21 A = new char[n][5]; // Array to store the answers of every participants
K = new char[5]; // Array to store answer key
22
S = new int[n]; // Array to store score of every participant
23 System.out.println("\n* Enter answer of each participant row-wise in a single line *\n"
24 for(int i = 0; i<n; i++)
25 {
26 System.out.print("Participant "+(i+1)+" : ");
for(int j=0; j<5; j++)
27 {
28 A[i][j] = sc.next().charAt(0);
29 }
30 }
31 System.out.print("\nEnter Answer Key : ");
for(int i = 0; i<5; i++)
32 {
33 K[i] = sc.next().charAt(0);
34 }
35 }
36
void CalcScore() // Function to calculate score of every participant
37 {
38
39 for(int i = 0; i<n; i++)
40 {
41 S[i] = 0;
42 for(int j=0; j<5; j++)
{
43 if(A[i][j] == K[j]) // Checking if Answer of the participants match with the ke
44 {
45 S[i]++;
46 }
47 }
}
48 }
49
50 void printScore()
51 {
52 int max = 0;
System.out.println("\nSCORES : ");
53 for(int i = 0; i<n; i++)
54 {
55 System.out.println("\tParticipant "+(i+1)+" = "+S[i]);
56 if(S[i]>max)
57 {
max = S[i]; // Storing the Highest Score
58 }
59 }
60 System.out.println();
61
62 System.out.println("\tHighest Score : "+max);
63
64 System.out.println("\tHighest Scorers : ");
for(int i = 0; i<n; i++) // Printing all those participant number who got highest score
65 {
66 if(S[i] == max)
67 {
68 System.out.println("\t\t\tParticipant "+(i+1));
}
69
}
70 }
71
72
73
74
75
76
77
78
79
public static void main(String args[])
80 {
81 QuizResult_ISC2017 ob = new QuizResult_ISC2017();
82 ob.input();
83 ob.CalcScore();
ob.printScore();
84
}
85 }
86
87
88
89
90
91
92
93
Output:
Enter number of participants : 4
* Enter answer of each participant row-wise in a single line *
Participant 1 : A C C B D
Participant 2 : B C A A C
Participant 3 : B C B A A
Participant 4 : C C D D B
Enter Answer Key : A C D B B
SCORES :
Participant 1 = 3
Participant 2 = 1
Participant 3 = 1
Participant 4 = 3
Highest Score : 3
Highest Scorers :
Participant 1
Participant 4
Question:4
A company manufactures packing cartons in four sizes, i.e. cartons to accommodate 6 boxes, 12 boxes, 24 boxes and 48
boxes. Design a program to accept the number of boxes to be packed (N) by the user (maximum up to 1000 boxes) and display
the break-up of the cartons used in descending order of capacity (i.e. preference should be given to the highest capacity
available, and if boxes left are less than 6, an extra carton of capacity 6 should be used.)
Test your program with the sample data and some random data:
Example 1
INPUT : N = 726
OUTPUT :
48 x 15 = 720
6 x 1 = 6
Remaining boxes = 0
Total number of boxes = 726
Total number of cartons = 16
Example 2
INPUT : N = 140
OUTPUT :
48 X 2 = 96
24 x 1 = 24
12 x 1 = 12
6 x 1 = 6
Remaining boxes 2 x 1 = 2
Total number of boxes = 140
Total number of cartons = 6
Example 3
INPUT : N = 4296
OUTPUT : INVALID LENGTH
Programming Code:
1 /**
* The class BoxPacking_ISC2017 inputs number of boxes to be packed
2 * and display the break-up of the cartons used in descending order of capacity
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2017 Question 1
6 */
7
import java.util.*;
8 class BoxPacking_ISC2017
9 {
10 public static void main(String args[])
11 {
12 Scanner sc = new Scanner(System.in);
13
System.out.print("Enter number of boxes to be packed : ");
14 int N = sc.nextInt();
15 if(N<1 || N > 1000)
16 {
17 System.out.println("INVALID INPUT");
}
18
else
19 {
20 int cart[] = {48, 24, 12, 6};
21 int copy = N;
22 int totalCart = 0,count = 0;
System.out.println("OUTPUT :");
23 for(int i=0; i<4; i++)
24 {
25 count = N / cart[i];
26 if(count!=0)
27 {
System.out.println("\t"+cart[i]+"\tx\t"+count+"\t= "+cart[i]*count);
28 }
29 totalCart = totalCart + count;
30 N = N % cart[i];
31 }
32
33
34
35
36 if(N>0)
37 {
38 System.out.println("\tRemaining Boxes "+N+" x 1 = "+N);
totalCart = totalCart + 1;
39 }
40 else
41 {
42 System.out.println("\tRemaining Boxes\t\t= 0");
}
43
System.out.println("\tTotal number of boxes = "+copy);
44 System.out.println("\tTotal number of cartons = "+totalCart);
45 }
46 }
47 }
48
49
50
51
Output:
Enter number of boxes to be packed : 815
OUTPUT :
48 x 16 = 768
24 x 1 = 24
12 x 1 = 12
6 x 1 = 6
Remaining Boxes 5 x 1 = 5
Total number of boxes = 815
Total number of cartons = 20
Question:5
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.
Write a program to accept a plain text of length L, where L must be greater than 3 and less than 100.
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
Programming Code:
1 /**
* The class CaesarCipher_ISC2017 inputs a sentence and encrypts it by shifting
2 * every alphabet 13 places ahead in a circular fashion
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2017 Question 3
6 */
import java.util.*;
7 class CaesarCipher_ISC2017
8 {
9 void rot13(String w)
10 {
11 char ch;
int a = 0;
12 String ans = "";
13 for(int i = 0; i<w.length(); i++)
14 {
15 ch = w.charAt(i);
if(Character.isLetter(ch))
16 {
17 a = ch + 13;
18
19 if((Character.isUpperCase(ch) && a>90) || (Character.isLowerCase(ch) && a>122))
20 {
21 a = a - 26;
}
22 ch = (char)a;
23 }
24 ans = ans + ch;
25 }
26 System.out.println("OUTPUT : The cipher text is :\n"+ans);
}
27
28 public static void main(String args[])
29 {
30 CaesarCipher_ISC2017 ob = new CaesarCipher_ISC2017();
31 Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence : ");
32
String s = sc.nextLine();
33 int L = s.length();
34 if(L<4 || L>99)
35 {
36 System.out.println("INVALID LENGTH");
}
37 else
38 {
39 ob.rot13(s);
40 }
41 }
}
42
43
44
45
46
47
48
49
50
Output:
Enter a sentence :- Encryption helps to secure data.
OUTPUT :- The cipher text is :
Rapelcgvba urycf gb frpher qngn.
Question:6
Write a program to declare a square matrix A[][] of order (M x M) where ‘M’ must be greater than 3 and less than 10. Allow the
user to input positive integers into this matrix. Perform the following tasks on the matrix:
(a) Sort the boundary elements in descending order using any standard sorting technique and rearrange them in the matrix.
(b) Calculate the sum of the boundary elements.
(c) Display the original matrix, rearranged matrix and sum of the boundary elements.
Test your program with the sample data and some random data:
Example 1
INPUT :M = 4
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
OUTPUT:
ORIGINAL MATRIX
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
REARRANGED MATRIX
23 15 12 11
1 13 8 9
2 6 3 8
4 5 7 8
The sum of boundary elements is = 105
Programming Code:
1 /**The class SortBoundary, sorts the boundary elements of a 2-D square matrix in descending or
* It also finds the sum of the boundary elements
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class SortBoundary
{
8 int A[][], B[], m, n;
9 static int sum=0;
10
11 void input() //Function for taking all the necessary inputs
{
12 Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the square matrix : ");
13
m=sc.nextInt();
14 if(m<4 || m>10)
15 {
16 System.out.println("Invalid Range");
17 System.exit(0);
}
18 else
19 {
20 A = new int[m][m];
21 n = m*m;
22 B = new int[n]; // 1-D Array to store Boundary Elements
23
System.out.println("Enter the elements of the Matrix : ");
24 for(int i=0;i<m;i++)
25 {
26 for(int j=0;j<m;j++)
27 {
System.out.print("Enter a value : ");
28 A[i][j]=sc.nextInt();
29 }
30 }
31 }
32 }
33
/* The below function is used to store Boundary elements
34 * from array A[][] to array B[]
35 */
36 void convert()
37 {
38 int x=0;
for(int i=0;i<m;i++)
39 {
40 for(int j=0;j<m;j++)
41 {
42 if(i == 0 || j == 0 || i == m-1 || j == m-1) // Condition for boundary elements
{
43 B[x] = A[i][j];
44 x++;
45 sum = sum + A[i][j]; // Finding sum of boundary elements
46 }
47 }
}
48 }
49
50 void sortArray() //Function for sorting Boundary elements stored in array B[]
51 {
52 int c = 0;
for(int i=0; i<n-1; i++)
53
{
54 for(int j=i+1; j<n; j++)
55 {
56 if(B[i]<B[j]) // for ascending use B[i]>B[j]
57 {
c = B[i];
58 B[i] = B[j];
59 B[j] = c;
60 }
61 }
62 }
}
63
64
/* Function fillSpiral is filling the boundary of 2-D array in spiral
65 * way from the elements of 1-D array
66 */
67 void fillSpiral()
68 {
int R1=0, R2=m-1, C1=0, C2=m-1, x=0;
69
70
for(int i=C1;i<=C2;i++) // accessing the top row
71 {
72 A[R1][i]=B[x++];
73 }
74 for(int i =R1+1;i<=R2;i++) // accessing the right column
{
75 A[i][C2]=B[x++];
76 }
77 for(int i =C2-1;i>=C1;i--) // accessing the bottom row
78 {
A[R2][i]=B[x++];
79
}
80 for(int i =R2-1;i>=R1+1;i--) // accessing the left column
81 {
82 A[i][C1]=B[x++];
83 }
}
84
85
void printArray() //Function for printing the array A[][]
86 {
87 for(int i=0;i<m;i++)
88 {
89 for(int j=0;j<m;j++)
{
90 System.out.print(A[i][j]+"\t");
91 }
92 System.out.println();
93 }
}
94
95
public static void main(String args[])
96 {
97 SortBoundary ob = new SortBoundary();
98 ob.input();
99 System.out.println("*********************");
System.out.println("The original matrix:");
100 System.out.println("*********************");
101 ob.printArray(); //Printing the original array
102 ob.convert(); //Storing Boundary elements to a 1-D array
103 ob.sortArray(); //Sorting the 1-D array (i.e. Boundary Elements)
104 ob.fillSpiral(); //Storing the sorted Boundary elements back to original 2-D array
105
System.out.println("*********************");
106 System.out.println("The Rearranged matrix:");
107 System.out.println("*********************");
108 ob.printArray(); //Printing the rearranged array
109 System.out.println("*********************");
System.out.println("The sum of boundary elements is = "+sum); //Printing the sum of bo
110 }
111 }
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
See:
How to access Boundary Elements.
How to fill in a spiral format.
Output:
Enter the size of the square matrix : 4
Enter the elements of the Matrix :
Enter a value : 9
Enter a value : 2
Enter a value : 1
Enter a value : 5
Enter a value : 8
Enter a value : 13
Enter a value : 8
Enter a value : 4
Enter a value : 15
Enter a value : 6
Enter a value : 3
Enter a value : 11
Enter a value : 7
Enter a value : 12
Enter a value : 23
Enter a value : 8
*********************
The original matrix:
*********************
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
*********************
The Rearranged matrix:
*********************
23 15 12 11
1 13 8 9
2 6 3 8
4 5 7 8
*********************
The sum of boundary elements is = 105
[Question 3] ISC 2016 Computer Practical Paper Solved – Words Beginning and
Ending with Vowel
Question:7
Write a program to accept a sentence which may be terminated by either’.’, ‘?’or’!’ only. The words may be separated by more
than one blank space and are in UPPER CASE.
(a) Find the number of words beginning and ending with a vowel.
(b) Place the words which begin and end with a vowel at the beginning, followed by the remaining words as they occur in the
sentence.
Test your program with the sample data and some random data:
Example 1
INPUT: ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.
OUTPUT: NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL= 3
ANAMIKA ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL
Example 2
INPUT: YOU MUST AIM TO BE A BETTER PERSON TOMORROW THAN YOU ARE TODAY.
OUTPUT: NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL= 2
A ARE YOU MUST AIM TO BE BETTER PERSON TOMORROW THAN YOU TODAY
Example 3
INPUT: LOOK BEFORE YOU LEAP.
OUTPUT: NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL= 0
LOOK BEFORE YOU LEAP
Example 4
INPUT: HOW ARE YOU@
OUTPUT: INVALID INPUT
Programming Code:
1 /**
* The class ISC2016_Q3 inputs a sentence, and prints and counts the words
2
* beginning and ending with a vowel, before other words
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2016 Question 3
*/
6
7
import java.util.*;
8 class ISC2016_Q3
9 {
10 boolean isVowel(String w) // Function to check if a word begins and ends with a vowel or no
11 {
int l = w.length();
12 char ch1 = w.charAt(0); // Storing the first character
13 char ch2 = w.charAt(l-1); // Storing the last character
14 if((ch1=='A' || ch1=='E' || ch1=='I' || ch1=='O' || ch1=='U') &&
15 (ch2=='A' || ch2=='E' || ch2=='I' || ch2=='O' || ch2=='U'))
16 {
return true;
17 }
18 else
19 {
20 return false;
}
21 }
22
23 public static void main(String args[])
24 {
25 ISC2016_Q3 ob = new ISC2016_Q3();
26 Scanner sc = new Scanner(System.in);
27
System.out.print("Enter a sentence : ");
28 String s = sc.nextLine();
29 s = s.toUpperCase();
30 int l = s.length();
31 char last = s.charAt(l-1); // Extracting the last character
32
33 /* Checking whether the sentence ends with '.' or '?' or not */
if(last != '.' && last != '?' && last != '!')
34 {
35 System.out.println("Invalid Input. End a sentence with either '.', '?' or '!' only"
36 }
37 else
{
38 StringTokenizer str = new StringTokenizer(s," .?!");
39 int x = str.countTokens();
40 int c = 0;
41 String w = "", a = "", b = "";
42
43 for(int i=1; i<=x; i++)
{
44 w = str.nextToken(); // Extracting words and saving them in w
45
46 if(ob.isVowel(w))
47 {
48 c++; // Counting all words beginning and ending with a vowel
a = a + w + " "; // Saving all words beginning and ending with a vowel in v
49
}
50 else
51 b = b + w + " "; // Saving all other words in variable 'b'
52 }
53 System.out.println("OUTPUT : \nNUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL =
System.out.println(a+b);
54
55
56
57
58
59
60
61 }
62 }
63 }
64
65
66
67
68
Output:
Enter a sentence : ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.
OUTPUT :
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 3
ANAMIKA ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL
Question:8
Write a program to declare a square matrix A[][] of order (M x M) where ‘M’ must be greater than 3 and less than 10. Allow the
user to input positive integers into this matrix. Perform the following tasks on the matrix:
(a) Sort the non-boundary elements in ascending order using any standard sorting technique and rearrange them in the matrix.
(b) Calculate the sum of both the diagonals.
(c) Display the original matrix, rearranged matrix and only the diagonal elements of the rearranged matrix with their sum.
Test your program with the sample data and some random data:
Example 1
INPUT :M = 4
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
OUTPUT:
ORIGINAL MATRIX
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
REARRANGED MATRIX
9 2 1 5
8 3 6 4
15 8 13 11
7 12 23 8
DIAGONAL ELEMENTS
9 5
3 6
8 13
7 8
SUM OF THE DIAGONAL ELEMENTS = 59
Programming Code:
1 /**
* The class SortNonBoundary_ISC2016 inputs a square matrix and
2
* sorts the non-boundary elements in ascending order
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2016 Question 2
6 */
7
import java.util.*;
8 class SortNonBoundary_ISC2016
9 {
10 int A[][],B[],m,n;
11
12 void input() //Function for taking all the necessary inputs
13 {
Scanner sc = new Scanner(System.in);
14 System.out.print("Enter the size of the square matrix : ");
15 m=sc.nextInt();
16 if(m<4 || m>10)
17 {
System.out.println("Invalid Range");
18 System.exit(0);
19 }
20 else
21 {
22 A = new int[m][m];
n = (m-2)*(m-2);
23 B = new int[n]; //Array to store Non-Boundary Elements
24
25 System.out.println("Enter the elements of the Matrix : ");
26 for(int i=0;i<m;i++)
27 {
28 for(int j=0;j<m;j++)
{
29 System.out.print("Enter a value : ");
30 A[i][j]=sc.nextInt();
31 }
32 }
}
33 }
34
35 /* The below function stores Non-Boundary elements
36 * from array A[][] to array B[] if s = 1
37 * else stores the Non-Boundary elements in array A[][] from array B[]
38 */
void convert(int s)
39 {
40 int x=0;
41 for(int i=0;i<m;i++)
42 {
for(int j=0;j<m;j++)
43
{
44 if(i != 0 && j != 0 && i != m-1 && j != m-1)
45 {
46 if(s==1)
47 B[x] = A[i][j];
48 else
A[i][j] = B[x];
49
x++;
50 }
51 }
52 }
53 }
54
void sortArray() //Function for sorting Non-Boundary elements stored in array B[]
55 {
56 int c = 0;
57 for(int i=0; i<n-1; i++)
58 {
59 for(int j=i+1; j<n; j++)
{
60 if(B[i]>B[j])
61 {
62 c = B[i];
63 B[i] = B[j];
B[j] = c;
64 }
65 }
66 }
67 }
68
69 void printArray() //Function for printing the array A[][]
{
70 for(int i=0;i<m;i++)
71 {
72 for(int j=0;j<m;j++)
73 {
74 System.out.print(A[i][j]+"\t");
}
75 System.out.println();
76 }
77 }
78
79 void printDiagonal() //Function for printing the diagonal elements and their sum
{
80 int sum = 0;
81 for(int i=0;i<m;i++)
82 {
83 for(int j=0;j<m;j++)
84 {
if(i==j || (i+j)==m-1)
85 {
86 System.out.print(A[i][j]+"\t");
87 sum = sum + A[i][j];
88 }
else
89
System.out.print("\t");
90 }
91 System.out.println();
92 }
93 System.out.println("Sum of the Diagonal Elements : "+sum);
}
94
95
public static void main(String args[])
96 {
97 SortNonBoundary_ISC2016 ob = new SortNonBoundary_ISC2016();
98
99
100
101
102
103
104
105
106
107
108
109 ob.input();
110 System.out.println("*********************");
System.out.println("The original matrix:");
111 System.out.println("*********************");
112 ob.printArray(); //Printing the original array
113 ob.convert(1); //Storing Non-Boundary elements to a 1-D array
114 ob.sortArray(); //Sorting the 1-D array (i.e. Non-Diagonal Elements)
115 ob.convert(2); //Storing the sorted Non-Boundary elements back to original 2-D array
116
System.out.println("*********************");
117 System.out.println("The Rearranged matrix:");
118 System.out.println("*********************");
119 ob.printArray(); //Printing the rearranged array
120 System.out.println("*********************");
System.out.println("The Diagonal Elements:");
121 System.out.println("*********************");
122 ob.printDiagonal(); //Printing the diagonal elements and their sum
123 }
124 }
125
126
127
128
129
130
131
132
133
134
135
Output:
Enter the size of the square matrix : 4
Enter the elements of the Matrix :
Enter a value : 9
Enter a value : 2
Enter a value : 1
Enter a value : 5
Enter a value : 8
Enter a value : 13
Enter a value : 8
Enter a value : 4
Enter a value : 15
Enter a value : 6
Enter a value : 3
Enter a value : 11
Enter a value : 7
Enter a value : 12
Enter a value : 23
Enter a value : 8
*********************
The original matrix:
*********************
9 2 1 5
8 13 8 4
15 6 3 11
7 12 23 8
*********************
The Rearranged matrix:
*********************
9 2 1 5
8 3 6 4
15 8 13 11
7 12 23 8
*********************
The Diagonal Elements:
*********************
9 5
3 6
8 13
7 8
Sum of the Diagonal Elements : 59
Question:9
A Circular Prime is a prime number that remains prime under cyclic shifts of its digits. When the leftmost digit is removed and
replaced at the end of the remaining string of digits, the generated number is still prime. The process is repeated until the
original number is reached again.
A number is said to be prime if it has only two factors I and itself.
Example:
131
311
113
Hence, 131 is a circular prime.
Test your program with the sample data and some random data:
Example 1
INPUT :N = 197
OUTPUT:
197
971
719
197 IS A CIRCULAR PRIME
Example 2
INPUT :N = 1193
OUTPUT:
1193
1931
9311
3119
1193 IS A CIRCULAR PRIME
Example 3
INPUT :N = 29
OUTPUT:
29
92
29 IS NOT A CIRCULAR PRIME
Programming Code:
1 /**
* The class CircularPrime_Q1_ISC2016 inputs a number and
2 * checks whether it is a Circular Prime or not
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2016 Question 1
6 */
7
import java.util.*;
8 class CircularPrime_Q1_ISC2016
9 {
10 boolean isPrime(int n) // Function for checking whether a number is prime or not
11 {
12 int c = 0;
for(int i = 1; i<=n; i++)
13 {
14 if(n%i == 0)
15 c++;
16 }
if(c == 2)
17 return true;
18 else
19 return false;
20 }
21
22 int circulate(int n) //Function for circulating the digits to form new number
{
23 String s = Integer.toString(n);
24 String p = s.substring(1)+s.charAt(0);
25 int a = Integer.parseInt(p);
26 return a;
27 }
28
void isCircularPrime(int n) //Function to check for circular prime
29 {
30 int f = 0,a = n;
31 do
32 {
System.out.println(a);
33
if(isPrime(a)==false)
34 {
35 f = 1;
36 break;
37 }
a = circulate(a);
38 }while(a!=n);
39
40 if(f==1)
41 System.out.println(n+" IS NOT A CIRCULAR PRIME");
42 else
43 System.out.println(n+" IS A CIRCULAR PRIME");
}
44
45
46
47
48
49
50
public static void main(String args[])
51 {
52 CircularPrime_Q1_ISC2016 ob = new CircularPrime_Q1_ISC2016();
53 Scanner sc = new Scanner(System.in);
54 System.out.print("Enter a number : ");
55 int n = sc.nextInt();
ob.isCircularPrime(n);
56 }
57 }
58
59
60
61
62
Output:
Enter a number : 87
87
87 IS NOT A CIRCULAR PRIME
Enter a number : 1193
1193
1931
9311
3119
1193 IS A CIRCULAR PRIME
Enter a number : 123
123
231
312
123 IS NOT A CIRCULAR PRIME
Question:10
Write a program to accept the year, month and the weekday name of the 1st day of that month and generate its calendar.
Example :
INPUT :
Year : 2016
Month : February
1st day of February : Monday
OUTPUT :
---------------------------------
February 2016
---------------------------------
SUN MON TUE WED THU FRI SAT
---------------------------------
1 2 3 4 5 6
---------------------------------
7 8 9 10 11 12 13
---------------------------------
14 15 16 17 18 19 20
---------------------------------
21 22 23 24 25 26 27
---------------------------------
28 29
---------------------------------
Programming Code:
1 /**
* The class CalendarProgram inputs a year, month and the weekday name
2
* of the 1st day of that month and generates its calendar
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 */
6
7 import java.util.*;
class CalendarProgram
8 {
9 //Function to match the given month and return its maximum days
10 int findMaxDay(String mname, int y)
11 {
12 String months[] = {"","January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
13 int D[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
14
15 if((y%400==0) || ((y%100!=0)&&(y%4==0)))
16 {
17 D[2]=29;
}
18
int max = 0;
19 for(int i=1; i<=12; i++)
20 {
21 if(mname.equalsIgnoreCase(months[i]))
22 {
max = D[i]; //Saving maximum day of given month
23 }
24 }
25 return max;
26 }
27
28 //Function to match the given weekday name and return its weekday no.
int findDayNo(String wname)
29 {
30 String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
31 "Saturday"};
32 int f = 0;
for(int i=0; i<7; i++)
33
{
34 if(wname.equalsIgnoreCase(days[i]))
35 {
36 f = i; //Saving week day no. given day (e.g. '0' for Sunday)
37 }
}
38 return f;
39 }
40
41 //Function for creating the calendar
42 void fillCalendar(int max, int f, String mname, int y)
43 {
int A[][] = new int[6][7];
44 int x = 1, z = f;
45
46
47 for(int i=0;i<6;i++)
48 {
for(int j=f; j<7; j++)
49 {
50 if(x<=max)
51 {
52 A[i][j] = x;
x++;
53 }
54 }
55 f = 0;
56 }
57
58 for(int j=0; j<z; j++) //Adjustment to bring last (6th) row elements to first row
{
59 A[0][j]=A[5][j];
60 }
61
62 printCalendar(A, mname, y); //Calling function to print the calendar
63 }
64
65 //Function for printing the calendar
void printCalendar(int A[][], String mname, int y)
66 {
67 System.out.println("\n\t----------------------------------------------------");
68 System.out.println("\t\t\t "+mname+" "+y);
69 System.out.println("\t----------------------------------------------------");
70 System.out.println("\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSAT");
System.out.println("\t----------------------------------------------------");
71
72 for(int i = 0; i < 5; i++)
73 {
74 for(int j = 0; j < 7; j++)
75 {
if(A[i][j]!=0)
76 System.out.print("\t "+A[i][j]);
77 else
78 System.out.print("\t ");
79 }
80 System.out.println("\n\t----------------------------------------------------");
}
81 }
82
83 public static void main(String args[])
84 {
85 CalendarProgram ob = new CalendarProgram();
86 Scanner sc = new Scanner(System.in);
System.out.print("Enter the year : ");
87 int y = sc.nextInt();
88 System.out.print("Enter the month name (e.g. January) : ");
89 String mname = sc.next();
90 System.out.print("Enter the week day name (e.g. Sunday) of 1st day of "+mname+" : ");
String wname = sc.next();
91
92
int max = ob.findMaxDay(mname,y);
93 int f = ob.findDayNo(wname);
94 ob.fillCalendar(max,f,mname,y);
95 }
96
97
98
99
100
101
102
103
104 }
105
106
107
108
109
110
111
112
113
Output:
Enter the year : 2016
Enter the month name (e.g. January) : October
Enter the week day name (e.g. Sunday) of 1st day of October : Saturday
---------------------------------
October 2016
---------------------------------
SUN MON TUE WED THU FRI SAT
---------------------------------
30 31 1
---------------------------------
2 3 4 5 6 7 8
---------------------------------
9 10 11 12 13 14 15
---------------------------------
16 17 18 19 20 21 22
---------------------------------
23 24 25 26 27 28 29
---------------------------------
Question:11
Accept a paragraph of text consisting of sentences that are terminated by either ‘.’ (full stop), ‘!’ (exclamation mark) or a ‘?’
(question mark). Assume that there can be maximum 10 sentences in a paragraph. Write a program to arrange the sentences in
increasing order of their number of words.
Example :
INPUT : Please come and attend the party. Hello! How are you?
OUTPUT :
Hello = 1
How are you = 3
Please come and attend the party = 6
Programming Code:
1 /**
* The class sortParagraph inputs a paragraph and arranges the
2 * sentences in ascending order of their number of words
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
*/
5
6
import java.util.*;
7 class sortParagraph
8 {
9 // Function to count no. of words in every sentence
10 int countWords(String s)
{
11 StringTokenizer str = new StringTokenizer(s," .,?!");
12 int c = str.countTokens();
13 return c;
14 }
15
16 // Function to sort the sentences in ascending order of their no. of words
void sort(String w[], int p[])
17 {
18 int n = w.length, t1 = 0;
19 String t2 = "";
20
21 for(int i=0; i<n-1; i++)
22 {
for(int j=i+1; j<n; j++)
23 {
24 if(p[i]>p[j]) // for descending use p[i]<p[j]
25 {
26 t1 = p[i];
p[i] = p[j];
27 p[j] = t1;
28 t2 = w[i];
29 w[i] = w[j];
30 w[j] = t2;
31 }
}
32 }
33 printResult(w,p); // Calling function for printing the result
34 }
35
36 void printResult(String w[], int p[]) // Function to print the final result
37 {
int n = w.length;
38 for(int i=0; i<n; i++)
39 {
40 System.out.println(w[i]+"\t=\t"+p[i]);
41 }
}
42
43
public static void main(String args[])
44 {
45 sortParagraph ob = new sortParagraph();
46 Scanner sc = new Scanner(System.in);
47
48 System.out.print("Enter a paragraph : "); //Inputting a paragraph
String pg = sc.nextLine();
49
50
StringTokenizer str = new StringTokenizer(pg,".?!");
51 int count = str.countTokens(); //Counting no. of sentences in the paragraph
52 if(count > 10)
53 System.out.println("A maximum of 10 sentences are allowed in the paragraph");
54 else
55 {
56 String sent[] = new String[count]; //Array to store the sentences separately
57 int p[] = new int[count]; //Array to store no. of words of each sentence
58
59 for(int i=0; i<count; i++)
{
60 sent[i] = str.nextToken().trim(); // Saving sentences one by one in an array
61 p[i] = ob.countWords(sent[i]); // Saving no. of words of every sentence
62 }
63 ob.sort(sent,p);
64 }
}
65 }
Output:
Enter a paragraph : Please come and attend the party. Hello! How are you?
OUTPUT :
Hello = 1
How are you = 3
Please come and attend the party = 6
Question:12
Write a Program in Java to input a number and check whether it is a Bouncy Number or not.
Increasing Number : Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for
example, 22344.
Decreasing Number : Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example,
774410.
Bouncy Number : We shall call a positive integer that is neither increasing nor decreasing a “bouncy” number; for example,
155349. Clearly there cannot be any bouncy numbers below 100.
Solution:
1 /**
* The class BouncyNumber inputs a number and checks whether it is a Bouncy Number or not
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class BouncyNumber
{
8 boolean isIncreasing(int n) //Function to check whether a number is Increasing
9 {
10 String s = Integer.toString(n);
11 char ch;
12 int f = 0;
for(int i=0; i<s.length()-1; i++)
13 {
14 ch = s.charAt(i);
15 if(ch>s.charAt(i+1))// If any digit is more than next digit then we have to stop ch
16 {
f = 1;
17 break;
18 }
19 }
20 if(f==1)
21 return false;
else
22
23
24
25
26
27
28 return true;
}
29
30 boolean isDecreasing(int n) //Function to check whether a number is Decreasing
31 {
32 String s = Integer.toString(n);
33 char ch;
34 int f = 0;
for(int i=0; i<s.length()-1; i++)
35 {
36 ch = s.charAt(i);
37 if(ch<s.charAt(i+1))// If any digit is less than next digit then we have to stop ch
38 {
f = 1;
39 break;
40 }
41 }
42 if(f==1)
43 return false;
else
44 return true;
45 }
46
47 void isBouncy(int n)
48 {
49 if(isIncreasing(n)==true)
System.out.println("The number " + n + " is Increasing and Not Bouncy");
50 else if(isDecreasing(n)==true)
51 System.out.println("The number " + n + " is Decreasing and Not Bouncy");
52 else
53 System.out.println("The number " + n + " is bouncy");
}
54
55
public static void main(String args[])
56 {
57 Scanner sc = new Scanner(System.in);
58 BouncyNumber ob = new BouncyNumber();
59 System.out.print("Enter a number : ");
int n = sc.nextInt();
60 ob.isBouncy(n);
61 }
62 }
63
64
65
66
67
68
Output:
Enter a number : 22344
The number 22344 is Increasing and Not Bouncy
Enter a number : 774410
The number 774410 is Decreasing and Not Bouncy
Enter a number : 155349
The number 155349 is bouncy
Question:13
Given a square matrix M [ ] [ ] of order ‘n’. The maximum value possible for ‘n’ is 10. Accept three different characters from the
keyboard and fill the array according to the instruction given below.
Fill the upper and lower elements formed by the intersection of the diagonals by character 1.
Fill the left and right elements formed by the intersection of the diagonals by character 2.
Fill both the diagonals by character 3.
Output the result in format given below:
Example 1
ENTER SIZE : 4
INPUT : FIRST CHARACTER : ‘*’
SECOND CHARACTER : ‘?’
THIRD CHARACTER : ‘#’
OUTPUT :
# * * #
? # # ?
? # # ?
# * * #
Example 2
ENTER SIZE : 5
INPUT : FIRST CHARACTER : ‘$’
SECOND CHARACTER : ‘!’
THIRD CHARACTER : ‘@’
OUTPUT :
@ $ $ $ @
! @ $ @ !
! ! @ ! !
! @ $ @ !
@ $ $ $ @
Example 3
ENTER SIZE : 65
OUTPUT : SIZE OUT OF RANGE
Programming Code:
1 /**
* The class MatrixFill creates a matrix using 3 characters taken as inputs
2 * Upper and lower elements formed by the intersection of the diagonals are filled by character
3 * Left and right elements formed by the intersection of the diagonals are filled by character 2
4 * Both the diagonals are filled by character 3.
5 * @author : www.guideforschool.com
6 * @Program Type : BlueJ Program - Java
* @ISC Computer Science Practical Specimen Paper - Question 2
7 */
8
9 import java.util.*;
10 class MatrixFill
11 {
12 public static void main(String args[])
{
13 Scanner sc = new Scanner(System.in);
System.out.print("Enter size of the matrix : ");
14
int n = sc.nextInt();
15
16 if(n<2 || n>10)
17 System.out.println("Size out of Range");
18 else
19 {
char A[][]=new char[n][n];
20 System.out.print("Enter the 1st character : ");
21 char c1 = sc.next().charAt(0);
22 System.out.print("Enter the 2nd character : ");
23 char c2 = sc.next().charAt(0);
24 System.out.print("Enter the 3rd character : ");
char c3 = sc.next().charAt(0);
25
26 for(int i=0; i<n; i++)
27 {
28 for(int j=0; j<n; j++)
29 {
30 if(i==j || (i+j)==(n-1))
A[i][j] = c3; // Filling the diagonals with 3rd character
31 else
32 A[i][j] = c2; // Filling all other positions with 2nd character
33 }
34 }
35
for(int i=0; i<n/2; i++)
36
{
37 for(int j=i+1; j<n-1-i; j++)
38 {
39 A[i][j] = c1; // Filling the upper positions formed by intersection of diag
40 A[n-1-i][j] = c1; // Filling the lower positions formed by intersection of
}
41 }
42
43 // Printing the Matrix
44 System.out.println("\nOutput : \n");
45 for(int i=0; i<n; i++)
46 {
for(int j=0; j<n; j++)
47 {
48 System.out.print(A[i][j]+" ");
49 }
50 System.out.println();
}
51
}
52 }
53 }
54
55
56
57
58
59
60
61
62
63
64
Output:
Enter size of the matrix : 7
Enter the 1st character : @
Enter the 2nd character : #
Enter the 3rd character : %
Output :
% @ @ @ @ @ %
# % @ @ @ % #
# # % @ % # #
# # # % # # #
# # % @ % # #
# % @ @ @ % #
% @ @ @ @ @ %
Question:14
The encryption of alphabets are to be done as follows:
A = 1
B = 2
C = 3
.
.
.
Z = 26
The potential of a word is found by adding the encrypted value of the alphabets.
Example: KITE
Potential = 11 + 9 + 20 + 5 = 45
Accept a sentence which is terminated by either “ . ” , “ ? ” or “ ! ”. Each word of sentence is separated by single space. Decode
the words according to their potential and arrange them in ascending order.
Example 1
INPUT : THE SKY IS THE LIMIT.
POTENTIAL : THE = 33
SKY = 55
IS = 28
THE = 33
LIMIT = 63
OUTPUT : IS THE THE SKY LIMIT
Example 2
INPUT : LOOK BEFORE YOU LEAP.
POTENTIAL : LOOK = 53
BEFORE = 51
YOU = 61
LEAP = 34
OUTPUT : LEAP BEFORE LOOK YOU
Programming Code:
1 /**
* The class WordPotential inputs a sentence and arranges the words
2
* in ascending order of their potential
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @ISC Computer Science Practical Specimen Paper - Question 2
6 */
7
import java.util.*;
8 class WordPotential
9 {
10 int findPotential(String s) // Function to find potential of a word
11 {
12 s = s.toUpperCase();
int p = 0, l = s.length();
13 char ch;
14 for(int i=0; i<l; i++)
15 {
16 ch = s.charAt(i);
p = p + (ch-64); // if ch = 'A', then 'A'-64 = ASCII value of 'A' - 64 = 65-64 = 1
17 }
18 return p;
19 }
20
21 // Function to sort the words in ascending order of their potential
22 void sortPotential(String w[], int p[])
{
23 int n = w.length, t1 = 0;
24 String t2 = "";
25
26 for(int i=0; i<n-1; i++)
27 {
28 for(int j=i+1; j<n; j++)
{
29 if(p[i]>p[j])
30 {
31 t1 = p[i];
32 p[i] = p[j];
p[j] = t1;
33
t2 = w[i];
34 w[i] = w[j];
35 w[j] = t2;
36 }
37 }
}
38
39 printResult(w,p);
40 }
41
42 void printResult(String w[], int p[]) // Function to print the final result
43 {
44 int n = w.length;
String ans = "";
45 for(int i=0; i<n; i++)
46 {
47 ans = ans + " " + w[i];
48
49
50
51
52
53
54
55 }
ans = ans.trim();
56 System.out.println("\nOutput\t\t : \t"+ans);
57 }
58
59 public static void main(String args[])
60 {
61 WordPotential ob = new WordPotential();
Scanner sc = new Scanner(System.in);
62
63 System.out.print("Enter a sentence : \t");
64 String s = sc.nextLine();
65
66 StringTokenizer str = new StringTokenizer(s," .,?!");
67 int n = str.countTokens();
68
69 String words[] = new String[n];
int potential[] = new int[n];
70
71 for(int i=0; i<n; i++)
72 {
73 words[i] = str.nextToken(); // Saving words one by one in an array
74 potential[i] = ob.findPotential(words[i]); // Saving potential of every word
75 }
76
// Printing the words along with their potential
77 System.out.print("\nPotential\t : \t");
78 for(int i=0; i<n; i++)
79 {
80 System.out.println(words[i]+"\t= "+potential[i]);
81 System.out.print("\t\t\t");
}
82
83 ob.sortPotential(words,potential);
84 }
85 }
86
87
88
89
90
91
92
Output:
Enter a sentence : Look before you leap.
Potential : Look = 53
before = 51
you = 61
leap = 34
Output : leap before Look you
Enter a sentence : The sky is the limit.
Potential : The = 33
sky = 55
is = 28
the = 33
limit = 63
Output : is The the sky limit
Example 1
INPUT : 15
BINARY EQUIVALENT : 1111
NO. OF 1’s : 4
OUTPUT : EVIL NUMBER
Example 2
INPUT : 26
BINARY EQUIVALENT : 11010
NO. OF 1’s : 3
OUTPUT : NOT AN EVIL NUMBER
Programming Code:
1 /**
* The class EvilNumber inputs a number and checks whether it is an Evil Number or not
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 * @ISC Computer Science Practical Specimen Paper - Question 1
5 */
6 import java.util.*;
class EvilNumber
7 {
8 String toBinary(int n) // Function to convert a number to Binary
9 {
10 int r;
11 String s=""; //variable for storing the result
12
char dig[]={'0','1'}; //array storing the digits (as characters) in a binary number sys
13
14 while(n>0)
15 {
16 r=n%2; //finding remainder by dividing the number by 2
17 s=dig[r]+s; //adding the remainder to the result and reversing at the same time
18
19
20
21
22 n=n/2;
23 }
24 return s;
25 }
26
int countOne(String s) // Function to count no of 1's in binary number
27 {
28 int c = 0, l = s.length();
29 char ch;
30 for(int i=0; i<l; i++)
31 {
ch=s.charAt(i);
32 if(ch=='1')
33 {
34 c++;
35 }
}
36 return c;
37 }
38
39 public static void main(String args[])
40 {
41 EvilNumber ob = new EvilNumber();
Scanner sc = new Scanner(System.in);
42
43 System.out.print("Enter a positive number : ");
44 int n = sc.nextInt();
45
46 String bin = ob.toBinary(n);
47 System.out.println("Binary Equivalent = "+bin);
48
49 int x = ob.countOne(bin);
System.out.println("Number of Ones = "+x);
50
51 if(x%2==0)
52 System.out.println(n+" is an Evil Number.");
53 else
54 System.out.println(n+" is Not an Evil Number.");
55 }
}
56
57
58
59
60
Output:
Enter a positive number : 26
Binary Equivalent = 11010
Number of Ones = 3
26 is Not an Evil Number.
Enter a positive number : 420
Binary Equivalent = 110100100
Number of Ones = 4
420 is an Evil Number.
Enter a positive number : 659
Binary Equivalent = 1010010011
Number of Ones = 5
659 is Not an Evil Number.
Java program to find value of Mobius Function for a number [ISC 1999]
Question:16
The MOBIUS function M(N) for a natural number N is defined as follows:
Programming Code:
1 /**
* The class MobiusFn inputs a number and calculates the value of Mobius Function
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 * @Question Year : ISC Theory 1999
5 */
6
7 import java.util.*;
class MobiusFn
8 {
9 int n;
10
11 MobiusFn()
12 {
13 n = 0;
}
14
15 void input()
16 {
Scanner sc = new Scanner(System.in);
17 System.out.print("Enter a number : ");
18 n = sc.nextInt();
19 }
20
21 /* The function primefac() either returns '0' if prime factors are repeated
* or returns the no.of prime factors */
22 int primeFac()
23 {
24 int a=n, i=2, m=0, c=0, f=0;
25
26 while(a > 1) // loop to generate prime factors
27 {
c = 0; // variable to store frequency of every prime factor
28 while(a%i == 0) // if 'i' is a prime factor
29 {
30 c++; // counting frequency of 'i'
31 f++; // counting no of prime factors
32 a=a/i;
}
33 i++;
34
35 if(c > 1) // returning '0' if prime factors are repeated
36 return 0;
37 }
return f; // returning no. of prime factors
38
}
39
40 void display() // function to display value of mobius function
41 {
42 int mob,x;
43 if(n == 1) // condition 1
mob = 1;
44 else
45 {
46 x = primeFac();
47 if(x == 0) // condition 2
48 mob = 0;
else // condition 3
49 mob = (int)Math.pow(-1,x);
50 }
51 System.out.println("Value of Mobius Function : "+mob);
52 }
53
54 public static void main(String args[])
{
55 MobiusFn ob = new MobiusFn();
56 ob.input();
57 ob.display();
58 }
}
59
60
61
62
63
64
65
66
67
68
69
70
Output:
Enter a number : 78
Value of Mobius Function : -1
Enter a number : 12
Value of Mobius Function : 0
Enter a number : 34
Value of Mobius Function : 1
Enter a number : 17
Value of Mobius Function : -1
Some examples of fascinating Numbers are : 192, 219, 273, 327, 1902, 1920, 2019 etc.
Programming Code:
1 /**
* The class FascinatingNumber inputs a number and checks if it a Fascinating Number or not
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class FascinatingNumber
{
8 boolean isUnique(String q)
9 {
10 int A[] = {0,0,0,0,0,0,0,0,0,0};
11 //to store frequency of every digit from '0' to '9'
12 int i, flag = 0;
char ch;
13 for(i=0; i<q.length(); i++)
14 {
15 ch = q.charAt(i);
16 A[ch-48]++;
/* increasing A[5] if ch='5' as '5'-48 = 53-48=5
17 * (ASCII values of '0' to '9' are 48 to 57) */
18 }
19
20 for(i=1; i<10; i++)
21 {
22 //checking if every digit from '1' to '9' are present exactly once or not
if(A[i]!=1)
23 {
24 flag = 1; //flag is set to 1 if frequency is not 1
25 break;
26 }
27 }
28
if(flag == 1)
29 return false;
30 else
31 return true;
}
32 public static void main(String args[])
33 {
34 Scanner sc = new Scanner(System.in);
35 FascinatingNumber ob = new FascinatingNumber();
36
System.out.print("Enter a number : ");
37 int n = sc.nextInt();
38 String p = Integer.toString(n); //converting the number to String
39
40 if(p.length()<3)
41 System.out.println("Number should be of atleast 3 digits.");
42
43 else
{
44 String s = Integer.toString(n*1) + Integer.toString(n*2) + Integer.toString(n*3);
45 /* Joining the first, second and third multiple of the number
46 * by converting them to Strings and concatenating them*/
47 if(ob.isUnique(s))
System.out.println(n+" is a Fascinating Number.");
48
else
49 System.out.println(n+" is not a Fascinating Number.");
50 }
51 }
}
Output:
Enter a number : 273
273 is a Fascinating Number.
Enter a number : 853
853 is not a Fascinating Number.
Enter a number : 95
Number should be of atleast 3 digits.
Note: Anagrams are words made up of all the characters present in the original word by re-arranging the characters.
Example: Anagrams of the word TOP are: TOP, TPO, OPT, OTP, PTO and POT
Programming Code:
1 /**
* The class Anagrams inputs a word and generates its anagrams
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class Anagrams
{
8
9 int c = 0;
10
void input()throws Exception
11
{
12 Scanner sc = new Scanner(System.in);
13 System.out.print("Enter a word : ");
14 String s = sc.next();
15 System.out.println("The Anagrams are : ");
display("",s);
16 System.out.println("Total Number of Anagrams = "+c);
17 }
18
19 void display(String s1, String s2)
20 {
21 if(s2.length()<=1)
{
22 c++;
23 System.out.println(s1+s2);
24 }
25 else
{
26
for(int i=0; i<s2.length(); i++)
27 {
28 String x = s2.substring(i, i+1);
29 String y = s2.substring(0, i);
30 String z = s2.substring(i+1);
display(s1+x, y+z);
31 }
32 }
33 }
34
35 public static void main(String args[])throws Exception
36 {
Anagrams ob=new Anagrams();
37 ob.input();
38 }
39 }
Output:
Enter a word : BACK
The Anagrams are :
BACK
BAKC
BCAK
BCKA
BKAC
BKCA
ABCK
ABKC
ACBK
ACKB
AKBC
AKCB
CBAK
CBKA
CABK
CAKB
CKBA
CKAB
KBAC
KBCA
KABC
KACB
KCBA
KCAB
Total Number of Anagrams = 24
[Question 8] ISC 2015 Computer Paper Solved – Binary Search Using Recursion
Question:
A class Admission contain the admission numbers of 100 students. Some of the data members/ member functions are given
below:
Class name: Admission
Data member/instance variable:
Adno[ ]: Integer array to store admission numbers
Member functions/methods:
Admission(): constructur to initialize the array elements
void fillArray(): to accept the element of the array in ascending order
int binSearch(int l, int u, int v): to search for a particular admission number(v) using binary search and recursive technique and
return 1 if found otherwise returns -1
Specify the class Admission giving details of the constructor, void fillArrray() and int binSearch(int, int, int).
Define the main() function to create an object and call the functions accordingly to enable task.
Programming Code:
1 /**
* The class Admission searches for an Admission number using Binary Search
2
* @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 * @Question Year : ISC 2015 (Theory) Question 8
5 */
6
7 import java.util.*;
class Admission
8 {
9 int Adno[]=new int[100];
10 static Scanner sc = new Scanner(System.in);
11
12 Admission() // Default constructor
13 {
for(int i=0; i<100; i++)
14 {
15 Adno[i]=0;
16 }
17 }
18
void fillArray()throws Exception // Function to accept elements in ascending order
19
{
20 for(int i=0; i<100; i++)
21 {
22 System.out.print("Enter Admission no of student "+(i+1)+": ");
23 Adno[i] = sc.nextInt();
}
24
25 /*Sorting the array in ascending order */
26
27
28 int temp=0;
29 for(int i=0; i<99; i++)
{
30 for(int j=i+1; j<100; j++)
31 {
32 if(Adno[i]>Adno[j])
33 {
34 temp = Adno[i];
Adno[i] = Adno[j];
35 Adno[j] = temp;
36 }
37 }
38 }
39 }
40
int binSearch(int l, int u, int v) // Recursive function implementing binary search
41 {
42 int mid = (l + u)/2;
43 if(u < l) // condition if the search is unsuccessful
44 {
return -1;
45
}
46 if(v==Adno[mid]) // condition if the search is successful
47 {
48 return 1;
49 }
else if(v>Adno[mid])
50 {
51 return binSearch(mid+1,u,v);
52 }
53 else
54 {
return binSearch(l,mid-1,v);
55 }
56 }
57
58 public static void main(String args[])throws Exception
59 {
Admission ob = new Admission();
60
System.out.println("Enter Admission number in ascending order");
61 ob.fillArray();
62 System.out.print("Enter an Admission number to search : ");
63 int v = sc.nextInt();
64 int f = ob.binSearch(0,99,v);
System.out.println("*****************************");
65 if(f == 1)
66 {
67 System.out.println("Admission Number found");
68 }
69 else
{
70 System.out.println("Admission Number Not found");
71 }
72 }
}
Output:
Note: The output has been taken for 5 elements in the array
Enter Admission number in ascending order
Enter Admission no of student 1: 205
Enter Admission no of student 2: 310
Enter Admission no of student 3: 670
Enter Admission no of student 4: 887
Enter Admission no of student 5: 952
Enter an Admission number to search : 887
*****************************
Admission Number found
Note: Since insertion and deletion both takes place from different ends, we have to keep record of the index of both the front as
well as the rear end.
Consider a queue implemented using an array Q[ ]. The index of the front (first) element is stored in the variable ‘front’ and
index of the last element is stored in the variable ‘rear’.
Let the size of the queue be denoted by the variable ‘size’. In our example, the value of ‘size’ = 5.
Initially the values of ‘front’ and ‘rear’ are 0. So insertion will start from index zero.
Similarly, when we insert the next element, after insertion, the value of ‘rear’ should increase from 1 to 2 and so on.
Now when the last element is inserted at index 4, the value of ‘rear’ changes from 4 to 5. We now see that the queue is full and
no more element can be inserted. This situation is known as ‘OVERFLOW’.
While inserting element in the queue, always remember to check for a condition where the queue is full and no more element
can be inserted.
So, if(rear == size) then OVERFLOW will occur and you cannot insert any more element. In all other cases you can insert, by
first inserting at the rear end and then increasing the ‘rear’ index.
To cut the long story short, while inserting, ‘rear’ index increases.
Similarly, when we delete the next element, the value of ‘front’ should increase from 1 to 2 and so on.
Now, when the value of ‘front’ and ‘rear’ becomes equal, there will be no element in the queue. So, we re-set their values to 0 to
denote that the queue is now in its initial state (empty). So now no more element can be deleted. This situation is known as
‘UNDERFLOW’.
While deleting element from the queue, always remember to check for a condition where the queue is empty and no more
element can be deleted.
So, if(front == 0 && rear == 0) then UNDERFLOW will occur and you cannot delete any more element. In all other cases you
can delete, by increasing ‘front’.
To cut the long story short, while deleting, ‘front’ index increases.
Note: Since insertion and deletion both takes place from the top end only, we have to keep record of the position of the
topmost (last) element only.
Consider a stack implemented using an array ST[ ]. The index of the last element inserted (top most element) is stored in the
stack pointer variable ‘top’.
Initially when the stack is empty, the value of Stack Pointer (top) should be = -1 (and not any other index from 0-4)
Similarly, when we insert the next element, the value of stack pointer ‘top’ should increase from 1 to 2 and then we insert the
element at index 2 and so on.
Now when the stack is full, the index of stack pointer ‘top’ will become 4 (size-1). So now no more element can be inserted. This
situation is known as ‘OVERFLOW’
While inserting element in the stack, always remember to check for a condition where the stack is full and no more element can
be inserted.
So, if(top == size – 1) then OVERFLOW will occur and you cannot insert any more element. In all other cases you can insert,
by first increasing ‘top’ and then saving the element at this index.
To cut the long story short, while inserting ‘top’ increases.
Programming Code Implementing Push Operation:
1
2 void push(int n) // Function to insert element in Stack
3 {
if(top == size-1) // Condition for Overflow
4 {
5 System.out.println("OVERFLOW");
6 }
7 else
{
8
top = top + 1;
9 ST[top] = n;
10 }
11 }
12
Similarly, when we delete the next element, the value of stack pointer ‘top’ should decrease from 3 to 2 and so on.
Now when the stack is empty, the index of stack pointer ‘top’ will become -1. So now no more element can be deleted. This
situation is known as ‘UNDERFLOW’
While deleting element from the stack, always remember to check for a condition where the stack is empty and no more
element can be deleted.
So, if(top == – 1) then UNDERFLOW will occur and you cannot delete any more element. In all other cases you can delete, by
decreasing ‘top’.
To cut the long story short, while deleting, ‘top’ decreases.
Programming Code Implementing Pop Operation:
1 int pop() // Function to delete element in Stack
{
2
if(top == -1) // Condition for Underflow
3 {
4 System.out.println("UNDERFLOW");
5 return -999;
6 }
7
8 else
9 {
int val = ST[top]; // Storing the element which will be removed
10 top = top - 1;
11 return val;
12 }
13 }
14
Question:
Write a program to accept a sentence which may be terminated by either ‘.’ or ‘?’ only. The words are to be separated by a
single blank space. Print an error message if the input does not terminate with ‘.’ or ‘?’. You can assume that no word in the
sentence exceeds 15 characters, so that you get a proper formatted output.
Example 1
INPUT: Intelligence plus character is education.
OUTPUT:
Intelligence Plus Character Is Education
Word Vowels Consonants
Intelligence 5 7
Plus 1 3
Character 3 6
Is 1 1
Education 5 4
Example 2
INPUT: God is great.
OUTPUT:
God is Great
Word Vowels Consonants
God 1 2
Is 1 1
Great 2 3
Example 3
INPUT: All the best!
OUTPUT:
Invalid Input.
Programming Code:
1 /**
* The class Q3_ISC2015 inputs a sentence, converts the first letter of each word to
2
* uppercase and find the number of vowels and consonants
3 * @author : www.javaforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2015 Question 3
6 */
7
import java.util.*;
8 class Q3_ISC2015
9 {
10 int countVowel(String s) // Function to count no. of vowels in a word
11 {
12 s = s.toUpperCase();
int count = 0;
13 char ch;
14 for(int i=0; i<s.length(); i++)
15 {
16 ch = s.charAt(i);
if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U')
17
{
18 count++;
19 }
20 }
21 return count;
}
22
23 String convert(String s) // Function to convert 1st character to UpperCase
24 {
25 char ch = s.charAt(0); // Extracting the first character
26 ch = Character.toUpperCase(ch); // Converting that character to UpperCase
27 String f = ch + s.substring(1); // Adding it with the rest of the string
return f;
28 }
29
30 String addSpace(String s, int max) // Function for addng extra space to make every word equ
31 {
32 int x = max-s.length();
33 for(int i=1; i<=x; i++)
{
34 s = s+" ";
35 }
36 return s;
37 }
38
public static void main(String args[])
39 {
40 Q3_ISC2015 ob = new Q3_ISC2015();
41 Scanner sc=new Scanner(System.in);
42
43 System.out.print("Enter a sentence : ");
44 String s=sc.nextLine();
int l = s.length();
45 char last = s.charAt(l-1); // Extracting the last character
46
47 /* Checking whether the sentence ends with '.' or '?' or not */
48 if(last != '.' && last != '?')
49 {
50 System.out.println("Invalid Input. End a sentence with either '.' or '?'");
}
51 else
52 {
53 StringTokenizer str = new StringTokenizer(s," .?");
54 int x = str.countTokens();
String ans="";
55 String word[]=new String[x];
56 int vow, con, max=0;
57
58 for(int i=0; i<x; i++)
59 {
60 word[i] = str.nextToken(); // Extracting words and saving them in an array
ans = ans + " " + ob.convert(word[i]);
61 if(word[i].length()>max)
62 {
63 max = word[i].length();
64 }
65 }
System.out.println("Sentence = "+ans.trim());
66
67 String y=ob.addSpace("Word",max);
68 System.out.println(y+"\tVowels\tConsonant");
69 for(int i=0; i<x; i++)
70 {
vow = ob.countVowel(word[i]);
71
con = word[i].length()-vow; // Consonant = Length - Vowel
72 y = ob.addSpace(word[i],max);
73 System.out.println(y+"\t"+vow+"\t"+con);
74 }
75 }
}
76 }
77
Output:
Enter a sentence : God is great.
Sentence = God Is Great
Word Vowels Consonants
God 1 2
Is 1 1
Great 2 3
Enter a sentence : All the best!
Invalid Input. End a sentence with either ‘.’ or ‘?’
Test your program for the following data and some random data:
Example 1
INPUT : M = 3
3 4 9
2 5 8
1 6 7
OUTPUT :
ORIGINAL MATRIX
3 4 9
2 5 8
1 6 7
MATRIX AFTER ROTATION
1 2 3
6 5 4
7 8 9
Sum of the corner elements = 20
Example 2
INPUT : M = 4
1 2 4 9
2 5 8 3
1 6 7 4
3 7 6 5
OUTPUT :
ORIGINAL MATRIX
1 2 4 9
2 5 8 3
1 6 7 4
3 7 6 5
MATRIX AFTER ROTATION
3 1 2 1
7 6 5 2
6 7 8 4
5 4 3 9
Sum of the corner elements = 18
Example 3
INPUT :
M = 14
OUTPUT :
SIZE OUT OF RANGE
Example 4
INPUT :
M = 112
N = 130
OUTPUT :
INVALID INPUT
Programming Code:
1 /**
* The class Q2_ISC2015 inputs a square matrix and rotates it 90° clockwise
2 * It also finds and displays the sum of the corner elements
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2015 Question 2
6 */
7
import java.util.*;
8 class Q2_ISC2015
9 {
10 public static void main(String args[])throws Exception
11 {
12 Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the matrix : ");
13 int m=sc.nextInt();
14
15 if(m<3 || m>9)
16 System.out.println("Size Out Of Range");
17 else
18 {
int A[][]=new int[m][m];
19
20 /* Inputting the matrix */
21 for(int i=0;i<m;i++)
22 {
23 for(int j=0;j<m;j++)
24 {
25 System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
26 }
27 }
28 /* Printing the original matrix */
29 System.out.println("*************************");
30 System.out.println("ORIGINAL MATRIX");
for(int i=0;i<m;i++)
31 {
32 for(int j=0;j<m;j++)
33 {
34 System.out.print(A[i][j]+"\t");
}
35
System.out.println();
36 }
37
38 /* Rotation of begins here */
39 System.out.println("*************************");
40 System.out.println("MATRIX AFTER ROTATION");
for(int i=0;i<m;i++)
41 {
42 for(int j=m-1;j>=0;j--)
43 {
44 System.out.print(A[j][i]+"\t");
45 }
System.out.println();
46 }
47
48 int sum = A[0][0]+A[0][m-1]+A[m-1][0]+A[m-1][m-1]; // Finding sum of corner element
49 System.out.println("Sum of the corner elements = "+sum);
50 }
51 }
}
Programming Code:
1 /**
* The class Q2_ISC2015 inputs a square matrix and rotates it 90° clockwise
2
* It also finds and displays the sum of the corner elements
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2015 Question 2
6 */
7
import java.util.*;
8 class Q2_ISC2015
9 {
10 public static void main(String args[])throws Exception
11 {
12 Scanner sc=new Scanner(System.in);
System.out.print("Enter the size of the matrix : ");
13 int m=sc.nextInt();
14
15
16 if(m<3 || m>9)
17 System.out.println("Size Out Of Range");
else
18 {
19 int A[][]=new int[m][m];
20
21 /* Inputting the matrix */
22 for(int i=0;i<m;i++)
23 {
for(int j=0;j<m;j++)
24 {
25 System.out.print("Enter an element : ");
26 A[i][j]=sc.nextInt();
27 }
}
28 /* Printing the original matrix */
29 System.out.println("*************************");
30 System.out.println("ORIGINAL MATRIX");
31 for(int i=0;i<m;i++)
32 {
for(int j=0;j<m;j++)
33 {
34 System.out.print(A[i][j]+"\t");
35 }
36 System.out.println();
}
37
38
/* Rotation of begins here */
39 int B[][]=new int[m][m];
40 int x = m-1;
41 for(int i=0;i<m;i++)
42 {
x = m-1;
43 for(int j=0;j<m;j++)
44 {
45 B[i][j] = A[x][i];
46 x--;
47 }
}
48
49 System.out.println("*************************");
50 System.out.println("MATRIX AFTER ROTATION");
51 for(int i=0;i<m;i++)
52 {
53 for(int j=0;j<m;j++)
{
54 System.out.print(B[i][j]+"\t");
55 }
56 System.out.println();
57 }
58
int sum = A[0][0]+A[0][m-1]+A[m-1][0]+A[m-1][m-1]; // Finding sum of corner element
59
System.out.println("Sum of the corner elements = "+sum);
60 }
61 }
}
Output:
Enter the size of the matrix : 4
Enter an element : 1
Enter an element : 2
Enter an element : 4
Enter an element : 9
Enter an element : 2
Enter an element : 5
Enter an element : 8
Enter an element : 3
Enter an element : 1
Enter an element : 6
Enter an element : 7
Enter an element : 4
Enter an element : 3
Enter an element : 7
Enter an element : 6
Enter an element : 5
*************************
ORIGINAL MATRIX
1 2 4 9
2 5 8 3
1 6 7 4
3 7 6 5
*************************
MATRIX AFTER ROTATION
3 1 2 1
7 6 5 2
6 7 8 4
5 4 3 9
Sum of the corner elements = 18
Question:
Given two positive numbers M and N, such that M is between 100 and 10000 and N is less than 100. Find the smallest integer
that is greater than M and whose digits add up to N. For example, if M = 100 and N = 11, then the smallest integer greater than
100 whose digits add up to 11 is 119.
Write a program to accept the numbers M and N from the user and print the smallest required number whose sum of all its digits
is equal to N. Also, print the total number of digits present in the required number. The program should check for the validity of
the inputs and display an appropriate message for an invalid input.
Test your program with the sample data and some random data:
Example 1
INPUT :
M = 100
N = 11
OUTPUT :
The required number = 119
Total number of digits = 3
Example 2
INPUT :
M = 1500
N = 25
OUTPUT :
The required number = 1699
Total number of digits = 4
Example 3
INPUT :
M = 99
N = 11
OUTPUT :
INVALID INPUT
Example 4
INPUT :
M = 112
N = 130
OUTPUT :
INVALID INPUT
Programming Code:
1 /**
* The class Q1_ISC2015 inputs two integers 'm' and 'n' and prints smallest integer
2 * greater than 'm' whose sum of digits is equal to 'n'
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2015 Question 1
6 */
7
import java.util.*;
8 class Q1_ISC2015
9 {
10 int sumDig(long n) // Function to find sum of digits of a number
11 {
12 int sum = 0, d;
while(n>0)
13 {
14 d = (int)(n%10);
15 sum = sum + d;
16 n = n/10;
}
17 return sum;
18 }
19
20 int countDig(long n) // Function to count the number of digits in a number
21 {
22 String s = Long.toString(n);
int len = s.length();
23 return len;
24 }
25
26 public static void main()throws Exception
27 {
28 Q1_ISC2015 ob = new Q1_ISC2015();
Scanner sc = new Scanner(System.in);
29 System.out.print("Enter a value of 'm' from 100 to 10000 : ");
30 int m = sc.nextInt();
31 System.out.print("Enter a value of n from 1 to 99 : ");
32 int n = sc.nextInt();
33
34 if(m<100 || m>10000 || n<1 || n>99)
{
35 System.out.println("Invalid Input");
36 }
37 else
38 {
long i = (long)m; // Required number can be out of range of 'int'
39 /* The required number must be greater than 'm',
40
41 so loop will go on as long as that number is not obtained.*/
while(ob.sumDig(i)!=n)
42 {
43 i=i+1;
44 }
45 System.out.println("The required number = "+i);
System.out.println("Total number of digits = "+ob.countDig(i));
46
}
47 }
48 }
Output:
Enter a value of ‘m’ from 100 to 10000 : 1500
Enter a value of ‘n’ from 1 to 99 : 25
The required number = 1699
Total number of digits = 4
Enter a value of ‘m’ from 100 to 10000 : 100
Enter a value of ‘n’ from 1 to 99 : 20
The required number = 299
Total number of digits = 3
Enter a value of ‘m’ from 100 to 10000 : 112
Enter a value of ‘n’ from 1 to 99 : 130
Invalid Input
Lower Triangular Matrix : A Lower Triangular matrix is a square matrix in which all the entries above the main diagonal (↘) are
zero. The entries below or on the main diagonal themselves may or may not be zero.
Example:
5 0 0 0
3 1 0 0
4 9 4 0
6 8 7 2
Solution:
1 /**
* The class LowerTriangularMatrix inputs a Matrix and checks whether it is a Lower Triangular
2
* @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class LowerTriangularMatrix
{
8 public static void main(String args[])throws Exception
9 {
10 Scanner sc=new Scanner(System.in);
11 System.out.print("Enter the size of the matrix : ");
12 int m=sc.nextInt();
int A[][]=new int[m][m];
13
14
15
16
17
18
19
20 /* Inputting the matrix */
for(int i=0;i<m;i++)
21 {
22 for(int j=0;j<m;j++)
23 {
24 System.out.print("Enter an element : ");
A[i][j]=sc.nextInt();
25
}
26 }
27 // printing the matrix
28 System.out.println("*************************");
29 System.out.println("The Matrix Is : ");
for(int i=0;i<m;i++)
30 {
31 for(int j=0;j<m;j++)
32 {
33 System.out.print(A[i][j]+"\t");
34 }
System.out.println();
35 }
36 System.out.println("*************************");
37 //Checking for lower triangular matrix
38 int p=0;
for(int i=0;i<m;i++)
39
{
40 for(int j=i+1;j<m;j++)
41 {
42 if(A[i][j]!=0) //all elements above diagonal must be zero if any element is not
43 {
p = 1;
44 break;
45 }
46 }
47 }
48
49 if(p == 0)
{
50 System.out.println("The Matrix is Lower Triangular");
51 }
52 else
53 {
System.out.println("The Matrix is NOT Lower Triangular");
54 }
55 }
56 }
57
58
59
60
61
Output:
Enter the size of the matrix : 4
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 3
Enter an element : 1
Enter an element : 0
Enter an element : 0
Enter an element : 4
Enter an element : 9
Enter an element : 4
Enter an element : 0
Enter an element : 6
Enter an element : 8
Enter an element : 7
Enter an element : 2
*************************
The Matrix Is :
5 0 0 0
3 1 0 0
4 9 4 0
6 8 7 2
*************************
The Matrix is Lower Triangular
Upper Triangular Matrix : An Upper Triangular matrix is a square matrix in which all the entries below the main diagonal (↘)
are zero. The entries above or on the main diagonal themselves may or may not be zero.
Example:
5 3 0 7
0 1 9 8
0 0 4 6
0 0 0 2
Solution:
1 /**
* The class UpperTriangularMatrix inputs a Matrix and checks whether it is a Lower Triangular
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class UpperTriangularMatrix
{
8 public static void main(String args[])throws Exception
9 {
10 Scanner sc=new Scanner(System.in);
11 System.out.print("Enter the size of the matrix : ");
12 int m=sc.nextInt();
int A[][]=new int[m][m];
13
14 /* Inputting the matrix */
15 for(int i=0;i<m;i++)
16 {
17
18
19
20
21
22 for(int j=0;j<m;j++)
23 {
System.out.print("Enter an element : ");
24 A[i][j]=sc.nextInt();
25 }
26 }
27 // printing the matrix
28 System.out.println("*************************");
System.out.println("The Matrix Is : ");
29 for(int i=0;i<m;i++)
30 {
31 for(int j=0;j<m;j++)
32 {
System.out.print(A[i][j]+"\t");
33
}
34 System.out.println();
35 }
36 System.out.println("*************************");
37 //Checking for upper triangular matrix
int p=0;
38 for(int i=0;i<m;i++)
39 {
40 for(int j=0;j<i;j++)
41 {
42 if(A[i][j]!=0) //all elements below main diagonal must be zero if not then we s
{
43 p = 1;
44 break;
45 }
46 }
}
47
48
if(p == 0)
49 {
50 System.out.println("The Matrix is Upper Triangular");
51 }
52 else
{
53 System.out.println("The Matrix is NOT Upper Triangular");
54 }
55 }
56 }
57
58
59
60
61
Output:
Enter the size of the matrix : 4
Enter an element : 5
Enter an element : 3
Enter an element : 0
Enter an element : 7
Enter an element : 0
Enter an element : 1
Enter an element : 9
Enter an element : 8
Enter an element : 0
Enter an element : 0
Enter an element : 4
Enter an element : 6
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 2
*************************
The Matrix is :
5 3 0 7
0 1 9 8
0 0 4 6
0 0 0 2
*************************
The matrix is Upper Triangular
Scalar Matrix : A scalar matrix is a diagonal matrix in which the main diagonal (↘) entries are all equal.
See : Java program to check for Diagonal Matrix
Example:
5 0 0 0
0 5 0 0
0 0 5 0
0 0 0 5
Solution:
1 /**
* The class ScalarMatrix inputs a Matrix and checks whether it is a scalar matrix or not
2
* @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class ScalarMatrix
{
8 public static void main(String args[])throws Exception
9 {
10 Scanner sc=new Scanner(System.in);
11 System.out.print("Enter the size of the matrix : ");
12 int m=sc.nextInt();
int A[][]=new int[m][m];
13
14 /* Inputting the matrix */
15 for(int i=0;i<m;i++)
16 {
17 for(int j=0;j<m;j++)
{
18
19
20
21
22
23
System.out.print("Enter an element : ");
24 A[i][j]=sc.nextInt();
25 }
26 }
27
28 /* Printing the matrix */
System.out.println("*************************");
29 System.out.println("The Matrix is : ");
30 for(int i=0;i<m;i++)
31 {
32 for(int j=0;j<m;j++)
33 {
System.out.print(A[i][j]+"\t");
34 }
35 System.out.println();
36 }
37 System.out.println("*************************");
38
39 int p = 0, q = 0, x = A[0][0]; // 'x' is storing the 1st main diagonal element
40
for(int i=0;i<m;i++)
41 {
42 for(int j=0;j<m;j++)
43 {
44 /* Checking that the matrix is diagonal or not */
45 if(i!=j && A[i][j]!=0) // All non-diagonal elements must be zero
{
46 p=1;
47 break;
48 }
49 /* Checking the matrix for scalarity */
// All main diagonal elements must be equal to 'x' and non-zero
50 if(i==j && (A[i][j]==0 || A[i][j]!=x))
51 {
52 q=1;
53 break;
54 }
}
55 }
56
57 if(p==0 && q==0)
58 System.out.println("The matrix is scalar");
59 else
60 System.out.println("The matrix is not scalar");
}
61 }
62
63
64
65
66
67
Output:
Enter the size of the matrix : 4
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 5
*************************
The Matrix is :
5 0 0 0
0 5 0 0
0 0 5 0
0 0 0 5
*************************
The matrix is Scalar
Diagonal Matrix : A diagonal matrix is a matrix (usually a square matrix) in which the entries outside the main diagonal (↘) are
all zero. The diagonal entries themselves may or may not be zero (but all diagonal entries cannot be zero).
Example:
5 0 0 0
0 1 0 0
0 0 0 0
0 0 0 7
Solution:
1 /**
* The class DiagonalMatrix inputs a Matrix and checks whether it is a diagonal matrix or not
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class DiagonalMatrix
{
8 public static void main(String args[])throws Exception
9 {
10 Scanner sc=new Scanner(System.in);
11 System.out.print("Enter the size of the matrix : ");
12 int m=sc.nextInt();
int A[][]=new int[m][m];
13
14 /* Inputting the matrix */
15 for(int i=0;i<m;i++)
{
16 for(int j=0;j<m;j++)
17 {
18 System.out.print("Enter an element : ");
19 A[i][j]=sc.nextInt();
}
20 }
21
22 /* Printing the matrix */
23 System.out.println("*************************");
24 System.out.println("The Matrix is : ");
25 for(int i=0;i<m;i++)
{
26 for(int j=0;j<m;j++)
27 {
28 System.out.print(A[i][j]+"\t");
29 }
30 System.out.println();
}
31 System.out.println("*************************");
32
33 int p=0, q=0;
34
35 for(int i=0;i<m;i++)
36 {
37 for(int j=0;j<m;j++)
{
38 if(i!=j && A[i][j]!=0) // Checking non-diagonal elements
39 {
40 p=1;
41 break;
}
42 if(i==j && A[i][j]==0) // Checking diagonal elements
43 {
44 q++;
45 }
46 }
}
47
48 if(p==0 && q<m)
49 System.out.println("The matrix is Diagonal");
50 else
51 System.out.println("The matrix is not Diagonal");
52 }
}
53
54
55
56
57
58
59
60
61
62
63
Output:
Enter the size of the matrix : 4
Enter an element : 5
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 1
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 0
Enter an element : 7
*************************
The Matrix is :
5 0 0 0
0 1 0 0
0 0 0 0
0 0 0 7
*************************
The matrix is Diagonal
Illustration:
Solution:
1 /**
* The class MatrixMultiplication inputs 2 Matrices and performs Matrix Multiplication on them
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5 import java.util.*;
6 class MatrixMultiplication
{
7 void printMatrix(int P[][], int r, int c) // Funtion for printing an array
8 {
9 for(int i=0; i<r; i++)
10 {
11 for(int j=0; j<c; j++)
{
12 System.out.print(P[i][j]+"\t");
13 }
14 System.out.println();
15 }
}
16
17
public static void main(String args[])
18 {
19 MatrixMultiplication ob = new MatrixMultiplication();
20 Scanner sc = new Scanner(System.in);
21 System.out.print("Enter no of rows for 1st array : "); //Inputting the rows of array A
int r1=sc.nextInt();
22 System.out.print("Enter no of columns for 1st array : "); //Inputting the columns of a
23 int c1=sc.nextInt();
24 System.out.print("Enter no of rows for 2nd array : "); //Inputting the rows of array B
25 int r2=sc.nextInt();
26 System.out.print("Enter no of columns for 2nd array : "); //Inputting the rows of arra
int c2=sc.nextInt();
27 if(c1 != r2) //condition for multiplication to be possible
{
28
System.out.println("Matrix multiplication of the given order is not possible");
29 }
30
31 else
32 {
33
34 if(r1>0&&r2>0&&c1>0&&c2>0)
{
35 int A[][]=new int[r1][c1];
36 int B[][]=new int[r2][c2];
37 System.out.println("*************************");
38 System.out.println("Inputting the 1st Matrix:"); //Accepting the values of arr
39 System.out.println("*************************");
for(int i=0;i<r1;i++)
40 {
41 for(int j=0;j<c1;j++)
42 {
43 System.out.print("Enter any value : ");
A[i][j]=sc.nextInt();
44 }
45 }
46
47 System.out.println("*************************");
48 System.out.println("Inputting the 2nd Matrix:"); //Accepting the values of arr
49 System.out.println("*************************");
for(int i=0;i<r2;i++)
50 {
51 for(int j=0;j<c2;j++)
52 {
53 System.out.print("Enter any value : ");
54 B[i][j]=sc.nextInt();
}
55 }
56
57 //Matrix Multiplication begins here
58 int C[][]=new int[r1][c2];
59 int sum;
for(int i=0;i<r1;i++)
60 {
61 for(int j=0;j<c2;j++)
62 {
63 sum=0;
64 for(int k=0;k<c1;k++)
{
65 sum = sum + A[i][k]*B[k][j];
66 }
67 C[i][j] = sum;
68 }
}
69
//end of matrix multiplication
70
71 System.out.println("*************************");
72 System.out.println("The 1st Matrix is:"); //Printing the array A
73 System.out.println("*************************");
74 ob.printMatrix(A,r1,c1);
System.out.println("*************************");
75 System.out.println("The 2nd Matrix is:"); //Printing the array A
76 System.out.println("*************************");
77
78
79
80
81
82
83
84
85
86 ob.printMatrix(B,r2,c2);
87 System.out.println("*************************");
System.out.println("The Result of Multiplication is:"); //Printing the array A
88 System.out.println("*************************");
89 ob.printMatrix(C,r1,c2);
90 }
91 else
92 {
System.out.print("Enter positive no of rows and columns");
93 }
94 }
95 }
96 }
97
98
99
100
101
102
103
104
105
Output:
Enter no of rows for 1st array : 2
Enter no of columns for 1st array : 2
Enter no of rows for 2nd array : 2
Enter no of columns for 2nd array : 2
*************************
Inoutting the 1st Matrix:
*************************
Enter any value : 1
Enter any value : 0
Enter any value : -3
Enter any value : 2
*************************
Inputting the 2nd Matrix:
*************************
Enter any value : -1
Enter any value : 4
Enter any value : 3
Enter any value : 5
*************************
The 1st Matrix is:
*************************
1 0
-3 2
*************************
The 2nd Matrix is:
*************************
-1 4
3 5
*************************
The Result of Multiplication is:
*************************
-1 4
9 -2
Example:
INPUT – abcabcabc
OUTPUT – abc
INPUT – javaforschool
OUTPUT – javforschl
INPUT – Mississippi
OUTPUT – Misp
Programming Code:
1 /**
* The class RemoveDupChar inputs a word and removes duplicate characters
2
* @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class RemoveDupChar
{
8 public static void main(String args[])
9 {
10 Scanner sc = new Scanner(System.in);
11 System.out.print("Enter any word : ");
12 String s = sc.next();
int l = s.length();
13 char ch;
14 String ans="";
15
16 for(int i=0; i<l; i++)
17 {
ch = s.charAt(i);
18
if(ch!=' ')
19 ans = ans + ch;
20 s = s.replace(ch,' '); //Replacing all occurrence of the current character by a spa
21 }
22
23 System.out.println("Word after removing duplicate characters : " + ans);
}
24 }
25
26
27
28
29
Output:
Example 1:
Enter any word : Mississippi
Word after removing duplicate characters : Misp
Example 2:
Enter any word : Attitude
Word after removing duplicate characters : Atiude
This question came in Question 3 of ISC 2003 Computer Science Practical Examination.
Programming Code:
1 /**
* The class SaddlePoint inputs a matrix of n*n size and finds its
2 * saddle point if any
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC 2003 Question 3 (Practical)
6 */
7
import java.util.*;
8 class SaddlePoint
9 {
10 public static void main()
11 {
12 Scanner sc = new Scanner(System.in);
System.out.print("Enter the order of the matrix : ");
13 int n=sc.nextInt();
14 int A[][]=new int[n][n];
15 System.out.println("Inputting the elements in the matrix");
16 System.out.println("******************************");
for(int i=0;i<n;i++)
17 {
18 for(int j=0;j<n;j++)
19 {
20 System.out.print("Enter Element at ["+i+"]["+j+"] : ");
21 A[i][j]=sc.nextInt();
}
22 }
23
24 /* Printing the Original Matrix */
System.out.println("******************************");
25 System.out.println("The Original Matrix is");
26 for(int i=0;i<n;i++)
27 {
28 for(int j=0;j<n;j++)
{
29 System.out.print(A[i][j]+"\t");
30 }
31 System.out.println();
32 }
33
34
35 int max, min, x, f=0;
for(int i=0;i<n;i++)
36 {
37 /* Finding the minimum element of a row */
38 min = A[i][0]; // Initializing min with first element of every row
39 x = 0;
40 for(int j=0;j<n;j++)
{
41 if(A[i][j]<min)
42 {
43 min = A[i][j];
44 x = j; // Saving the column position of the minimum element of the row
}
45
}
46
47 /* Finding the maximum element in the column
48 * corresponding to the minimum element of row */
49 max = A[0][x]; // Initializing max with first element of that column
50 for(int k=0;k<n;k++)
{
51 if(A[k][x]>max)
52 {
53 max = A[k][x];
54 }
55 }
56
/* If the minimum of a row is same as maximum of the corresponding column,
57 then, we have that element as the Saddle point */
58 if(max==min)
59 {
60 System.out.println("********************");
61 System.out.println("Saddle point = "+max);
System.out.println("********************");
62 f=1;
63 }
64 }
65
66 if(f==0)
{
67
System.out.println("********************");
68 System.out.println("No saddle point");
69 System.out.println("********************");
70 }
71 }
72 }
Output:
Programming Code:
1 /**
* The class TwinPrimeRange inputs 2 numbers and prints all the
2 * twin prime numbers within that range
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 */
6
7 import java.util.*;
class TwinPrimeRange
8 {
9 boolean isPrime(int n) //funton for checking prime
10 {
11 int count=0;
12 for(int i=1; i<=n; i++)
{
13 if(n%i == 0)
14 count++;
15 }
16 if(count == 2)
return true;
17
else
18 return false;
19 }
20
21
22 public static void main(String args[])
23 {
24 TwinPrimeRange ob = new TwinPrimeRange();
25 Scanner sc = new Scanner(System.in);
26
System.out.print("Enter the lower range : ");
27
int p = sc.nextInt();
28 System.out.print("Enter the upper range : ");
29 int q = sc.nextInt();
30
31 if(p>q)
32 System.out.println("Invalid Range !");
else
33 {
34 System.out.println("\nThe Twin Prime Numbers are : ");
35 for(int i=p; i<=(q-2); i++)
36 {
37 if(ob.isPrime(i) == true && ob.isPrime(i+2) == true)
{
38 System.out.print("("+i+","+(i+2)+") ");
39 }
40 }
41 }
42 }
}
43
Output:
Enter the lower range : 1
Enter the upper range : 200
The Twin Prime Numbers within the given range are :
(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73) (101,103) (107,109) (137,139) (149,151) (179,181) (191,193)
(197,199)
Output:
Enter size of the 1st array : 5
Fibonacci String
Question:
A sequence of Fibonacci Strings is generated as follows:
S0 = “a”, S1 = “b”, Sn = S(n-1) + S(n-2) where ‘+’ denotes concatenation. Thus the sequence is:
a, b, ba, bab, babba, babbabab, ………. n terms.
Design a class FiboString to generate Fibonacci strings. Some of the members of the class are given below:
Class name : FiboString
Data members/instance variables:
x : to store the first string
y : to store the second string
z : to store the concatenation of the previous two strings
n : to store the number of terms
Member functions/methods:
FiboString() : constructor to assign x=”a”, y=”b”, z=”ba”
void accept() : to accept the number of terms ‘n’
void generate() : to generate and print the fibonacci strings. The sum of (‘+’ i.e. concatenation) first two strings is the
third string. Eg. “a” is first string, “b” is second string then the third string will be “ba” and fourth will be “bab” and so on.
Specify the class FiboString, giving details of the constructor(), void accept() and void generate(). Define the main() function
to create an object and call the functions accordingly to enable the task.
Programming Code:
1 /**
* The class FiboString prints the sequence of fibonacci strings
2
* @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 * @Question Year : ISC 2014 Question 10
5 */
6
7 import java.util.*;
class FiboString
8 {
9 String x,y,z;
10 int n;
11
12 FiboString()
13 {
x = "a";
14 y = "b";
15 z = "ba"; // mentioned in the question otherwise not required. z = "" is sufficient
16 }
17
18 void accept()
19 {
Scanner sc = new Scanner(System.in);
20
21 System.out.print("\nEnter the number of terms : ");
n = sc.nextInt();
22 }
23
24 void generate()
25 {
26 System.out.print("\nThe Fibonacci String Series is : ");
if(n <= 1) // If no of terms is less than or equal to 1
27
System.out.print(x);
28 else
29 {
30 System.out.print(x+", "+y);
31 for(int i=3; i<=n; i++)
{
32 z = y+x;
33 System.out.print(", "+z);
34 x = y;
35 y = z;
36 }
}
37 }
38
39 public static void main(String args[])
40 {
41 FiboString ob = new FiboString();
ob.accept();
42
ob.generate();
43 }
44 }
Output:
1) Enter the number of terms : 2
The Fibonacci String Series is : a, b
2) Enter the number of terms : 5
The Fibonacci String Series is : a, b, ba, bab, babba
Composite number:
A composite number is a number that has more than two factors.
For example: 10
Factors are: 1, 2, 5, 10
Magic number:
A magic number is a number in which the eventual sum of the digits is equal to 1
For example: 28=2+8=10=1+0=1
Accept two positive integers m and n, where m is less than n as user input. Display the number of Composite magic integers
that are in the range between m and n (both inclusive) and output them along with the frequency, in the format specified below.
Test your program with the sample data and some random data:
Example 1:
INPUT:
m = 10
n = 100
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
10, 28, 46, 55, 64, 82, 91, 100
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 8
Example 2:
INPUT:
m = 1200
n = 1300
OUTPUT:
THE COMPOSITE MAGIC INTEGERS ARE:
1207, 1216, 1225, 1234, 1243, 1252, 1261, 1270, 1288
FREQUENCY OF COMPOSITE MAGIC INTEGERS IS: 9
Example 3:
INPUT:
m = 120
n = 99
OUTPUT:
INVALID INPUT
Programming Code:
1 /**
* The class MagicComposite_ISC2014 inputs two integers and prints all those numbers
2 * which are composite as well as Magic
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2014 Question 1
6 */
import java.util.*;
7 class MagicComposite_ISC2014
8 {
9 boolean isComposite(int n) // Function to check for Composite number
10 {
11 int count=0;
for(int i=1;i<=n;i++)
12 {
13 if(n%i==0)
14 count++;
15 }
if(count>2)
16 return true;
17 else
18 return false;
19 }
20
21 int sumDig(int n)
{
22 int s = 0;
23 while(n>0)
24 {
25 s = s + n%10;
26 n = n/10;
}
27 return s;
28 }
29
30 boolean isMagic(int n) // Function to check for Magic number
31 {
int a = sumDig(n);
32 while(a>9)
33 {
34 a = sumDig(a);
35 }
36
if(a == 1)
37 return true;
38 else
39 return false;
40 }
41
42 public static void main(String args[])
{
43 MagicComposite_ISC2014 ob = new MagicComposite_ISC2014();
44 Scanner sc = new Scanner(System.in);
45 System.out.print("Enter the lower limit(m) : ");
46 int m = sc.nextInt();
47 System.out.print("Enter the upper limit(n) : ");
int n = sc.nextInt();
48
49 int c=0;
50 if (m<n)
51 {
52 System.out.println("The Composite Magic Integers are: ");
for(int i=m; i<=n; i++)
53
{
54 if(ob.isComposite(i)==true && ob.isMagic(i)==true)
55 {
56 if (c==0) // Printing the first number without any comma
57 System.out.print(i);
else
58 System.out.print(", "+i);
59 c++;
60 }
61 }
62 System.out.println("\nThe frequency of Composite Magic Integers is : "+c);
}
63 else
64 System.out.println("OUT OF RANGE");
65 }
66 }
67
68
69
70
71
72
73
74
75
76
77
78
79
Output:
Enter the lower limit(m) : 1200
Enter the upper limit(n) : 1300
The Composite Magic Integers are:
1207, 1216, 1225, 1234, 1243, 1252, 1261, 1270, 1288
The frequency of Composite Magic Integers is : 9
Symmetric Matrix
Question:
Write a program to declare a square matrix A[ ] [ ] of order (M x M) where ‘M’ is the number of rows and the number of columns
such that M must be greater than 2 and less than 10. Accept the value of M as user input. Display an appropriate message for
an invalid input. Allow the user to input integers into this matrix. Perform the following tasks:
Example 1
INPUT : M = 3
1 2 3
2 4 5
3 5 6
OUTPUT :
ORIGINAL MATRIX
1 2 3
2 4 5
3 5 6
THE GIVEN MATRIX IS SYMMETRIC
The sum of the left diagonal = 11
The sum of the right diagonal = 10
Example 2
INPUT : M = 4
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
OUTPUT :
ORIGINAL MATRIX
7 8 9 2
4 5 6 3
8 5 3 1
7 6 4 2
THE GIVEN MATRIX IS NOT SYMMETRIC
The sum of the left diagonal = 17
The sum of the right diagonal = 20
Example 3
INPUT : M = 22
OUTPUT : THE MATRIX SIZE IS OUT OF RANGE
Programming Code:
1 /**
* The class SymmetricMatrix_ISC2014 inputs a 2D array and checks whether it is Symmetric or not
2 * It then finds the sum of the left and the right diagonals
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2014 Question 2
6 */
import java.util.*;
7 class SymetricMatrix_ISC2014
8 {
9 public static void main(String args[])
10 {
11 Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements : ");
12 int m = sc.nextInt();
13 int A[][]=new int[m][m];
14
15 if(m>2 && m<10) // Checking for valid input of rows and columns size
16 {
System.out.println("\nInputting the elements in the Matrix: \n");
17
for(int i=0;i<m;i++)
18 {
19 for(int j=0;j<m;j++)
20 {
21 System.out.print("Enter the elements : ");
A[i][j]=sc.nextInt();
22 }
23 }
24
25 /* Printing the Original Matrix */
26 System.out.println("\nThe Original Matrix is : ");
27 for(int i=0;i<m;i++)
{
28 for(int j=0;j<m;j++)
29 {
30 System.out.print(A[i][j]+"\t");
31 }
System.out.println();
32
}
33
34 /* Checking whether the matrix is symmetric or not */
35 int flag = 0;
36 for(int i=0;i<m;i++)
37 {
for(int j=0;j<m;j++)
38 {
39 if(A[i][j] != A[j][i])
40 {
41 flag = 1; // Setting flag = 1 when elements do not match
42 break;
}
43 }
44 }
45
46 if(flag == 1)
47 System.out.println("\nThe given Matrix is Not Symmetric");
48
49
50
51
52
53
54
else
55 System.out.println("\nThe given Matrix is Symmetric");
56
57 /* Finding sum of the diagonals */
58 int ld = 0, rd = 0;
59 for(int i=0;i<m;i++)
{
60 for(int j=0;j<m;j++)
61 {
62 if(i == j) // Condition for the left diagonal
63 {
64 ld = ld + A[i][j];
}
65 if((i+j) == (m-1)) // Condition for the right diagonal
66 {
67 rd = rd + A[i][j];
68 }
69 }
}
70
71 System.out.println("The sum of the left diagonal = "+ld);
72 System.out.println("The sum of the right diagonal = "+rd);
73 }
74
75 else
76 System.out.println("The Matrix Size is Out Of Range");
}
77 }
78
79
80
81
82
83
84
Output:
Removing Words
Question:
Write a program to accept a sentence which may be terminated by either ‘.’ ‘?’ or ‘!’ only. Any other character may be ignored.
The words may be separated by more than one blank space and are in UPPER CASE.
(a) Accept the sentence and reduce all the extra blank space between two words to
a single blank space.
(b) Accept a word from the user which is part of the sentence along with its
position number and delete the word and display the sentence.
Test your program with the sample data and some random data:
Example 1
INPUT: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6
OUTPUT: A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.
Example 2
INPUT: AS YOU SOW, SO SO YOU REAP.
WORD TO BE DELETED: SO
WORD POSITION IN THE SENTENCE: 4
OUTPUT: AS YOU SOW, SO YOU REAP.
Example 3
INPUT: STUDY WELL ##.
OUTPUT: INVALID INPUT.
Programming Code:
1 /**
* The class RemoveWord_ISC2014 inputs a sentence. It also inputs a word and an integer.
2 * It then removes the word present at that position in the sentence
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Practical 2014 Question 3
6 */
import java.util.*;
7 class RemoveWord_ISC2014
8 {
9 public static void main (String args[])
10 {
11 Scanner sc = new Scanner(System.in);
12
System.out.print("Enter a sentence : ");
13 String s = sc.nextLine();
14 s = s.toUpperCase();
15 int l = s.length();
16 char last = s.charAt(l-1); // Extracting the last character
17
/* Checking whether the sentence ends with '.' or '?' or not */
18 if(last != '.' && last != '?' && last != '!')
19 {
20 System.out.println("Invalid Input. End a sentence with either '.', '?' or '!' only"
21 }
22 else
{
23 StringTokenizer str = new StringTokenizer(s," .?!");
24 int c = str.countTokens();
25 String w="",ans = "";
26 System.out.print("Enter the word to delete : ");
27 String del = sc.next();
System.out.print("Enter the word position is the sentence : ");
28 int x = sc.nextInt();
29
30 if(x<1 || x>c) // Checking whether integer inputted is acceptable or not
31 {
32 System.out.println("Sorry! The word position entered is out of range");
}
33 else
34 {
35
36
37
38
39
for(int i=1; i<=c; i++)
40 {
41 w = str.nextToken();
42 /* Skipping if the word to delete and the position matches */
43 if(w.equals(del)==true && i == x)
continue;
44 ans = ans + w + " ";
45 }
46 System.out.print("Output : "+ans.trim()+last);
47 }
48 }
}
49 }
50
51
52
53
54
Output:
1. Enter any sentence : A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
Enter the word to delete : IS
Enter the word position is the sentence : 6
Output : A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.
For example: if n = 5, then n*n = 25, hence the array will be filled as given below.
Note: Don’t be confused as to how the filling will start from the center. Just treat the above program as (see the difference in the
direction of the arrows):
So, you see, this question is nothing but the same circular matrix which we did earlier (See: Java Program to print Circular
(Spiral) Matrix). The only change is that here the filling of numbers is from ‘n*n’ to 1 every time decreasing by one. In the earlier
program it was from 1 to ‘n*n’ every time increasing by one.
So slight changes in our earlier program will result into this new spiral matrix. The changes will be:
Solution:
1 /**
* The class Circular_Matrix2 creates a Square Matrix of size n*n and fills it in a circular fa
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class Circular_Matrix2
{
8 public static void main(String args[])
9 {
10 Scanner sc = new Scanner(System.in);
11 System.out.print("Enter the number of elements : ");
12 int n = sc.nextInt();
int A[][] = new int[n][n];
13
14 int k=n*n, c1=0, c2=n-1, r1=0, r2=n-1;
15 while(k>=1)
16 {
17 for(int i=c1;i<=c2;i++)
{
18 A[r1][i]=k--;
19 }
20 for(int j=r1+1;j<=r2;j++)
21 {
22 A[j][c2]=k--;
}
23 for(int i=c2-1;i>=c1;i--)
24 {
25 A[r2][i]=k--;
26 }
27 for(int j=r2-1;j>=r1+1;j--)
28
29
30
31
32 {
33 A[j][c1]=k--;
34 }
c1++;
35 c2--;
36 r1++;
37 r2--;
38 }
39
40 /* Printing the Spiral matrix */
System.out.println("The Spiral Matrix is:");
41 for(int i=0;i<n;i++)
42 {
43 for(int j=0;j<n;j++)
44 {
System.out.print(A[i][j]+ "\t");
45 }
46 System.out.println();
47 }
48 }
49 }
50
51
52
53
Output:
For example: If rows = 4 and columns = 5, then the result should be:
Solution:
1 /**
* The class Fill_Prime fills a 2D array with 'r*c' Prime numbers
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5 import java.util.*;
6 class Fill_Prime
{
7
8 boolean isPrime(int n) // Function for checking whether a number is prime or not
9 {
10 int c = 0;
11 for(int i = 1; i<=n; i++)
12 {
if(n%i == 0)
13 c++;
14 }
15 if(c == 2)
16 return true;
else
17
return false;
18 }
19
20 public static void main(String args[])
21 {
22 Fill_Prime ob = new Fill_Prime();
Scanner sc = new Scanner(System.in);
23 System.out.print("Enter the number of rows: ");
24 int r1 = sc.nextInt();
25 System.out.print("Enter the number of columns: ");
26 int c1 = sc.nextInt();
27
28 int A[][]=new int[r1][c1]; // 2D array for storing 'r*c' prime numbers
int B[] = new int [r1*c1]; // 1D array for storing 'r*c' prime numbers
29
30 int i = 0, j;
31 int k = 1; // For generating natural numbers
32
33
34
35
36
37
38
/* First saving the 'r*c' prime numbers into a 1D Array */
39
while(i < r1*c1)
40 {
41 if(ob.isPrime(k)==true)
42 {
43 B[i] = k;
i++;
44 }
45 k++;
46 }
47
48 /* Saving the 'r*c' prime numbers from 1D array into the 2D Array */
49 int x = 0;
for(i=0;i<r1;i++)
50 {
51 for(j=0;j<c1;j++)
52 {
53 A[i][j] = B[x];
x++;
54
}
55 }
56
57 /* Printing the resultant 2D array */
58 System.out.println("The Filled Array is :");
59 for(i=0;i<r1;i++)
{
60 for(j=0;j<c1;j++)
61 {
62 System.out.print(A[i][j]+"\t");
63 }
64 System.out.println();
}
65 }
66 }
67
68
69
70
71
72
Note: If you are asked to input a square matrix of size ‘n*n’ then just input the value of ‘n’ and replace ‘r’ and ‘c’ in the above
program with ‘n’.
Similarly, you can fill a 2D array with any type of number. Just replace the function isPrime() in the above program with
the appropriate function.
Output:
Java Program to find check digit of an IMEI Number
Question:
Write a program in Java to input the first 14 digits of an IMEI number and find the check (last) digit of it.
The check digit (x) is obtained by computing the sum of digits then computing 9 times that value modulo 10.
In algorithm form:
The IMEI (15 decimal digits: 14 digits plus a check digit) includes information on the origin, model, and serial number of the
device.
1. Starting from the right, double every other digit (e.g., 7 becomes 14).
2. Sum the digits (e.g., 14 → 1 + 4).
3. Check if the sum is divisible by 10.
For Example:
If input is IMEI = 490154203237518
Design a program to accept a fifteen digit number from the user and check whether it is a valid IMEI number or not. For an
invalid input, display an appropriate message.
Programming Code:
1 /**
* The class IMEI inputs a 15 digit number and checks whether it is a valid IMEI or not
2
* @author : www.javaforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.io.*;
7 class IMEI
{
8 int sumDig(int n) // Function for finding and returning sum of digits of a number
9 {
10
11
12
13
14 int a = 0;
15 while(n>0)
16 {
a = a + n%10;
17 n = n/10;
18 }
19 return a;
20 }
21
22 public static void main(String args[])throws IOException
{
23 IMEI ob = new IMEI();
24 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
25
26 System.out.print("Enter a 15 digit IMEI code : ");
27 long n = Long.parseLong(br.readLine()); // 15 digits cannot be stored in 'int' data typ
28
29 String s = Long.toString(n); // Converting the number into String for finding length
int l = s.length();
30
31 if(l!=15) // If length is not 15 then IMEI is Invalid
32 System.out.println("Output : Invalid Input");
33 else
34 {
35 int d = 0, sum = 0;
for(int i=15; i>=1; i--)
36 {
37 d = (int)(n%10);
38
39 if(i%2 == 0)
40 {
41 d = 2*d; // Doubling every alternate digit
}
42
43 sum = sum + ob.sumDig(d); // Finding sum of the digits
44
45 n = n/10;
46 }
47
48 System.out.println("Output : Sum = "+sum);
49
50 if(sum%10==0)
System.out.println("Valid IMEI Code");
51 else
52 System.out.println("Invalid IMEI Code");
53 }
54 }
}
55
56
57
58
59
Output:
1. Enter a 15 digit IMEI code : 654122487458946
Output : Sum = 80
Valid IMEI Code
2. Enter a 15 digit IMEI code : 799273987135461
Output : Sum = 79
Invalid IMEI Code
3. Enter a 15 digit IMEI code : 79927398713
Output : Invalid Input
For example:
Programming Code:
1 /**
* The class Boundary_Element accesses and prints the boundary elements of a 2D array
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5 import java.util.*;
6 class Boundary_Element
{
7 public static void main(String args[])
8 {
9 int i,j,r1,c1;
10 Scanner sc = new Scanner(System.in);
11 System.out.print("Enter the no. of rows: "); //Inputting the number of rows
r1 = sc.nextInt();
12 System.out.print("Enter the no. of columns: "); //Inputting the number of columns
13 c1 = sc.nextInt();
14 int A[][]=new int[r1][c1];
15
16 /* Inputting the array */
for(i=0;i<r1;i++)
17
{
18 for(j=0;j<c1;j++)
19 {
20
21
22
23 System.out.print("Enter the elements: ");
24 A[i][j] = sc.nextInt();
25 }
26 }
27
28 System.out.println("The Boundary Elements are:");
for(i=0;i<r1;i++)
29 {
30 for(j=0;j<c1;j++)
31 {
32 if(i==0 || j==0 || i == r1-1 || j == c1-1) //condition for accessing boundary el
System.out.print(A[i][j]+"\t");
33
else
34 System.out.print(" \t");
35 }
36 System.out.println();
37 }
}
38 }
39
40
41
42
Output:
Java Program to Print Magic Square Matrix
Question:
A square matrix is said to be a Magic Square, if the sum of each row, each column and each diagonal is same. Write a program
to enter an integer number ‘n’. Create a magic square of size ‘n*n’. Finally, print the elements of the matrix as Magic Square.
Note: n <= 5
Sample Input: Enter the size of the matrix : 4
Sample Output: The Magic Matrix of size 4×4 is:
Sample Input: Enter the size of the matrix : 5
Sample Output: The Magic Matrix of size 5×5 is:
Solution:
1 /**
* The class Magic_Matrix creates a Square Matrix of size n*n and fills it
2 * in such a way that sum of every row and every column is the same
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 */
6 import java.io.*;
class Magic_Matrix
7 {
8 public static void main()throws IOException
9 {
10 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11 System.out.print("\n\nEnter the size of the matrix : ");
int n=Integer.parseInt(br.readLine());
12 int A[][]=new int[n][n]; // Creating the Magic Matrix
13 int i,j,k,t;
14
15 /*Initializing every cell of the matrix with 0 */
16 for(i=0;i<n;i++)
{
17 for(j=0;j<n;j++)
18 {
19 A[i][j] = 0;
20 }
21 }
22
/* When the size of the matrix is Odd */
23 if(n%2!=0)
24 {
i=0;
25
j = n/2;
26 k = 1;
27 while(k<=n*n)
28 {
29 A[i][j] = k++;
i--; // Making one step upward
30 j++; // Moving one step to the right
31 if(i<0 && j>n-1) // Condition for the top-right corner element
32 {
33 i = i+2;
34 j--;
}
35 if(i<0) // Wrapping around the row if it goes out of boundary
36 i = n-1;
37 if(j>n-1) // Wrapping around the column if it goes out of boundary
38 j = 0;
if(A[i][j]>0) // Condition when the cell is already filled
39 {
40 i = i+2;
41 j--;
42 }
43 }
}
44
45 /* When the size of the matrix is even */
46 else
47 {
48 k = 1;
49
50 /* Filling the matrix with natural numbers from 1 till n*n */
for(i=0;i<n;i++)
51 {
52 for(j=0;j<n;j++)
53 {
54 A[i][j] = k++;
}
55 }
56
57 j = n-1;
58
59 for(i=0; i<n/2; i++)
60 {
61 /* swapping corner elements of primary diagonal */
t = A[i][i];
62 A[i][i] = A[j][j];
63 A[j][j] = t;
64
65 /* swapping corner elements of secondary diagonal */
66 t = A[i][j];
A[i][j] = A[j][i];
67
A[j][i] = t;
68
69 j--;
70 }
71 }
72
73 /* Printing the Magic matrix */
74
75
76
77
78
79
80
81
82 System.out.println("The Magic Matrix of size "+n+"x"+n+" is:");
for(i=0;i<n;i++)
83 {
84 for(j=0;j<n;j++)
85 {
86 System.out.print(A[i][j]+ "\t");
87 }
System.out.println();
88 }
89 }
90 }
91
92
93
94
95
96
97
98
Output:
Program to replace words of a sentence in Special Fashion
Question:
A sentence in the Special Fashion can be printed by taking two integers (not beyond total number of words in the sentence or
less than 1). These integers tell the word number of the sentence. Replace only those words present at those given integer
places by the next character in a circular fashion according to the English Alphabets. If both the integers are same then replace
only one word. let us consider the following examples:
In the first example given above, word number 2, i.e. “has” is replaced by next characters and hence it becomes “ibt”. Similarly,
word number 4, i.e. “Books” is replaced by next characters and hence it becomes “Cpplt”.
Solution:
1 /**
* The class Special_Fashion inputs a sentence and two integers representing word numbers
2 * It then replaces the characters of those words by the next character in circular fashion
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 */
6
7 import java.util.*;
class Special_Fashion
8 {
9 String repChar(String s) //function doing the work of replacing characters
10 {
11 int l = s.length(), a = 0;
12 char ch;
String res="";
13 for(int i=0; i<l; i++)
14 {
15 ch = s.charAt(i); //extracting characters one by one
16 a = ch + 1; //storing ASCII values after adding 1 to the current character
if(ch=='z' || ch=='Z')
17 {
18 a = a - 26;
19 }
20 res = res + (char)a; //finally adding the changed character to the new String
21 }
return res;
22 }
23
24 public static void main (String args[])
25 {
26 Scanner sc = new Scanner(System.in);
27 Special_Fashion ob = new Special_Fashion();
System.out.print("\nEnter any sentence : "); //Inputting the sentence
28 String s = sc.nextLine();
29 String ans=""; //String variable to store the final result
30
31 String word[]=s.split("[. ]+"); //saving the words in an array using split()
32 int c = word.length;
33
34 System.out.print("Enter the 1st word number : ");
int x = sc.nextInt();
35 System.out.print("Enter the 2nd word number : ");
36 int y = sc.nextInt();
37
38 if(x<1 || y<1 || x>c || y>c) //checking whether integers inputted are acceptable or not
39 {
System.out.println("Sorry! The word numbers inputted are out of range");
40
}
41 else
42 {
43 if(x != y)
44 {
word[y-1]=ob.repChar(word[y-1]); //sending the words to the repChar() funct
45 }
46 word[x-1]=ob.repChar(word[x-1]);
47
48 for(int i=0; i<c; i++)
49 {
50 ans = ans + word[i] + " ";
51 }
52 System.out.print("Output = "+ans.trim()+".");
53 }
}
54 }
Output:
1) Enter any sentence : I love Java for School.
Enter the 1st word number : 2
Enter the 2nd word number : 5
Output = I mpwf Java for Tdippm.
2) Enter any sentence : I love Java for School
Enter the 1st word number : 4
Enter the 2nd word number : 4
Output = I love Java gps School.
3) Enter any sentence : I love Java for School
Enter the 1st word number : 2
Enter the 2nd word number : 6
Sorry! The word numbers inputted are out of range
For example: if n = 4, then n*n = 16, hence the array will be filled as given below.
We will take a variable ‘k’ which will begin with 1 and will do the work of filling. i.e. for every cell, it will increase by 1. The below
given processes will repeat till the value of ‘k’ becomes ‘n*n’
C1 denotes the index of the column from where we have to begin. Hence its initial value will be 0.
C2 denotes the index of the column where we have to end. Hence its initial value will be ‘n-1’ (n is the size of the matrix).
R1 denotes the index of the row from where we have to begin. Hence its initial value will be 0.
R2 denotes the index of the row where we have to end. Hence its initial value will be ‘n-1’ (n is the size of the matrix).
The filling up of the matrix in circular fashion will consist of 4 different steps which will continue till the matrix is filled completely.
Step 1: We will fill the elements of Row 0 (R1), starting from Column 0 (C1) till ‘n-1’ (C2). The cells which will be filled are marked
in the image above in yellow color.
The elements will be accessed as follows: A[R1][i], where ‘i’ will go from C1 to C2 (A[ ][ ] is the array)
Step 2: Now, we will fill the elements of Column ‘n-1’ (C2), starting from Row R1+1 till R2. The cells which will be filled are
marked in the image above in grey color.
The elements will be accessed as follows: A[j][C2], where ‘j’ will go from R1+1 to R2 (A[ ][ ] is the array)
Step 3: Next we will fill the elements of Row ‘n-1’ (R2), starting from Column C2-1 till C1. The cells which will be filled are marked
in the image above in green color.
The elements will be accessed as follows: A[R2][i], where ‘i’ will go from C2-1 to C1 (A[ ][ ] is the array)
Step 4: Now, we will fill the elements of Column C1, starting from Row R2-1 till R1+1. The cells which will be filled are marked in
the image above in blue color.
The elements will be accessed as follows: A[j][C1], where ‘j’ will go from R2-1 to R1+1 (A[ ][ ] is the array)
The above 4 steps will now repeat with the inner matrix which is marked in white color in the above image. For the inner matrix,
C1 will increase by 1 i.e. it will be C1+1.
C2 will decrease by 1 i.e. it will be C 2-1.
R1 will increase by 1 i.e. it will be R1+1.
R2 will decrease by 1 i.e. it will be R2-1.
The above processes will repeat till we have filled in ‘n*n’ values.
Output:
Number in Words
Question:
Write a program to input a natural number less than 1000 and display it in words. [Note we have solved the program for
numbers in the range [1-9999]
Test your program for the given sample data and some random data.
Sample Data:
Input: 29
Output: TWENTY NINE
Input: 17001
Output: OUT OF RANGE
Input: 119
Output: ONE HUNDRED AND NINETEEN
Input: 500
Output: FIVE HUNDRED
Programming Code:
1 /**
* The class Num2Word_ISC2011 accepts a number in the range [1-9999] and prints it in words.
2
* @author : www.javaforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.io.*;
7 class Num2Word_ISC2011
{
8 public static void main(String args[]) throws IOException
9 {
10 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
11
12 String ty[]={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety
13
14 String ten[]={"","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Sev
"Eighteen","Nineteen"};
15
16 String unit[]={"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
17
18 System.out.print("Enter a Number : ");
19 int n=Integer.parseInt(br.readLine());
20
21 /*checking whether the number is in the range [1-9999] or not*/
if(n<1 || n>9999)
22
System.out.println("Out of Range");
23
24 else
25 {
26 int th=n/1000; //finding the digit at thousand's place
27 int h=(n/100)%10; //finding the digit at hundred's place
int t=(n/10)%10; //finding the digit at ten's place
28 int u=n%10; //finding the digit at unit's place
29
30 System.out.print("Output = ");
31
32
33
34
35
36 /*Condition for printing digit at thousand's place, is that it should not be zero*/
if(th!=0)
37
System.out.print(unit[th]+" Thousand");
38
39 /*Condition for printing digit at hundred's place, is that it should not be zero*/
40 if(h!=0)
41 System.out.print(" "+unit[h]+" Hundred");
42
43 /*Condition for printing the word "And"*/
if((t!=0 || u!=0)&&(th!=0 || h!=0))
44 System.out.print(" And");
45
46 /*Condition for printing digit at ten's place*/
47 if(t==1) //When digit at ten's place is 1, we have different words like Ten, Eleven etc
48 System.out.print(" "+ten[u+1]);
49
50 else //if it is not 1 then we print the words following a normal pattern
System.out.print(" "+ty[t]+" "+unit[u]);
51 }
52 }
53 }
54
55
56
57
Output:
1. Enter a Number : 129
Output = One Hundred And Twenty Nine
2. Enter a Number : 8307
Output = Eight Thousand Three Hundred And Seven
3. Enter a Number : 54987
Out of Range
If a Fibonacci-like sequence (in which each term in the sequence is the sum of the ‘d’ previous terms) is formed, with the first ‘d’
terms being the decimal digits of the number N, then N itself occurs as a term in the sequence.
Some keith numbers are: 14 ,19, 28 , 47 , 61, 75, 197, 742, 1104, 1537……………
Solution:
1 import java.io.*;
class Keith
2 {
3 public static void main()throws IOException
4
5
6
7 {
8 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
9 System.out.print("Enter the number : "); //inputting the number
int n=Integer.parseInt(br.readLine());
10 int copy=n;
11 String s=Integer.toString(n);
12 int d=s.length(); //finding the number of digits (d) in the number
13 int arr[]=new int[n]; //array for storing the terms of the series
14
15 for(int i=d-1; i>=0; i--)
{
16 arr[i]=copy%10; //storing the digits of the number in the array
17 copy=copy/10;
18
19 }
20
21 int i=d,sum=0;
22 while(sum<n) //finding the sum till it is less than the number
{
23 sum = 0;
24 for(int j=1; j<=d; j++) //loop for generating and adding the previous 'd' terms
25 {
26 sum=sum+arr[i-j];
}
27
arr[i]=sum; //storing the sum in the array
28 i++;
29 }
30 /* When the control comes out of the while loop, either the
31 sum is equal to the number or greater than it */
if(sum==n) //if sum is equal to the number, then it is a Keith number
32 System.out.println("The number is a Keith Number");
33 else
34 System.out.println("The number is a not a Keith Number");
35 }
36 }
37
38
39
Output:
Enter the number : 197
The number is a Keith Number
Enter the number : 14
The number is a Keith Number
Enter the number : 53
The number is a not a Keith Number
Test your program for the following data and some random data.
SAMPLE DATA
INPUT:
N=9
OUTPUT:
4+5
2 + 3+ 4
INPUT:
N = 15
OUTPUT:
7 +8
1 +2+ 3+ 4+ 5
4 +5+ 6
INPUT:
N = 21
OUTPUT:
10+ 11
1+ 2+ 3+ 4+ 5+ 6
6+ 7+ 8
Programming Code:
1 /**
* The class Q1_ISC2006 inputs a number and prints all the series of consecutive natural number
2 sum equals the number
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program – Java
5 * @Question Year : ISC Practical 2006 Question 1
6 */
7
import java.util.*;
8 class Q1_ISC2006
9 {
10 public static void main(String args[])
11 {
12 Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
13 int n = sc.nextInt();
14 int sum = 0, c = 0, j = 0;
15 for(int i=1; i<n; i++)
16 {
sum = i;
17 j = i+1;
18 while(sum < n)
19 {
20 sum = sum + j;
21 j++;
}
22 if(sum == n)
23 {
24 for(int k=i; k<j; k++)
25 {
26
27
28
29 if(k==i)
30 System.out.print(k);
31 else
32 System.out.print(" + "+k);
}
33 System.out.println();
34 }
35 }
36 }
}
37
38
39
40
Output:
1. Enter a number : 15
1+2+3+4+5
4+5+6
7+8
2. Enter a number : 95
5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14
17 + 18 + 19 + 20 + 21
47 + 48
Example:
INPUT – Jaaavvvvvvvvaaaaaaaaaaa
OUTPUT – Java
INPUT – Heeeiiiissggoiinggg
OUTPUT – Heisgoing
Programming Code:
1 /**
* The class RemoveRepChar inputs a word and replaces the sequence of repeated characters by its
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class RemoveRepChar
{
8 public static void main(String args[])
9 {
10 Scanner sc = new Scanner(System.in);
11 System.out.print("Enter any word: "); // Inputting the word
12 String s = sc.nextLine();
13
14
15 s = s + " "; // Adding a space at the end of the word
16 int l=s.length(); // Finding the length of the word
17 String ans=""; // Variable to store the final result
18 char ch1,ch2;
19 for(int i=0; i<l-1; i++)
{
20 ch1=s.charAt(i); // Extracting the first character
21 ch2=s.charAt(i+1); // Extracting the next character
22
23 /* Adding the first extracted character to the result
24 if the current and the next characters are different*/
25
if(ch1!=ch2)
26
{
27 ans = ans + ch1;
28 }
29 }
30 System.out.println("Word after removing repeated characters = "+ans); // Printing the r
}
31 }
32
33
34
Output:
Example 1:
Enter any word: Jaaavvvvvvvvaaaaaaaaaaa
Word after removing repeated characters = Java
Example 2:
Enter any word: iiiiiisssssfffffffffffffuunnnnn
Word after removing repeated characters = isfun
This short article will cover few simple but smart steps which we can use to sort a 2D array. Now, there are two different
approaches which you can take while sorting a given 2D array.
Method 1: Convert the 2D array into 1D and then sort that 1D array.
Below are the steps that follow:
Programming Code:
1 /**
* The class Sort2D_Method1 inputs a two dimensional array and sorts it in ascending order
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program – Java
4 */
5
6 import java.util.*;
7 class Sort2D_Method1
{
8 public static void main(String args[])
9 {
10 Scanner sc = new Scanner(System.in);
11 System.out.print("Enter the no. of rows: ");
12 int m = sc.nextInt();
System.out.print("Enter the no. of columns: ");
13 int n = sc.nextInt();
14 int A[][]=new int[m][n];
15 for(int i=0;i<m;i++)
16 {
for(int j=0;j<n;j++)
17 {
18 System.out.print("Enter the elements: ");
19 A[i][j] = sc.nextInt();
20 }
21 }
22
System.out.println("The original matrix:");
23 for(int i=0;i<m;i++)
24 {
25 for(int j=0;j<n;j++)
26 {
27 System.out.print(A[i][j]+"\t");
}
28 System.out.println();
29 }
30
31 /* Saving the 2D Array into a 1D Array */
32 int B[]=new int[m*n];
int x = 0;
33 for(int i=0;i<m;i++)
34 {
35 for(int j=0;j<n;j++)
36 {
37 B[x] = A[i][j];
x++;
38 }
39 }
40
41 /*Sorting the 1D Array in Ascending Order*/
42 int t=0;
43 for(int i=0; i<(m*n)-1; i++)
{
44 for(int j=i+1; j<(m*n); j++)
45 {
46
47
48
49
50
51
52
53 if(B[i]>B[j])
54 {
t=B[i];
55 B[i]=B[j];
56 B[j]=t;
57 }
58 }
}
59
60
/*Saving the sorted 1D Array back into the 2D Array */
61 x = 0;
62 for(int i=0;i<m;i++)
63 {
64 for(int j=0;j<n;j++)
{
65 A[i][j] = B[x];
66 x++;
67 }
68 }
69
70 System.out.println("The Sorted Array:");
for(int i=0;i<m;i++)
71 {
72 for(int j=0;j<n;j++)
73 {
74 System.out.print(A[i][j]+"\t");
}
75
System.out.println();
76 }
77 }
78 }
79
80
81
82
83
84
85
Programming Code:
1 /**
* The class Sort2D_Method2 inputs a two d
2
and sorts it in ascending order
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program – Java
*/
5
6
import java.util.*;
7 class Sort2D_Method2
8 {
9 public static void main(String args[])
10 {
Scanner sc = new Scanner(System.in)
11 System.out.print("Enter the no. of
12 int m = sc.nextInt();
13 System.out.print("Enter the no. of
14 int n = sc.nextInt();
15 int A[][]=new int[m][n];
for(int i=0;i<m;i++)
16 {
17 for(int j=0;j<n;j++)
18 {
19 System.out.print("Enter th
A[i][j] = sc.nextInt();
20 }
21 }
22
23 System.out.println("The original m
24 for(int i=0;i<m;i++)
25 {
for(int j=0;j<n;j++)
26 {
27 System.out.print(A[i][j]+"
28 }
29 System.out.println();
30 }
31
/* Sorting the 2D Array */
32 int t=0;
33 for(int x=0;x<m;x++)
34 {
35 for(int y=0;y<n;y++)
{
36 for(int i=0;i<m;i++)
37 {
38 for(int j=0;j<n;j++)
39 {
40 if(A[i][j]>A[x][y]
{
41 t = A[x][y];
42 A[x][y] = A[i]
43 A[i][j] = t;
44 }
}
45
}
46 }
47 }
48
49 System.out.println("The Sorted Arr
50 for(int i=0;i<m;i++)
{
51 for(int j=0;j<n;j++)
52 {
53 System.out.print(A[i][j]+"
54
55
56
57
}
System.out.println();
}
}
}
PendulumArrangementofalistofIntegersinanArra
y
Question:
Write a program to input a list of integers in an array and arrange them in a way similar to the to-and-fro movement of a
Pendulum.
The minimum element out of the list of integers, must come in center position of array. The number in the ascending order next
to the minimum, goes to the left, the next higher number goes to the right of minimum number and it continues. As higher
numbers are reached, one goes to either side of the minimum value in a to-and-fro manner similar to that of a Pendulum.
Example:
INPUT – 1 2 3 4 5
OUTPUT – 5 3 1 2 4
INPUT – 11 12 31 14 5
OUTPUT – 31 12 5 11 14
Programming Code:
1 /**
* The class Pendulum_Array_V1 inputs a set of integers in an Array and arranges them in Pendulu
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class Pendulum_Array_V1
{
8 public static void main(String args[])
9 {
10 Scanner sc = new Scanner(System.in);
11 System.out.print("\nEnter number of elements: "); // Inputting the number of elements
12 int n = sc.nextInt();
int A[] = new int[n]; //original array
13 int B[] = new int[n]; //array for storing the result
14
15 /*Inputting the Array*/
16 for(int i=0; i<n; i++)
17 {
System.out.print("Enter Element "+(i+1)+": ");
18
A[i] = sc.nextInt();
19 }
20
21 /*Sorting the Inputted Array in Ascending Order*/
22 int t=0;
23 for(int i=0; i<n-1; i++)
24
25
26
27
28
29 {
30 for(int j=i+1; j<n; j++)
{
31 if(A[i]>A[j])
32 {
33 t=A[i];
34 A[i]=A[j];
35 A[j]=t;
}
36 }
37 }
38
39 /*Printing the Sorted Array*/
40 System.out.println("\nThe Sorted Array Is");
41 for(int i=0; i<n; i++)
{
42 System.out.print(A[i]+"\t");
43 }
44
45 int mid = (n-1)/2;
46 int x = 1, lim = n-1-mid;
47
48 /* Pendulum Arrangement Starts Here */
B[mid]=A[0];
49 for(int i=1; i<=lim; i++)
50 {
51 if((mid+i)<n) //going to the right of middle
52 B[mid+i]=A[x++];
if((mid-i)>=0) //going to the left of middle
53 B[mid-i]=A[x++];
54 }
55
56 /*Printing the Result*/
57 System.out.println("\n\nThe Result Is");
58 for(int i=0; i<n; i++)
{
59 System.out.print(B[i]+"\t");
60 }
61 }
62 }
63
64
65
66
67
Output:
Example 1:
Enter number of elements: 5
Enter Element 1: 1
Enter Element 2: 2
Enter Element 3: 3
Enter Element 4: 4
Enter Element 5: 5
The Sorted Array Is
1 2 3 4 5
The Result Is
5 3 1 2 4
Example 2:
Enter number of elements: 6
Enter Element 1: 12
Enter Element 2: 34
Enter Element 3: 11
Enter Element 4: 5
Enter Element 5: 67
Enter Element 6: 20
The Sorted Array Is
5 11 12 20 34 67
The Result Is
34 12 5 11 20 67
Note: If you are told to do the same thing but instead of the minimum element coming in the middle cell, you are told to put the
maximum element in the middle cell, the next highest element goes to the left, then the next to the right of the middle cell and so
on.
Example:
INPUT – 1 2 3 4 5
OUTPUT – 2 4 5 3 1
Programming Code:
1 /**
* The class Pendulum_Array_V2 inputs a set of integers in an Array and arranges them in Pendulu
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.util.*;
7 class Pendulum_Array_V2
{
8 public static void main(String args[])
9 {
10 Scanner sc = new Scanner(System.in);
11 System.out.print("\nEnter number of elements: "); // Inputting the number of elements
12 int n = sc.nextInt();
int A[] = new int[n]; //original array
13 int B[] = new int[n]; //array for storing the result
14
15 /*Inputting the Array*/
16 for(int i=0; i<n; i++)
17 {
System.out.print("Enter Element "+(i+1)+": ");
18
A[i] = sc.nextInt();
19 }
20
21 /*Sorting the Inputted Array in Descending Order*/
22 int t=0;
23 for(int i=0; i<n-1; i++)
{
24 for(int j=i+1; j<n; j++)
25 {
26
27
28
29
30
31 if(A[i]<A[j])
32 {
33 t=A[i];
A[i]=A[j];
34
A[j]=t;
35 }
36 }
37 }
38
39 /*Printing the Sorted Array*/
System.out.println("\nThe Sorted Array Is");
40 for(int i=0; i<n; i++)
41 {
42 System.out.print(A[i]+"\t");
43 }
44
45 int mid = (n-1)/2;
int x = 1, lim = n-1-mid;
46
47 /* Pendulum Arrangement Starts Here */
48 B[mid]=A[0];
49 for(int i=1; i<=lim; i++)
50 {
51 if((mid-i)>=0)
B[mid-i]=A[x++]; //going to left of middle
52 if((mid+i)<n)
53 B[mid+i]=A[x++]; //going to right of middle
54 }
55
56 /*Printing the Result*/
57 System.out.println("\n\nThe Result Is");
for(int i=0; i<n; i++)
58 {
59 System.out.print(B[i]+"\t");
60 }
61 }
}
62
63
64
65
66
67
Output:
Example 1:
Enter number of elements: 5
Enter Element 1: 1
Enter Element 2: 2
Enter Element 3: 3
Enter Element 4: 4
Enter Element 5: 5
The Sorted Array Is
5 4 3 2 1
The Result Is
2 4 5 3 1
Example 2:
Enter number of elements: 6
Enter Element 1: 12
Enter Element 2: 34
Enter Element 3: 11
Enter Element 4: 5
Enter Element 5: 67
Enter Element 6: 20
The Sorted Array Is
67 34 20 12 11 5
The Result Is
12 34 67 20 11 5
Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Code: U V W X Y Z A B C D E F G H I J K L M N O P Q R S T
Fist an extra space is added to the end of the string. To make things little more difficult, spaces within the original text are
replaced with QQ before the text is encrypted. Double Q (QQ) was selected because no English word ends in Q or contains
QQ.
Additionally the coded message is printed in blocks of six characters separated by spaces. The last block might not contain six
characters. Write a program that takes the coded text (less than 100 characters), the shift value and prints the decoded original
text.Your program must reject any non-valid value for shift and display an error message “INVALID SHIFT VALUE)”. Assume all
characters are upper case. Test your program for the following data and some data that you have coded, using the rules given
above:
SAMPLE DATA:
1. INPUT:
CODED TEXT : “UHINBY LKKQCH HYLKK”
SHIFT : 7
OUTPUT:
DECODED TEXT : ANOTHER VALUE
2. INPUT:
CODED TEXT : “RUIJGG EVGGBK SAGG”
SHIFT : 11
OUTPUT:
DECODED TEST : BEST OF LUCK
3. INPUT:
CODED TEXT : “DKSMMW NAMMUK QMM”
SHIFT : 29
OUTPUT:
INVALID SHIFT VAULE
Programming Code:
1 /**
* The class Decode_ISC2003 inputs an encrypted coded text and then decodes it by adding the giv
2
* @author : www.javaforschool.com
3
4 * @Program Type : BlueJ Program - Java
* @Question Year : ISC Practical 2003, Question 1
5
*/
6
7 import java.io.*;
8 public class Decode_ISC2003
9 {
10 public static void main(String args[])throws IOException
{
11 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
12 System.out.print("Enter Coded Text : "); // inputting coded text
13 String s = br.readLine();
14 int l = s.length();
15 s = s.toUpperCase(); // converting the coded text into Uppercase
s = s + " "; // adding a space at the end
16
17 if(l>=100) // checking whether length of inputted code is less than 100
18 System.out.println("!!! Invalid Length of Coded Text !!!");
19
20 else
21 {
System.out.print("Enter the Shift Value : ");
22 int shift = Integer.parseInt(br.readLine());
23
24 if(shift<1 || shift>26) // checking whether shift value is between 1 and 26
25 System.out.println("!!! Invalid Shift Value !!!");
26
27 else
28 {
int a, b;
29 char ch1, ch2;
30 String dec=""; //new String for storing the decoded text
31
32 for(int i=0; i<l; i++)
33 {
34 ch1 = s.charAt(i); // extracting characters one by one
ch2 = s.charAt(i+1); // extracting the next character
35
36 /* Below we are adding shift value to the characters
37 * if ch1 = 'A' and shift = 7,
38 * then ch1 + shift - 1 will give us: 'A'+7-1 = 65+7-1 = 71
39 * which is the ASCII value of 'G'
*/
40 a = ch1 + shift - 1; // storing ASCII values after adding shift to the curr
41 b = ch2 + shift - 1; // storing ASCII values after adding shift to the next
42
43 /* If the currrent character and the next character are both 'Q' then we ha
44 * hence the ASCII value should be 32
45 */
if((char)a == 'Q' && (char)b == 'Q')
46 {
47 a = 32;
48 i++;
49 }
50
51 /* If ASCII value after adding the shift becomes more than 90,
* then we subtract 26 from it, to make it circular,
52 * eg. 'U'+7-1 = 85+7-1 = 91, but we want 'A' whose ASCII value is 65
53 * so 91-26 will give us 65
54
55
56
57
58
59 */
60 if(a>90)
61 a = a - 26;
62 if(ch1 != ' ')
dec = dec + (char)a; // finally adding the decoded character to the new
63 }
64 System.out.println("Decoded Text : "+dec);
65 }
66 }
67 }
}
68
69
70
71
72
73
Output:
Example 1:
Example 2:
Example 3:
Programming Code:
1 /**
* The class TimeInWords_ISC2003 inputs hours & minutes and then prints out the time they repre
2 * @author : www.guideforschool.com
3 * @Program Type : BlueJ Program – Java
4 * @Question Year : ISC Practical 2003, Question 2
5 */
6
7 import java.util.*;
class TimeInWords_ISC2003
8 {
9 public static void main(String args[])
10 {
11 Scanner sc = new Scanner(System.in);
12 /* Inputting hours and minutes */
System.out.print("Enter Hours : ");
13 int h = sc.nextInt();
14 System.out.print("Enter Minutes : ");
15 int m = sc.nextInt();
16
17 if((h>=1 && h<=12) && (m>=0 && m<=59)) // checking whether given input is legal or not.
{
18 /* creating an array containing numbers from 1-29 in words */
19 String words[]={"", "One", "Two", "Three", "Four", "Five",
20 "Six","Seven", "Eight", "Nine","Ten",
21 "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen",
"Seventeen","Eighteen","Nineteen", "Twenty",
22
23
24
25
26
27 "Twenty one", "Twenty two", "Twenty three", "Twenty four", "Twenty five",
28 "Twenty six","Twenty seven", "Twenty eight", "Twenty nine"};
29
30 /* The below code is for finding whether to print the word 'minute' or 'minutes' */
String plu, a;
31
if(m == 1)
32 plu = "Minute";
33 else
34 plu = "Minutes";
35
36 /* When we have minutes from 31-59, we print the hour ahead of the given hour
* like 6:55 will be 5 minutes to 7 and not 5 minutes to six
37 * when we print the hour ahead of the given hour, we face a problem at hour = 12
38 * because if we print an hour ahead of 12, it will be thirteen, but we want 1
39 * so the below code checks this and decides what hour to print in words when minut
40 */
41 if(h==12)
a = words[1];
42 else
43 a = words[h+1];
44
45 /* The below code checks minutes and accordingly prints the time in words with the
46 */
System.out.print("Output : "+h+":"+m+" ----- "); //printing the given time in numbe
47
if(m==0)
48 System.out.println(words[h]+" O' clock");
49 else if(m==15)
50 System.out.println("Quarter past "+words[h]);
51 else if(m==30)
System.out.println("Half past "+words[h]);
52 else if(m==45)
53 System.out.println("Quarter to "+a);
54 else if(m<30) // condition for minutes between 1-29
55 System.out.println(words[m]+" "+plu+" past "+words[h]);
56 else
System.out.println(words[60-m]+" "+plu+" to "+a);
57 } //end of outer if
58 else
59 System.out.println("Invalid Input !"); //printing error message for illegal input
60 }
}
61
62
63
64
65
66
Output:
Example 1:
Enter Hours : 12
Enter Minutes : 39
Output : 12:39 —– Twenty one Minutes to One
Example 2:
Enter Hours : 12
Enter Minutes : 39
Output : 12:39 —– Twenty one Minutes to One
Example 3:
Enter Hours : 7
Enter Minutes : 16
Output : 7:16 —– Sixteen Minutes past Seven
Example 4:
Enter Hours : 5
Enter Minutes : 30
Output : 5:30 —– Half past Five
Example 5:
Enter Hours : 8
Enter Minutes : 45
Output : 8:45 —– Quarter to Nine
Example 6:
Enter Hours : 2
Enter Minutes : 60
Invalid Input !
Example 7:
Enter Hours : 4
Enter Minutes : 0
Output : 4:0 —– Four ‘O’ clock
INPUT:
Enter number of sentences: 2
Enter the sentences:
This is a sample piece of text to illustrate this question
if you are smart you will solve this right.
OUTPUT: right this solve will you smart are you if question this illustrate to text of piece sample a is this
NOTE : Individual words (i.e. characters of every word) are not reversed
Test your program for the following data and some random data:
Sample Input 1 :
Enter number of sentences: 1
Enter the text:
Do not judge a book by its cover.
Sample Output: Cover its by book a judge not do
Sample Input 2:
Enter number of sentences: 2
Enter the text:
Emotions, controlled and directed to work, is character.
By Swami Vivekananda.
Sample Output: Vivekananda Swami By character is work to dedicated and controlled Emotions
Programming Code:
1
2
3
/**
4 * The class Sent_Merge_Rev inputs multiple sentences and prints the words in reverse order
5 * without any punctuation marks other than blanks
6 * @author : www.guideforschool.com
7 * @Program Type : BlueJ Program – Java
8 */
9
import java.util.*;
10 class Sent_Merge_Rev
11 {
12 public static void main(String args[])
13 {
14 Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of sentences: ");
15 int n = sc.nextInt();
16 sc.nextLine(); //for absorbing the extra line (enter key input from above)
17 String s = "";
18 for(int i=1; i<=n; i++)
{
19 System.out.print("Enter Sentence "+i+": ");
20 s = s + sc.nextLine();
21 }
22
23 StringTokenizer str = new StringTokenizer(s," '.,;:!?");
24 int c = str.countTokens();
String w = "", rev = "";
25 for(int i=1; i<=c; i++)
26 {
27 w = str.nextToken();
28 rev = w+" "+rev;
29 }
30
System.out.println("Output: "+rev);
31 }
32 }
33
34
35
Output:
Example 1:
Enter the number of sentences: 2
Enter Sentence 1: Emotions, controlled and directed to work, is character.
Enter Sentence 2: By Swami Vivekananda.
Output: Vivekananda Swami By character is work to directed and controlled Emotions
Example 2:
Enter the number of sentences: 3
Enter Sentence 1: Did you know?
Enter Sentence 2: ICSE and ISC computer is really easy.
Enter Sentence 3: Thanks to guideforschool!
Output: guideforschool to Thanks easy really is computer ISC and ICSE know you Did
Programming Code:
1 /**
* The class Alphabet_Freq inputs a string and counts the frequency of each alphabet present in
2
* @author : www.guideforschool.com
3 * @Program Type : BlueJ Program – Java
4 */
5
6 import java.util.*;
7 class Alphabet_Freq
{
8 public static void main(String args[])
9 {
10 Scanner sc = new Scanner(System.in);
11 System.out.print("Enter any word: ");
12 String s = sc.next();
s=s.toLowerCase(); //converting the string into lowercase
13 int l=s.length(); //finding the length of the string
14 char alph[] = new char[26]; //array for storing alphabets from 'a' to 'z'
15 int freq[] = new int[26]; //array for storing frequency of all alphabets
16 char c = 'a';
for(int i=0; i<26; i++)
17 {
18 alph[i]=c; //storing all alphabets from 'a' till 'z' in alph[] array
19 freq[i]=0; //intializing the count of every alphabet with '0'
20 c++;
21 }
22
System.out.println("Output:");
23 System.out.println("=========================="); //this is just for styling the look o
24
25
26
27
28 System.out.println("Alphabet\tFrequency");
29 System.out.println("==========================");
30
char ch;
31
for(int i=0; i<26; i++)
32 {
33 for(int j=0; j<l; j++)
34 {
35 ch = s.charAt(j); //extracting characters of the string one by one
if(ch == alph[i]) //first checking the whole string for 'a', then 'b' and so on
36 freq[i]++; //increasing count of those aplhabets which are present in the s
37 }
38 }
39
40 for(int i=0; i<26; i++)
41 {
if(freq[i]!=0) //printing only those alphabets whose count is not '0'
42 System.out.println(" "+alph[i]+"\t\t "+freq[i]);
43 }
44 }
45 }
46
47
48
49
Output:
Enter any string: iloveguideforschool
Output:
==========================
Alphabet Frequency
==========================
c 1
d 1
e 2
f 1
g 1
h 1
i 2
l 2
o 4
r 1
s 1
u 1
v 1
[Note: We will be writing the main() function also in this program so as to familiarize the students on how to run programs based
on the concept of inheritance.]
Programming Code:
/**
* The superclass Record stores the stores the name and ranks of 50 students and
* the subclass Rank finds the highest rank along with the name
* the class Question11_ISC2011 is used to run the above classes.
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
* @Question Year : ISC Theory 2011 Question 11
*/
import java.util.*;
class Record //superclass
{
String name[];
int rnk[];
Record()
{
name = new String[5];
rnk = new int[5];
}
void readvalues()
{
Scanner sc = new Scanner(System.in);
System.out.println("*** Inputting The Names And Ranks ***");
for(int i=0;i<5;i++)
{
System.out.print("Enter name of student "+(i+1)+" : ");
name[i] = sc.nextLine();
System.out.print("Enter his rank : ");
rnk[i] = sc.nextInt();
sc.nextLine(); //to absorb the extra line (enter key input from above)
}
}
void display()
{
System.out.println("Name\t\tRank");
System.out.println("-------\t\t-------");
for(int i=0;i<5;i++)
{
System.out.println(name[i]+"\t\t"+rnk[i]);
}
}
} //end of superclass Record
class Rank extends Record //subclass
{
int index;
Rank()
{
super(); //invoking the constructor of superclass
index = 0;
}
void highest()
{
int max = rnk[0];
for(int i=0;i<5;i++)
{
if(rnk[i]>max)
{
index = i;
}
}
}
void display()
{
super.display(); //calling the superclass function display()
System.out.println("\nTop most rank = "+rnk[index]);
System.out.println("Student with topmost rank = "+name[index]);
}
} //end of subclass Rank
public class Question11_ISC2011 //Class which will contain the main() method and execute the pro
{
public static void main(String args[])
{
Rank ob = new Rank(); //creating object of subclass
ob.readvalues();
ob.highest();
System.out.println("*** Output ***");
ob.display(); //calling display() function of subclass
}
}
Output:
[Note: We have shown output of the same program with only 5 students and not 50. But the above program works likewise for
50 students]
*** Inputting The Names And Ranks ***
Enter name of student 1 : Aamir
Enter his rank : 5
Enter name of student 2 : Zakir
Enter his rank : 2
Enter name of student 3 : Saalim
Enter his rank : 7
Enter name of student 4 : Samir
Enter his rank : 3
Enter name of student 5 : Saif
Enter his rank : 6
*** Output ***
Name Rank
—– —–
Aamir 5
Zakir 2
Saalim 7
Samir 3
Saif 6
Top most rank = 2
Student with topmost rank = Zakir
[Note: We will be writing the main() function also in this program so as to familiarize the students on how to run programs based
on the concept of inheritance.]
Programming Code:
1 /**
* The superclass Detail stores the details of a customer and the subclass Bill calculates the
2 * the class Question12_ISC2012 is used to run the above classes.
3 * @author : www.guideforschool.com
4 * @Program Type : BlueJ Program - Java
5 * @Question Year : ISC Theory 2012 Question 12
6 */
7
import java.util.*;
8 class Detail //superclass
9 {
10 String name, address;
11 long telno;
12 double rent;
13
Detail(String n1, String a1, long t1, double r1)
14 {
15 name = n1;
16 address = a1;
17 telno = t1;
rent = r1;
18 }
19
20 void show()
21 {
22 System.out.println("Name of customer = "+name);
23 System.out.println("Address = "+address);
System.out.println("Telephone Number = "+telno);
24 System.out.println("Monthly Rental = "+rent);
25 }
26 } //end of superclass Detail
27
28 class Bill extends Detail //subclass
29 {
int n;
30 double amt;
31
32 Bill(String n1, String a1, long t1, double r1, int c)
33 {
34 super(n1,a1,t1,r1); //initializing data members of superclass by calling its constructo
n = c;
35 amt = 0.0;
36 }
37
38 void cal()
39 {
40 if(n>=1 && n<=100)
amt = rent;
41 else if(n>=101 && n<=200)
42 amt = 0.6*n + rent;
43
44
45
46
47
48
49
50 else if(n>=201 && n<=300)
amt = 0.8*n + rent;
51 else
52 amt = 1*n + rent;
53 }
54
55 void show()
56 {
super.show(); //calling the superclass function show()
57 System.out.println("No. of calls = "+n);
58 System.out.println("Amount to be paid = Rs. "+amt);
59 }
60 } //end of subclass Bill
61
public class Question12_ISC2012 //Class which will contain the main() method and execute the pro
62 {
63 public static void main(String args[])
64 {
65 Scanner sc = new Scanner(System.in);
66 System.out.print("Enter the name : ");
String n1 = sc.nextLine();
67 System.out.print("Enter the address : ");
68 String a1 = sc.nextLine();
69 System.out.print("Enter the telephone number : ");
70 long t1 = sc.nextLong();
System.out.print("Enter the monthly rental : ");
71
double r1 = sc.nextDouble();
72 System.out.print("Enter the number of calls : ");
73 int c = sc.nextInt();
74
75 Bill ob = new Bill(n1,a1,t1,r1,c); //creating object of subclass
76 System.out.println("*** Output ***");
ob.cal();
77 ob.show(); //calling show() function of subclass
78 }
79 }
80
81
82
83
84
85
86
Output:
Enter the name : Guide For School
Enter the address : 123, Sample Street
Enter the telephone number : 1234567890
Enter the monthly rental : 180
Enter the number of calls : 270
*** Output ***
Name of customer = Guide For School
Address = 123, Sample Street
Telephone Number = 1234567890
Monthly Rental = Rs. 180.0
No. of calls = 270
Amount to be paid = Rs. 396.0
Programming Code:
/**
* The class Smith inputs a number and checks whether it is a Smith Number or not
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
* @Question Year : ISC Practical 2008 Question 1
*/
import java.util.*;
class Smith
{
//function for finding sum of digits
int sumDig(int n)
{
int s=0;
while(n>0)
{
s=s+n%10;
n=n/10;
}
return s;
}
//function for generating prime factors and finding their sum
int sumPrimeFact(int n)
{
int i=2, sum=0;
while(n>1)
{
if(n%i==0)
{
sum=sum+sumDig(i); //Here 'i' is the prime factor of 'n' and we are finding its
n=n/i;
}
else
i++;
}
return sum;
}
//function to check for composite number
boolean isComposite(int n)
{
int c=0;
for(int i=1; i<=n; i++)
{
if(n%i==0)
{
c++;
}
}
if(c>2)
return true;
else
return false;
}
public static void main(String args[])
{
Smith ob=new Smith();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number : ");
int n=sc.nextInt();
if(ob.isComposite(n) == false)
{
System.out.println("You have entered a non-Composite Number. Please enter a composi
}
else
{
int a=ob.sumDig(n);// finding sum of digit
int b=ob.sumPrimeFact(n); //finding sum of prime factors
System.out.println("Sum of Digit = "+a);
System.out.println("Sum of Prime Factor = "+b);
if(a==b)
System.out.print(n+" is a Smith Number");
else
System.out.print(n+" is Not a Smith Number");
}
}
}
Output:
1. Enter a Number : 94
Sum of Digit = 13
Sum of Prime Factor = 13
94 is a Smith Number
2. Enter a Number : 102
Sum of Digit = 3
Sum of Prime Factor = 13
102 is Not a Smith Number
3. Enter a Number : 4937775
Sum of Digit = 42
Sum of Prime Factor = 42
4937775 is a Smith Number
Question:
A super class Perimeter has been defined to calculate the perimeter of a parallelogram. Define a subclass Area to compute the
area of the parallelogram by using the required data members of the super class. The details are given below:
Class name : Perimeter
Data members/instance variables:
a : to store the length in decimal
b : to store the breadth in decimal
Member functions:
Perimeter( … ) : parameterized constructor to assign values to data members
double Calculate( ) : calculate and return the perimeter of a parallelogram as 2 * (length + breadth)
void show() : to display the data members along with the perimeter of the parallelogram
Class name : Area
Data members/instance variables:
h : to store the height in decimal
area : to store the area of the parallelogram
Member functions:
Area( … ) : parameterized constructor to assign values to data members of both the classes
void doarea( ) : compute the area as (breadth * height)
void show() : display the data members of both classes along with the area and perimeter of the parallelogram.
Specify the class Perimeter giving details of the constructor( … ), void Calculate( ) and void show( ). Using the concept of
inheritance, specify the class Area giving details of the constructor( … ), void doarea( ) and void show( ).
The main function and algorithm need not be written.
[Note: We will be writing the main() function also in this program so as to familiarize the students on how to run programs based
on the concept of inheritance.]
Programming Code:
/**
* The superclass Perimeter calculate the perimeter of a parallelogram and
* the subclass Area calculates the area of a parallelogram
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
* @Question Year : ISC Theory 2013 Question 11
*/
import java.io.*;
class Perimeter //superclass
{
double a,b;
Perimeter(double x, double y)
{
a=x;
b=y;
}
double Calculate()
{
double p=2*(a+b);
return p;
}
void show()
{
System.out.println("Length = "+a);
System.out.println("Breadth = "+b);
System.out.println("Perimeter = "+Calculate()); //printing perimeter by calling Cal
}
} //end of superclass Perimeter
class Area extends Perimeter //subclass
{
double h, area;
Area(double x, double y, double z)
{
super(x,y); //initializing data members of superclass by calling its constructor
h=z;
}
void doarea()
{
area=b*h;
}
void show()
{
super.show(); //calling the superclass function show()
System.out.println("Height = "+h);
System.out.println("Area = "+area);
}
} //end of subclass Area
/* In your exams you don't need to write the below given code
We are writing it so as to familiarize the students on how to run
programs based on the concept of inheritance.*/
public class Question11_ISC2013 //Class which will contain the main() method and execute the pro
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter The Length : ");
double x=Double.parseDouble(br.readLine());
System.out.print("Enter The Breadth : ");
double y=Double.parseDouble(br.readLine());
System.out.print("Enter The Height : ");
double z=Double.parseDouble(br.readLine());
Area ob=new Area(x,y,z); //creating object of subclass
System.out.println("*** Output ***");
ob.doarea();
ob.show(); //calling show() function of subclass
}
}
Output:
Enter The Length : 5
Enter The Breadth : 7
Enter The Height : 9
*** Output ***
Length = 5.0
Breadth = 7.0
Perimeter = 24.0
Height = 9.0
Area = 63.0
Programming Code:
/**
* The class Fibonacci_Recursion prints the Fibonacci Series upto ‘n’ terms using the concept of
* @author : www.guideforschool.com
* @Program Type : BlueJ Program – Java
* @Question Year : ISC Theory 2005 Question 12
*/
import java.util.*;
class Fibonacci_Recursion
{
int a,b,c,limit;
Fibonacci_Recursion()
{
a=0;
b=1;
c=0;
limit=0;
}
void input()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the limit : ");
limit = sc.nextInt();
}
int fib(int n)
{
if(n<=1)
return a;
else if(n==2)
return b;
else
return (fib(n-1)+fib(n-2));
}
void generate_fibseries()
{
System.out.println("The Fibonacci Series is:");
for(int i=1;i<=limit;i++)
{
c=fib(i);
System.out.print(c+" ");
}
}
public static void main(String args[])
{
Fibonacci_Recursion ob = new Fibonacci_Recursion();
ob.input();
ob.generate_fibseries();
}
}
Output:
Enter the limit : 11
The Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34 55
Enter the limit : 20
The Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Note: Hexadecimal Number system is a number system which can represent a number in any other number system in terms of
digits ranging from 0 to 9 and then A – F only. This number system consists of only sixteen basic digits i.e. 0, 1, 2, 3, 4, 5, 6, 7,
8, 9, A, B, C, D, E and F. Here 10 is represented as A, 11 as B and so on till 15 which is represented as F.
For Example: 47 in the Decimal number system can be represented as 2F in the Hexadecimal number system.
Figure Illustrating Decimal to Hexadecimal
Number System Conversion
Solution:
1
2
3 /**
4 * The class Dec2Hex inputs a Decimal number and converts it into its equivalent Hexadecimal num
5 * @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
6 */
7
8 import java.io.*;
9 class Dec2Hex
10 {
11 public static void main(String args[])throws IOException
{
12 BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
13 System.out.print("Enter a decimal number : ");
14 int n=Integer.parseInt(br.readLine());
15
16 int r;
String s=""; //variable for storing the result
17
18
//array storing the digits (as characters) in a hexadecimal number system
19 char dig[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
20
21 while(n>0)
22 {
23 r=n%16; //finding remainder by dividing the number by 16
s=dig[r]+s; //adding the remainder to the result
24 n=n/16;
25 }
26 System.out.println("Output = "+s);
27 }
28 }
29
30
Output:
Enter a decimal number : 47
Output = 2F
Enter a decimal number : 1243
Output = 4DB
Program on Decimal to Octal Number Conversion
Question:
Write a Program in Java to input a number in Decimal number system and convert it into its equivalent number in the Octal
number system.
Note: Octal Number system is a number system which can represent a number in any other number system in terms of digits
ranging from 0 to 7 only. This number system consists of only eight basic digits i.e. 0, 1, 2, 3, 4, 5, 6 and 7.
For Example: 25 in the Decimal number system can be represented as 31 in the Octal number system.
Note: Binary Number system is a number system which can represent a number in any other number system in terms of 0 and
1 only. This number system consists of only two basic digits i.e. 0 and 1.
For Example: 25 in the Decimal number system can be represented as 11001 in the Binary number system.
Solution:
1 /**
The class UniqueNumber inputs a number and checks whether it is a Unique Number or not
2 @author : www.guideforschool.com
3 @Program Type : BlueJ Program - Java
4 */
5 import java.io.;
6 class UniqueNumber
{
7 public static void main()throws IOException
8 {
9 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
10 System.out.print("Enter any number : ");
11 int n=Integer.parseInt(br.readLine());
String s=Integer.toString(n);
12 int l=s.length();
13 int flag=0;
14 for(int i=0;i<l-1;i++)
15 {
for(int j=i+1;j<l;j++)
16
17
18
19
{
20 if(s.charAt(i)==s.charAt(j))
21 {
22 flag=1;
23 break;
24 }
}
25 }
26 if(flag==0)
27 System.out.println("**** The Number is a Unique Number ****");
28 else
System.out.println("**** The Number is Not a Unique Number ****");
29 }
30 }
31
32
33
Output:
Enter any number : 3121
**** The Number is Not a Unique Number ****
Enter any number : 5243
**** The Number is a Unique Number ****
Programming Code:
1 /**
* The class Swap_Strings takes 2 Strings as input and swaps their value without using any 3rd
2
* @author : www.javaforschool.com
3 * @Program Type : BlueJ Program - Java
4 */
5
6 import java.io.*;
7 class Swap_Strings
{
8 public static void main(String args[])throws IOException
9 {
10 BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
11 System.out.print("Enter the 1st String : ");
12 String s1=br.readLine();
int len1=s1.length();
13
14 System.out.print("Enter the 2nd String : ");
15 String s2=br.readLine();
16
17 System.out.println("-------------------------------");
18 System.out.println("Strings Before Swapping : ");
System.out.println("1st String = "+s1);
19
20
21
22 System.out.println("2nd String = "+s2);
23
24 /*Swapping Process Begins*/
s1=s1+s2;
25 s2=s1.substring(0,len1);
26 s1=s1.substring(len1);
27 /*Swapping Process Ends*/
28
29 System.out.println("-------------------------------");
System.out.println("Strings After Swapping : ");
30
System.out.println("1st String = "+s1);
31 System.out.println("2nd String = "+s2);
32 }
33 }
34
35
36
Output:
Enter the 1st String : Java For
Enter the 2nd String : School is Fun
——————————-
Strings Before Swapping :
1st String = Java For
2nd String = School is Fun
——————————-
Strings After Swapping :
1st String = School is Fun
2nd String = Java For
Working:
Initially s1 = “Java For” and s2 = “School is Fun”,
Now, the variable, ‘len1’ stores the length of the 1st String. Hence, in this case, ‘len1’ = 8
Step 1: s1 = s1+s2; gives s1 = “Java For”+”School is Fun”;
i.e. s1 = “Java ForSchool is Fun” [Note: There will be no space when we join the 1st and the 2nd String]
Step 2: s2=s1.substring(0,len1); gives, s2=”Java ForSchool is Fun”.substring(0,8);
i.e. s2 = “Java For”
Step 3: s1 = s1.substring(len1); gives, s1 = “Java ForSchool is Fun.substring(8);
i.e. s1 = “School is Fun”
Hence, finally we have s1 = “School is Fun” and s2 = “Java For”. [Swapping Done].
This is the first method in which we have used the concept of Bitwise XOR operator which is indicated by a caret ( ^ ).
This is the second method in which we have used the concept of simple mathematical operations including addition and
subtraction.
Method 1 of swapping two numbers using bitwise XOR operator and without using any third
variable can be read from here: [Method 1]
Programming Code:
1 /**
* The class Swapping_Method2 takes 2 numbers as input and swaps their value without using any
2
* This is Method 2
3 * @author : www.javaforschool.com
4 * @Program Type : BlueJ Program - Java
5 */
6
7 import java.io.*;
class Swapping_Method2
8 {
9 public static void main(String args[])throws IOException
10 {
11
12
13
14 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b;
15 System.out.print("Enter the 1st no: ");
16 a=Integer.parseInt(br.readLine());
17 System.out.print("Enter the 2nd no: ");
18 b=Integer.parseInt(br.readLine());
19
System.out.println("-------------------------------");
20 System.out.println("The numbers before swapping are");
21 System.out.println("a = "+a);
22 System.out.println("b = "+b);
23
24 //Beginning of Swapping
25 a=a+b;
b=a-b;
26 a=a-b;
27
28 //End of Swapping
29 System.out.println("-------------------------------");
30 System.out.println("The numbers after swapping are");
System.out.println("a = "+a);
31
System.out.println("b = "+b);
32 }
33 }
34
35
36
Output:
Enter the 1st no: 25
Enter the 2nd no: 13
——————————-
The numbers before swapping are
a = 25
b = 13
——————————-
The numbers after swapping are
a = 13
b = 25
Working:
Initially a=25 and b=13,