0% found this document useful (0 votes)
29 views

Shashwat Computer Project

Uploaded by

Shashwat Mishra
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)
29 views

Shashwat Computer Project

Uploaded by

Shashwat Mishra
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
You are on page 1/ 51

CITY

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;

public Perfect(int num)


{
this.num = num;
f = 1;
}

public int sumOfFactors(int i)


{
if (i == f)
{
return 0;
}
else if (i % f == 0)
{
return f++ + sumOfFactors(1);
}
else
{
f++;
return sumOfFactors(i);
}
}

public void check()


{
if (num == sumOfFactors(num))
{
System.out.println(num + " is a Perfect Number");
}
else
{
System.out.println(num + " is not a Perfect Number");
}
}

public static void main(String args[])


{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number:");
int n = sc.nextInt();
Perfect obj = new Perfect(n);
obj.check();
}
}

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.");
}
}

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number :");
int a = sc.nextInt();

Emirp emp = new Emirp(a);


emp.isEmirp();
}
}
Algorithm
1. Start and take input from the user.
2. Check if the number is prime.
3. Reverse the number.
4. Check if the reversed number is prime.
5. If both the original and reversed numbers are prime and different, print it is Emirp.
6. Otherwise, print it is not Emirp.
7. End.
Variable Description Table
Typ
Variable Name e Description
n int Stores the number input by the user for Emirp checking.
rev int Stores the reverse of the input number.
f int Used as a divisor to check for prime numbers.
x int Temporary variable to hold the number while reversing.
Stores the result of prime check for the original number (1 if
ans1 int
prime, 0 if not).
Stores the result of prime check for the reversed number (1 if
ans2 int
prime, 0 if not).
a int Used to store the user's input number in main method.

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();

System.out.println("Array in column major form:");


for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(arr[j][i] + " ");
}
}
}
}

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;
}

int num2 = num * 2;


int num3 = num * 3;
boolean isFascinating = true;
String str = "" + num + num2 + num3;
for (char i = '1'; i <= '9'; i++)
{
int idx1 = str.indexOf(i);
int idx2 = str.lastIndexOf(i);
if (idx1 == -1 || idx1 != idx2)
{
isFascinating = false;
break;
}
}

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();
}

public void main(String[] args)


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the row and column size for the array: ");
int a = sc.nextInt();
int b = sc.nextInt();
EqMat A = new EqMat(a, b);
EqMat B = new EqMat(a, b);
A.readarray();
B.readarray();
A.print();
System.out.println();
B.print();
if (A. check (A, B)==1)
{
System.out.println("Both are equal matrix");
}
else
{
System.out.println("Both are unequal matrix");
}

}
}
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);
}

public static void main(String[] args)


{
Toggle obj=new Toggle();
obj.read();
obj.toggle(); obj.display();
}
}
Algorithm
1. Start the program.
2. Initialize variables:
 A string to store the input word.
 A string to store the toggled case result.
 An integer to store the length of the input string.
3. Read the input word from the user.
4. Determine the length of the input string.
5. Toggle the case of each character in the input string:
 Convert lowercase letters to uppercase.
 Convert uppercase letters to lowercase.
 Append the toggled character to the result string.
6. Display the original and toggled case strings.
7. End the program.

Variable Description Table

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;
}

public static boolean isAdam(int num)


{
int sqNum = num * num;
int revNum = reverse(num);
int sqRevNum = revNum * revNum;
int rev = reverse(sqNum);
return rev == sqRevNum;
}

public static boolean isPrime(int num)


{
int c = 0;
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
c++;
}
}
return c == 2;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.print("Enter the value of m and n : ");
int m = in.nextInt();
int n= in.nextInt();
int count = 0;
if (m >=n ) {
System.out.println("INVALID INPUT");
return;
}
System.out.println("THE PRIME-ADAM INTEGERS ARE:");
for (int i = m; i <= n; i++) {
boolean adam = isAdam(i);
if (adam) {
boolean prime = isPrime(i);
if (prime) {
System.out.print(i + " ");
count++;
}
}
}
if (count == 0) {
System.out.print("NIL");
}

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.

Variable Description Table


Variable Name Type Description
m int Starting value of the range for checking Prime-Adam numbers.
n int Ending value of the range for checking Prime-Adam numbers.
count int Counter to keep track of the number of Prime-Adam integers found.
i int Loop variable used to iterate through the range from m to n.
adam boolean Indicates whether the current number is a Prime-Adam number.
prime boolean Indicates whether the current number is prime.

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];

for (int i = 0; i < wordCount; i++)


{
st.nextToken();
}
for (int i = 0; i < wordCount - 1; i++)
{
for (int j = 0; j < wordCount - 1; j++)
{
if (strArr[j].length() > strArr[j + 1].length())
{
String t = strArr[j];
strArr[j] = strArr[j + 1];
strArr[j + 1] = t;
}
if (strArr[j].length() == strArr[j + 1].length() && (strArr[j].compareTo(strArr[j + 1]) > 0))
{
String t = strArr[j];
strArr[j] = strArr[j + 1];
strArr[j + 1] = t;
}
}

}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < wordCount; i++)
{
sb.append(strArr[i]);
sb.append(" ");
}
return sb.toString().trim();
}

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
int len = str.length();
System.out.println();
if (str.charAt(len - 1) != '.' && str.charAt(len - 1) != '?' && str.charAt(len - 1) != '!')
{
System.out.println("INVALID INPUT");
return;
}
String sortedStr = sortString(str.substring(0, len - 1));
System.out.println(str);
System.out.println(sortedStr);
}
}
Algorithm
1. Start the program.
2. Input a sentence from the user.
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. Sort the words primarily by length (ascending) and secondarily by lexicographic order if
lengths are equal.
7. Join the sorted words into a single string.
8. Print the original and sorted strings.
9. End the program
Variable Description Table
Variable Name Type Description
str String Stores the input sentence from the user.
len int Stores the length of the input string.
sortedStr String Stores the sentence with words sorted by length and
lexicographically.
st StringTokenizer Tokenizer used to split the input string into words.
wordCount int Number of words in the input string.
strArr String[] Array to hold words for sorting.
sb StringBuffer Buffer to build the sorted string from the array of words.
t String Temporary variable used for swapping during sorting.
Output

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;
}

String nDateStr = computeDate(nDays, nYear);


System.out.println();
System.out.println("DATE: " + dateStr);
System.out.println("DATE AFTER " + n + " DAYS: " + nDateStr);
}
}
Algorithm
1. Start the program.
2. Input the day number, year, and number of days to add.
3. Check if the day number is within the valid range (1 to 366):
 If not, print "DAY NUMBER OUT OF RANGE" and end the program.
4. Check if the number of days to add is within the valid range (1 to 100):
 If not, print "DATE AFTER (N DAYS) OUT OF RANGE" and end the program.
5. Compute the date corresponding to the given day number and year:
 Check if the year is a leap year.
 Adjust February days if it is a leap year.
 Calculate the month and date from the day number.
6. Add the given number of days to the day number:
 Adjust the year and day number if the new day number exceeds 365 or 366 (for
leap years).
7. Compute the new date after adding the days:
 Follow the same process as in step 5.
8. Print the original date and the new date after adding the days.
9. End the program.
Variable Description Table
Variable Name Type Description
dayNum int The day number in the year (1 to 366).
year int The year for which the date is to be calculated.
n int Number of days to add to the given day number.
monthDays int[] Array storing the number of days in each month.
monthNames String[] Array storing the names of the months.
leap boolean Indicates if the year is a leap year.
date int Day of the month calculated from the day number.
daySum int Cumulative sum of days up to the current month.
nDays int Day number after adding n days.
nYear int Year adjusted after adding n days if necessary.
dateStr String The formatted date string corresponding to dayNum.
nDateStr String The formatted date string after adding n days.

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();
}

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);
StringTokenizer st = new StringTokenizer(str);
StringBuffer sb = new StringBuffer();
while (st.hasMoreTokens())
{
String word = st.nextToken();
boolean isPalinWord = isPalindrome(word);
if (isPalinWord)
{
sb.append(word);
}
else
{
String palinWord = makePalindrome(word);
sb.append(palinWord);

}
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;
}

public static void main(String args[])


{
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
if (n == 9 || n >= 50)
{
System.out.println("INVALID INPUT. NUMBER OUT OF RANGE.");
return;
}

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.

Variable Description Table


Variable Name Type Description
num int The input number provided by the user.
a int One number in the pair to be checked for being a prime.
b int The complementary number in the pair such that a + b = num.
Counter used to count divisors (not used in the final version but used
c int in primality check).

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.

Variable Description Table


Variable Name Type Description
n int Number of boxes to be packed into cartons.
cartonSizes int[] Array holding the sizes of cartons available.
total int Total number of cartons used.
t int Remaining boxes to be packed after using each carton size.
cartonCount int Number of cartons needed for a specific carton size.

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;
}

public static int getDigitCount(int num)


{
int c = 0;
while (num != 0)
{
c++;
num /= 10;
}
return c;
}

public static <isCircular> void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("ENTER INTEGER TO CHECK (N): ");
int n = in.nextInt();
if (n <= 0)
{
System.out.println("INVALID INPUT");
return;
}
boolean isCircularPrime = true;
if (isPrime(n))
{
System.out.println(n);
int digitCount = getDigitCount(n);
int divisor = (int) (Math.pow(10, digitCount - 1));
int n2 = n;
for (int i = 1; i < digitCount; i++)
{
int t1 = n2 / divisor;
}
for (int i = 1; i < digitCount; i++)
{
int t1 = n2 / divisor;
int t2 = n2 % divisor;
n2 = t2 * 10 + t1;
System.out.println(n2);
if (!isPrime(n2))
{
isCircularPrime = false;
break;
}
}
}
else
{
isCircularPrime = false;
}
if (isCircularPrime)
{
System.out.println(n+" IS A CIRCULAR PRIME.");
}
else
{
System.out.println(n + "IS NOT A CIRCULAR PRIME.");
}
}
}

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);

StringTokenizer st = new StringTokenizer(str);


StringBuffer sbVowel = new StringBuffer();
StringBuffer sb = new StringBuffer();
int c = 0;
while (st.hasMoreTokens())
{
String word = st.nextToken();
int wordLen = word.length();
if (isVowel(word.charAt(0)) && isVowel(word.charAt(wordLen - 1)))
{
c++;
sbVowel.append(word);
sbVowel.append(" ");
} else
{
sb.append(word);
sb.append(" ");
}
}
String newStr = sbVowel.toString() + sb.toString();
System.out.println("NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = "
+ c);
System.out.println(newStr);
}

public static boolean isVowel(char ch)


{
ch = Character.toUpperCase(ch);
boolean ret = false;
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == '0' || ch == 'U')
{
ret = true;
}
return ret;

}
}
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

Q.16) 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.
Program
import java.util.Scanner;

public class QuizCompetition


{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of participants (N): ");
int n = in.nextInt();
if (n <= 3 || n >= 11)
{
System.out.println("INPUT SIZE OUT OF RANGE.");
return;
}

char[][] answers = new char[n][5];


char[] key = new char[5];

System.out.println("Enter answers of participants:");


for (int i = 0; i < n; i++)
{
System.out.println("Participant " + (i + 1) + ":");
for (int j = 0; j < 5; j++)
{
answers[i][j] = in.next().charAt(0);
}
}

System.out.println("Enter answer key:");


for (int i = 0; i < 5; i++)
{
key[i] = in.next().charAt(0);
}

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]++;
}
}

if (score[i] > hScore)


{
hScore = score[i];
}

System.out.println("Participant " + (i + 1) + " = " + 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.

Variable Description Table


Variable Name Type Description
n int Number of participants.
answers char[][] 2D array storing answers of each participant.
key char[] Array storing the correct answers for the quiz.
hScore int Highest score among all participants.
score int[] Array storing the score of each participant.
i, j int Loop counters.
Output

Q.17) 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
Program
import java.util.Scanner;

public class CaesarCipher


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter plain text:");
String str = in.nextLine();
int len = str.length();

if (len <= 3 || len >= 100) {


System.out.println("INVALID LENGTH");
return;
}

StringBuffer sb = new StringBuffer();


for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if ((ch >= 'A' && ch <= 'M') || (ch >= 'a' && ch <= 'm')) {
sb.append((char)(ch + 13));
}
else if ((ch >= 'N' && ch <= 'Z') || (ch >= 'n' && ch <= 'z')) {
sb.append((char)(ch - 13));
}
else {
sb.append(ch);
}
}

String cipher = sb.toString();


System.out.println("The cipher text is:");
System.out.println(cipher);
}
}
Algorithm
1. Input:
 Read str from user.
 If str length is not between 4 and 99, print "INVALID LENGTH" and exit.
2. Encrypt:
 For each character ch in str:
 If ch is 'A'-'M' or 'a'-'m', shift by +13.
 If ch is 'N'-'Z' or 'n'-'z', shift by -13.
 Otherwise, keep ch unchanged.
3. Output: Print the encrypted string.
Variable Description Table
Variable Name Type Description
str String Input plain text string from the user.
len int Length of the input string str.
ch char Current character being processed.
sb StringBuffer StringBuffer to build the encrypted text.
cipher String Final encrypted text after processing.

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;

public class OctalMatrix


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of rows (M): ");
int m = in.nextInt();
System.out.print("Enter the number of columns (N): ");
int n = in.nextInt();

if (m <= 0 || m >= 10 || n <= 2 || n >= 6) {


System.out.println("OUT OF RANGE");
return;
}

int a[][] = new int[m][n];

for (int i = 0; i < m; i++) {


System.out.println("ENTER ELEMENTS FOR ROW " + (i + 1) + ": ");
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
if (a[i][j] < 0 || a[i][j] > 7) {
System.out.println("INVALID INPUT");
return;
}
}
}

System.out.println("FILLED MATRIX\tDECIMAL EQUIVALENT");

for (int i = 0; i < m; i++) {


int decNum = 0;
for (int j = 0; j < n; j++) {
decNum += a[i][j] * Math.pow(8, n - j - 1 );
System.out.print(a[i][j] + " ");
}
System.out.print("\t\t" + decNum);
System.out.println();
}
}
}
Algorithm
1. Input Dimensions:
 Read the number of rows (M) and columns (N).
 Check if M is between 1 and 9, and N is between 3 and 5. If not, output "OUT OF
RANGE" and exit.
2. Initialize Matrix:
 Create an M x N matrix.
3. Input Matrix Values:
 For each element in the matrix, input its value and ensure it's between 0 and 7. If
not, output "INVALID INPUT" and exit.
4. Process and Display Matrix:
 For each row in the matrix:
 Compute the decimal value of the row from its octal representation.
 Print the row's octal values and its decimal equivalent.
5. Print Results:
 Output the filled matrix and its decimal equivalents.
6. End Program.

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 storing the octal matrix values.
i int Row index used in loops.
j int Column index used in loops.
decNum int Decimal equivalent of the current row in the matrix.
Output

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;
}
}
}
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.print("ENTER VALUE OF N: ");
int n = in.nextInt();

if (n <= 2 || n >= 10) {


System.out.println("MATRIX SIZE OUT OF RANGE");
return;
}

int a[] = new int[n];


int b[][] = new int[n][n];

System.out.println("ENTER ELEMENTS OF SINGLE DIMENSIONAL ARRAY:");


for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}

sortArray(a);
System.out.println("SORTED ARRAY:");
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}

for (int i = n - 1, r = 0; i >= 0; i--, r++) {


for (int j = 0; j <= i; j++) {
b[r][j] = a[j];
}

for (int k = n - 1; k > i; k--) {


b[r][k] = a[k - i - 1];
}
}
System.out.println();
System.out.println("FILLED MATRIX:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
}
}
Algorithm
1. Read Input:
 Read integer N and validate it (3 ≤ N ≤ 9). Exit if invalid.
2. Initialize:
 Create array a and matrix b of size N.
3. Input and Sort:
 Read N integers into a.
 Sort a using bubble sort.
4. Fill Matrix:
 Populate matrix b using elements from sorted array a.
5. Print:
 Display sorted array a.
 Print matrix b.

Variable Description Table


Variable Name Type Description
n int Size of the array and matrix (input value)
a int[] One-dimensional array of size n (input values)
b int[][] Two-dimensional matrix of size n x n
i int Loop index for iterating through elements of the array or matrix
j int Loop index for iterating through elements in rows of the matrix
r int Row index for filling the matrix b
k int Loop index for filling remaining cells in the matrix b
Temporary variable used for swapping elements in the array
t int during sorting

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;

public class Banner


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt();
in.nextLine();

if (n <= 2 || n >= 9) {
System.out.println("INVALID INPUT");
return;
}

String teams[] = new String[n];


int highLen = 0;

for (int i = 0; i < n; i++) {


System.out.print("Team " + (i+1) + ": ");
teams[i] = in.nextLine();
if (teams[i].length() > highLen) {
highLen = teams[i].length();
}
}
for (int i = 0; i < highLen; i++) {
for (int j = 0; j < n; j++) {
int len = teams[j].length();
if (i >= len) {
System.out.print(" \t");
}
else {
System.out.print(teams[j].charAt(i) + "\t");
}
}
System.out.println();
}
}
}
Algorithm
1. Input:
 Read integer N.
 If N is not between 3 and 8, print "INVALID INPUT" and exit.
2. Store Team Names:
 Read N team names and store them in an array.
 Track the maximum length of the team names.
3. Print Banner:
 For each character position up to the maximum length:
 For each team:
 Print the character at the current position or a space if out of
bounds.
 Move to the next line.

Variable Description Table


Variable Name Type Description
n int Number of team names to read
teams String[] Array of team names
highLen int Maximum length of team names
i int Loop index for iterating over character positions
j int Loop index for iterating over team names
len int Length of the current team name
Output
Q.21) Write a menu driven program that prompts the user to select one of the four triangle
patterns (a, b, c, or d). The program then accepts number of rows and prints the selected pattern
as shown below:
1
12
123
1234
12345
123456
1234567
12345678
Program
import java.util.Scanner;

public class TriangleChoice


{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Type a for Pattern a");
System.out.println("Type b for Pattern b");
System.out.println("Type c for Pattern c");
System.out.println("Type d for Pattern d");

System.out.print("Enter your choice: ");


char ch = in.next().charAt(0);

System.out.print("Enter the number of terms: ");


int n = in.nextInt();

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':

for (int i = 1; i <= n; 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 '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."

Variable Description Table


Variable Name Type Description
ch char User's choice of pattern type (e.g., 'a', 'b', 'c', 'd')
n int Number of terms for the pattern
Output

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;

public class Series


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter x: ");
int x = in.nextInt();

double sinx = 0, cosx = 0;


int a = 1;

for (int i = 1; i <= 20; i += 2) {


long f = 1;
for (int j = 1; j <= i; j++)
f *= j;

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;
}

System.out.println("Sin x = " + sinx);


System.out.println("Cos x = " + cosx);
}
}
Algorithm
1. Input the value.
2. Initialize results and alternating sign.
3. For odd terms (1 to 20):
 Compute factorial.
 Update result using Taylor series term.
4. For even terms (0 to 20):
 Compute factorial.
 Update result using Taylor series term.
5. Output results.

Variable Description Table


Variable Name Type Description
x int Input value for calculations
sinx double Sum for sine approximation
cosx double Sum for cosine approximation
a int Alternating sign for terms
i int Current term index (in loops)
j int Loop counter for factorial calculation
f long Factorial value
t double Current term value for the series

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;

public class FactRange


{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);


System.out.print("Enter p: ");
int p = in.nextInt();
System.out.print("Enter q: ");
int q = in.nextInt();

if (p > q && p > 0 && q > 0) {


for (int i = q; i <= p; i++) {
long fact = 1;
for (int j = 1; j <= i; j++)
fact *= j;
System.out.println("Factorial of " + i +
" = " + fact);
}
}
else {
System.out.println("Invalid Input");
}

}
}
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".

Variable Description Table


Variable Name Type Description
p int Upper limit of the range for which factorials are calculated.
q int Lower limit of the range for which factorials are calculated.
i int Loop variable used to iterate from q to p.
j int Loop variable used to compute the factorial of i.
fact long Variable to store the factorial value of i.

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;

public class SDAMarks


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = in.nextInt();

String name[] = new String[n];


int totalmarks[] = new int[n];
int grandTotal = 0;

for (int i = 0; i < n; i++) {


in.nextLine();
System.out.print("Enter name of student " + (i+1) + ": ");
name[i] = in.nextLine();
System.out.print("Enter total marks of student " + (i+1) + ": ");
totalmarks[i] = in.nextInt();
grandTotal += totalmarks[i];
}

double avg = grandTotal / (double)n;


System.out.println("Average = " + avg);

for (int i = 0; i < n; i++) {


System.out.println("Deviation for " + name[i] + " = "
+ (totalmarks[i] - avg));
}
}

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.

Variable Description Table


Variable Name Type Description
n int Number of students.
name String[] Array to store names of students.
totalmarks int[] Array to store total marks of each student.
grandTotal int Sum of all students' total marks.
avg double Average of total marks.
Output

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;

public class StdCodes


{
public static void main(String args[]) {
final int SIZE = 10;
Scanner in = new Scanner(System.in);
String cities[] = new String[SIZE];
String stdCodes[] = new String[SIZE];
System.out.println("Enter " + SIZE +
" cities and their STD codes:");

for (int i = 0; i < SIZE; i++) {


System.out.print("Enter City Name: ");
cities[i] = in.nextLine();
System.out.print("Enter its STD Code: ");
stdCodes[i] = in.nextLine();
}

System.out.print("Enter name of city to search: ");


String city = in.nextLine();
int idx;
for (idx = 0; idx < SIZE; idx++) {
if (city.compareToIgnoreCase(cities[idx]) == 0) {
break;
}
}

if (idx < SIZE) {


System.out.println("Search Successful");
System.out.println("City: " + cities[idx]);
System.out.println("STD Code: " + stdCodes[idx]);
}
else {
System.out.println("Search Unsuccessful");
}
}
}
Algorithm
1. Initialize Arrays:
 Define an array for city names and another for STD codes.
2. Input Data:
 Read city names and STD codes into the arrays.
3. Search:
 Read the city name to search and find its index in the array.
4. Output:
 Print the STD code if the city is found, otherwise print "Search Unsuccessful".
Variable Description Table
Variable Name Type Description
SIZE int Number of cities and STD codes to be entered
String[
cities ] Array holding city names
String[
stdCodes ] Array holding STD codes corresponding to cities
city String City name input by the user for searching
idx int Index of the city in the cities array if found
Output

You might also like