[Go to site: main page, start]

0% found this document useful (0 votes)
7 views52 pages

Sample Java Program

The document outlines a Computer Science project for Class 11 students at City Montessori School, focusing on Java programming with 20 practical programs. It includes program descriptions, algorithms, and sample inputs/outputs for various tasks such as identifying Prime-Adam integers, generating star patterns, converting day numbers to dates, calculating decimal equivalents of octal matrices, and sorting sentences. The project emphasizes practical applications of Java concepts and acknowledges the support of teachers and the school.

Uploaded by

xyzklm626
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views52 pages

Sample Java Program

The document outlines a Computer Science project for Class 11 students at City Montessori School, focusing on Java programming with 20 practical programs. It includes program descriptions, algorithms, and sample inputs/outputs for various tasks such as identifying Prime-Adam integers, generating star patterns, converting day numbers to dates, calculating decimal equivalents of octal matrices, and sorting sentences. The project emphasizes practical applications of Java concepts and acknowledges the support of teachers and the school.

Uploaded by

xyzklm626
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ISC CLASS 11 COMPUTER SCIENCE PROJECT FILE

====================================================

CITY MONTESSORI SCHOOL,GOMTI NAGAR EXTENSION

COMPUTER SCIENCE PROJECT


SESSION 2025-2026

JAVA PROGRAMMING
(20 PRACTICAL PROGRAMS)

CLASS XI

Roll Number: ______________


Name: ______________
Section: ______________
Subject: Computer Science
Teacher: ______________
Date of Submission: ______________
===========================================
ACKNOWLEDGEMENT
 I am grateful to acknowledge the valuable guidance and
support provided by my Computer Science teacher,
_________________, throughout the completion of this practical
project.

 I would like to thank my school, City Montessori School, for


providing the necessary facilities and resources to complete
this project successfully.

 This project has helped me understand the practical


application of Java programming concepts including nested
loops, arrays, strings, object-oriented programming, file
handling, and recursion.

 The effort put into this practical work has enhanced my


programming skills and given me hands-on experience with
fundamental data structures and algorithms.

 Date: ________________
====================================
==============================
QUESTION 1: Write a program to accept two positive integers m and n (where m <
n) and display all Prime-Adam integers between m and n (both inclusive). A Prime-Adam
integer is a positive integer which is: - A prime number (has exactly two factors: 1 and
itself) - An Adam number (the square of the number and the square of its reverse are
reverse of each other) If m >= n, display "INVALID INPUT"

import [Link];
class PrimeAdam {
// Check if number is prime
public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
} // Reverse a number
public static int reverse(int num) {
int rev = 0;
while (num > 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
return rev;
}
// Check if Adam number
public static boolean isAdam(int num) {
int rev = reverse(num);
long sqNum = (long) num * num; // Original square
long sqRev = (long) rev * rev; // Reverse square
// Reverse of original square
int revSqNum = reverse((int) sqNum);
return sqRev == revSqNum;
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter m and n (m < n): ");
int m = [Link]();
int n = [Link](); // Validate input
if (m >= n || m < 1 || n < 1) {
[Link]("INVALID INPUT");
return;
} // Find Prime-Adam numbers
[Link]("Prime-Adam numbers between " + m + " and " + n + ": ");
boolean found = false;
for (int i = m; i <= n; i++) {
if (isPrime(i) && isAdam(i)) {
[Link](i + " ");
found = true;
} }
if (!found) {
[Link]("NONE"); }
[Link]();
[Link]();
}
}
ALGORITHM:

Steps: 1. Read m and n


2. IF m <= 0 OR n <= 0 OR m >= n THEN Print "INVALID INPUT" Stop
3. count = 0, result = empty string
4. FOR num = m TO n DO a) Check if num is prime
b) IF num is prime THEN
- Calculate reverse of num
- Calculate square of num and square of reverse
- Check if square of num reversed equals square of reverse
- IF yes, add to result, increment count
5. IF count = 0 THEN Print "THE PRIME-ADAM INTEGERS ARE: NIL" ELSE Print "THE PRIME-ADAM
INTEGERS ARE: " + result
6. Print "FREQUENCY OF PRIME-ADAM INTEGERS IS: " + count
7. Stop

INPUT/OUTPUT:

Enter m and n (m < n): 10 100


Prime-Adam numbers between 10 and 100: 11 13 NONE

Enter m and n (m < n): 1 20


Prime-Adam numbers between 1 and 20: 2 3 11 13
Enter m and n (m < n): 5 5
INVALID INPUT
Question 2: Write a java program using nested loop to print a pyramid pattern of stars.

import [Link];

public class StarPyramid {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input number of rows for pyramid
[Link]("Enter number of rows for pyramid: ");
int n = [Link]();
// Outer loop for each row
for (int i = 1; i <= n; i++) {
// Inner loop 1: Print spaces before stars
for (int j = 1; j <= n - i; j++) {
[Link](" ");
}
// Inner loop 2: Print stars
for (int k = 1; k <= 2 * i - 1; k++) {
[Link]("*");
}
// Move to next line
[Link]();
}
[Link]();
}
}

ALGORITHAM:

1. START
2. INPUT number of rows (n)
3. FOR i = 1 to n DO // Outer loop: controls each row
4. FOR j = 1 to (n - i) DO // Inner loop 1: print leading spaces
5. PRINT " "
6. END FOR
7. FOR k = 1 to (2*i - 1) DO // Inner loop 2: print stars
8. PRINT "*"
9. END FOR
10. PRINT newline
11. END FOR
12. STOP

OUTPUT/INPUT:
Enter number of rows for pyramid: 5
*
***
*****
*******
*********
Question 3: 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 .
import [Link];

public class DayNumberToDate {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
String[] months = {"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Input day number (1-366)
[Link]("Enter day number (1-366): ");
int dayNum = [Link]();
if (dayNum < 1 || dayNum > 366) {
[Link]("ERROR: Day number must be between 1 and 366");
return;
}
// Input year (4 digits)
[Link]("Enter year (YYYY): ");
int year = [Link]();
if (year < 1000 || year > 9999) {
[Link]("ERROR: Year must be 4 digits (1000-9999)");
return;
}
// Check leap year and adjust February days
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeap) daysInMonth[2] = 29;
int totalDays = isLeap ? 366 : 365;
// Input N days forward
[Link]("Enter N days ahead (1-100): ");
int N = [Link]();
if (N < 1 || N > 100) {
[Link]("ERROR: N must be between 1 and 100");
return;
}
// Find original date from day number
int month = 1, day = 0;
while (dayNum > daysInMonth[month]) {
dayNum -= daysInMonth[month];
month++;
}
day = dayNum;
// Display original date
[Link]("\nDate for day %d: %d-%s-%d\n", dayNum + N, day,
months[month], year);
// Calculate future date (dayNum + N)
int futureDayNum = dayNum + N;
int futureYear = year;
// Handle year overflow
while (futureDayNum > totalDays) {
futureDayNum -= totalDays;
futureYear++;
isLeap = (futureYear % 4 == 0 && futureYear % 100 != 0) || (futureYear % 400 == 0);
totalDays = isLeap ? 366 : 365;
}
// Find future date components
int futureMonth = 1, futureDay = 0;
if (isLeap) daysInMonth[2] = 29; else daysInMonth[2] = 28;
while (futureDayNum > daysInMonth[futureMonth]) {
futureDayNum -= daysInMonth[futureMonth];
futureMonth++;
}
futureDay = futureDayNum;

// Display future date


[Link]("Date after %d days: %d-%s-%d\n", N, futureDay,
months[futureMonth], futureYear);

[Link]();
}
}

ALGORITHAM:
1. INPUT dayNum, year, N
2. VALIDATE 1≤dayNum≤366, 1000≤year≤9999, 1≤N≤100
3. IF INVALID → ERROR → STOP
4. isLeap ← leapYear(year)
5. FIND originalDate(dayNum)
6. futureDay ← dayNum + N
7. WHILE futureDay > yearDays → nextYear()
8. FIND futureDate(futureDay)
9. DISPLAY both dates
10. STOP
OUTPUT/INPUT:
Enter day number (1-366): 32
Enter year (YYYY): 2024
Enter N days ahead (1-100): 15

Date for day 32: 2-February-2024


Date after 15 days: 17-February-2024
Question 4: Write a program to declare a matrix A[][] of order (M x N) where M is
rows and N is columns. M must be greater than 0 and less than 10, N must be greater than 2
and less than 6. Each row represents an octal number. Calculate and display the decimal
equivalent of each row.

import [Link];

public class OctalMatrix {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input dimensions with validation
[Link]("Enter rows M (1-9): ");
int M = [Link]();
[Link]("Enter columns N (3-5): ");
int N = [Link]();

if (M <= 0 || M >= 10 || N <= 2 || N >= 6) {


[Link]("INVALID DIMENSIONS");
return;
}
// Declare matrix
int[][] A = new int[M][N];

// Input octal digits (0-7 only)


for (int i = 0; i < M; i++) {
[Link]("Row " + i + ":");
for (int j = 0; j < N; j++) {
int digit;
do {
[Link]("A[" + i + "][" + j + "] (0-7): ");
digit = [Link]();
} while (digit < 0 || digit > 7);
A[i][j] = digit;
}
}
// Display matrix and decimal equivalents
[Link]("\nMatrix A:");
for (int i = 0; i < M; i++) {
// Print row
for (int j = 0; j < N; j++) {
[Link](A[i][j] + " ");
}
[Link]("→ ");
// Calculate decimal: d0*8^(N-1) + d1*8^(N-2) + ... + d(N-1)*8^0
int decimal = 0;
for (int j = 0; j < N; j++) {
decimal = decimal * 8 + A[i][j];
}
[Link](decimal);
}
[Link]();
}
}
ALGORITHAM:

1. INPUT M, N
2. IF M ∉ [1,9] OR N ∉ [3,5] → "INVALID" → STOP
3. DECLARE A[M][N]
4. FOR i=0 TO M-1
FOR j=0 TO N-1
INPUT A[i][j] VALIDATE 0-7
5. FOR i=0 TO M-1
PRINT row i
decimal ← 0
FOR j=0 TO N-1
decimal ← decimal*8 + A[i][j]
PRINT decimal
6. STOP

OUTPUT/INPUT:
Enter rows M (1-9): 2
Enter columns N (3-5): 3
Row 0:
A[0][0] (0-7): 1
A[0][1] (0-7): 2
A[0][2] (0-7): 3
Row 1:
A[1][0] (0-7): 4
A[1][1] (0-7): 5
A[1][2] (0-7): 6

Matrix A:
1 2 3 → 83
4 5 6 → 342
Question 5: Write a program to accept a sentence terminated by '.', '?' or '!' only. Words
are separated by single space and in UPPER case. Perform the following: (a) Check validity
of terminating character (b) Arrange words in ascending order of length. If lengths are
equal, sort alphabetically. (c) Display original and sorted sentences.

import [Link];

public class SentenceSort {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input sentence
[Link]("Enter sentence (ends with . ? !): ");
String sentence = [Link]();

// (a) Validate terminating character


char last = [Link]([Link]()-1);
if (last != '.' && last != '?' && last != '!') {
[Link]("INVALID TERMINATION");
return;
}

// Split into words (UPPER CASE assumed)


String[] words = [Link](0, [Link]()-1).split(" ");

// (b) Bubble sort by length, then alphabetically


for (int i = 0; i < [Link]-1; i++) {
for (int j = 0; j < [Link]-1-i; j++) {
if (words[j].length() > words[j+1].length() ||
(words[j].length() == words[j+1].length() &&
words[j].compareTo(words[j+1]) > 0)) {
String temp = words[j];
words[j] = words[j+1];
words[j+1] = temp;
}
}
}

// (c) Display results


[Link]("Original: " + sentence);
[Link]("Sorted: ");
for (int i = 0; i < [Link]; i++) {
[Link](words[i]);
if (i < [Link]-1) [Link](" ");
}
[Link](last);

[Link]();
}
}
ALGORITHAM:

1. INPUT sentence
2. last ← sentence[last char]
3. IF last ∉ {.,?,!} → "INVALID" → STOP
4. words ← split(sentence without last char)
5. BUBBLE SORT words BY:
length ASC → if equal, alphabetical ASC
6. PRINT "Original: " + sentence
7. PRINT "Sorted: " + words + last
8. STOP

OUTPUT/INPUT:
Enter sentence (ends with . ? !): HELLO WORLD THIS IS JAVA.
Original: HELLO WORLD THIS IS JAVA.
Sorted: IS THIS JAVA HELLO WORLD.

Enter sentence (ends with . ? !): CAT DOG BIRD?


Original: CAT DOG BIRD?
Sorted: CAT DOG BIRD?
Question 6: Write a program to accept a positive integer n and count the frequency of
each digit (0-9) present in n. Display the digit and its frequency in descending order of
frequency. If the number is negative or zero, display "INVALID INPUT".

import [Link];

public class DigitFrequency {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input
[Link]("Enter positive integer: ");
int n = [Link]();

// Validate
if (n <= 0) {
[Link]("INVALID INPUT");
return;
}

// Count frequency of each digit (0-9)


int[] freq = new int[10];
int temp = n;
while (temp > 0) {
freq[temp % 10]++;
temp /= 10;
}

// Bubble sort: frequency DESC, digit DESC if tie


for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9-i; j++) {
if (freq[j] < freq[j+1] ||
(freq[j] == freq[j+1] && j < j+1)) {
int t = freq[j]; freq[j] = freq[j+1]; freq[j+1] = t;
}
}
}

// Display
[Link]("Digit | Frequency");
[Link]("------+----------");
for (int i = 0; i < 10; i++) {
if (freq[i] > 0) {
[Link]("%4d |%5d\n", i, freq[i]);
}
}
[Link]();
}
}
ALGORITHAM:
1. INPUT n
2. IF n ≤ 0 → "INVALID INPUT" → STOP
3. freq[10] ← 0
4. WHILE n > 0
freq[n%10]++
n ← n/10
5. BUBBLE SORT freq[]: frequency DESC, digit DESC
6. PRINT digits with freq > 0 in table format
7. STOP.
OUTPUT/INPUT:
Enter positive integer: 122333
Digit | Frequency
------+----------
3 | 3
2 | 2
1 | 1

Enter positive integer: 0


INVALID INPUT
Question 7: Write a program to accept a positive integer n and generate Pascal's
Triangle with n rows. Each element in Pascal's Triangle is the sum of the two elements
above it. If n is invalid (n <= 0 or n > 15), display "INVALID INPUT".

import [Link];

public class PascalTriangle {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input
[Link]("Enter number of rows (1-15): ");
int n = [Link]();

// Validation
if (n <= 0 || n > 15) {
[Link]("INVALID INPUT");
return;
}

// Generate and print Pascal's Triangle


for (int i = 0; i < n; i++) {
// Print spaces for alignment
for (int k = 0; k < n - i - 1; k++) {
[Link](" ");
}

// Calculate and print row


int C = 1;
[Link](C);

for (int j = 1; j <= i; j++) {


C = C * (i - j + 1) / j;
[Link](" " + C);
}
[Link]();
}
[Link]();
}
}
ALGORITHAM:
1. INPUT n
2. IF n ∉ [1,15] → "INVALID INPUT" → STOP
3. FOR row = 0 TO n-1
PRINT (n-row-1) spaces
C ← 1, PRINT C
FOR col = 1 TO row
C ← C × (row-col+1) ÷ col
PRINT " " + C
PRINT newline
5. STOP
OUTPUT/INPUT:
Enter number of rows (1-15): 5
1
11
121
1331
11331
Question 8: Write a program to declare a 2D array matrix of size m×n where m is
number of rows (0 < m < 5) and n is number of columns (0 < n < 5). Input elements and
find the largest element in the matrix. Display the largest element and its position (row and
column).

import [Link];

public class MatrixLargest {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input dimensions
[Link]("Enter rows m (1-4): ");
int m = [Link]();
[Link]("Enter columns n (1-4): ");
int n = [Link]();

// Validation
if (m <= 0 || m >= 5 || n <= 0 || n >= 5) {
[Link]("INVALID DIMENSIONS");
return;
}

// Declare 2D array and input elements


int[][] matrix = new int[m][n];
[Link]("Enter matrix elements:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
[Link]("matrix[" + i + "][" + j + "] = ");
matrix[i][j] = [Link]();
}
}

// Find largest element and position


int max = matrix[0][0];
int maxRow = 0, maxCol = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxRow = i;
maxCol = j;
}
}
}

// Display result
[Link]("\nMatrix:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
[Link]("Largest: %d at position matrix[%d][%d]\n",
max, maxRow, maxCol);

[Link]();
}
}
ALGORITHAM:
1. INPUT m, n
2. IF m,n ∉ [1,4] → "INVALID" → STOP
3. DECLARE matrix[m][n]
4. INPUT all matrix elements
5. max ← matrix[0][0], maxRow=0, maxCol=0
6. FOR i=0 TO m-1
FOR j=0 TO n-1
IF matrix[i][j] > max
max ← matrix[i][j]
maxRow ← i, maxCol ← j
7. PRINT matrix
8. PRINT "Largest:", max, "at", [maxRow][maxCol]
9. STOP
OUTPUT/INPUT:
Enter rows m (1-4): 3
Enter columns n (1-4): 3
Enter matrix elements:
matrix[0][0] = 5
matrix[0][1] = 12
matrix[0][2] = 3
matrix[1][0] = 7
matrix[1][1] = 8
matrix[1][2] = 15
matrix[2][0] = 2
matrix[2][1] = 9
matrix[2][2] = 4

Matrix:
5 12 3
7 8 15
294
Largest: 15 at position matrix[1][2]
Question 9: Write a program to check whether a given string is a palindrome or not
using recursion. A palindrome string reads the same forwards and backwards (e.g.,
RACECAR, RADAR, MADAM).

import [Link];

public class PalindromeRecursion {


// Recursive function to check palindrome
public static boolean isPalindrome(String str, int start, int end) {
// Base cases
if (start >= end) return true; // Empty or single char

// Compare first and last characters


if ([Link](start) != [Link](end))
return false;

// Recursive call for inner substring


return isPalindrome(str, start + 1, end - 1);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Input
[Link]("Enter string: ");
String str = [Link]().toUpperCase(); // Case insensitive

// Call recursive function


int len = [Link]();
boolean result = isPalindrome(str, 0, len - 1);

// Display result
[Link](str + " is " + (result ? "" : "not ") + "a palindrome");

[Link]();
}
}
ALGORITHAM:
1. INPUT string
2. CALL isPalindrome(str, 0, len-1)
3. FUNCTION isPalindrome(str, start, end):
IF start ≥ end RETURN true
IF str[start] ≠ str[end] RETURN false
RETURN isPalindrome(str, start+1, end-1)
4. PRINT result
5. STOP
OUTPUT/INPUT:
Enter string: RACECAR
RACECAR is a palindrome

Enter string: HELLO


HELLO is not a palindrome
Question 10: Write a program to accept a positive integer n and calculate its factorial
using recursion. Factorial of n (n!) = n × (n-1) × (n-2) × ... × 1. For example, 5! = 120. If n is
negative, display "INVALID INPUT".

import [Link];

public class FactorialRecursion {


// Recursive factorial function
public static long factorial(int n) {
// Base case
if (n == 0 || n == 1)
return 1;

// Recursive case
return n * factorial(n - 1);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Input
[Link]("Enter positive integer n: ");
int n = [Link]();

// Validation
if (n < 0) {
[Link]("INVALID INPUT");
return;
}

// Calculate and display


long result = factorial(n);
[Link](n + "! = " + result);

[Link]();
}
}
ALGORITHAM:
1. INPUT n
2. IF n < 0 → "INVALID INPUT" → STOP
3. CALL factorial(n)
4. FUNCTION factorial(n):
IF n = 0 OR 1 RETURN 1
RETURN n × factorial(n-1)
5. PRINT n! = result
6. STOP
OUTPUT/INPUT:
Enter positive integer n: 5
5! = 120

Enter positive integer n: 0


0! = 1

Enter positive integer n: -3


INVALID INPUT

factorial(5)
→ 5 × factorial(4)
→ 4 × factorial(3)
→ 3 × factorial(2)
→ 2 × factorial(1)
→1✓
= 2×1 = 2 → 3×2 = 6 → 4×6 = 24 → 5×24 = 120
Question 11: Write a program in java to accept a positive integer n and generate
Fibonacci series up to n terms using recursion. Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Each term is the sum of the previous two terms. If n <= 0, display "INVALID INPUT".

import [Link];

public class FibonacciRecursion {


// Recursive Fibonacci function
public static int fibonacci(int n, int a, int b) {
// Base case
if (n == 0) return a;
if (n == 1) return b;

// Recursive case: next term = a + b


return fibonacci(n - 1, b, a + b);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Input
[Link]("Enter number of terms: ");
int n = [Link]();

// Validation
if (n <= 0) {
[Link]("INVALID INPUT");
return;
}

// Display series
[Link]("Fibonacci series (" + n + " terms): ");
for (int i = 0; i < n; i++) {
[Link](fibonacci(i, 0, 1) + " ");
}
[Link]();

[Link]();
}}
ALGORITHAM:
1. INPUT n
2. IF n ≤ 0 → "INVALID INPUT" → STOP
3. PRINT "Fibonacci series (n terms): "
4. FOR i = 0 TO n-1
PRINT fibonacci(i, 0, 1) + " "
5. FUNCTION fibonacci(n, a, b):
IF n = 0 RETURN a
IF n = 1 RETURN b
RETURN fibonacci(n-1, b, a+b)
6. STOP
OUTPUT/INPUT:
Enter number of terms: 8
Fibonacci series (8 terms): 0 1 1 2 3 5 8 13

Enter number of terms: 0


INVALID INPUT
fibonacci(3, 0, 1)
→ fibonacci(2, 1, 1)
→ fibonacci(1, 1, 2)
→ n=1 ✓ RETURN 1
Question 12: Write a program to accept a string and convert it to:
(a) UPPERCASE
(b) lowercase
(c) Title Case (First letter of each word in UPPERCASE, rest in lowercase) Display all three
conversions.
import [Link];

public class StringCaseConverter {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input
[Link]("Enter string: ");
String str = [Link]();

// (a) UPPERCASE
String upper = [Link]();

// (b) lowercase
String lower = [Link]();

// (c) Title Case (manual logic - Class 11 level)


String[] words = [Link](" ");
String title = "";
for (int i = 0; i < [Link]; i++) {
if (words[i].length() > 0) {
title += [Link](words[i].charAt(0));
title += words[i].substring(1);
}
if (i < [Link] - 1) title += " ";
}

// Display all conversions


[Link]("Original: " + str);
[Link]("UPPERCASE: " + upper);
[Link]("lowercase: " + lower);
[Link]("Title Case: " + title);

[Link]();
}
}
ALGORITHAM:
1. INPUT string
2. upper ← [Link]()
3. lower ← [Link]()
4. words ← split(lower by space)
5. FOR each word in words
title += UpperCase(first char) + rest lowercase + " "
6. PRINT all 4 versions
7. STOP
OUTPUT/INPUT:
Enter string: Hello World Java Programming
Original: Hello World Java Programming
UPPERCASE: HELLO WORLD JAVA PROGRAMMING
lowercase: hello world java programming
Title Case: Hello World Java Programming
Question 13: Write a program to accept a string and count the number of vowels,
consonants, digits, and special characters. Vowels: A, E, I, O, U (case-insensitive)
Consonants: All other alphabets Digits: 0-9 Special characters: All other characters
including spaces Display the count of each category

import [Link];

public class CharacterCounter {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input
[Link]("Enter string: ");
String str = [Link]();

// Initialize counters
int vowels = 0, consonants = 0, digits = 0, special = 0;

// Count each character


for (int i = 0; i < [Link](); i++) {
char ch = [Link]([Link](i));

if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {


vowels++;
}
else if (ch >= 'A' && ch <= 'Z') {
consonants++;
}
else if (ch >= '0' && ch <= '9') {
digits++;
}
else {
special++;
}
}

// Display results
[Link]("Vowels: " + vowels);
[Link]("Consonants: " + consonants);
[Link]("Digits: " + digits);
[Link]("Special characters: " + special);

[Link]();
}
}
ALGORITHAM:

1. INPUT string
2. vowels, consonants, digits, special ← 0
3. FOR each char ch in string
ch ← UPPERCASE(ch)
IF ch IN {A,E,I,O,U} → vowels++
ELSE IF ch IN [A-Z] → consonants++
ELSE IF ch IN [0-9] → digits++
ELSE → special++
4. PRINT all 4 counts
5. STOP
OUTPUT/INPUT:
Enter string: Hello World! 123 @
Vowels: 3
Consonants: 7
Digits: 3
Special characters: 5
Question 14: Write a program to accept n integers in an array and perform:
(a) Linear Search to find a given element (returns first occurrence)
(b) Binary Search to find a given element (array must be sorted first) Display whether the
element is found and its position, or "NOT FOUND".
import [Link];

public class ArraySearch {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input array size and elements


[Link]("Enter array size: ");
int n = [Link]();
int[] arr = new int[n];

[Link]("Enter " + n + " elements:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Input search element


[Link]("Enter element to search: ");
int key = [Link]();

// (a) Linear Search


int linearPos = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
linearPos = i;
break;
}
}

// (b) Sort array for Binary Search (Bubble Sort)


for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1-i; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

// Binary Search on sorted array


int binaryPos = -1, left = 0, right = n-1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == key) {
binaryPos = mid;
break;
}
else if (arr[mid] < key) {
left = mid + 1;
}
else {
right = mid - 1;
}
}

// Display results
[Link]("\nLinear Search: " + (linearPos != -1 ? "FOUND at " + linearPos :
"NOT FOUND"));
[Link]("Binary Search: " + (binaryPos != -1 ? "FOUND at " + binaryPos :
"NOT FOUND"));
[Link]("Sorted array: ");
for (int x : arr) [Link](x + " ");

[Link]();
}
}
ALGORITHAM:
1. INPUT n, array[n]
2. INPUT key
3. LINEAR SEARCH:
FOR i=0 TO n-1
IF arr[i]==key → RETURN i
RETURN -1
4. BUBBLE SORT array (ASC)
5. BINARY SEARCH:
left=0, right=n-1
WHILE left≤right
mid=(left+right)/2
IF arr[mid]==key → RETURN mid
ELSE IF arr[mid]<key → left=mid+1
ELSE → right=mid-1
RETURN -1
6. PRINT both results
7. STOP
OUTPUT/INPUT:
Enter array size: 7
Enter 7 elements:
64 34 25 12 22 11 90
Enter element to search: 22

Linear Search: FOUND at 4


Binary Search: FOUND at 2
Sorted array: 11 12 22 25 34 64 90
Question 15: Write a program to create a Student class with attributes: rollNo, name,
marks (3 subjects). Implement methods to:
(a) Input student details
(b) Calculate total and average marks
(c) Display student details with total and average Create an array of student objects and
display details of all students.
import [Link];

class Student {
int rollNo;
String name;
int marks[] = new int[3]; // 3 subjects

// (a) Input student details


void input() {
Scanner sc = new Scanner([Link]);
[Link]("Roll No: ");
rollNo = [Link]();
[Link](); // consume newline
[Link]("Name: ");
name = [Link]();
[Link]("Enter 3 subject marks:");
for (int i = 0; i < 3; i++) {
marks[i] = [Link]();
}
}

// (b) Calculate total and average


int total() {
int sum = 0;
for (int m : marks) {
sum += m;
}
return sum;
}

double average() {
return (double) total() / 3;
}
// (c) Display student details
void display() {
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
[Link]("Marks: ");
for (int m : marks) {
[Link](m + " ");
}
[Link]("\nTotal: %d, Average: %.2f\n\n", total(), average());
}
}

public class StudentArray {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of students: ");


int n = [Link]();

// Array of Student objects


Student[] students = new Student[n];

// Input all students


[Link]("Enter student details:");
for (int i = 0; i < n; i++) {
students[i] = new Student();
students[i].input();
}

// Display all students


[Link]("\n--- STUDENT DETAILS ---");
for (int i = 0; i < n; i++) {
[Link]("Student " + (i+1) + ":");
students[i].display();
}

[Link]();
}
}
ALGORITHAM:
1. CLASS Student:
ATTRIBUTES: rollNo, name, marks[3]
METHOD input(): READ rollNo, name, marks
METHOD total(): SUM marks → RETURN
METHOD average(): total()/3 → RETURN
METHOD display(): PRINT all details

2. MAIN:
INPUT n
students[n] ← new Student[n]
FOR i=0 TO n-1
students[i].input()
FOR i=0 TO n-1
students[i].display()
3. STOP
OUTPUT/INPUT:

Enter number of students: 2


Enter student details:
Roll No: 101
Name: RAM
Enter 3 subject marks:
85 90 78
Roll No: 102
Name: SHYAM
Enter 3 subject marks:
92 88 95

--- STUDENT DETAILS ---


Student 1:
Roll No: 101
Name: RAM
Marks: 85 90 78
Total: 253, Average: 84.33

Student 2:
Roll No: 102
Name: SHYAM
Marks: 92 88 95
Total: 275, Average: 91.67
Question 16: Write a program to create a Circle class with radius as attribute.
Implement methods to: (a) Input circle details (radius) (b) Calculate area = π × r² (c)
Calculate circumference = 2 × π × r (d) Display circle details Create objects and perform
operations on multiple circles.

import [Link];

class Circle {
double radius;

// (a) Input circle details


void input() {
Scanner sc = new Scanner([Link]);
[Link]("Enter radius: ");
radius = [Link]();
}

// (b) Calculate area = π × r²


double area() {
return [Link] * radius * radius;
}

// (c) Calculate circumference = 2 × π × r


double circumference() {
return 2 * [Link] * radius;
}

// (d) Display circle details


void display() {
[Link]("Radius: %.2f\n", radius);
[Link]("Area: %.2f sq units\n", area());
[Link]("Circumference: %.2f units\n\n", circumference());
}
}

public class CircleDemo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of circles: ");


int n = [Link]();

// Array of Circle objects


Circle[] circles = new Circle[n];

// Create and input circles


for (int i = 0; i < n; i++) {
circles[i] = new Circle();
[Link]("Circle " + (i+1) + ":");
circles[i].input();
}

// Display all circles


[Link]("\n--- CIRCLE DETAILS ---");
for (int i = 0; i < n; i++) {
[Link]("Circle " + (i+1) + ":");
circles[i].display();
}

[Link]();
}}
ALGORITHAM:
1. CLASS Circle:
ATTRIBUTE: radius
METHOD input(): READ radius
METHOD area(): RETURN π × radius²
METHOD circumference(): RETURN 2 × π × radius
METHOD display(): PRINT radius, area, circumference

2. MAIN:
INPUT n
circles[n] ← new Circle[n]
FOR i=0 TO n-1
circles[i].input()
FOR i=0 TO n-1
circles[i].display()
3. STOP
OUTPUT/INPUT:
Enter number of circles: 2
Circle 1:
Enter radius: 5
Circle 2:
Enter radius: 7

--- CIRCLE DETAILS ---


Circle 1:
Radius: 5.00
Area: 78.54 sq units
Circumference: 31.42 units

Circle 2:
Radius: 7.00
Area: 153.94 sq units
Circumference: 43.98 units
Question 17: Write a program to create a BankAccount class with attributes:
accountNo, accountHolder, balance. Implement methods to: (a) Input account details (b)
Deposit money (c) Withdraw money (d) Display account details Create multiple account
objects and perform operations

import [Link];

class BankAccount {
int accountNo;
String accountHolder;
double balance;

// (a) Input account details


void input() {
Scanner sc = new Scanner([Link]);
[Link]("Account No: ");
accountNo = [Link]();
[Link](); // consume newline
[Link]("Account Holder: ");
accountHolder = [Link]();
[Link]("Initial Balance: ");
balance = [Link]();
}

// (b) Deposit money


void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: ₹" + amount);
} else {
[Link]("Invalid amount!");
}
}

// (c) Withdraw money


void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Withdrawn: ₹" + amount);
} else {
[Link]("Insufficient balance or invalid amount!");
}
}

// (d) Display account details


void display() {
[Link]("\nAccount No: " + accountNo);
[Link]("Holder: " + accountHolder);
[Link]("Balance: ₹%.2f\n", balance);
}
}

public class BankDemo {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of accounts: ");


int n = [Link]();

// Array of BankAccount objects


BankAccount[] accounts = new BankAccount[n];

// Create accounts
for (int i = 0; i < n; i++) {
accounts[i] = new BankAccount();
[Link]("\nAccount " + (i+1) + ":");
accounts[i].input();
}

// Perform operations (demo)


for (int i = 0; i < n; i++) {
[Link]("\n--- Operations on Account " + (i+1) + " ---");
accounts[i].deposit(500.0);
accounts[i].withdraw(200.0);
}

// Display all accounts


[Link]("\n--- ALL ACCOUNT DETAILS ---");
for (int i = 0; i < n; i++) {
[Link]("Account " + (i+1) + ":");
accounts[i].display();
}

[Link]();
}
}
ALGORITHAM:

1. CLASS BankAccount:
ATTRIBUTES: accountNo, accountHolder, balance
METHOD input(): READ accountNo, name, balance
METHOD deposit(amount): IF amount>0 → balance += amount
METHOD withdraw(amount): IF amount>0 AND amount≤balance → balance -= amount
METHOD display(): PRINT all details

2. MAIN:
INPUT n
accounts[n] ← new BankAccount[n]
FOR i=0 TO n-1
accounts[i].input()
accounts[i].deposit(500)
accounts[i].withdraw(200)
FOR i=0 TO n-1
accounts[i].display()
3. STOP
OUTPUT/INPUT:
Enter number of accounts: 2

Account 1:
Account No: 1001
Account Holder: RAM KUMAR
Initial Balance: 1000.0

Account 2:
Account No: 1002
Account Holder: SITA DEVI
Initial Balance: 2000.0

--- Operations on Account 1 ---


Deposited: ₹500.0
Withdrawn: ₹200.0
--- Operations on Account 2 ---
Deposited: ₹500.0
Withdrawn: ₹200.0

--- ALL ACCOUNT DETAILS ---


Account 1:
Account No: 1001
Holder: RAM KUMAR
Balance: ₹1300.00

Account 2:
Account No: 1002
Holder: SITA DEVI
Balance: ₹2300.00
Question 18: Write a program to: (a) Write text data to a file (b) Read and display data
from the file (c) Append additional data to the file Use FileWriter and FileReader classes for
file operations.

import [Link].*;

public class FileOperations {


public static void main(String[] args) {
// (a) Write text data to file
try {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello World\n");
[Link]("Java File Handling\n");
[Link]("Class 11 Level");
[Link]();
[Link]("Data written to file");
} catch (IOException e) {
[Link]("Write error: " + e);
}

// (b) Read and display from file


try {
FileReader fr = new FileReader("[Link]");
[Link]("\n--- File Content ---");
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();
} catch (IOException e) {
[Link]("Read error: " + e);
}

// (c) Append data to file


try {
FileWriter fw = new FileWriter("[Link]", true); // true = append mode
[Link]("\nNew data appended!");
[Link]();
[Link]("\nData appended successfully");
// Display updated file
[Link]("\n--- Updated File ---");
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();
} catch (IOException e) {
[Link]("Append error: " + e);
}
}
}
ALGORITHAM:
1. WRITE TO FILE:
FileWriter fw = new FileWriter("[Link]")
[Link](text)
[Link]()

2. READ FROM FILE:


FileReader fr = new FileReader("[Link]")
WHILE (ch = [Link]()) ≠ -1
PRINT (char)ch
[Link]()

3. APPEND TO FILE:
FileWriter fw = new FileWriter("[Link]", true)
[Link](new text)
[Link]()

4. USE try-catch for IOException


5. STOP
OUTPUT/INPUT:
Data written to file

--- File Content ---


Hello World
Java File Handling
Class 11 Level
Data appended successfully

--- Updated File ---


Hello World
Java File Handling
Class 11 Level
New data appended!
Question 19: Write a program to:
(a) Read a text file
(b) Count total number of lines in the file
(c) Count total number of words in the file
(d) Count total number of characters in the file
Display all counts
import [Link].*;

public class FileCounter {


public static void main(String[] args) {
int lines = 0, words = 0, chars = 0;

try {
// Open file for reading
FileReader fr = new FileReader("[Link]");

// Read file line by line


BufferedReader br = new BufferedReader(fr);
String line;

while ((line = [Link]()) != null) {


lines++; // Count lines
chars += [Link](); // Count characters in line

// Count words (split by spaces)


String[] wordArray = [Link](" ");
words += [Link];
}

[Link]();
[Link]();

} catch (IOException e) {
[Link]("File not found!");
return;
}

// Display counts
[Link]("Lines: " + lines);
[Link]("Words: " + words);
[Link]("Characters: " + chars);
}
}
ALGORITHAM:
1. OPEN FileReader("[Link]")
2. lines, words, chars ← 0
3. WHILE (line = readLine()) ≠ null
lines++
chars += [Link]()
words += [Link](" ").length
4. CLOSE file
5. PRINT lines, words, chars
6. STOP
OUTPUT/INPUT:
Hello World
Java Programming
Class 11
Lines: 3
Words: 5
Characters: 29
Question 20: Write a program to accept a sentence terminated by '.', '?' or '!' only.
Words are separated by single space and in UPPER case. Perform the following: (a) Check
validity of terminating character (b) Arrange words in ascending order of length. If lengths
are equal, sort alphabetically. (c) Display original and sorted sentences.

import [Link];

public class SentenceSort {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// (a) Input and validate terminating character


[Link]("Enter sentence (ends with . ? !): ");
String sentence = [Link]();

char lastChar = [Link]([Link]() - 1);


if (lastChar != '.' && lastChar != '?' && lastChar != '!') {
[Link]("INVALID TERMINATION");
return;
}

// Split into words (remove terminator)


String[] words = [Link](0, [Link]() - 1).split(" ");

// (b) Bubble Sort: length ASC, then alphabetical ASC


for (int i = 0; i < [Link] - 1; i++) {
for (int j = 0; j < [Link] - 1 - i; j++) {
if (words[j].length() > words[j + 1].length() ||
(words[j].length() == words[j + 1].length() &&
words[j].compareTo(words[j + 1]) > 0)) {
// Swap
String temp = words[j];
words[j] = words[j + 1];
words[j + 1] = temp;
}
}
}

// (c) Display original and sorted


[Link]("Original: " + sentence);
[Link]("Sorted: ");
for (int i = 0; i < [Link]; i++) {
[Link](words[i]);
if (i < [Link] - 1) [Link](" ");
}
[Link](lastChar);

[Link]();
}
}
ALGORITHAM:
1. INPUT sentence
2. IF lastChar ∉ {.,?,!} → "INVALID" → STOP
3. words ← split(sentence without lastChar)
4. BUBBLE SORT words:
IF len(words[j]) > len(words[j+1]) OR
(len equal AND words[j] > words[j+1])
SWAP words[j], words[j+1]
5. PRINT "Original:", sentence
6. PRINT "Sorted:", words + lastChar
7. STOP
OUTPUT/INPUT:
Enter sentence (ends with . ? !): HELLO WORLD THIS IS JAVA.
Original: HELLO WORLD THIS IS JAVA.
Sorted: IS THIS JAVA HELLO WORLD.

Enter sentence (ends with . ? !): CAT DOG BIRD?


Original: CAT DOG BIRD?
Sorted: CAT DOG BIRD?

You might also like