Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 57

NAME : DIVYANSH JAIN

CLASS : 11

SECTION : A

ROLL NUMBER : 26

COMPUTER PROJECT

SEMESTER II
1. Write a program to print the sum of the rows and columns of a
rectangular matrix.

Algorithm:
i. Import the Scanner class from the java.util package
ii. Create a public class called "SumRec"
iii. Define the main method within the class
iv. Create a Scanner object "sc" to take input from the user
v. Prompt the user to enter the number of rows
vi. Read the number of rows entered by the user and store it in
the "rows" variable
vii. Prompt the user to enter the number of columns
viii. Read the number of columns entered by the user and store
it in the "columns" variable
ix. Prompt the user to enter the elements of the two-
dimensional array
x. Create a two-dimensional array called "array" with "rows"
number of rows and "columns" number of columns
xi. Use a nested loop to input the elements of the array and
print the array
xii. Use another nested loop to calculate the sum of each row
and print it
xiii. Use another nested loop to calculate the sum of each
column and print it
xiv. End the program.
import java.util.*;
public class SumRec {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number of rows");
int rows = sc.nextInt();
System.out.println("Enter the number of Columns");
int coloumbs = sc.nextInt();
System.out.println("Enter the Elemnts");
int array[][]=new int[rows][columns];

// loop for input and print the array

for(int i=0;i<rows;i++)
{
for(int j=0;j<coloumbs;j++)
{
array[i][j] = sc.nextInt();
System.out.print(array[i][j]+" ");
}
System.out.println();
}
sc.close();

for(int i=0;i<rows;i++)
{
int sum=0;
for(int j=0;j<coloumbs;j++)
{
sum=sum+array[i][j];
}
System.out.println("Sum of rows "+(i+1)+"="+sum);
}

for(int i=0;i<coloumbs;i++)
{
int sum=0;
for(int j=0;j<rows;j++)
{
sum=sum+array[j][i];
}
System.out.println("Sum of Columns "+(i+1)+"="+sum);
}
}
}

Sample Input:
3
3
123
456
789

Sample Output:
Sum of row 1 = 6
Sum of row 1 = 15
Sum of row 1 = 24
Sum of column 1 = 12
Sum of column 1 = 15
Sum of column 1 = 18
Variable Table:

Variable
Name Data Type Purpose
Stores the number of rows of the
rows int two-dimensional array
Stores the number of columns of
columns int the two-dimensional array

array int[][] Stores the two-dimensional array


Object of the Scanner class that is
sc Scanner used to take input from the user
Counter variable used in the for
i int loops
Counter variable used in the for
j int loops
Stores the sum of the elements of
sum int a row or column

2. Write a program to input a string in any case and print each


letter of the string with the frequency of vowels in it.

Algorithm:
i. Import the Scanner class from the java.util package
ii. Create a class named WordWise and define a constructor
with an empty string named str.
iii. Create a method named readsent to read a sentence from
the user. In this method, a Scanner object is created to take
input from the user and store it in the str variable.
iv. Create a method named freq_vowel to find the frequency
of vowels in a word. This method takes a word as a
parameter and returns the frequency of vowels in the word.
The word is converted to lowercase using toLowerCase()
method. Then, a loop is used to traverse the word and
count the frequency of vowels using an if-else condition.
v. Create a method named arrange to arrange the words in the
sentence based on the frequency of vowels. In this method,
the sentence is tokenized using StringTokenizer class and
the words are stored in a variable. Using a while loop, the
frequency of vowels in each word is calculated by calling
the freq_vowel method and the words are printed along
with their frequency.
vi. In the main method, an object of the WordWise class is
created and the readsent method is called to read the
sentence from the user. Then, the arrange method is called
to arrange the words in the sentence based on the
frequency of vowels.
vii. The program ends.

import java.util.*;
public class WordWise {
String str;
WordWise()
{
str="";
}
void readsent()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Sentence");
str=sc.nextLine();
sc.close();
}
int freq_vowel(String w)
{
int len = w.length();
int freq=0;
w=w.toLowerCase();
for(int i=0;i<len;i++)
{
char ch = w.charAt(i);
if(ch =='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')
{
freq++;
}
}
return freq;
}
void arrange()
{
StringTokenizer st = new StringTokenizer(str);
while(st.hasMoreTokens())
{
String w = st.nextToken();
System.out.println(w+" Freq="+freq_vowel(w));
}
}
public static void main(String[] args) {
WordWise obj = new WordWise();
obj.readsent();
obj.arrange();
}

Sample Input:
I am Divyansh

Sample Output:
I Freq= 1
am Freq= 1
Divyansh Freq= 3

Variable Table:
Variable Name Data Type Purpose

str String To store the input sentence

sc Scanner To read the input from the user

len int To store the length of a word

freq int To store the frequency of vowels in a word

st StringTokenizer To tokenize the sentence into words

w String To store a single word from the sentence

ch char To store a single character of a word

3. Write a program to input name, age and basic salary of a person.


Calculate the net salary. Net salary = hra + da + pf. hra = 18.5%
of basic da = 17.45% of basic and pf = 8.10% of basic if the age
of the person is above 50 years additional 5000 allowance is
given.

Algorithm:
i. Import the Scanner class from the java.util package
ii. The class Employee is declared.
iii. Declare the static variables: name, age, hra, pf, da, basic,
and net.
iv. Create an instance method accept() that accepts input from
the user for the employee's name, age, and basic salary.
v. Create an instance method calc() that calculates the
employee's HRA, DA, PF, and net salary. The calculation
of HRA is done by multiplying 18.5% of the basic salary.
The calculation of DA is done by multiplying 17.45% of
the basic salary. The calculation of PF is done by
multiplying 8.10% of the basic salary. If the employee's
age is greater than 50, the net salary is calculated by
adding HRA, DA, PF and 5000, otherwise, the net salary
is calculated by adding HRA, DA, and PF.
vi. Create an instance method print() that prints the
employee's basic salary, HRA, DA, PF, and net salary.
vii. The main method is declared and an object of the
Employee class is created.
viii. The accept() method is called on the object created to
accept the input from the user.
ix. The calc() method is called on the object to calculate the
employee's HRA, DA, PF, and net salary.
x. The print() method is called on the object to print the
employee's basic salary, HRA, DA, PF, and net salary.
xi. The program ends.

import java.util.*;
class Employee
{
static String name;
static int age;
static double hra;
static double pf;
static double da;
static double basic;
static double net=0;
void accept()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the name");
name = sc.nextLine();
System.out.println("Enter the age");
age = sc.nextInt();
System.out.println("Enter the basic salary");
basic = sc.nextInt();
sc.close();
}
void calc()
{
hra = ((18.5/100)*basic);
da = ((17.45/100)*basic);
pf = ((8.10/100)*basic);
if(age>50)
{
net = hra +da +pf+5000;
}
else
{
net = hra+ da +pf;
}
}
void print()
{
System.out.println("Basic Salary = "+basic);
System.out.println("HRA = "+hra);
System.out.println("PA = "+da);
System.out.println("PF = "+pf);
System.out.println("Net Salary = "+net);
}
public static void main(String[] args) {
Employee obj = new Employee();
obj.accept();
obj.calc();
obj.print();
}
}

Sample Input:
Divyansh
61
5000

Sample Output:
Basic Salary = 5000.0
HRA = 925.0
PA = 872.4999999999999
PF = 405.0
Net Salary = 7202.5
Variable Table:

Variable Name Data Type Purpose


name String To store the name of the employee
age int To store the age of the employee

To store the House Rent Allowance


hra double (HRA) of the employee

To store the Provident Fund (PF) of


pf double the employee

To store the Dearness Allowance


da double (DA) of the employee

To store the basic salary of the


basic double employee

To store the net salary of the


net double employee
4. Write a program to declare a square matrix of order n where n
must be greater than 3 and less than 10. Accept 3 different
characters from the user and fill the matrix.
 Fill the 4 corners with character 1.
 Fill the boundary element except 4 corner with character
2.
 Fill the non-boundary elements with character 3.
Display the Matrix Formed.

Algorithm:
i. Import the Scanner class from java.util package
ii. Create a class named "Matrix"
iii. Create a Scanner object to get input from the user
iv. In the main method, prompt the user to enter a number
v. Check if the number is greater than or equal to 10 or less
than or equal to 3
vi. If the number is not within the desired range, print "Invalid
input" and end the program
vii. If the number is within the desired range, create a 2D char
array with the size of n x n, where n is the user input
viii. Prompt the user to enter three characters
ix. Store the first character in all the corners of the matrix
(m[0][0], m[0][n-1], m[n-1][0], m[n-1][n-1])
x. For all the other elements on the first row and last row,
store the second character (m[0][1]-m[0][n-2], m[n-1][1]-
m[n-1][n-2])
xi. For all the elements on the first column and last column,
store the second character (m[1][0]-m[n-2][0], m[1][n-1]-
m[n-2][n-1])
xii. For all the remaining elements in the matrix, store the third
character
xiii. Use two for loops to print the matrix
xiv. End the program.
import java.util.*;
class Matrix
{
Scanner sc=new Scanner(System.in);
void main()
{
System.out.println("Enter a number");
int n=sc.nextInt();
if(n>=10 || n<=3)
{
System.out.println("Invalid input");
}
else
{
char m[][]=new char[n][n];
int i,j;
System.out.println("Enter three characters");
char c1=sc.next().charAt(0);
char c2=sc.next().charAt(0);
char c3=sc.next().charAt(0);
m[0][0]=c1;
m[0][n-1]=c1;
m[n-1][0]=c1;
m[n-1][n-1]=c1;
for(i=1;i<n-1;i++)
{
m[0][i]=c2;
}
for(i=1;i<n-1;i++)
{
m[n-1][i]=c2;
}
for(i=1;i<n-1;i++)
{
m[i][0]=c2;
}
for(i=1;i<n-1;i++)
{
m[i][n-1]=c2;
}
for(i=1;i<n-1;i++)
{
for(j=1;j<n-1;j++)
{
m[i][j]=c3;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.print(m[i][j]+" ");
}
System.out.println();
}
}
}
}

Sample Input:
3
&
@
#

Sample output:
&@&
@#@
&@&
Variable Table:

Variable Name Data Type Purpose

n int to store the size of the matrix

m 2-D char array to store the matrix elements

c1 char to store the first character input

c2 char to store the second character input

c3 char to store the third character input

i int loop variable for the rows

j int loop variable for the columns

sc Scanner object to get input from the user


5. Write a program to enter a number and print the number in
ascending order.

Algorithm:
i. Import the Scanner class from the java.util package.
ii. Create a class named 'ascendnum'.
iii. Inside the class, create a main method.
iv. Inside the main method, create a Scanner object to read
input from the user.
v. Prompt the user to enter a number 'n'.
vi. Create variables to store the number in ascending order
'nf', number of digits 'count', a copy of the original number
'copy', the last digit 'd', and loop variables 'i', 'j' and 'c'.
vii. Calculate the number of digits in 'n' by continuously
dividing it by 10 and incrementing the 'count' until 'copy'
is less than or equal to 0.
viii. Create an array 'arr' with size 'count' to store each digit of
'n'.
ix. Extract each digit of 'n' by repeatedly taking the remainder
of 'copy' divided by 10, and store it in 'arr'.
x. Sort the array 'arr' in ascending order using a nested for
loop and bubble sort.
xi. Create the number 'nf' in ascending order by multiplying
'nf' by 10 and adding each digit from the sorted array 'arr'.
xii. Finally, print the number in ascending order 'nf'.
xiii. The program ends.
import java.util.*;
public class ascendnum
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
int nf=0;
int count=0;
int copy=n;
int d=0,i,j,c=0;
while(copy>0)
{
count++;//digit counter
copy/=10;
}
int arr[]=new int[count];
copy=n;
while(copy>0)
{
d=copy%10;
arr[c++]=d;
copy/=10;
}
for(i=0;i<count;i++)
{
for(j=0;j<count-1-i;j++)
{
if(arr[j]>arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
for(i=0;i<count;i++)
{
nf=nf*10+arr[i];
}
System.out.println("Number in ascending order is "+nf);
}
}

Sample Input:
6985326

Sample Output:
2356689
Variable Table:

Variable Name Data Type Purpose

sc Scanner To take input from the user

n int To store the input number from the user

nf int To store the number in ascending order

count int To store the number of digits in n

copy int To store a copy of n for further operations

d int To store a digit of the number

i int Loop control variable for outer loop

j int Loop control variable for inner loop

c int Loop control variable for filling the array

arr int[] Array to store the digits of the number


6. Write a program to input a sentence and print the largest word in
the sentence.

Algorithm:
i. Import the java.util package to use the Scanner class.
ii. Define the main method of the class LargestWord.
iii. Create a Scanner object 'sc' to get the input sentence from
the user.
iv. Read the sentence as input and store it in the string
variable 'sent'.
v. Convert the sentence to lowercase and close the Scanner.
vi. Split the sentence into words and store each word in an
array of strings 'arr'.
vii. Get the length of the array 'arr' and store it in the variable
'len'.
viii. Create a temporary string variable 'temp' to hold the values
during swapping.
ix. Use nested for loops to compare each word with the other
words.
x. If the length of the first word is greater than the length of
the second word, swap the two words.
xi. If the length of the first word is equal to the length of the
second word, compare the two words lexicographically. If
the first word is lexicographically greater than the second
word, swap the two words.
xii. Repeat the above steps for all words in the array.
xiii. The last word in the sorted array will be the largest word
in the sentence.
xiv. Print the largest word in the sentence.
xv. The program ends.
import java.util.*;
public class LargestWord {
public static void main(String[] args) throws
NoSuchElementException{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Sentence");
String sent = sc.nextLine();
sent=sent.toLowerCase();
sc.close();
String arr[] = sent.split(" ");
int len = arr.length;
String temp="";
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(arr[i].length()>arr[j].length())
{
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
else if(arr[i].length()==arr[j].length())
{
if(arr[i].compareTo(arr[j])>0)
{
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}

}
}
System.out.println("The largest word is: "+arr[len-1]);
}
}

Sample Input:
My name is Divyansh

Sample Output:
The largest word is: Divyansh

Variable Table:

Variable Name Data Type Purpose

sc Scanner Scanner object used to take input from the user

sent String String to store the input sentence

arr String[] String array to store the words in the sentence

Integer variable to store the length of the array


len int 'arr'

Temporary string variable used to swap


temp String elements in the array 'arr'

i int Variable used as an index in the first for loop

Variable used as an index in the second for


j int loop
7. Write a program to input 20 numbers in an array and print the
range of the array.

Algorithm:
i. Import the Scanner class from the java.util package.
ii. Define the main class "rangearr".
iii. Create a Scanner object "sc" to take input from the user.
iv. Declare an array "arr" of size 20 to store the numbers
entered by the user.
v. Using a for loop, take input of 20 numbers from the user
and store them in the "arr" array.
vi. Initialize two variables, "max" and "min" to the first
element of the array "arr".
vii. Use another for loop to iterate over the elements of the
array.
viii. For each iteration, compare the current element with the
maximum and minimum values. If it is greater than the
current maximum value, update the maximum value. If it
is less than the current minimum value, update the
minimum value.
ix. After the for loop, subtract the minimum value from the
maximum value to get the range.
x. Finally, print the range as the output of the program.
xi. The program ends.
import java.util.*;
public class rangearr
{
public static void main()
{
Scanner sc=new Scanner(System.in);
double arr[]=new double[20];
int i;
System.out.println("Enter 20 Numbers");
for(i=0;i<20;i++)
{
arr[i] = sc.nextInt();
}
double max=arr[0];
double min=arr[0];
double range=0.0;
for(i=0;i<20;i++)
{
if(arr[i]>max)
max=arr[i];
if(arr[i]<min)
min=arr[i];
}
range=max-min;
System.out.println("The range is : "+range);
}
}

Sample input:
1 2 3 4 5 6 7 8 910 11 12 13 14 15 16 17 18 19 20 21

Sample Output:
The range is: 909.0

Variable Table:

Variable
Name Data Type Purpose

A scanner object used to take input from the


sc Scanner user

An array of doubles to store 20 numbers


arr double[] entered by the user

i int A loop counter variable

A variable to store the maximum value


max double among the 20 numbers

A variable to store the minimum value


min double among the 20 numbers

A variable to store the range (difference


between the maximum and minimum values)
Range Double of the 20 numbers
8. Write a program to input a sentence ending with (! , . or ?) and
print each word in ascending order if two words are of same
length then print according to alphabetic order.

Algorithm:
i. Import the Scanner class from the java.util package.
ii. Create a class named "String_2" and define the variables 's'
as a string, and initialize an empty constructor.
iii. Create an "Input" method to take the input sentence from
the user using Scanner class.
iv. Create a boolean method named "isValid" to check if the
last character of the sentence is ".", "!" or "?"
v. If the last character is ".", "!" or "?", then the method will
return "true". If not, it will return false.
vi. Create an "Operate" method to split the sentence into
words using the StringTokenizer class and store the words
in an array.
vii. Sort the words in the array in ascending order of their
length.
viii. Print the original sentence and the sorted words.
ix. Create a method named "Vowel" to count the number of
vowels in a given word.
x. Create the main method to create an object of the class
"String_2" and call the methods "Input", "Operate" and
"Vowel"
xi. If the "isValid" method returns false, the program will
print "Not a valid string".
xii. If the "isValid" method returns true, the program will
execute the "Operate" method and sort the words in the
sentence.
xiii. The program ends.
import java.util.*;
import java.io.*;
class String_2
{
String s;
void Input()
{
Scanner sc = new Scanner (System.in);
System.out.println("Enter a sentence ending with ?,. or !");
s = sc.nextLine();
}

boolean isValid()
{
int i = s.length() - 1;
if(".?!".indexOf(s.charAt(i)) != -1)
return true ;
else
return false ;
}

void Operate()
{
StringTokenizer str = new StringTokenizer (s);
int k =0,i,j,p;
if(isValid() == true)
{
String arr[] = new String[str.countTokens()];
while(str.hasMoreTokens())
{
arr[k++] = str.nextToken();
}
for(i =0; i < k; i ++)
{
for(j =0; j < k - i-1; j ++)
{
if (arr[j].length() > arr[j + 1].length())
{
String temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(s);
for(i=0;i<k;i++)
{
System.out.println(arr[i]);
}
}
else
{
System.out.println("Not a valid string");
}
}

int Vowel(String w)
{
int i,j=0;
for(i=0;i<w.length();i++)
{
if("AEIOUaeiou".indexOf(w.charAt(i)) != -1)
{
j=j+1;
}
}
return j;
}

void main()throws IOException


{
String_2 ob = new String_2();
ob.Input();
ob.Operate();
}
}

Sample input:
My name is Divyansh?

Sample Output:
is
My
name
Divyansh
Variable Table:

Variable
Name Data Type Purpose

s String To store the sentence entered by the user

sc Scanner To take input from the user

str StringTokenizer To split the sentence into words

Counter for the number of words in the


k int sentence

i int Loop counter for various loops

j int Loop counter for various loops

p int To store the number of vowels in a word

arr String[] To store the words of the sentence

To temporarily store a word while swapping


temp String words during sorting

ob String_2 Object of the class


9. Write a program to print n buzz number. n is entered by the
user. Buzz numbers are those numbers that are divisible by
seven or end with seven.

Algorithm:
i. Import the Scanner class from the java.util package.
ii. Create an object of the class 'Buzz'.
iii. Read the limit, 'n', for the number of buzz numbers to be
displayed.
iv. Call the 'Number' method with the parameters '7' (start
value), '1' (counter), and 'n' (limit).
v. Inside the 'Number' method, check if the counter is less
than or equal to the limit.
vi. If the counter is less than or equal to the limit, check if the
number is divisible by 7 or the last digit of the number is
7.
vii. If the condition is true, print the number and increment the
counter by 1.
viii. Call the 'Number' method again with the updated
parameters (number + 1, counter, limit).
ix. Repeat steps 4 to 7 until the counter becomes greater than
the limit.
x. If the counter becomes greater than the limit, the program
terminates.
xi. The program ends.
import java.util.Scanner ;
class Buzz
{
void Number(int n,int c,int a)
{
if(c<=a)
{
if((n%10)==7 || n%7 ==0)
{
System.out.print(n+" ");
c ++ ;
}
Number(n+1,c,a);
}

}
void main()
{
Buzz obj = new Buzz();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the limit");
int n = sc.nextInt();
System.out.println("Buzz numbers are");
obj.Number(7,1,n);
}
}

Sample input:
5

Sample Output:
7 14 17 21 27
Variable Table:

Variable
Name Data Type Description

Limit of the number of Buzz numbers to be


n int printed

Counter to keep track of the number of Buzz


c int numbers printed

Same as n, limit of the number of Buzz


a int numbers to be printed

obj Buzz Object of the Buzz class

sc Scanner Object to take input from the user


10. Write a program to input a sentence and print the number
of words starting with capital letters.

Algorithm:
i. Import the Scanner class from the java.util package.
ii. Start the program with the main method.
iii. Create an object of the class Capital using the statement
Capital obj = new Capital().
iv. Call the input() method to get the input sentence from the
user. The input() method creates a Scanner object sc to
read the input and stores the sentence in the sent variable.
v. Call the display() method to display the number of words
starting with a capital letter.
vi. In the display() method, first, call the isCap(sent) method
to check if there are any words starting with a capital
letter.
vii. The isCap(sent) method adds a space at the beginning of
the sentence and checks for a space before each word. If
the first character of a word is uppercase, then it
increments the frequency counter freq. At the end of the
loop, the flag variable is set to true if there are any words
starting with a capital letter.
viii. After the isCap(sent) method returns a value, the display()
method checks the value of flag. If flag is true, it prints the
frequency of words starting with a capital letter. If flag is
false, it prints "No capital letter found".
ix. End the program.
import java.util.*;
public class Capital {
static int freq;
static String sent;
Capital()
{
freq=0;
sent="";
}
public void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence");
sent = sc.nextLine();
sc.close();
}
public static boolean isCap(String w)
{
String sent2 = " "+sent;
boolean flag=false;
for(int i=0;i<sent2.length();i++)
{
if(sent2.charAt(i)==' ')
{
char ch2 = sent2.charAt(i+1);
if(Character.isUpperCase(ch2)==true)
{
flag=true;
freq++;
}
else{
flag=false;
}
}
}
if(flag==true)
{
return true;
}
else
{
return false;
}

}
public void display()
{
boolean flag = Capital.isCap(sent);
if(flag==true)
{
System.out.println("The Number of words Starting with
Capital letter is: "+freq);
}
else{
System.out.println("No capital letter found");
}
}
public static void main(String[] args) {
Capital obj = new Capital();
obj.input();
obj.display();
}
}

Sample input:
My name is Divyansh

Sample Output:
The Number of words starting with Capital letter is: 2
Variable table:

Variable Data
Name Type Purpose

sent String to store the sentence entered by the user

to store the frequency of words starting with capital


freq int letter

sc Scanner to input the sentence

flag boolean to check if the first letter of a word is capital or not

to store the sentence with a space in the beginning,


sent2 String used to check the first letter of every word

to store the first character of a word, used to check if


ch2 char it's a capital letter or not
Variable Data
Name Type Purpose

to loop through the sentence and check each word's


i int first letter

11. Write a program to input a number and check and print


whether it is a goldbach number or not. A Goldbach number is a
positive integer that is the sum of two odd prime numbers.

Algorithm:

i. Import the Scanner class from the java.util package.


ii. Create a class goldbach.
iii. Define a method main in the class.
iv. In the main method, create an object of the Scanner class
to take input from the user.
v. Read an integer n from the user.
vi. Check if n is odd or less than 8. If yes, print "Not a
Goldbach number".
vii. If n is not odd and greater than 8, then create a loop
starting from 3 to n-1 with a step of 2.
viii. In the loop, call the method check with the current
iteration value.
ix. If both the values returned by the method check are true,
then print "Goldbach number" and set the flag to 1.
x. If the loop is completed and the flag value is still 0, print
"Not a Goldbach number".
xi. Define a method check in the class goldbach which takes
an integer a as input.
xii. In the method check, create a variable c and initialize it
with 0.
xiii. Create a loop from 2 to a-1.
xiv. In the loop, check if a is divisible by the current iteration
value. If yes, increment c.
xv. After the loop is completed, if c is 0, then return true, else
return false.
xvi. Print the appropriate message.
xvii. The program ends.

import java.util.*;
class goldbach
{
void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt(),flag=0;
sc.close();
if(n%2==1 || n<8)
{
System.out.println("Not a Goldbach number");
}
else
{
for(int i=3;i<n;i+=2)
{
if(check(i) && check(n-i))
{
System.out.println("Goldbach number");
flag=1;
break;
}
}
if(flag==0)
{
System.out.println("Not a Goldbach number");
}
}
}
boolean check(int a)
{
int c=0;
for(int j=2;j<a;j++)
{
if(a%j==0)
{
c++;
}
}
if(c==0)
{
return true;
}
return false;
}
}

Sample input:
66

Sample Output:
Goldbatch Number
Variable Table:

Variable Data
Name Type Purpose

n int To store the input number

To check if the number is a Goldbach number or


flag int not

sc Scanner To take input from the user

i int Loop variable used in the for loop

c int To store the count of numbers that are not prime

a int To store the number passed to the check function

Loop variable used in the for loop inside the check


j int function
12. Write a program to print the Fibonacci series with limit n
entered by the user.

Algorithm:

i. Import the java.util package.


ii. Create a public class named Fibonacci.
iii. Declare three static integer variables a, b, and c with initial
values of 0, 1, and 0 respectively.
iv. Create a public static method named fibo that takes an
integer num as a parameter.
a. The method contains a conditional statement that
checks if num is greater than or equal to 1.
b. If the condition is true, the variable c is set to the
sum of a and b.
c. The value of c is then printed to the console.
d. The values of a and b are updated with b and c
respectively.
e. The value of c is set to 0 and the method is called
recursively with num decremented by 1.
v. Create a public static void method named main which is
the entry point of the program.
a. The method declares a Scanner object named sc and
initializes it to receive input from the console.
b. The console displays a message asking the user to
enter the length of the Fibonacci series.
c. The user inputs an integer value which is stored in a
variable named num.
d. The Scanner object is closed.
e. The values of a and b are printed to the console.
f. The fibo method is called with num as the argument

vi. The program ends.

import java.util.*;
public class Fibonacci {
static int a=0,b=1,c=0;
public static void fibo(int num)
{
if(num>=1)
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
c=0;
fibo(num-1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter the Length of the Fibonacci
Series");
int num = sc.nextInt();
sc.close();
System.out.print(a+" "+b);
fibo(num);
}
}

Sample input:
8

Sample output:
0 1 1 2 3 5 8 13 21 34

Variable Table:

Variable Name Data Type Purpose

To store the first two elements of the


a int Fibonacci series

To store the first two elements of the


b int Fibonacci series

To store the sum of two consecutive


c int elements in the Fibonacci series

To store the length of the Fibonacci series


num int entered by the user
Variable Name Data Type Purpose

sc Scanner To read input from the user.

13. Write a program to print all the combinations of a three


digit number taken as user input

Algorithm:

i. Import the java.util package.


ii. Create a public class named combinations.
iii. Initialize a Scanner object 'sc' to take input from the user.
iv. Prompt the user to enter a three-digit number and store the
value in the variable 'a'.
v. Declare two arrays 'a1' and 'a2' of size 3 to store the
individual digits of the number.
vi. Using a while loop, extract each digit of the number 'a' and
store it in the array 'a1'.
vii. Using three nested for loops, find all the possible
combinations of the digits stored in 'a1' and store it in the
array 'a2'.
viii. Calculate the integer value of the combination stored in
'a2' by multiplying the first digit with 100, second digit
with 10, and third digit with 1 and then adding them.
ix. Print the integer value 'c' obtained in the previous step.
x. Repeat steps 5 to 7 for all the possible combinations of the
digits.
xi. End the program.

import java.util.*;

class Combinations {
void main() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a three-digit number:");
int num = sc.nextInt();
sc.close();
int[] digits = new int[3];
int i = 0;
while (num > 0) {
int digit = num % 10;
digits[i] = digit;
num /= 10;
i++;
}
for (int j = 0; j < 3; j++) {
int[] combination = {digits[0], digits[1], digits[2]};
int firstDigit = combination[j];
for (int k = 0; k < 3; k++) {
if (k != j) {
int secondDigit = combination[k];
for (int l = 0; l < 3; l++) {
if (l != k && l != j) {
int thirdDigit = combination[l];
int result = (firstDigit * 100) + (secondDigit *
10) + thirdDigit;
System.out.println(result);
}
}
}
}
}
}
}

Sample Input:
369

Sample Output:
963
936
693
639
396
369
Variable Table:

Variable Data
Name Type Purpose

sc Scanner To read input from the user

To store the 3-digit number entered by the


a int user

b int Not used in the code

To store the last digit of the number 'a' after


n int each iteration
Variable Data
Name Type Purpose

m int To store the index of the array 'a1'

To store the final combination of 3 digits


c int after rearrangement

a1[] int array To store the digits of the number 'a'

To store the combination of the digits of 'a'


a2[] int array after rearrangement

14. Write a program to input a 2d matrix and swap the


diagonals of the matrix.

Algorithm:
i. Import the java.util package.
ii. Create a public class named DiagonalSwap2d.
iii. Define the main method.
iv. Create a Scanner object sc to get user input.
v. Ask the user to enter the size of the 2D array.
vi. Create a 2D array with the specified size and take inputs for
the elements of the array.
vii. Display the original 2D array.
viii. Use two nested for loops to swap the diagonals of the 2D
array.
a. The outer for loop runs from 0 to size-1.
b. The inner for loop swaps the diagonal elements.
ix. Display the modified 2D array after swapping the diagonals.
x. End the program.

import java.util.*;
public class DiagonalSwap2d {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter the size of the 2d Array");
int size = sc.nextInt();
System.out.println("Enter the Elemnts");
int array[][]=new int[size][size];
int temp=0;

// loop for input and print the array

for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
array[i][j] = sc.nextInt();
System.out.print(array[i][j]+" ");
}
System.out.println();
}
sc.close();
// for swapping the diagonals we use this loop

for(int i=0;i<size;i++)
{
temp = array[i][i];
array[i][i] = array[i][size-i-1];
array[i][size-1-i]=temp;
}
// Reprinting the Modified Array
System.out.println("Array after swapping");

for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}

Sample input:
3
123
456
789

Sample output:
321
456
987
Variable table:

Variable Name Type Description

size int The size of the 2D array.

array int[][] The 2D array of integers.

A temporary variable used for swapping the


temp int elements of the diagonals.
Variable Name Type Description

A loop control variable used in the first and


i int third for loops.

A loop control variable used in the second


j int for loop.

An instance of the Scanner class used to read


sc Scanner input from the user.

15. Write a program to input a word and check whether it a


‘Happy Word’ or not. Take a word and calculate the word’s
value based on position of the letters in English alphabet. On the
basis of word’s value, find the sum of the squares of its digits.
Repeat the process with the resultant number until the number
equals 1 (one). If the number ends with 1 then the word is called
a 'Happy Word'.

Algorithm:
i. Import the java.util package.
ii. Create a public class named HappyWrod.
iii. Define the main method.
iv. Read a word from the user using a Scanner object.
v. Convert the word to uppercase and store it in a String
variable word.
vi. Initialize an empty String variable wordValueStr to
store the numerical value of the word.
vii. Loop through each character in the word and convert
it to its corresponding numerical value (A=1, B=2, ...,
Z=26) by subtracting 64 from its ASCII code.
viii. Append the numerical value to the wordValueStr.
ix. Convert the wordValueStr to an integer wordValue.
x. Check if wordValue is a "happy number" by calling
the isHappyNumber method. A number is called a
"happy number" if the sum of the squares of its digits
eventually becomes 1. The method isHappyNumber
calculates the sum of the squares of the digits of the
number and returns true if the sum is 1 and false
otherwise.
xi. If wordValue is a "happy number", print "A Happy
Word". If not, print "Not a Happy Word".

import java.util.*;
public class HappyWord
{
static boolean isHappyNumber(int num)
{
int sum = 0;
int n = num;
do {
sum = 0;
while (n != 0) {
int d = (int)(n % 10);
sum += d * d;
n /= 10;
}
n = sum;
} while (sum > 6);
return (sum == 1);
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = in.next();
word = word.toUpperCase();
String wordValueStr = "";
int len = word.length();
for (int i = 0; i < len; i++) {
wordValueStr += String.valueOf(word.charAt(i) - 64);
}
int wordValue = Integer.parseInt(wordValueStr);
boolean isHappy = isHappyNumber(wordValue);
if (isHappy)
System.out.println("A Happy Word");
else
System.out.println("Not a Happy Word");
}
}

Sample Input:
VAT

Sample Output:
A Happy Word

Variable Table:
Variable Data
Name Type Purpose
To store the word entered by the
word String user.
To store the numerical value of
wordValueStr String the word.

len int To store the length of the word.

To store the numerical value of


the word after converting
wordValue int wordValueStr to an integer.

To store the result of checking if


isHappy boolean wordValue is a "happy number".
To read the word entered by the
in Scanner user.

You might also like