0% found this document useful (0 votes)
17 views30 pages

Java Programs for String and Array Manipulation

java programing class 11th icse project file with questions & answers and written programs

Uploaded by

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

Java Programs for String and Array Manipulation

java programing class 11th icse project file with questions & answers and written programs

Uploaded by

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

Program 1- Write a program to accept a string. Convert the string to uppercase.

Count and
output the number of double letter sequences that exist in the string. Sample Input: “SHE WAS
FEEDING THE LITTLE RABBIT WITH AN APPLE
Answer:
import [Link];
class LetterSeq
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter string: ");
String s = [Link]();
String str = [Link]();
int count = 0;
int len = [Link]();
for (int i = 0; i < len - 1; i++) {
if ([Link](i) == [Link](i + 1))
count++;
}
[Link]("Double Letter Sequence Count = " + count);
}
}

Program 2- Write a program to input 10 numbers into an integer array and interchange the
largest number with the smallest number within the array and print the modified array. Assume
that there is only one largest and smallest number. For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 67 34 15 16 89 15
After interchange it should have the elements arranged as:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 89 7 67 34 15 16 3 15
Answer:
import [Link];

class Q3
{
public static void main(String args[])
{
int a[]=new int[10], i,ln=0,lnp=0,sn=0,snp=0;
Scanner sc=new Scanner([Link]);

[Link]("Enter 10 numbers");
for(i=0; i<10; i++)
{
a[i]=[Link]();
}

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


{
if(i==0)
{
ln=a[i];
sn=a[i];
lnp=i;
snp=i;
}
else if(a[i]>ln)
{
ln=a[i];
lnp=i;
}
else if(a[i]<sn)
{
sn=a[i];
snp=i;
}
}

a[lnp]=sn;
a[snp]=ln;

[Link]("\nArray after interchanging largest with the smallest");


for(i=0; i<10; i++)
{
[Link](a[i]+" ");
}
}
}

Program 3- Write a program to input 10 numbers into an integer array and interchange the
consecutive elements in it. That is, interchange a[0] with a[1], a[2] with a[3], a[4] with a[5] …
For example, if array contains
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
9 12 3 7 89 34 15 16 67 25
After interchange it should have the elements arranged as:
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
12 9 7 3 34 89 16 15 25 67

Answer:
import [Link];

public class Q8
{
public static void main(String args[])
{
int a[]=new int[10], i,t;
Scanner sc=new Scanner([Link]);

[Link]("Enter 10 numbers");
for(i=0; i<10; i++)
{
a[i]=[Link]();
}
for(i=0; i<10; i=i+2)
{
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
[Link]("\nModified array after interchanging the consecutive numbers");
for(i=0; i<10; i++)
{
[Link](a[i]+" ");
}
}
}
Program 4- Write a program to accept the names of 10 cities in a single dimension string array
and their STD (Subscribers Trunk Dialing) codes in another single dimension integer array.
Search for a 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’.
Answer:
import [Link];

public class StdCodes


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

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


[Link]("Enter City Name: ");
cities[i] = [Link]();
[Link]("Enter its STD Code: ");
stdCodes[i] = [Link]();
}

[Link]("Enter name of city to search: ");


String city = [Link]();

int idx;
for (idx = 0; idx < SIZE; idx++) {
if ([Link](cities[idx]) == 0) {
break;
}
}

if (idx < SIZE) {


[Link]("Search Successful");
[Link]("City: " + cities[idx]);
[Link]("STD Code: " + stdCodes[idx]);
}
else {
[Link]("Search Unsuccessful");
}
}
}

Program 5-Write a program to store 6 element in an array P, and 4 elements in an array Q and
produce a third array R, containing all elements of array P and Q. Display the resultant array.
Answer:
import [Link];

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

Scanner in = new Scanner([Link]);

int P[] = new int[6];


int Q[] = new int[4];
int R[] = new int[10];
int i = 0;

[Link]("Enter 6 elements of array P:");


for (i = 0; i < [Link]; i++) {
P[i] = [Link]();
}

[Link]("Enter 4 elements of array Q:");


for (i = 0; i < [Link]; i++) {
Q[i] = [Link]();
}

i = 0;
while(i < [Link]) {
R[i] = P[i];
i++;
}

int j = 0;
while(j < [Link]) {
R[i++] = Q[j++];
}

[Link]("Elements of Array R:");


for (i = 0; i < [Link]; i++) {
[Link](R[i] + " ");
}
}
}
Program 6. Write a program to input numbers into a 5×5 integer matrix and print the largest
and smallest number from it.
Answer:
import [Link].*;
class P7
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int a[][] = new int[5][5];
int i,j,max=0,min=0;
[Link]("enter 25 numbers:");
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
a[i][j]=[Link]();
}
}

for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==0 && j==0)
max=min=a[i][j];
if(a[i][j]>max)
max=a[i][j];
if(a[i][j]<min)
min=a[i][j];
}

}
[Link]("Largest number: "+max);
[Link]("Smallest number: "+min);
}
}

Program 7. Write a program to input numbers into a 5×5 integer matrix and print the largest
and the smallest number among both the diagonals.
Answer:
import [Link].*;
class diagonaldisplay
{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
int n[][] = new int[5][5];
int i,j,s;
[Link]("Enter numbers in array:");
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
n[i][j]=[Link]();
}
}
[Link]("Elements of array:");
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
[Link](n[i][j]+"\t");
}
[Link]();
}
int ld1 = n[0][0], sd1 = n[0][0];
int ld2 = n[0][0], sd2 = n[0][4];
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==j)
{
if(n[i][j]>ld1)
ld1=n[i][j];
if(n[i][j]<sd1)
sd1=n[i][j];
}
if(i+j==4)
{
if(n[i][j]>ld2)
ld2=n[i][j];
if(n[i][j]<sd2)
sd2=n[i][j];
}
}
}
[Link]("Largest number of diagonal 1 : "+ld1);
[Link]("Smallest number of diagonal 1 : "+sd1);
[Link]("Largest number of diagonal 2 : "+ld2);
[Link]("Smallest number of diagonal 2 : "+sd2);
}
}
Program 8- Write a program to input and sort the weight of ten people. Sort and display them in
descending order using the selection sort technique.
Answer:
import [Link];

class SelectionSort
{
public static void main(String args[]) {
Scanner in = new Scanner([Link]);
double weightArr[] = new double[10];
[Link]("Enter weights of 10 people: ");
for (int i = 0; i < 10; i++) {
weightArr[i] = [Link]();
}

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


int idx = i;
for (int j = i + 1; j < 10; j++) {
if (weightArr[j] > weightArr[idx])
idx = j;
}

double t = weightArr[i];
weightArr[i] = weightArr[idx];
weightArr[idx] = t;
}

[Link]("Sorted Weights Array:");


for (int i = 0; i < 10; i++) {
[Link](weightArr[i] + " ");
}
}
}

Program 9- Write a program to input 10 numbers into a float type array and arrange the
numbers in ascending order using Bubble Sorting technique.
Answer:
import [Link];

class BubbleSortDsc
{
public static void main(String args[]) {
Scanner in = new Scanner([Link]);
int n = 10;
int arr[] = new int[n];

[Link]("Enter the elements of the array:");


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

//Bubble Sort
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;
}
}
}

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

Q10. A class Rearrange has been defined to modify a word by bringing all the vowels in the
word at the beginning followed by the consonants.
Example: ORIGINAL becomes OIIARGNL
Some of the members of the class are given below:
Class name: Rearrange
Data Member/instance variable:
wrd: to store a word
newwrd: to store the rearranged word
Member functions/methods:
Rearrange(): default constructor
void readword(): to accept the word in UPPER case
void freq_vow_con(): finds the frequency of vowels and consonants in the word and displays
them with an
appropriate message
void arrange(): rearranges the word by bringing the vowels at the beginning followed by
consonants
void display(): displays the original word along with the rearranged word
Specify the class Rearrange, giving the details of the constructor(),void readword(),void
freq_vow_con(), void arrange() and void display(). Define the main() function to create an object
and call the functions accordingly to enable the task.
ANSWER:-

import [Link].*;
import [Link].*;
class Rearrange
{
private String wrd;
private String newwrd;
public Rearrange()
{
wrd =new String();
newwrd = new String();
}
public void readword() throws IOException
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the words");
wrd=[Link]();
}
public void freq_vow_con()
{
wrd=[Link]();
int v=0;
int c=0;
for(int i=0;i<[Link]();i++)
{
char ch=[Link](i);
if ( [Link](ch))
{
switch (ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
v++;
break;
default:
c++;
}
}
}
[Link]("Frequency of vowels"+v);
[Link]("Frequency of consonants"+c);
}
public void arrange()
{
String v=new String();
String c=new String();
wrd = [Link]();
for(int i=0;i<[Link]();i++)
{
char ch=[Link](i);
if ( [Link](ch))
{
switch (ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
v+=ch;
break;
default:
c+=ch;
}
}
}
newwrd=v+c;
}
public void display()
{
[Link]("Original word"+wrd);
[Link]("Rearranged word:"+newwrd);
}
public static void main(String []args) throws IOException
{
Rearrange obj=new Rearrange();
[Link]();
obj.freq_vow_con();
[Link]();
[Link]();
}
}

Q11. Design a class ArmNum to check if a given number is an Armstrong number or not. (A
number is said to be Armstrong if sum of its digits raised to the power of length of the number
is equal to the number].
Example: 371 = 33+ 73 + 13
1634 = 14 + 64 + 34 + 44
54748= 55 + 45 + 75 + 45 + 85
Thus, 371, 1634 and 54748 are all examples of Armstrong numbers.
Some of the members of the class are given below:
Class name: ArmNum
Data members/instance variables:
n: to store the number
I: to store the length of the number
Methods/Member functions:
ArmNum (intnn): parameterized constructor to initialize the data member n = nn
intsum_pow(inti): returns the sum of each digit raised to the power of the length of the
number using recursive
technique eg., 34 will return 32 + 42 (as the length of the number is 2)
void isArmstrong(): checks whether the given number is an Armstrong number by invoking the
function sum_pow()
and displays the result with an appropriate message.
Specify the class ArmNum giving details of the constructor, intsum_pow(int) and void
isArmstrong( ).
Define a main() function to create an object and call the functions accordingly to enable the
task.
ANSWER:-

import [Link].*;
import [Link].*;
class ArmNum
{
static int n;
static int l;
public ArmNum(int num)
{
n=num;
l=0;
for(int i=n;i!=0;i/=10)
l++;
}
public int sumPow(int i)
{
if(i<10)
return (int)[Link](i,1);
return (int)[Link](i%10,1)+ sumPow(i/10);
}
public void isArmstrong()
{
if(n==sumPow(n))
[Link](n+"is an Armstrong Number");
else
[Link](n+"is not an Armstrong Number");
}
public static void main(String []args)throws IOException
{
Scanner sc=new Scanner([Link]);
[Link]("N=");
int num=[Link]();
ArmNum obj=new ArmNum(num);
[Link]();

}
}

Q12. 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]
Example: 6 = 1+2+3 (where 1,2 and 3 are factors of 6, excluding itself)
Some of the members of the class are given below:
Class name: Perfect
Data members/instance variables:
num: to store the number
Methods/Member functions:
Perfect (intnn): parameterized constructor to initialize the data member num=nn
intsum_of_factors(inti): returns the sum of the factors of the number(num), excluding itself,
using a recursive
technique
Void check(): checks whether the given number is perfect by invoking the function
sum_of_factors() and displays
the result with an appropriate message.
Specify the class Perfect giving details of the constructor(), intsum_of_factors(int) and void
check().
Define a main() function to create an object and call the functions accordingly to enable
ANSWER:-

import [Link].*;
import [Link].*;
class Perfect
{
private int num;
private int f;
public Perfect(int num)
{
[Link]=num;
f=1;
}
public int sumOfFactors(int i)
{
if(i==f)
{
return 0;
}
else if(i%f==0)
{
return f++ + sumOfFactors(i);
}
else
{
f++;
return sumOfFactors(i);
}
}
public void check()
{
if (num==sumOfFactors(num))
{
[Link](num+"is a perfect number");
}
else
{
[Link](num+"Not a perfect number");
}
}
public static void main (String []args) throws IOException
{
Scanner sc=new Scanner ([Link]);
[Link]("Enter the number:");
int n=[Link]();
Perfect obj= new Perfect(n);
[Link]();

}
}

Q13. A class Palin has been defined to check whether a positive number is a Palindrome number
or not.
The number N is palindrome if the original number and its reverse are the same.
Some of the members of the class are given below:
Class name: Palin
Data members/instance variables:
num: integer to store the number
revnum: integer to store the reverse of the number
Methods/Member functions:
Palin(): constructor to initialize data members with legal initial values
void accept(): to accept the number
int reverse(int y): reverses the parameterized argument y' and stores it in revenue using a
recursive technique
void check(): checks whether the number is a Palindrome by invoking the function reverse() and
display the result
with an appropriate message.
Specify the class Palin giving the details of the constructor(), void accept(), int reverse(int) and
void check(). Define
the main() function to create an object and call the functions accordingly to enable the task.
ANSWER:-

import [Link].*;
import [Link].*;
class Palin
{
int num;
int revnum;
Palin()
{
num=0;
revnum=0;
}
void accept() throws IOException
{
Scanner sc=new Scanner ([Link]);
[Link]("Enter the number:");
String a=[Link]();
num=[Link](a);
}
int reverse(int y)
{
int len=(y+"").length();
if(len==1)
{
return y;
}
else
{
return (((y%10)*(int)[Link](10,len-1))+reverse(y/10));
}
}
void check()
{
revnum=reverse(num);
if(num==revnum)
{
[Link]("/n Number is palindrome");
}
else
{
[Link]("/n Number is not palindrome");
}
}
public static void main (String args[]) throws IOException
{
Palin p=new Palin();
[Link]();
[Link]();
}
}

Q14. A class SwapSort has been defined to perform string related operations on a word input.
Some of the members of the class are as follows:
Class name: SwapSort
Data members/instance variables:
wrd: to store a word
len: integer to store the length of the word
swapwrd: to store the swapped word
sortwrd: to store the sorted word
Member functions/methods:
SwapSort():default constructor to initialize data members with legal initial values
void readword(): to accept a word in UPPER CASE
void swapchar(): to interchange/swap the first and last characters of the word in 'wrd' and
stores the new word in '\ Swapwrd'
void sortword(): sorts the characters of the original word in alphabetical order and stores it in
'sortwrd'
void display():displays the original word, swapped word and the sorted word
Specify the class SwapSort, giving the details of the constructor(). void readword().,
void swapchar(), voidsortword()
and void display(). Define the main() function to create an object and call the functions
accordingly to enable the task.
ANSWER:-

import [Link].*;
import [Link].*;
class SwapSort
{
String wrd;
int len;
String swapwrd;
String sortwrd;
SwapSort()
{
wrd="";
len=0;
swapwrd="";
sortwrd="";
}
void readword() throws IOException
{
Scanner sc=new Scanner ([Link]);
[Link]("Enter word");
wrd=[Link]();
}
void swapwrd()
{
String w=wrd;
swapwrd=[Link]([Link]()-1)+[Link](1,[Link]()-1)+[Link](0);
}
void sortwrd()
{
String w=wrd;
char[] charArray=[Link]();
int length=[Link];
for(int i=0;i<length;i++)
{
for (int j=0;j<length;j++)
{
if(charArray[j]<charArray[i])
{
char temp=charArray[i];
charArray[i]=charArray[j];
charArray[j]=temp;
}
}
}
for(char c:charArray)
{
sortwrd=sortwrd+c;
}
}
void display()
{
[Link]("Original word"+wrd);
[Link]("Swapped word"+swapwrd);
[Link]("Sorted Array"+sortwrd);
}
public static void main(String []args) throws IOException
{
SwapSort obj=new SwapSort();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Q15. A disarium number is a number in which the sum of the digits to the power of their
respective position is equal to the
number itself. Example: 135 = 11 + 32 + 53
Hence, 135 is a disarium number.
Design a class Disarium to check if a given number is a disarium number or not.
Some of the members of the class are given below:
Class name: Disarium
Data members/instance variables:
intnum: stores the number
int size: stores the size of the number
Methods/Member functions: Disarium (intnn): parameterized constructor to initialize the data
members n= nn and size = 0
void countDigit(): counts the total number of digits and assigns it to size
intsumofDigits (intn, int p): returns the sum of the digits of the number(n) to the power of their
respective
positiors (p) using recursive technique
Void check(): checks whether the number is a disarium number and displays the result with an
appropriate message
Specify the class Disarium giving the details of the constructor),void countDigit(),
intsumofdigits(int,int) and
void check().
Define the main() function to create an object and call the functions accordingly to enable the
task.
ANSWER:-

import [Link].*;
import [Link].*;
class Disarium
{
public static void main (String []args)
{
Scanner sc=new Scanner([Link]);
[Link]("Enter a number");
int n=[Link]();
int copy=n,d=0,sum=0;
String s=[Link](n);
int len=[Link]();
while(copy>0)
{
d=copy%10;
sum=sum+(int)[Link](d,len);
len--;
copy=copy/10;
}
if (sum==n)
[Link]("Is a disarium number");
else
[Link]("Is not a disarium number");

}
}

Common questions

Powered by AI

The program calculates the largest and smallest elements of the diagonals in a 5x5 matrix. For the main diagonal, elements where the row index equals the column index are processed to find the largest and smallest values. For the secondary diagonal, where the sum of row and column indices equals four, similar calculations are performed. Two separate loops with checks ensure each relevant element is considered, allowing the extraction of maximum and minimum values from both diagonals independently .

Rearranging vowels to the front can emphasize vowel distribution and improve phonetic analysis by segregating vowel structures from consonant sequences. The program implementation involves looping over each character, identifying vowels, and concatenating them to form a new string. Subsequently, consonants follow this new vowel substring, constructing an output that organizes phonetic components distinctly, aiding further analysis for linguistic or readability applications .

To count the number of double letter sequences in a string, the program first converts the string to uppercase. Then it iterates through the string, comparing each character with the next. If a pair of consecutive characters matches, the count of double letter sequences increases. This is implemented utilizing a loop from the initial to the penultimate character of the string. The result is output after traversing the string .

Selection sort arranges values by repeatedly finding the largest remaining unsorted element and placing it next in the sequence of descending order. The program identifies the index of the largest element within the unsorted portion of the array, then swaps it with the first unsorted element. This results in the rest of the array being correctly sorted after each pass. The process continues until the entire array is sorted in descending order, ensuring accurate reordering through systematic element comparison and exchange .

The program identifies the largest and smallest numbers in a 5x5 matrix by initializing maximum and minimum with the first element of the matrix. It then loops through each element, updating the maximum if a larger value is found and the minimum if a smaller value is encountered. This double loop ensures that every element is compared, and the result gives the desired maximum and minimum values .

The program merges two arrays, P and Q, of sizes 6 and 4 respectively, into a third array R, which has size 10. First, it reads elements individually into arrays P and Q. Then, it copies contents from P into the beginning portion of array R, followed by the elements of Q, thereby filling the entire array R. This is achieved using sequential copying where indices are carefully managed to ensure no overlap or data loss .

Consecutive elements in an integer array are interchanged by iterating through the array with a step of two. During each iteration, two adjacent elements (a[i] and a[i+1]) are swapped. This process requires a temporary variable to hold one of the values during the swap to avoid data loss. The array is read from user input, and the swapping technique updates the array in-place .

To find a city and its STD code, the program stores city names and their corresponding STD codes in parallel arrays. It reads the city name to be searched from the user. The search is conducted by iterating through the cities array and comparing each element with the input, ignoring case sensitivity. If a match is found, the search is successful, and the results, i.e., the city name and its STD code, are displayed. If no match is found, a message indicating the search was unsuccessful is shown .

The process involves scanning the array to identify the largest and smallest numbers and their respective positions. This is performed using a loop that compares and updates the current largest and smallest values and their positions. Once identified, the largest and smallest values are swapped by using their positions. The implementation involves reading the inputs into an array, determining the maximum and minimum values with a single traversal, and then exchanging these two values .

Bubble sort compares adjacent elements and swaps them if they are in the wrong order to ensure successive passes push the largest unsorted element to its final position. This method iteratively 'bubbles up' elements by examining each pair and continuing such until no more swaps are needed. The algorithm effectively sorts via repeated pairwise comparisons and interchanges until the array is fully sorted through proper sequential passes .

You might also like