Shashwat Computer Project
Shashwat Computer Project
MONTESSOR
Name: - SHASHWAT MISHRA
Class: - XII Section: - P1
Subject: - Computer Application
Subject Teacher: - Mr. Sanjay
Shukla
ACKNOWLEDGEMENT
I would like to express my sincere gratitude to all
these individuals for mentoring and supporting me
in completing this project.
My teacher Mr. Sanjay Shukla for providing me with
invaluable insights and direction.
Our esteemed principal Dr.Mrs.Vineeta Kamran for
fostering an environment of learning and creativity
within our school.
To my parents, their constant encouragement,
patience, and understanding have been the pillars of
my success.
I am grateful to my friends who contributed ideas
and perspectives that enriched the project. Thank
you everyone for shaping this project and enhancing
my learning experience.
PROGRAMS
Q.1) Design a class Perfect to check if a given number is a perfect number or not. [A number is
said to be perfect if sum of the factors of the number excluding itself is equal to the original
number]
Program
import java.io.*;
import java.util.Scanner;
class Perfect
{
private int num;
private int f;
Algorithm
1. Start the program.
2. Take input from the user for the number to check.
3. Initialize a counter for potential factors.
4. Recursively or iteratively find all factors of the number (excluding the number itself) and
calculate their sum.
5. Compare the sum of factors with the original number.
6. If the sum equals the number, print that it is a perfect number; otherwise, print that it is not.
7. End the program.
Variable Description Table
Typ
Variable Name e Description
The number input by the user to check if it's
num int
perfect.
A counter used to track and sum the factors
f int
of num.
Stores the user input value in the main
n int
method.
Output
Q.2) An emirp number is a number which is prime backwards and forwards. Example: 13 and 31
are both prime numbers. Thus, 13 is an emirp number.
Design a class Emirp to check if a given number is Emirp number or not
Program
import java.util.Scanner;
class Emirp
{
int n, rev, f;
Emirp(int nn)
{
n = nn;
rev = 0;
f = 2;
}
int isprime(int x)
{
if (x > n / 2)
{
return 1;
}
else if (n % x == 0 || n == 1)
{
return 0;
}
else
{
return isprime(x + 1);
}
}
void isEmirp()
{
int original = n;
int x = n;
while (x != 0)
{
rev = rev * 10 + x % 10;
x = x / 10;
}
int ans1 = isprime(f);
n = rev;
f = 2;
int ans2 = isprime(f);
if (ans1 == 1 && ans2 == 1 && original != rev)
{
System.out.println(original + " is an Emirp number.");
}
else
{
System.out.println(original + " is not an Emirp number.");
}
}
Output
Q.3) Write a program that inputs a 2D array and displays how the array elements will look in row
major form and column major form.
Program
import java.util.Scanner;
public class DDARowColMajor
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = in.nextInt();
System.out.print("Enter number of columns: ");
int cols = in.nextInt();
int[][] arr = new int[rows][cols];
System.out.println("Enter the 2D array: ");
for (int i = 0; i < rows; i++)
{
System.out.println("Enter elements of row " + (i + 1));
for (int j = 0; j < cols; j++)
{
arr[i][j] = in.nextInt();
}
}
System.out.println("Array in row major form:");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
System.out.print(arr[i][j] + " ");
}
}
System.out.println();
Algorithm
1. Start the program.
2. Input the number of rows and columns from the user.
3. Initialize a 2D array with the given number of rows and columns.
4. Populate the 2D array by taking input from the user for each element row by row.
5. Print the array in row-major order: -Traverse the array row by row and print each element.
6. Print the array in column-major order:- Traverse the array column by column and print each
element.
7. End the program.
Variable Description Table
Variable Name Type Description
rows int Stores the number of rows in the 2D array.
cols int Stores the number of columns in the 2D array.
arr int[][] 2D array to store the user-input values.
i int Loop variable used for iterating over rows.
j int Loop variable used for iterating over columns.
Output
Q.4) Write a Program in Java to input a number and check whether it is a Fascinating Number or
not.
Fascinating Numbers: Some numbers of 3 digits or more exhibit a very interesting property. The
property is such that, when the number is multiplied by 2 and 3, and both these products are
concatenated with the original number, all digits from 1 to 9 are present exactly once, regardless
of the number of zeroes.
Program
import java.util.Scanner;
public class FascinatingNumber
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the number to check: ");
int num = in.nextInt();
if (num < 100)
{
System.out.println(num + "is not a Fascinating Number");
return;
}
if (isFascinating)
{
System.out.println(num + " is a Fascinating Number");
}
else
{
System.out.println(num + " is not a Fascinating Number");
}
}
}
Algorithm
1. Start the program.
2. Input a number to check.
3. If the number is less than 100, print that it is not a Fascinating Number and end the
program.
4. Calculate twice and thrice the number, then concatenate these values into a single string.
5. Check if the concatenated string contains each digit from 1 to 9 exactly once:
For each digit from 1 to 9, verify that the digit appears exactly once in the string.
6. Print the result based on the check:
If all digits are present exactly once, print that the number is a Fascinating
Number.
Otherwise, print that it is not a Fascinating Number.
7. End the program
Variable Description Table
Variable Name Type Description
num int Stores the number input by the user to check.
num2 int Stores the value of num multiplied by 2.
num3 int Stores the value of num multiplied by 3.
isFascinating boolean Indicates whether the number is a Fascinating Number (true) or
not (false).
str String Concatenated string of num, num2, and num3.
i char Loop variable used to iterate through digits '1' to '9'.
idx1 int Index of the first occurrence of a digit in str.
idx2 int Index of the last occurrence of a digit in str.
Output
Q.5) Two matrices are said to be equal if they have the same dimension and their corresponding
elements are equal. Design a class EqMat to check if tow matrices are equal or not. Assume that
the two matrices have the same dimension.
Program
import java.util.*;
class EqMat
{
int[][] a;
int m;
int n;
EqMat( int mm, int nn)
{
m=mm;
n=nn;
a=new int[m][n];
}
public void readarray()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the elements for the array: ");
for(int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}
}
public int check (EqMat P, EqMat Q)
{
for (int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
if(P.a[i][j]!=Q.a[i][j])
{
return 0;
}
}
}
return 1;
}
public void print()
{
for(int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
System.out.print(a[i][j] + "\t");
}
}
System.out.println();
}
}
}
Algorithm
1. Start the program.
2. Input the number of rows and columns for the matrices.
3. Create two matrices, A and B, with the specified dimensions.
4. Read elements into matrix A from user input.
5. Read elements into matrix B from user input.
6. Print matrix A.
7. Print matrix B.
8. Check if matrices A and B are equal:
Compare each element of A with the corresponding element in B.
If all elements match, the matrices are equal.
If any element does not match, the matrices are not equal.
9. Output whether the matrices are equal or not.
10. End the program.
Variable Description Table
Variable Name Type Description
a int Number of rows in the matrices.
b int Number of columns in the matrices.
m int Number of rows in the matrix (for instance creation).
n int Number of columns in the matrix (for instance creation).
a int[][] 2D array to store the elements of the first matrix.
b int[][] 2D array to store the elements of the second matrix.
i int Loop variable for iterating over rows.
j int Loop variable for iterating over columns.
Output
Q.6) A toggle string is a string where the case of each character is flipped. All uppercase letters
become lowercase, and all lowercase letters become uppercase. For example, if the input string
is "HelloWorld," the output of toggling its characters would be "hELLOwORLD."
Write a program in java to change a string into its corresponding toggle string
Program
import java.util.*;
class Toggle
{
String str, newstr; int len;
Toggle()
{
str=" ";
newstr="";
len=0;
}
void read()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Word");
str=sc.nextLine();
len=str.length();
}
void toggle()
{
char c = ' ';
for (int i = 0; i < len; i++)
{
c = str.charAt(i);
if (Character.isLowerCase(c))
{
c = Character.toUpperCase(c);
} else
{
c = Character.toLowerCase(c);
newstr += c;
}
}
}
void display()
{
System.out.println("Word "+str);
System.out.println("Toggle Word "+news);
}
Variable
Name Type Description
str String Stores the original input word.
newstr String Stores the word with toggled case (result).
len int Stores the length of the input word.
c char Temporary variable used to store and toggle each character.
Output
Q.7) 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.
Example: 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
Program
import java.util.Scanner;
public class PrimeAdam
{
public static int reverse(int num)
{
int rev = 0;
while (num != 0)
{
int d = num % 10;
rev = rev * 10 + d;
num /= 10;
}
return rev;
}
System.out.println();
System.out.println("FREQUENCY OF PRIME-ADAM INTEGERS IS: " + count);
}
}
Algorithm
1. Start the program.
2. Input two integers.
3. Check if the first integer is greater than or equal to the second:
If true, print "INVALID INPUT" and end.
4. For each number in the range:
Check if it is a Prime-Adam number:
Verify the Prime-Adam property.
Verify primality.
Print the number and count it if it meets the criteria.
5. If no Prime-Adam numbers are found, print "NIL".
6. Print the count of Prime-Adam numbers.
7. End the program.
Output
Q.8) Write a program to accept a sentence which may be terminated by either * single blank
space and are in UPPER CASE.
Perform the following tasks:
'?' or '!' only. The words are to be separated by a
Check for the validity of the accepted sentence only for the terminating character.
Arrange the words in ascending order of their length. If two or more words have the same length,
then sort them alphabetically. Display the original sentence along with the converted sentence.
Program
import java.util.*;
public class StringCheck
{
public static String sortString(String ipStr)
{
StringTokenizer st = new StringTokenizer(ipStr);
int wordCount = st.countTokens();
String[] strArr = new String[wordCount];
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < wordCount; i++)
{
sb.append(strArr[i]);
sb.append(" ");
}
return sb.toString().trim();
}
Q.9) 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 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
Program
import java.util.Scanner;
public class DateCalculator
{
public static boolean isLeapYear(int y)
{
boolean ret = false;
if (y % 400 == 0)
{
ret = true;
}
else if (y % 100 == 0)
{
ret = false;
}
else if (y % 4 == 0)
{
ret = false;
}
else
{
ret = false;
}
return ret;
}
public static String computeDate(int day, int year)
{
int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String[] monthNames = {"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
"JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"};
boolean leap = isLeapYear(year);
if (leap)
{
monthDays[1] = 29;
}
int i = 0;
int daySum = 0;
for (i = 0; i < monthDays.length; i++)
{
daySum += monthDays[i];
if (daySum >= day)
{
break;
}
}
int date = day + monthDays[i] - daySum;
StringBuffer sb = new StringBuffer();
sb.append(date);
sb.append("TH ");
sb.append(monthNames[i]);
sb.append(", ");
sb.append(year);
return sb.toString();
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("DAY NUMBER: ");
int dayNum = in.nextInt();
System.out.print("YEAR: ");
int year = in.nextInt();
System.out.print("DATE AFTER n DAYS): ");
int n = in.nextInt();
if (dayNum < 1 || dayNum > 366)
{
System.out.println("DAY NUMBER OUT OF RANGE");
return;
}
if (n < 1 || n > 100)
{
System.out.println("DATE AFTER (N DAYS) OUT OF RANGE");
return;
}
String dateStr = computeDate(dayNum, year);
int nDays = dayNum + n;
int nYear = year;
boolean leap = isLeapYear(year);
if (leap && nDays > 366)
{
nYear = nYear + 1;
nDays = nDays - 366;
} else if (nDays > 365)
{
nYear = nYear + 1;
nDays = nDays - 365;
}
Output
Q.10) 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 and are in uppercase.
Perform the following tasks:
(a) Check for the validity of the accepted sentence.
(b) Convert the non-palindrome words of the sentence into palindrome words by concatenating
the word by its reverse (excluding the last character)
Program
import java.util.*;
public class Palindrome
{
public static boolean isPalindrome(String word)
{
boolean palin = true;
int len = word.length();
for (int i = 0; i <= len / 2; i++)
{
if (word.charAt(i) != word.charAt(len - 1 - i))
{
palin = false;
break;
}
}
return palin;
}
public static String makePalindrome(String word)
{
int len = word.length();
char lastChar = word.charAt(len - 1);
int i = len - 1;
while (word.charAt(i) == lastChar)
{
i--;
}
StringBuffer sb = new StringBuffer(word);
for (int j = i; j >= 0; j--)
{
sb.append(word.charAt(j));
}
return sb.toString();
}
}
sb.append(" ");
}
String convertedStr = sb.toString().trim();
System.out.println();
System.out.println(ipStr);
System.out.println(convertedStr);
}
}
Algorithm
1. Start the program.
2. Input a sentence from the user and process it:
Convert the input to uppercase and trim any leading or trailing spaces.
3. Check if the sentence ends with a period (.), question mark (?), or exclamation mark (!):
If not, print "INVALID INPUT" and end the program.
4. Remove the punctuation from the end of the sentence.
5. Split the sentence into words.
6. For each word in the split sentence:
Check if the word is a palindrome:
If yes, append the word as is to the result.
If no, convert it to a palindrome by appending its reverse and append it to
the result.
7. Join the processed words into a single string.
8. Print the original and processed sentences.
9. End the program.Variable Description Table
Variable
Name Type Description
word String The individual word being checked or processed.
len int Length of the input word or sentence.
palin boolean Indicates if a word is a palindrome.
lastChar char The last character of the input sentence.
i int Index used for traversing characters in the word.
sb StringBuffer Buffer used to build the final output string.
The input sentence processed by trimming and converting
ipStr String to uppercase.
str String The input sentence with punctuation removed.
st StringTokenizer Tokenizer used to split the sentence into words.
word String The current word being processed from the tokenizer.
convertedStr String The final string with palindrome processing applied.
Output
Q.11) A Goldbach number is a positive even integer that can be expressed as the sum of two odd
primes.
Program
import java.util.*;
public class GoldbachNumber
{
public static boolean isPrime(int num)
{
int c = 0;
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
{
c++;
}
}
return c == 2;
}
if (n % 2 != 0)
{
System.out.println("INVALID INPUT. NUMBER IS ODD.");
return;
}
System.out.println("PRIME PAIRS ARE: ");
int a = 3;
int b;
while (a <= n / 2) {
b = n - a;
if (isPrime(a) && isPrime(b)) {
System.out.println(a + ", " + b);
}
a += 2;
}
}
}
Algorithm
1. Start the program.
2. Input a number.
3. Validate the input:
If the number is 9 or 50 or greater, print "INVALID INPUT. NUMBER OUT OF
RANGE." and end the program.
If the number is odd, print "INVALID INPUT. NUMBER IS ODD." and end the
program.
4. Initialize two numbers to check for pairs.
5. For each pair of numbers where the sum equals the input number:
Check if both numbers are prime.
Print the pair if both are prime.
6. End the program.
Output
Q.12) Write a program to declare a matrix a[][] of order (m x n) where 'm' is the number of rows
and 'n' is the number of columns
* such that the values of both 'm' and 'n' must be greater than 2 and less than 10. Allow the user
to input integers into this matrix. * Perform the following tasks on the matrix:
Display the original matrix.
Sort each row of the matrix in ascending order using any standard sorting technique.
Display the changed matrix after sorting each row.
Program
import java.util.Scanner;
public class ArraySort
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF M: ");
int m = in.nextInt();
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
if (m <= 2 || m >= 10 || n <= 2 || n >= 10)
{
System.out.println("MATRIX SIZE OUT OF RANGE.");
return;
}
int a[][] = new int[m][n];
System.out.println("ENTER ELEMENTS OF MATRIX:");
for (int i = 0; i < m; i++) {
System.out.println("ENTER for ELEMENTS OF ROW " + (i + 1) + ":");
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}
System.out.println("ORIGINAL MATRIX");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n - 1; j++)
{
for (int k = 0; k < n - j - 1; k++)
{
if (a[i][k] > a[i][k + 1])
{
int t = a[i][k];
a[i][k] = a[i][k + 1];
a[i][k + 1] = t;
}
}
}
}
System.out.println("MATRIX AFTER SORTING ROWS");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
Algorithm
1. Start the program.
2. Input m (rows) and n (columns).
3. Validate:
If m or n are not in the range (3 to 9), print "MATRIX SIZE OUT OF RANGE."
and end.
4. Initialize a matrix of size m x n.
5. Input matrix elements.
6. Print the original matrix.
7. Sort each row of the matrix using Bubble Sort.
8. Print the matrix after sorting.
9. End.
Variable Description Table
Variable Name Type Description
m int Number of rows in the matrix.
n int Number of columns in the matrix.
a int[][] 2D array (matrix) to store matrix elements.
i int Index for rows in the matrix.
j int Index for columns in the matrix.
k int Index for Bubble Sort comparisons within a row.
t int Temporary variable used for swapping elements during sorting.
Output
Q.13) 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 * (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.
Program
import java.util.Scanner;
public class CartonBoxes
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print ("Enter number of boxes (N): ");
int n = in.nextInt();
if (n <1 || n > 1000)
{
System.out.println("INVALID INPUT");
return;
}
int[] cartonSizes = {48, 24, 12, 6};
int total = 0;
int t = n;
for (int i =0; i < cartonSizes.length; i++)
{
int cartonCount = t / cartonSizes[i];
t = t % cartonSizes[i];
total += cartonCount;
if (cartonCount != 0)
{
System.out.println(cartonSizes[i] + " * " + cartonCount +" = "+(cartonSizes [i] *
cartonCount));
}
}
if (t != 0)
{
System.out.println("Remaining boxes = " + t + " * 1 = " + t);
total++;
}
else
{
System.out.println("Remaining boxes = 0");
}
System.out.println("Total number of boxes = "+ n);
System.out.println("Total number of cartons = " + total);
}
}
Algorithm
1. Start the program.
2. Input the number of boxes.
3. Validate the number of boxes:
If it is less than 1 or greater than 1000, print "INVALID INPUT" and end.
4. Initialize carton sizes and set counters.
5. Process each carton size to determine how many are needed and compute remaining
boxes.
6. If there are remaining boxes:
Print the count and total size.
7. Print the total number of boxes and cartons used.
8. End.
Output
Q.14) 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.
Program
import java.util.Scanner;
public class CircularPrime
{
public static boolean isPrime(int num)
{
int c = 0;
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
{
c++;
}
}
return c == 2;
}
Algorithm
1. Start the program.
2. Input an integer to check.
3. Validate the input:
If the number is less than or equal to 0, print "INVALID INPUT" and end.
4. Check if the number is prime:
If it is not, print the number is not a circular prime and end.
5. Determine the number of digits in the number.
6. Generate and check all rotations of the number:
Rotate the number and check if each rotation is prime.
If any rotation is not prime, mark as not a circular prime and end.
7. Print if the number is a circular prime or not.
8. End.
Variable Description Table
Variable Name Type Description
n int Integer input to check for circular prime status.
digitCount int Number of digits in the integer n.
divisor int Power of 10 used to extract digits from the integer.
n2 int Rotated version of the integer n used for checking.
t1 int Temporary variable used to store extracted digits.
t2 int Temporary variable used to store the remainder of the division.
isCircularPrime boolean Flag to indicate if the integer is a circular prime.
Output
Q.15) 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.
Perform the following tasks:
*Find the number of words beginning and ending with a vowel.
*Place the words which begin and end with a vowel at the beginning, followed by the remaining
words as they occur in the sentence.
Program
import java.util.*;
public class VowelWor
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("ENTER THE SENTENCE:");
String ipStr = in.nextLine().trim().toUpperCase();
int len = ipStr.length();
char lastChar = ipStr.charAt(len - 1);
if (lastChar != '.' && lastChar != '?' && lastChar != '!')
{
System.out.println("INVALID INPUT");
return;
}
String str = ipStr.substring(0, len - 1);
}
}
Algorithm
1. Read and Validate Input:
Read and trim the sentence.
Check if the last character is a valid punctuation mark; if not, print "INVALID
INPUT" and exit.
2. Process Sentence:
Remove the punctuation and tokenize the sentence into words.
3. Categorize and Count Words:
For each word, check if it starts and ends with a vowel.
Append such words to a vowel-buffer and others to a non-vowel buffer.
Count words that start and end with a vowel.
4. Output Results:
Concatenate and print the vowel-buffer and non-vowel buffer.
Print the count of words that start and end with vowels.
Variable Description Table
Variable Name Type Description
ipStr String Input sentence read from the user.
len int Length of the input sentence (ipStr).
lastChar char Last character of the input sentence.
str String Input sentence without the last punctuation mark.
StringTokenize
st r Tokenizer to split the sentence into individual words.
sbVowel StringBuffer Buffer to accumulate words that begin and end with a vowel.
Buffer to accumulate words that do not start and end with a
sb StringBuffer vowel.
Counter for the number of words that begin and end with a
c int vowel.
word String Current word being processed from the tokenizer.
wordLen int Length of the current word.
ch char Character used in the vowel check function.
ret boolean Result of the vowel check, indicating if the character is a vowel.
Output
int hScore = 0;
int[] score = new int[n];
System.out.println("Scores:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 5; j++)
{
if (answers[i][j] == key[j])
{
score[i]++;
}
}
System.out.println("Highest Score:");
for (int i = 0; i < n; i++)
{
if (score[i] == hScore)
{
System.out.println("Participant " + (i + 1));
}
}
}
}
Algorithm
1. Read Number of Participants (N):
If NN is not between 4 and 10, print "INPUT SIZE OUT OF RANGE" and stop.
2. Initialize Arrays:
Create a 2D array for participant answers and a 1D array for the answer key.
3. Input Participants' Answers:
For each participant, input answers for 5 questions.
4. Input Answer Key:
Input the correct answers for 5 questions.
5. Calculate Scores:
For each participant, compare answers with the key and compute the score.
Track the highest score.
6. Print Scores:
Output each participant's score.
7. Identify Highest Scorers:
Print participants with the highest score.
Output
Q.18) Write a program to declare a matrix A[][] of order (M x N) where 'M' is the number of rows
and 'N' is the number of columns such that the value of 'M' must be greater than 0 and less than
10 and the value of 'N' must be greater than 2 and less than 6. Allow the user to input digits (0 -
7) only at each location, such that each row represents an octal number.
Program
import java.util.Scanner;
Q.19) Write a program to declare a single-dimensional array a[] and a square matrix b[][] of size
N, where N > 2 and N < 10. Allow the user to input positive integers into the single dimensional
array.
Program
import java.util.Scanner;
public class Array
{
public static void sortArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}
}
sortArray(a);
System.out.println("SORTED ARRAY:");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
Output
Q.20) The names of the teams participating in a competition should be displayed on a banner
vertically, to accommodate as many teams as possible in a single banner. Design a program to
accept the names of N teams, where 2 < N < 9 and display them in vertical order, side by side
with a horizontal tab (i.e. eight spaces).
Program
import java.util.Scanner;
if (n <= 2 || n >= 9) {
System.out.println("INVALID INPUT");
return;
}
switch (ch)
{
case 'a':
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
System.out.print(j);
System.out.println();
}
break;
case 'b':
for (int i = n; i >= 1; i--)
{
for (int j = i; j < n; j++)
System.out.print(" ");
for (int k = 0; k < i; k++)
System.out.print(k);
System.out.println();
}
break;
case 'c':
case 'd':
for (int i = n; i >= 1; i--)
{
for (int j = 1; j < i; j++)
System.out.print(j);
System.out.println();
}
break;
default:
System.out.println("Incorrect choice");
break;
}
}
}
Algorithm
1. Display Choices: Show pattern options ('a', 'b', 'c', 'd') and prompt user for choice and
number of terms.
2. Read Input: Obtain the user’s pattern choice and the number of terms.
3. Generate Pattern: Based on the user’s choice, generate and print the corresponding
pattern:
For 'a': Print increasing sequences.
For 'b': Print right-aligned sequences decreasing in length.
For 'c': Print right-aligned sequences increasing in length.
For 'd': Print decreasing sequences.
4. Invalid Choice: If the choice is invalid, print "Incorrect choice."
Q.22) Write a program that computes sin x and cos x by using the following power series:
sin x = x - x3/3! + x5/5! - x7/7! + ……
cos x = 1 - x2/2! + x4/4! - x6/6! + ……
Program
import java.util.Scanner;
double t = Math.pow(x, i) / f * a;
sinx += t;
a *= -1;
}
a = 1;
for (int i = 0; i <= 20; i += 2) {
long f = 1;
for (int j = 1; j <= i; j++)
f *= j;
double t = Math.pow(x, i) / f * a;
cosx += t;
a *= -1;
}
Output
Q.23) Write a program to compute and display factorials of numbers between p and q where p >
0, q > 0, and p > q.
Program
import java.util.Scanner;
}
}
Algorithm
1. Input Reading: Read integers p and q from the user.
2. Input Validation: Check if p is greater than q, and both p and q are positive.
3. Factorial Calculation: If valid, iterate from q to p, computing the factorial for each
integer.
4. Output: Print the factorial of each integer.
5. Error Handling: If the input condition is not met, print "Invalid Input".
Output
Q.24) Write a program to accept name and total marks of N number of students in two single
subscript arrays name[ ] and totalmarks[ ].
Calculate and print:
(i) The average of the total marks obtained by N number of students.
[average = (sum of total marks of all the students)/N]
(ii) Deviation of each student's total marks with the average.
[deviation = total marks of a student - average]
Program
import java.util.Scanner;
Algorithm
1. Read number of students (n).
2. Initialize arrays for student names and total marks.
3. For each student:
Read the student's name.
Read the student's total marks.
Update the grand total of marks.
4. Compute the average of total marks.
5. For each student:
Calculate and print the deviation from the average.
Q.25) Write a program to accept the names of 10 cities in a single dimensional string array and
their STD (Subscribers Trunk Dialling) codes in another single dimension integer array. Search
for the name of a city input by the user in the list. If found, display "Search Successful" and print
the name of the city along with its STD code, or else display the message "Search unsuccessful,
no such city in the list
Program
import java.util.Scanner;