Anda di halaman 1dari 53

SACRED HEART CONVENT HR. SEC.

SCHOOL
2014-2015

Computer
Project
File
Submitted To:
SubmittedBy:
Mr.Sanjay Chauhan

Harshita Goyal
XII-B
1

CERTIFICATE
This is to certify that Harshita Goyal of XII-B has
completed this project under my guidance and
supervision.She has taken proper care and shown utmost
sincerity in the completion of this project.It is the token of
her hard work.
It is further certified that this project is up to my
expectations and as per the guidelines issued by ISC.

Mr.Sanjay Chauhan

ACKNOWLEDGEMENT
By the grace of God I am very much pleased at the
completion of this project file,and it is my foremost duty
to express my sincere thanks and gratitude to all those
who have spared their valuable time and gave me their
cooperation to complete this project file.
Every successful work requires
inspiration,cooperation and assistance ,the same was the
experience with this project work.
So I thank my Computer teacher ,Mr.Sanjay Chauhan
for his guidance and supervision.
I also give my hearty thanks to my parents who
encouraged me and for their moral support which enabled
me to complete this project file.

Question 1:
.Write a program to print the pseudoarithmetic sequence of numbers .You are given a
sequence of N integers, which are called as pseudoarithmetic

sequences (sequences that are in

arithmetic progression).Sequence of N integers :2,5,6,8,9,12. We observe that 2+12=5+9=6+8=14.


The sum of the above sequence can be calculated as 14*3=42.
For sequence containing an odd numbers of elements the rule is to double the middle element, for
example 2,5,7,9,12=2+12=5+9=7+7=14 .
14*3=42 [middle element =7]
A class Pseudoarithmetic determines whether a given sequence is a pseudoarithmetic sequence.
The details of the class are given below:
Class name : Pseudoarithmetic
Data members/
Instance variables:
n

: to store the size of the sequence

a [ ] : integer array to store the sequence of numbers


ans ,flag : store the status
sum
r

: store the sum of sequence of numbers


: store the sum of the two numbers

Member functions:
Pseudoarithmetic (): default constructor

Void accept (int nn) : to assign nn to n and to create an integer array . Fill in the elements of the
array
boolean check(): return true if the sequence is pseudoarithmetic
sequence otherwise returns false.
Specify the class Pseudoarithmetic , giving the details of the constructor( ),void accept (int) and
boolean check( ).Also define a main ( ) function to create an object and call the member functions
accordingly to enable the task.

Solution:
import java.io.*;
class Pseudoarithmetic
{
int n,a[ ],ans, flag,sum,r;
public Pseudoarithmetic( )
{
n=ans=flag=sum=r=0;
}
void accept(int nn) throws IOException
{
int i;
n=nn;
a=new int[n];
BufferedReader br=new InputStreamReader(System.in));
for(i=0;i<n;i++)
{

System.out.println(Enter a number);
a[i]=Integer.parseInt (br.readLine());
}
}
boolean check( )
{
int i,j;
r=a[0]+a[n-1];
if(n%2==0)
{
ans=1;
}
for( i=0,j=n-1;i<n/2;i++,j--)
{
sum =a[i]+a[j];
if(sum!=r)
{
flag=1;
break;
}
}
if (ans==0)
{
sum =2* a[n/2];
if(sum!=r)

{
flag=1;
}
}
if (flag==o)
{
return(true);
}
else
{
return (false);
}
}
public static void main(String args [ ] ) throws IOException
{
pseudoarithmetic ob=new Pseudoarithmetic ( );
ob.accept(5);
boolean x=ob.check( );
if (x==true)
{
System.out.println(pseudoarithmetic sequence);
}
else
{
System.out.println(not a pseudoarithmetic sequence);

}}
}

Output:
Enter a number : 2 5 6 8 10 9 14
pseudoarithmetic sequence

Question 2:
A class Mixer has been defined to merge two sorted integer arrays in ascending order. Some of the
members of the class are given below:
Class name

Mixer

Data members/instance variables:


int arr[]
int n

:
:

to store the elements of an array


to store the size of the array

Member functions:
Mixer( int nn)
:
constructor to assign n = nn
void accept()
:
to accept the elements of the array in ascending order without
any duplicates
Mixer mix( Mixer A)
:
to merge the current object array elements with the
parameterized array elements and return the resultant object
void display()
:
to display the elements of the array
Specify the class Mixer, giving details of the constructor(int), void accept(), Mixer
mix(Mixer) and void display(). Define the main() function to create an object and call the function
accordingly to enable the task.

Solution:

import java.io.*;
class Mixer
{
int arr[];
int n;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
Mixer(int nn)
{
n = nn;
arr = new int[n];

}
void accept()throws IOException
{
System.out.println("\n* Input the Array *\n");
for(int i=0; i<n; i++)
{
System.out.print("Enter Element ["+(i+1)+"] : ");
arr[i] = Integer.parseInt(br.readLine());
}
System.out.println();
}
Mixer mix(Mixer A)
{
int size = this.arr.length + A.arr.length;
Mixer B = new Mixer(size);
int x = 0;
for(int i=0; i<size; i++)
{
if(i<A.arr.length)
B.arr[i] = A.arr[i];
else
{
B.arr[i] = this.arr[x];
x++;
}
}
int temp=0;
for(int i=0; i<size-1; i++)
{
for(int j=i+1; j<size; j++)
{
if(B.arr[i]>B.arr[j])
{
temp = B.arr[i];
B.arr[i] = B.arr[j];
B.arr[j] = temp;
}
}
}
return B;
}
void display()
{
for(int i=0; i<n; i++)
{

System.out.print(arr[i] + " ");


}
System.out.println();
}
public static void main(String args[])throws IOException
{
System.out.print("Enter size of the 1st array : ");
int p = Integer.parseInt(br.readLine());
Mixer obj1 = new Mixer(p);
obj1.accept();
System.out.print("Enter size of the 2nd array : ");
int q = Integer.parseInt(br.readLine());
Mixer obj2 = new Mixer(q);
obj2.accept();
Mixer obj3 = obj2.mix(obj1);
System.out.print("The 1st Array is : ");
obj1.display();
System.out.print("The 2nd Array is : ");
obj2.display();
System.out.print("The Merged Array is : ");
obj3.display();
}
}

Output:
Enter size of the 1st array : 5
* Input the Array *
Enter Element [1] : 11
Enter Element [2] : 13
Enter Element [3] : 17
Enter Element [4] : 24
Enter Element [5] : 33
Enter size of the 2nd array : 3
* Input the Array *
Enter Element [1] : 5
Enter Element [2] : 19
Enter Element [3] : 30

The 1st Array is : 11 13 17 24 33


The 2nd Array is : 5 19 30
The Merged Array is : 5 11 13 17 19 24 30 33

Question 3:
Write a program to accept a sentence which may be terminated by either . ? or ! only. Any other
character may be ignored. The words may be separated by more than one blank space and are in
UPPER CASE.
Perform the following tasks:
(a) Accept the sentence and reduce all the extra blank space between two words to
a single blank space.
(b) Accept a word from the user which is part of the sentence along with its
position number and delete the word and display the sentence.
Test your program with the sample data and some random data:
Example 1
INPUT:

MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.

WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6
OUTPUT:

A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.

Example 2
INPUT:

AS YOU

SOW, SO SO YOU REAP.

WORD TO BE DELETED: SO
WORD POSITION IN THE SENTENCE: 4
OUTPUT:

AS YOU SOW, SO YOU REAP.

Example 3
INPUT:

STUDY WELL ##.

OUTPUT:

INVALID INPUT.

Solution:
import java.io.*;
class RemoveWord

{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
System.out.print("Enter any sentence : "); // Inputting the sentence
String s = br.readLine();
s = s.toUpperCase(); // Converting the sentence into Upper Case
int l = s.length();
String ans=""; // String variable to store the final result
char last = s.charAt(l-1); // Extracting the last character
/* Checking whether the sentence ends with '.', '?' or a '!' or not */
if(last == '.' || last == '?' || last == '!')
{
String word[]=s.split("[.?! ]+"); // Saving the words in an array using split()
int c = word.length; // Finding the number of words
System.out.print("Enter the word to delete : ");
String del = br.readLine();
del = del.toUpperCase();
System.out.print("Enter the word position in the sentence : ");
int x = Integer.parseInt(br.readLine());
if(x<1 || x>c) // Checking whether integer inputted is acceptable or not
{
System.out.println("Sorry! The word position entered is out of range");
}
else
{
for(int i=0; i<c; i++)
{
/* Skipping if the word to delete and the position matches */
if(word[i].equals(del)==true && i == x-1)
continue;
ans = ans + word[i] + " ";
}
System.out.print("Output : "+ans.trim()+last);
}
}
else
{
System.out.println("Invalid Input. End a sentence with either '.', '?' or '!'");
}
}
}

Output:

1. Enter any sentence : A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
Enter
the
word
Enter the word position is the sentence : 6

to

delete

IS

Output : A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.

Question 4:
Write a program to input a word from the user and remove the consecutive repeated characters by
replacing the sequence of repeated characters by its single occurrence.
Example:
INPUT-Heeeiiiissggoiinggg
OUTPUT Heisgoing

Solution:
import java.io.*;
class RemoveRepChar
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any word: "); // Inputting the word
String s = br.readLine();
s = s + " "; // Adding a space at the end of the word
int l=s.length(); // Finding the length of the word
String ans=""; // Variable to store the final result
char ch1,ch2;
for(int i=0; i<l-1; i++)
{
ch1=s.charAt(i); // Extracting the first character
ch2=s.charAt(i+1); // Extracting the next character
// Adding the first extracted character to the result if the current and the next characters
are different

if(ch1!=ch2)
{
ans = ans + ch1;
}
}
System.out.println("Word after removing repeated characters = "+ans); // Printing th
result

}
}

Output:

Enter any word: Jaaavvvvvvvvaaaaaaaaaaa


Word after removing repeated characters = Java

Question 5:
Given a time in numbers we can convert it into words. For example :
5 : 00 five oclock
5 : 10 ten minutes past five
5 : 15 quarter past five
5 : 30 half past five
5 : 40 twenty minutes to six
5 : 45 quarter to six
5 : 47 thirteen minutes to six
Write a program which first inputs two integers, the first between 1 and 12 (both inclusive)
and second between 0 and 59 (both inclusive) and then prints out the time they represent, in words.
Your program should follow the format of the examples above.
SAMPLE DATA :
1. INPUT :
TIME : 3,0
OUTPUT : 3 : 00 Three o clock
2. INPUT :
TIME : 7,29
OUTPUT : 7 : 29 Twenty nine minutes past seven
3. INPUT :
TIME : 6,34
OUTPUT : 6 : 34 Twenty six minutes to seven

4. INPUT :
TIME : 12,1
OUTPUT : 12 : 01 One minute past Twelve
5. INPUT :
TIME : 12,45
OUTPUT : 12 : 45 Quarter to One
6. INPUT :
TIME : 10,59
OUTPUT : 10 : 59 One minute to Eleven
7. INPUT :
TIME : 14,60
OUTPUT : Incorrect Input
Test your program for the data values given in the examples above and some random data.

Solution:

import java.io.*;
public class TimeInWords
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
/* Inputting hours and minutes */
System.out.print("Enter Hours : ");
int h=Integer.parseInt(br.readLine());
System.out.print("Enter Minutes : ");
int m=Integer.parseInt(br.readLine());
if((h>=1 && h<=12) && (m>=0 && m<=59)) // checking whether given input is lega
{
or not
/* creating an array containing numbers from 1-29 in words *
String words[]={"", "One", "Two", "Three", "Four", "Five", "Six","Seven", "Eight", "Nin
"Ten", "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen",
"Eighteen","Nineteen","Twenty","Twenty one", "Twenty two", "Twenty three", "Twenty
four", "Twenty five","Twenty six","Twenty seven","Twenty eight", "Twenty nine"};
/* The below code is for finding whether to print the word 'minute' or 'minutes' */

String plu, a;
if(m == 1)
plu = "Minute";
else
plu = "Minutes";
if(h==12)
a = words[1]; //storing 'one' when hour is 12
else
a = words[h+1];
/* The below code checks minutes and accordingly prints the time in words using array.
System.out.print("Output : "+h+":"+m+" ----- "); //printing the given time in number
if(m==0)
System.out.println(words[h]+" O' clock");
else if(m==15)
System.out.println("Quarter past "+words[h]);
else if(m==30)
System.out.println("Half past "+words[h]);
else if(m==45)
System.out.println("Quarter to "+a);
else if(m<30) // condition for minutes between 1-29
System.out.println(words[m]+" "+plu+" past "+words[h]);
else // condition for minutes between 31-59
System.out.println(words[60-m]+" "+plu+" to "+a);
} //end of outer if
else
System.out.println("Invalid Input !"); //printing error message for illegal input
}
}

Output:
Example 1:
Enter Hours : 12
Enter Minutes : 39
Output : 12:39 Twenty one Minutes to One
Example 2:
Enter Hours : 12
Enter Minutes : 39
Output : 12:39 Twenty one Minutes to One

Question 6:
The input in this question will consist of a number of lines of English text consisting of the letters of
the English alphabets, the punctuation marks () apostrophe, (.) full stop, (,) comma , (;) semicolon ,
(:) colon and white space. Write a program to print the words of the input in reverse order without any
punctuation marks other than blanks. Individual words (i.e. characters of every word) are not
reversed .For example, Consider the following input text:
INPUT:
Enter number of sentences: 2
Enter the sentences:
This is a sample piece of text to illustrate this question
if you are smart you will solve this right.
OUTPUT: right this solve will you smart are you if question this illustrate to text of piece sample a is
this
Test your program for the following data and some random data:
Sample Input :
Enter number of sentences: 1
Enter the text:
Do not judge a book by its cover.
Sample Output: Cover its by book a judge not do

Solution:
import java.io.*;
import java.util.*;
class Sent_Merge_Rev
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of sentences: ");
int n = Integer.parseInt(br.readLine());
String s = "";
for(int i=1; i<=n; i++)
{
System.out.print("Enter Sentence "+i+": ");
s = s + br.readLine(); //inputting multiple sentences and joining them //
}
StringTokenizer str=new StringTokenizer(s," '.,;:!?");
int c=str.countTokens();
String w="", rev="";
for(int i=1; i<=c; i++)
{
w = str.nextToken(); //extracting one word at a time
rev = w+" "+rev; //joining the extracted words in reverse order
}
System.out.println("Output: "+rev);
}
}

Output:
Enter the number of sentences: 2
Enter Sentence 1: Emotions, controlled and directed to work, is character.
Enter Sentence 2: By Swami Vivekananda.
Output: Vivekananda Swami By character is work to directed and controlled Emotions

Question 7:
A class Recursion has been defined to find the Fibonacci series upto a limit. Some of the members
of the class are given below:
Class Name : Recursion
Data Members/instance variables : a, b, c, limit (all integers)
Member functions/methods :
Recursion() : constructor to assign a,b,c with appropriate values.
void input() : to accept the limit of the series.
int fib(int n) : to return the nth Fibonacci term using recursive technique.
void genearate_fibseries() : to generate the Fibonacci series upto the given limit.
Specify the class Recursion giving details of the constructor, int fib() , void generate_fibseries().
You may assume other functions are written for you and you need not write the main function.

Solution:

import java.io.*;
class Recursion
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b,c,limit;
Recursion() //Constructor
{
a=0;
b=1;
c=0;
limit=0;
}
void input()throws IOException //Function to input the limit
{

System.out.print("Enter the limit : ");


limit=Integer.parseInt(br.readLine());
}
int fib(int n) //Recursive function generating the 'nth' term of Fibonacci Series
{
if(n<=1)
return a;
else if(n==2)
return b;
else
return (fib(n-1)+fib(n-2));
}
void generate_fibseries() //Function generating all the Fibonacci Series no.s upto 'n' terms
{
System.out.println("The Fibonacci Series is:");
for(int i=1;i<=limit;i++)
{
c=fib(i);
System.out.print(c+" ");
}
}
public static void main(String args[])throws IOException
{
Recursion ob=new Recursion();
ob.input();
ob.generate_fibseries();
}
}

Output:
Enter the limit : 11
The Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34 55
Enter the limit : 20
The Fibonacci Series is:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Question 8:
Write a program to declare a square matrix A[ ] [ ] of order (M x M) where M is the number of rows
and the number of columns such that M must be greater than 2 and less than 10. Accept the value of
M as user input. Display an appropriate message for an invalid input. Allow the user to input integers
into this matrix. Perform the following tasks:
(a)

Display

(b)

Check

if

the

the

given

original

matrix

is

Symmetric

matrix.
or

not.

A square matrix is said to be Symmetric, if the element of the i th row and jth column is equal to
the

element

(c)

of

the

jth row

and

ith column.

Find the sum of the elements of left diagonal and the sum of the elements of right diagonal

of the matrix and display them.


Test your program with the sample data and some random data:
Example 1
INPUT

OUTPUT

ORIGINAL MATRIX
1

M=3

THE GIVEN MATRIX IS SYMMETRIC


The sum of the left diagonal = 11
The sum of the right diagonal = 10
Example 2
INPUT

M = 22

OUTPUT

THE MATRIX SIZE IS OUT OF RANGE

Solution:

import java.io.*;
class SymetricMatrix
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

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


int m=Integer.parseInt(br.readLine());
int A[][]=new int[m][m];

if(m>2 && m<10) // Checking for valid input of rows and columns size
{
System.out.println("nInputting the elements in the Matrix: n");
for(int i=0;i<m;i++)
{

for(int j=0;j<m;j++)
{
System.out.print("Enter the elements : ");
A[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("nThe Original Matrix is : ");
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(A[i][j]+"\t");
}
System.out.println();
}

/* Checking whether the matrix is symmetric or not */

int flag = 0;
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
if(A[i][j] != A[j][i])
{
flag = 1; // Setting flag = 1 when elements do not match
break;

}
}
}
if(flag == 1)
System.out.println("nThe given Matrix is Not Symmetric");
else
System.out.println("nThe given Matrix is Symmetric");
int ld = 0, rd = 0;

/* Finding sum of the diagonals */

for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
if(i == j) // Condition for the left diagonal
{
ld = ld + A[i][j];
}
if((i+j) == (m-1)) // Condition for the right diagonal
{
rd = rd + A[i][j];
}
}
}

System.out.println("The sum of the left diagonal = "+ld);

System.out.println("The sum of the right diagonal = "+rd);


}
else
System.out.println("The Matrix Size is Out Of Range");
}
}

Output:
Enter the number of elements:3
Inputting the elements in the matrix:
Enter the elements : 1
Enter the elements : 2
Enter the elements : 3
Enter the elements : 4
Enter the elements : 5
Enter the elements : 6
The Original Matrix Is:
1

The given Matrix is Symmetric


The sum of the left diagonal =11

The sum of the right diagonal =10

Question 9:
Write a Program in Java to fill a square matrix of size n*n in a spiral fashion (from the inside) with
natural numbers from 1 to n*n, taking n as input.
For example: if n = 5, then n*n = 25, hence the array will be filled as given below.

Note: Dont be confused as to how the filling will start from the center. Just treat the above program
as (see the difference in the direction of the arrows):

So, you see, this question is nothing but the same circular matrix which we did earlier (See: Java
Program to print Circular (Spiral) Matrix). The only change is that here the filling of numbers is from
n*n to 1 every time decreasing by one. In the earlier program it was from 1 to n*n every time
increasing by one.
So slight changes in our earlier program will result into this new spiral matrix. The changes will be:

Start k from n*n and not 1

Change the condition in while loop to while(k >= 1)

Decrease the value of k every time as k- -

Solution:
import java.io.*;
class Circular Matrix
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of elements : ");
int n=Integer.parseInt(br.readLine());
int A[][]=new int[n][n];
int k=n*n, c1=0, c2=n-1, r1=0, r2=n-1;
while(k>=1)
{
for(int i=c1;i<=c2;i++)
{
A[r1][i]=k--;

}
for(int j=r1+1;j<=r2;j++)
{
A[j][c2]=k--;
}
for(int i=c2-1;i>=c1;i--)
{
A[r2][i]=k--;
}
for(int j=r2-1;j>=r1+1;j--)
{
A[j][c1]=k--;
}
c1++;
c2--;
r1++;
r2--;
}
System.out.println("The Circular Matrix is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(A[i][j]+ "\t");

}
System.out.println();
}
}
}

Output:
Enter the number of elements:5
The Circular Matrix is:
25

24

23

22

21

10

20

11

19

12

18

13

14

15

16 17

Question 10:
Write a Program in Java to input a 2-D array of size m*n and print its boundary (border) elements.
For example:

Solution:

import java.io.*;
class Boundary_Element
{
public static void main(String args[])throws IOException
{
int i,j,m,n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the no. of rows: "); //Inputting the number of rows
m=Integer.parseInt(br.readLine());
System.out.print("Enter the no. of columns: "); //Inputting the number of columns
n=Integer.parseInt(br.readLine());
int A[][]=new int[m][n]; //Creating the array

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

/* Inputting the array */

{
for(j=0;j<n;j++)
{
System.out.print("Enter the elements: ");
A[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("The Boundary Elements are:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{

if(i==0 || j==0 || i == m-1 || j == n-1) //condition for accessing boundary eleme


System.out.print(A[i][j]+"\t");
else
System.out.print(" \t");
}
System.out.println();
}
}
}

Output:

Enter the no. of rows: 4


Enter the no. of columns: 3
Enter the elements : 1
Enter the elements : 2
Enter the elements : 3
Enter the elements : 4
Enter the elements : 5
Enter the elements : 6
Enter the elements : 7
Enter the elements : 8
Enter the elements : 9
Enter the elements : 10
Enter the elements : 11
Enter the elements : 12
The Boundary Elements are :
1

10

11

12

Question 11:

Write a program to input a number. Count and print the frequency of each digit present in that
number. The output should be given as:
Sample Input: 44514621
Sample Output:
=====================
Digit

Frequency

=====================
1

Solution:
import java.io.*;
class Digit_Freq
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any number : ");
int n = Integer.parseInt(br.readLine());
int freq[]=new int[10]; //array for storing frequency of all digits
for(int i=0; i<10; i++)
{
freq[i]=0; //intializing the count of every digit with '0'
}
/* Frequency of digit '0' is stored in freq[0], frequency of '1' in freq[1] and so on*/

System.out.println("Output:");
System.out.println("===================="); //this is just for styling the lo
output
System.out.println("Digit\tFrequency");
System.out.println("====================");

int d;
while(n>0)
{
d=n%10; //extracting digit from the end
freq[d]++; //increasing the frequency of that digit.
n=n/10;
}
for(int i=0; i<10; i++)
{
if(freq[i]!=0) //printing only those digits whose count is not '0'
System.out.println(" "+i+"\t "+freq[i]);
}
}
}

Output:
Enter any number : 937825770
Output:
=====================
Digit

Frequency

=====================
0

Question 12:

Write a program in Java to find the Roman equivalent of any Decimal number entered by the user.
[The number entered should be within the Range 1-3999]. The Roman numerals follow this basic
pattern,
1000 = M, 900 = CM, 500 = D, 400 = CD, 100 = C, 90 = XC, 50 = L, 40 = XL, 10 = X, 9 = IX, 5 = V, 4
= IV, 1 = I
The symbols I, X, C, and M can be repeated three times in succession, but no more. i.e. 234
can be represented as CCXXXIV, but 244 cannot be written as CCXXXXIV [Since we cannot repeat
X more than 3 times successively].
(They may only appear more than three times if they appear non-sequentially, such as XXXIX.) D,
L, and V can never be repeated.

Solution:
import java.io.*;
class Dec2Roman
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a Number : ");
int num=Integer.parseInt(br.readLine()); //accepting decimal number

if(num>0 && num<4000) //checking whether the no. entered is within the range [1-3999]
{ /*Saving the Roman of the thousand, hundred, ten and units place of a decimal number
String thou[]={"","M","MM","MMM"};
String hund[]={"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
String ten[]={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
String unit[]={"","I","II","III","IV","V","VI","VII","VIII","IX"};
int th=num/1000; /*Finding the digits in the thousand, hundred, ten and units place*/
int h=(num/100)%10;
int t=(num/10)%10;
int u=num%10;
System.out.println("Roman Equivalent= "+thou[th]+hund[h]+ten[t]+unit[u]);
}
else
System.out.println("nYou entered a number out of Range.nPlease enter a number in the

range [1-3999]");
}
}

Output:
Enter a Number : 3482
Roman Equivalent = MMMCDLXXXII

Question 13:
Write a program to swap two numbers without using any third variable

Solution:
import java.io.*;
class Swapping
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b;
System.out.print("Enter the 1st no: ");
a=Integer.parseInt(br.readLine());
System.out.print("Enter the 2nd no: ");
b=Integer.parseInt(br.readLine());
System.out.println("-------------------------------");
System.out.println("The numbers before swapping are");
System.out.println("a = "+a);
System.out.println("b = "+b);
a=a+b;
//Beginning of Swapping
b=a-b;
a=a-b;
//End of Swapping
System.out.println("-------------------------------");
System.out.println("The numbers after swapping are");
System.out.println("a = "+a);
System.out.println("b = "+b);
}
}

Output:
Enter the 1st no: 25
Enter the 2nd no: 13
The numbers before swapping are
a = 25
b = 13
The numbers after swapping are
a = 13
b = 25

Question 14:
Write a Program in Java to input a Date in ddmmyyyy 8-digit format and print it in:
1) dd/mm/yyyy format
2) dd, month name, yyyy format
Input: 01011943
Output:
01/10/1943
1 January, 1943

Solution:
import java.io.*;
class Date_DDMMYY
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int l, y, d, m;
String dd, mm, yy;
int maxdays[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
String month[]={ "", "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December" };
System.out.print("Enter any date in 8 digits (ddmmyyyy) format: ");
String date = br.readLine(); //inputting the date in String format
l = date.length(); //finding number of digits in the given input
if(l==8) //performing the task only when number of digits is 8
{
dd = date.substring(0,2); //extracting the day in String format
mm = date.substring(2,4); //extracting the month in String format
yy = date.substring(4); //extracting the year in String format
d = Integer.parseInt(dd); //day in Integer format
m = Integer.parseInt(mm); //month in Integer format
y = Integer.parseInt(yy); //year in Integer format
if((y%400==0) || ((y%100!=0)&&(y%4==0))) // condition for leap year
{
maxdays[2]=29;
}
if(m<0 || m>12 || d<0 || d>maxdays[m] || y<0 || y>9999)
System.out.println("The day, month or year are outside acceptable limit");

else
{
System.out.println("Date in dd/mm/yyyy format = "+dd+"/"+mm+"/"+yy);
System.out.print("Date in dd, month name, yyyy format = "+dd+" "+month[m]
"+yy);
}
}
else
System.out.println("Wrong Input");
}
}

Output:
1) Enter any date in 8 digits (ddmmyyyy) format: 02052013
Date in dd/mm/yyyy format = 02/05/2013
Date in dd, month name, yyyy format = 02 May, 2013
2) Enter any date in 8 digits (ddmmyyyy) format: 12111963
Date in dd/mm/yyyy format = 12/11/1963
Date in dd, month name, yyyy format = 12 November, 1963
3) Enter any date in 8 digits (ddmmyyyy) format: 252013
Wrong Input
4) Enter any date in 8 digits (ddmmyyyy) format: 29022013
The day, month or year are outside acceptable limit

Question 15:
Write a program to check whether a given number is palindrome or not.

Solution:
class palindrome
{
public static void main(String args[])
{
int num=989, n=num,q=0,dig,rn=0;
while(num>0)
{
q= num/10;
dig=num%10;
rn=rn*10+dig;
num=q;
}
System.out.println(Number is Palindrome);
else
System.out.println( Number is not Palindrome);
System.out.println(Number is +n);
}
}

OUTPUT:
Number is Palindrome

Number is 989

Question 16 :
Write a program to generate Fibonacci series.
For example:1,1,2,3,5,8,13.

Solution:
import java.io.*;
class Fibonacci
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader (new
InputStreamReader(System.in));
System.out.print(Enter the number of terms:);
int n=Integer.parseInt(br.readLine());
int a=0b=1,c=0,x;
while (c<n)
{
System.out.println( +a);
x=a+b;
a=b;
b=x;
c++;

}
}
}

Output:
Enter the number of terms: 1 1 2 3 5 8 13 21

Question 17
Write a program to take any word of length less than ten from the user and then print the number of
vowels present in the word.

Solution:
import java.io.*;
class length
{
public static void main(String args[])throws IOException
{
String str= ;
int i, count=0;
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Do
{
if(str.length()>=10)
System.out.print(Word Length must be less than 10.ReEnter);
else
System.out.print(Enter the word :);

str=br.readLine();
}
while(str.length()>=10)
str =str. toLowerCase();
for(i=0;i<str.length();i++)
{
c=str.charAt(i);
If(c==a||c==e||c==I||c==o||c==u)
{
count++;
}
}
System.out.println(The number of vowels are+count);
}
}

Output:
Enter the word ; Harshita
The number of vowels are : 3

Question 18:

Write a program to accept a sentence as input. The words in the string are to be separated by a
blank. Each word must be in upper case. The sentence is terminated by either .,! or ?. Perform
the following tasks:
(i) Obtain the length of the sentence. (measured in words)
(ii) Arrange the sentence in alphabetical order of the words.
Test your program with the sample data and some random data:
Example 1:
INPUT: NECESSITY IS THE MOTHER OF INVENTION.
OUTPUT:
Length: 6
Rearranged Sentence:
INVENTION IS MOTHER NECESSITY OF THE
Example 2:
INPUT: BE GOOD TO OTHERS.
OUTPUT:
Length: 4
Rearranged Sentence: BE GOOD OTHERS TO

Solution:
import java.io.*;
class WordsInSentence
{
public void take() throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
String str, words[], stk=;
int i,j,c=0,flag, len;
char ch;
while(true)
{
flag=0;
System.out.println(Enter the sentence:);
str=br.readLine();
len= str.length();
words=new String[len];
for(i=0;i
{
if(Character.isLowerCase(str.charAt(i)))
{
flag=1;
break;
}
}
if (flag==0)
break;
else
System.out.println(Enter the sentence again with all uppercase
letters);
}
i=0;
while(i<len)
{
ch=str.charAt(i);
if(ch== || ch==. || ch==? || ch==!)
{
words[c]=stk;
c++;
i++;
stk=;
}
else
{

stk+=ch;
i++;
}
}
for(i=0;i<c;i++)
{
for(j=0;j<c-1;j++)
{
if((words[j].compareTo(words[j+1]))>0)
{
stk=words[j];
words[j]=words[j+1];
words[j+1]=stk;
}
}
}
System.out.println(Length= +c);
System.out.println(\nRearranged Sentence:\n);
for(i=0;i<c;i++)
System.out.print(words[i]+ );
}
public static void main(String args[]) throws IOException
{
WordsInSentence ob=new WordsInSentence();
ob.take();
}
}

Output:
Enter the sentence: BE GOOD TO OTHERS
Length: 4
Rearranged Sentence: BE GOOD OTHERS TO

Question 19:
Write a program to declare a matrix A [][] of order (MXN) where M is the number of rows and
N is the number of columns such that both M and N must be greater than 2 and less than 20.
Allow the user to input integers into this matrix. Perform the following tasks on the matrix:

Display the input matrix


Find the maximum and minimum value in the matrix and display them along with their position.
Sort the elements of the matrix in ascending order using any standard sorting technique and
rearrange them in the matrix.

Output the rearranged matrix.


Test your program with the sample data and some random data:
Example 1.
INPUT:
M=3
N=4
Entered values: 8,7,9,3,-2,0,4,5,1,3,6,-4
OUTPUT:
Original matrix:
8 7 9 3
-2 0 4 5
1 3 6 -4
Largest Number: 9
Row: 0
Column: 2
Smallest Number: -4
Row=2
Column=3
Rearranged matrix:
-4 -2 0 1
3 3 4 5
6 7 8 9

Solution :
import java.io.*;
class Matrix
{
public void take()throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

int arr[][],m,n;
int g,h,i,j,max,min,maxr,maxc,minr,minc;
while(true)
{
System.out.println(\nEnter the number of rows :);
m=Integer.parseInt(br.readLine());
System.out.println(\nEnter the number of columns:);
n=Integer.parseInt(br.readLine());
if(m<2 || n<2 || m>20 || n>20)
System.out.println(\nEnter the number of rows and columns);
else
break;
}
arr=new int[m][n];
for(i=0;i<m; i++)
{
for(j=0;j<n;j++)
{
System.out.println(\nEnter Value:);
arr[i][j]=Integer.parseInt(br.readLine());
}
}
max=arr[0][0];
min=arr[0][0];
maxr=0;
minr=0;
maxc=0;
minc=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(arr[i][j]>max)
{
max=arr[i][j];
maxr=i;
maxc=j;
}
else if(arr[i][j]< min)
{
minr=i;
minc=j;
min=arr[i][j];
}
}

}
System.out.println(\nOriginal Matrix\n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(arr[i][j]+ );
}
System.out.println();
}
System.out.println(\nLargest Number =+max);
System.out.println(\nRow=+maxr);
System.out.println(\nColumn=+maxc);
System.out.println(\n Smallest Number =+min);
System.out.println(\nRow=+minr);
System.out.println(\nColumn=+minc);
for(g=0;g<m;g++)
{
for(h=0;h<n;h++)
{
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(arr[g][h]< arr[i][j])
{
min=arr[g][h];
arr[g][h]=arr[i][j];
arr[i][j]=min;
}
}
}
}
}
System.out.println(\nRearranged matrix\n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(arr[i][j]+ );
}
System.out.println();
}
}
public static void main(String args[]) throws Exception

{
Matrix ob=new Matrix();
ob.take();
}
}

OUTPUT:
Original matrix:
8 7 9 3
-2 0 4 5
1 3 6 -4
Largest Number: 9
Row: 0
Column: 2
Smallest Number: -4
Row=2
Column=3
Rearranged matrix:
-4 -2 0 1
3 3 4 5
6 7 8 9

Question 20:
Write a Program to sort the array using Exchange Selection Sort .

Solution:

class selection sort


{
public static void main (String args[])throws IOException
{
int i, j ,small, posn,temp;
for(i=0;i<a.length();i++)
{
small =a[i];
posn=i;
for(j=i+1;j<a.length()-1;j++)
{
if(a[j],small)
{
small =a[j];
posn = j;
}
}
temp=a[i];
a[i]=a[posn];
a[posn]=temp;
}
System.out.println(Array in ascending order);
for(i=0;i<a.length;i++)
System.out.println(a[i]);
}

Output:
Array in ascending order
4 5 6 9 13 20 34 48

Anda mungkin juga menyukai