Wednesday, February 23, 2011

2011 Collection of Programs


This Blog
Linked From Here
The Web
This Blog
 
 
 
 
Linked From Here
 
 
 

The Web
 
 
 

Tuesday, February 22, 2011

ISC 2005 Computer practical solved paper

Program Number 1



Write a program which takes a string (maximum 80 characters terminated by a full stop. The words in this string are assumed to be separated by one or more blanks. Arrange the words of the input string in descending order of their lenghts. Same length words should be sorted alphabetically. Each word must start with an uppercase letter and the sentence should be terminated by a full stop.

Test your program for the following data and some random data.

SAMPLE DATA:
INPUT:
"This is human resource department."

OUTPUT:
Department Resource Human This Is.

INPUT:
"To handle yourself use your head and to handle others use your heart."

OUTPUT:
Yourself Handle Handle Others Heart Head Your Your And Use Use To To.


Codes of the program



import java.io.*;
import java.util.*;
class Program1
{
String str,str2;
StringTokenizer stk;
String sr[];
int i,j,x;
int flag;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeString()throws Exception
{
char ch;
while(true)
{
System.out.println("\nEnter the sentence:");
str=br.readLine().trim();
if(str.length()>80)
{
System.out.println("\nString exceeds 80 characters.");
continue;
}
if(str.charAt(str.length()-1)!='.')
{

System.out.println("\nString must terminate with full stop.");
continue;
}
else
break;
}
str=str.substring(0,str.length()-1);
str2="";
x=str.length();
flag=0;
for(i=0;i< x;i++)
{
ch=str.charAt(i);
if(i==0)
str2=str2+(char)(ch-32);
else if(ch==' ')
{
flag=1;
str2=str2+ch;
}
else if(flag==1)
{
flag=0;
str2=str2+(char)(ch-32);
}
else
str2=str2+ch;
}
str=str2;
stk=new StringTokenizer(str);
x=stk.countTokens();
sr=new String[x];
x=0;
while(stk.hasMoreTokens())
{
str2=stk.nextToken().trim();
sr[x++]=str2;
}
display();
}
private void display()
{
for(i=0;i< x-1;i++)
{
for(j=i+1;j< x;j++)
{
if(sr[i].length()< sr[j].length())
{
str2=sr[i];
sr[i]=sr[j];
sr[j]=str2;
}
}
}
for(i=0;i< x;i++)
{
if(i!=x-1)
System.out.print(sr[i]+" ");
else
System.out.print(sr[i]);
}
System.out.print(".");
}
public static void main(String args[])throws Exception
{
Program1 ob=new Program1();
ob.takeString();
}
}


Program on wondrous square



A wondrous square is an n by n grid which fulfils the following conditions:
(i) It contains integers from 1 to n2, where each integer appears only once.
(ii) The sum of integers in any row or column must add up to 0.5 * n * (n2 + 1).

For example the following grid is a wondrous square where the sum of each row or column is 65 when n = 5 :

17 24 2 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

Write a program to read n (2 <= n <= 10) and the values stored in these n by n cells and output if the grid represents a wondrous square or not. Also output all the prime numbers in the grid along with their row index and column index as shown in the output. A natural number is said to be prime if it has exactly two divisors. E.g. 2, 3, 5, 7, 11,.......
The first element of the given grid i.e. 17 is stored at row index 0 and column index 0 and the next element in the row i.e. 24 is stored at row index 0 and column index 1.

Test your program for the following data and some random data.

SAMPLE DATA:
INPUT : N = 4


16 15 1 2
6 4 10 14
9 8 12 5
3 7 11 13

OUTPUT:
YES IT REPRESENTS A WONDROUS SQUARE.

PRIME ROW INDEX COLUMN INDEX
2 0 3
3 3 0
5 2 3
7 3 1
11 3 2
13 3 3

Codes of this Program



import java.io.*;
class Program2
{
int arr[][],arr1[];;
int n,i,j,x=0,r,c;
int flag;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void take()throws Exception
{
System.out.println("\nEnter the size of array(row and column same):");
n=Integer.parseInt(br.readLine().trim());
arr=new int[n][n];
arr1=new int[2*n];
for(i=0;i< n;i++)
{
for(j=0;j< n;j++)
{
System.out.println("\nEnter the value:");
arr[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("\nThe matrix is\n");
for(i=0;i< n;i++)
{
r=0;
c=0;
for(j=0;j< n;j++)
{
System.out.print(arr[i][j]+" ");
r=r+arr[i][j];
c=c+arr[j][i];
}
System.out.println();
arr1[x]=r;
arr1[x+n-1]=c;
x++;
}
for(i=0;i< x;i++)
{
if(arr1[i]!= 0.5 * n * (n*n + 1))
break;
}
if(i==x)
System.out.println("YES IT REPRESENTS A WONDROUS SQUARE.");
else
System.out.println("IT IS NOT A WONDROUS SQUARE.");
System.out.println("PRIME ROW COLUMN");
for(i=0;i< n;i++)
{
for(j=0;j< n;j++)
{
if(prime(arr[i][j]))
System.out.println(arr[i][j]+ " "+i+ " "+j);
}
}
}
private boolean prime(int no)
{
int index;
for(index=2;index< no;index++)
{
if(no%index==0)
break;
}
if(index==no)
return true;
else
return false;
}
public static void main(String args[])throws Exception
{
Program2 ob=new Program2();
ob.take();
}
}


Program on all possible anagrams of a word



We would like to generate all possible anagrams of a word. For example if the given word is 'TOP', there will be 6 possible anagrams:
TOP
TPO
OPT
OTP
PTO
POT

An anagram must be printed only once. You may output the anagrams in any order. Also output the total number of anagrams. You assume that the number of letter, n, in the word will be 7 at most, i.e. n<= 7
Test your program for the given data and some random data.

SAMPLE DATA:
INPUT:
TO

OUTPUT:
TO
OT
Total number of anagrams = 2

INPUT :
LEAN
OUTPUT:
LEAN
LENA
LAEN
LANE
LNEA
LNAE
EALN
EANL
ELAN
ELNA
ENLA
ENAL
ALNE
ALEN
ANLE
ANEL
AENL
NLEA
NLAE
NELA
NEAL
NALE
NAEL
Total number of anagrams = 24


Codes of this program on Anagrams.



import java.io.*;
public class Anagrams
{
String str;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int counter=0;
public void take()throws Exception
{
System.out.println("\nEnter the word:");
str=br.readLine();
show("", str);
System.out.println(“Total number of anagrams =”+counter);
}
public void show(String s, String str)
{
if(str.length() <= 1)
{
counter++;
System.out.println(s+str);
}
else
{
for(int i = 0; i < str.length(); i++)
{
String str1 = str.substring(i, i + 1);
String str2 = str.substring(0, i);
String str3 = str.substring(i + 1);
show(s + str1, str2 + str3);
}
}
}
public static void main(String args[])throws Exception
{
Anagrams ob=new Anagrams();
ob.take();
}
}



Technical analysis of all these above programs will be posted very soon. Due to ISC 2011 practical examination, so many comments are posted in this site by students and I am trying my best to solve those questions before February 25, 2011. So after February 25 I will be able to post the logics behind these above programs.



Related Posts:

ISC Computer Practical Programs - 2006
ISC 2007 Computer Practical Paper
ISC Computer Practical Paper - 2008
ISC 2010 Computer Practical

Program on Different Combination of number in BlueJ

import java.io.*;
class NumberCombination
{
int n,i,sum,j,flag;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void take()throws Exception
{
System.out.println("\nEnter the number:");
n=Integer.parseInt(br.readLine());
for(i=n;i>0;i--)
{
sum=0;
flag=0;
for(j=i;j>0;j--)
{
sum=sum+j;
if(sum>n)
{
flag=1;
break;
}
System.out.print(j+" ");
}
if(flag==0)
{
for(;sum< n;sum++)
System.out.print(1+" ");
}
else if( i==0 && ((j+n)-sum)==0)
System.out.print((j+n)-sum);
else if( i!=0 && ((j+n)-sum)!=0)
System.out.print((j+n)-sum);

System.out.println();
}
}
public static void main(String args[])throws Exception
{
NumberCombination ob=new NumberCombination();
ob.take();
}
}



Related posts:

Program on possible consecutive numbers
Program on Perfect Number
Program on Automorphic Number
Program on Saddle Number
Program on Armstrong Number
Program on Smith Number

Monday, February 21, 2011

BlueJ Program on displaying date in specific format

In this program we will take a specific date from user in dd.mm.yyyy format and number of days after that date. Out program will display the date after that specified number of days in dd.mm.yyyy format.

Sample input and output of the program



Enter the date in dd.mm.yyyy format: 21 .2.2011
Enter the number of days after: 10
Output: 3.3.2011
Enter the date in dd.mm.yyyy format: 22.2.2011
Enter the number of days after: 43
Output: 6.4.2011

Codes of the program



import java.io.*;
class DateDisplay
{
int day[]={31,28,31,30,31,30,31,31,30,31,30,31};
String str1,str2;
boolean bool;
int i,j;
int no1,no2,month1,year1;
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
public void take()throws Exception
{
while(true)
{
System.out.println("\nEnter the date in dd.mm.yyyy format:");
str1=br.readLine().trim();
bool=validateFormat(str1);
if(bool==false)
continue;
bool=validateDate(str1);
if(bool==false)
continue;
else
break;
}
i=str1.indexOf(".");
no1=Integer.parseInt(str1.substring(0,i));
str1=str1.substring(i+1);
i=str1.indexOf(".");
month1=Integer.parseInt(str1.substring(0,i));
year1=Integer.parseInt(str1.substring(i+1));
System.out.println("\nEnter the number of days after:");
no2=Integer.parseInt(br.readLine().trim());
i=month1-1;
for(j=0;j< i;j++)
{
no1=no1+day[j];
if(leap(year1)==true && i==1)
no1++;

}

no2=no2+no1;
no1=0;
i=0;
while(true)
{
no1=no1+day[i];
if(leap(year1)==true && i==1)
no1++;
if(no1>=no2)
{
no1=no1-day[i];
break;
}
i++;
if(i==12)
{
i=0;
year1++;
}
}
no1=no2-no1;
System.out.println("Output:"+no1+":"+(i+1)+":"+year1);
}
private boolean validateFormat(String s)
{
int counter=0;
int index;
while(true)
{
index=s.indexOf(".");
if(index<=0)
break;
else
{
counter++;
s=s.substring(index+1);
}
}
if (counter==2 && s.length()==4)
return true;
else
return false;
}
private boolean validateDate(String s)
{
int counter=0;
int li=0,d,m,y;
int index;
index=s.indexOf(".");
d=Integer.parseInt(s.substring(0,index));
s=s.substring(index+1);
index=s.indexOf(".");
m=Integer.parseInt(s.substring(0,index));
s=s.substring(index+1);
y=Integer.parseInt(s);
if(leap(y)==true)
li=1;
if(m==2 && d<=day[m-1]+1)
counter=1;
else if(m!=2 && d<=day[m-1])
counter=1;
if(m>0 && m<=12)
counter=2;
if(counter==2)
return true;
else
return false;
}
private boolean leap(int x)
{
if(x%100==0 && x%400==0)
return true;
else if(x%100!=0 && x%4==0)
return true;
else
return false;
}
public static void main(String args[])throws Exception
{
DateDisplay ob=new DateDisplay();
ob.take();
}
}


Technical analysis of the program



Number of days of each month is taken in an array in this program which will help us to count the number days. Specific date is taken from user and the number of days after that date is also taken. Function 'private boolean validateFormat(String s)' is defined in this class to check whether the date entered is in proper format, otherwise the date is again taken from user. After confirming the proper format of entry next job is to check the validity of date and month number. This job is performed using another function 'private boolean validateDate (String s)' defined in this program. When both the checking points in this programare satisfied, the date, month number and year entered are separated and the total number of days from start of the year up to that date is counter. We have taken the number of days after that date from user. Both are added and again using infinite loop days are counter from the start of the year. In this process year is also incremented when required. As soon as the counted number of days from the start of the year crosses the total number of days, the total days of the specific month is reduced from the counted days and the loop is terminated using break statement.

At the end counted number of days is deducted from total number of days and which is the date and our program displays the date. While counting number of days a function ‘private boolean leap(int x)’ is used to check for leap year as we have to count 29 days for February month in a leap year.

Sunday, February 20, 2011

BlueJ Program on sorting boundary elements of a 2 d array

This program is on sorting the boundary elements of a 2 d array. The number of rows and number of columns of the array may be same or different.

How to proceed on this boundary elements sorting program



Firstly take all the boundary elements of the 2 d array in an one dimensional array. Next step is to sort the elements of the one dimensional array and then the sorted elements are placed on the boundary locations of the 2 d array.

Codes of the program



import java.io.*;
class Spiral
{
int x;
int t,r,c,i,j,n,m;
int a[][],b[];
void show()throws IOException
{
t=1;

c=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number of rows:");
n=Integer.parseInt(br.readLine());
System.out.println("enter the number of columns:");
m=Integer.parseInt(br.readLine());

a=new int[n][m];
b=new int[2*(m+n)];
for(i=0;i< n;i++)
{
for(j=0;j< m;j++)
{
System.out.println("enter value:");
a[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("\nEntered values are\n");
for(i=0;i< n;i++)
{
for(j=0;j< m;j++)
{
System.out.print(" "+a[i][j]);
}
System.out.println();
}
System.out.println("\n\n");
for(i=0;i< m;i++)
{
b[c++]=a[0][i];
}
for(i=1;i< =n-1;i++)
{
b[c++]=a[i][m-1];
}
for(i=m-2;i>=0;i--)
{
b[c++]=a[n-1][i];
}
for(i=n-2;i>0;i--)
{
b[c++]=a[i][0];
}

bsort();
r=0;
c=-1;
t=0;
for(i=1;i<=m;i++)
{
a[r][++c]=b[t++];
}
for(i=1;i<=n-1;i++)
{
a[++r][c]=b[t++];
}
for(i=1;i<=m-1;i++)
{
a[r][--c]=b[t++];
}
for(i=1;i<=n-2;i++)
{
a[--r][c]=b[t++];
}
System.out.println("\nAfter sorting the boundary values\n");
for(i=0;i< n;i++)
{
for(j=0;j< m;j++)
{
System.out.print(" "+a[i][j]);
}
System.out.println();
}

}
private void bsort()
{
int flag;
for(i=0;i< c;i++)
{
flag=0;
for(j=0;j< c-i-1;j++)
{
if(b[j]>b[j+1])
{
flag=1;
t=b[j];
b[j]=b[j+1];
b[j+1]=t;
}
}
if(flag==0)
break;
}
}
public static void main(String args[])throws Exception
{
Spiral ob=new Spiral();
ob.show();
}
}

Saturday, February 19, 2011

BlueJ Program on Spiral Matrix

Spiral matrix means where the values are stored in ascending order in a spiral manner like

01 02 03 04
10 11 12 05
09 08 07 06

For a spiral matrix program, the matrix should be square means both rows and columns should be same.

Codes of the spiral matrix program



import java.io.*;
class Spiral
{
int x;
int t,r,c,i,j,n;
int a[][];
boolean checkDigit(int r)
{
if(r<10)
return true;
else
return false;
}
void show()throws IOException
{
t=1;
r=0;
c=-1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the size of array:");
n=Integer.parseInt(br.readLine());
x=n;
a=new int[n][n];
while(n>0)
{
for(i=1;i< =n;i++)
{
a[r][++c]=t++;
}
for(i=1;i< =n-1;i++)
{
a[++r][c]=t++;
}
for(i=1;i< =n-1;i++)
{
a[r][--c]=t++;
}
for(i=1;i< =n-2;i++)
{
a[--r][c]=t++;
}
n=n-2;
}
System.out.println("\nMatrics\n");
for(i=0;i< x;i++)
{
for(j=0;j< x;j++)
{
if(checkDigit(a[i][j]))
System.out.print("0"+a[i][j]+" ");
else
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static void main(String args[])throws Exception
{
Spiral ob=new Spiral();
ob.show();
}
}


Analysis of this spiral matrix program



In this program of spiral matrix, four loops within a loop body are required. Two loops are engaged to fill values in the rows of the matrix and the other two for filling the values in columns. The first inner loop fills the values in row from left to right. The second inner loop fills values in the matrix from top to bottom. The third inner loop fills values from right to left and the fourth inner loop fills values from bottom to top. The variable value is incremented by 1 every time it is set in the matrix. As ‘n’ holds the number of rows and columns in the matrix, after each iteration of the outer loop (here the while loop) value of ‘n’ is decremented by 2.

During display of the spiral matrix values, the values are checked whether it is single digit or not using the function ‘boolean checkDigit()’ which is defined in the class. In case of single digit number, 0 is displayed before the value.

Merge Sort on array in BlueJ Programming

Merge sort may be of different types. Firstly we will do merge sort on two different arrays of same or different sizes. Actually merge sort is a technique of sorting elements where any kind of sorting technique can be used.

Suppose there are two arrays int a[] and int b[] of size 10 each. The technique that combines these two arrays is called merging. The arrays are to be sorted first and then they may be merged. It is also possible to merge them first and after that the sorting will be done.

Algorithm for sorting the two arrays first and then merging them



A and B are two arrays with n and m number of elements. Both the arrays are sorted first. C is the final array where the final values will be stored and in sorted order. I, J and K are three integer type variables with initial value 0 .They will be used as array index or the three arrays.

Repeat the following steps while ((I< n) and (J< m))
If A[I]< =B[J]
C[K]=A[I]
I=I+1
K=K+1
Else
C[K]=B[J]
J=J+1
K=K+1

End of If
[End of loop]
If I< n [means first array has more values ]
Repeat the following steps for I=I,I+1…n-1
C[K]=A[I]
I=I+1
K=K+1
[End of loop]
Else If (J< m)
Repeat the following steps for J=J,J+1…m-1
C[K]=B[J]
J=J+1
K=K+1
[End of loop]
End


Program on merge sort using two arrays



import java.io.*;
class Merge
{
int a[],b[],c[],i,j,k;
int temp,flag;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n,m;
public void take()throws Exception
{
System.out.println("\nEnter size of the first array:");
n=Integer.parseInt(br.readLine());
System.out.println("\nEnter size of the second array:");
m=Integer.parseInt(br.readLine());
a=new int[n];
b=new int[m];
c=new int[n+m];
System.out.println("\nEnter values for first array:\n");
for(i=0;i< n;i++)
{
System.out.println("\nEnter value:");
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("\nEnter values for second array:\n");
for(i=0;i< m;i++)
{
System.out.println("\nEnter value:");
b[i]=Integer.parseInt(br.readLine());
}
bsort();
msort();
display();
}

private void bsort()
{
int flag;
for(i = 0 ; i< n - 1; i++)
{
flag=0;
for(j = 0 ; j< n - i - 1 ; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp ;
flag = 1;
}
}
if(flag==0)
break ;
}

for(i = 0 ; i< m - 1; i++)
{
flag=0;
for(j = 0 ; j< m - i - 1 ; j++)
{
if(b[j] > b[j+1])
{
temp = b[j];
b[j] = b[j+1];
b[j+1] = temp ;
flag = 1;
}
}
if(flag==0)
break ;
}
}
private void msort( )
{
int k = 0;
i = 0;
j = 0;
while((i < n) &&(j< m))
{
if(a[i] < =b[j])
{
c[k++] = a[i];
i++;
}
else
{
c[k++] = b[j];
j++;
}
}
if(i < n )
{
for( ; i < n ; i++)
{
c[k++] = a[i];
}
}
else if(j < m)
{
for(; j< m; j++)
{
c[k++] = b[j];
}
}
}
private void display()
{
System.out.println("\nFirst array in sorted order\n");
for(i=0 ; i < n ; i++)
System.out.print(" " + a[i]);

System.out.println("\nSecond array in sorted order\n");
for(i=0 ; i < m ; i++)
System.out.print(" " + b[i]);
System.out.println("\nMerged sorted values\n");
for(i=0 ; i < n+m ; i++)
System.out.print(" " + c[i]);
}
public static void main(String args[])throws Exception
{
Merge ob=new Merge();
ob.take();
}
}

Analysis of the merge sort program in BlueJ



Four functions are defined in this merge sort program. ‘public void take()’ function takes the number of elements to be stored in two arrays and the three arrays are created. Values are stored in the two arrays and both the arrays are sorted in ascending order using the ‘private void bsort ()’ function. The third function ‘private void msort ()’ performs the merging job. In this program ‘n’ is the size of the first array and ‘m’ is the size of the second array. Two variables ‘i’ and ‘j’ are made to point the starting indexes of first array and the second array. In the while loop the condition set is ‘i< n && j< m’ which means any one of the condition will become false when the loop breaks. Inside the loop the checking condition is set to check if the value in the first array pointed by variable ‘I’ is less than or equal to the value in second array pointed by ‘j’. If the condition becomes true, the value from the first array is stored in the third array and the variable ‘I’ is incremented by 1 to point the next location value. If the condition becomes false, the same process is carried out on second array and the variable ‘j’ is incremented by 1. Any one of the variables ‘i’ or ‘j’ will reach the value ‘n’ or ‘m’ first and the loop will break. Next job of the program is to check from which condition the loop breaks. If the condition i< n becomes false, it means that all the values of the first array is stored in the final array ‘c’ and the elements from second array are to be accessed and to be stored in the third array. The reverse condition may also happen.
‘private void display ()’ function displays the arrays.


Merge Sort on single array



This merge sort is carried out on a single array. This sorting is called external sorting as number of temporary locations will be created and sorting process will take place in those external locations. After sorting, the sorted elements will be placed in the original array. Suppose there are 8 values in an array and the values are to be sorted using merge sort. The array list is to be divided into 4 sublist each of which contains 2 elements and the sublists are to be sorted. After sorting the sublists, two consecutive lists will be merged to form a new sublists. In our case 2 sublists will be formed and the sublists will be sorted again. The sorting technique can be selection sort, bubble sort or any other. Then again the sublists will be merged and sorting process will continue until it becomes a single list. Then finally the single list will be sorted.

Suppose values are:

66 33 40 22 55 88 60 11

The groups will be like
66 33 40 22 55 88 60 11
After sorting we get
33 66 22 40 55 88 11 60
Now the new group
33 66 22 40 55 88 11 60
After sorting
22 33 40 66 11 55 60 88
The new group
22 33 40 66 11 55 60 88
After sorting
11 22 33 40 55 60 66 88

Codes of the merge sort Program on single array



class MergeSingle
{
void sort(int arr[],int top,int size,int bottom)
{
int temp[]=new int[20];
int f=top;
int s=size+1;
int t=top;
int upper;
while((f< =size)&&(s< =bottom))
{
if(arr[f]< =arr[s])
{
temp[t]=arr[f];
f++;
}
else
{
temp[t]=arr[s];
s++;
}
t++;
}
if(f< =size)
{
for(f=f;f< =size;f++)
{
temp[t]=arr[f];
t++;
}
}
else
{
for(s=s;s< =bottom;s++)
{
temp[t]=arr[s];
t++;
}
}
for(upper=top;upper< =bottom;upper++)
{
arr[upper]=temp[upper];
}
}
void pass(int arr[],int m,int n)
{
if(m!=n)
{
int mid=(m+n)/2;
pass(arr,m,mid);
pass(arr,mid+1,n);
sort(arr,m,mid,n);
}
}
public static void main(String args[])
{
MergeSingle ob=new MergeSingle();
int list[]={22,1,23,3,43,4,3,2,55,4,5,6,7,11,12,23,45,67,8,9};
int i;
System.out.println("\nElements as follows\n");
for(i=0;i< 20;i++)
System.out.print(" "+list[i]);
ob.pass(list,0,19);
System.out.println("\nElements after sorting---as follows\n");
for(i=0;i< 20;i++)
System.out.print(" "+list[i]);
}
}


N.B:- This merge sort on single array is not for ISC and ICSE examination.

BlueJ program on arranging digits of number

Program to enter a number upto 8 digits and form a new number where odd digits get sorted in ascending order followed by even digits in descending order.

import java.io.*;
class smith1
{
int n,even[],odd[],i,evenindex=0,oddindex=0;
String str;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeNumber() throws Exception
{
even=new int[8];
odd=new int[8];
do
{
System.out.println("Enter the number:");
str=br.readLine().trim();
if(str.length()<=8)
break;
}while(true);
n=Integer.parseInt(str);
do
{
i=n%10;
if(i%2==0)
even[evenindex++]=i;
else
odd[oddindex++]=i;
n=n/10;
}while(n!=0);
sortOdd();
sortEven();
n=0;
for(i=0;i< oddindex;i++)
n=n*10+odd[i];
for(i=0;i< evenindex;i++)
n=n*10+even[i];
System.out.println("Modified Number="+n);
}
private void sortEven()
{
int j,flag=0,t;
for(i=0;i< evenindex;i++)
{
flag=0;
for(j=0;j< evenindex-i-1;j++)
{
if(even[j]< even[j+1])
{
t=even[j];
even[j]=even[j+1];
even[j+1]=t;
flag=1;
}
}
if(flag==0)
break;
}
}
private void sortOdd()
{
int j,flag=0,t;
for(i=0;i< oddindex;i++)
{
flag=0;
for(j=0;j< oddindex-i-1;j++)
{
if(odd[j]>odd[j+1])
{
t=odd[j];
odd[j]=odd[j+1];
odd[j+1]=t;
flag=1;
}
}
if(flag==0)
break;
}
}
public static void main(String args[])throws Exception
{
smith1 obj=new smith1();
obj.takeNumber();
}
}

Related posts:

Program on possible consecutive numbers
Program on Perfect Number
Program on Automorphic Number
Program on Saddle Number
Program on Armstrong Number
Program on Smith Number

Friday, February 11, 2011

ISC Computer practical programs on 2006

Program Number 1



Write a program which inputs a positive natural number N and prints the possible consecutive number combinations, which when added give N. Test your program for the following data and some random data..

A positive natural number, (for e.g 27) can be represented as follows-
2+3+4+5+6+7
8+9+10
13+14
Every row represents a combination of consecutive natural numbers, which add up to 27.

SAMPLE DATA
INPUT
N = 9
OUTPUT
4 5
2 3 4
INPUT
N = 15
OUTPUT
7 8
1 2 3 4 5
4 5 6

Codes of this Program on possible consecutive numbers already posted in this blog.

Program on Merging two sorted string arrays



Write a program that inputs the names of people in to different arrays, A and B. Array a has N number of names while array B has M number of names, with no duplicates in either of them. Merge arrays A and B in to a single array C, such that the resulting array is stored alphabetically.
Display all the three arrays, A, B and C, stored alphabetically.
Test your program for the given data and some random data.

SAMPLE DATA
INPUT
Enter number of names in Array A, N = 2
Enter number of names in Array A, B = 2
First array: (A)
Suman
Anil
Second array: (B)
Usha
Sachin
John
OUTPUT
Stored Merged array: (C)
Anil
John
Sachin
Suman
Usha
Stored First array: (A)
Anil
Suman
Stored second array: (B)
John
Sachin
Usha


Codes of this program



import java.io.*;
class SortedNames
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str1[],str2[],str3[];
int n,m;
String s;
int i,j;
public void take ()throws Exception
{
System.out.println("Number of Names for first array:");
n=Integer.parseInt(br.readLine());
System.out.println("Number of Names for second array:");
m=Integer.parseInt(br.readLine());
str1=new String[n];
str2=new String[m];
str3=new String[n+m];
System.out.println("Names for 1st array:");
for(i=0;i< n;i++)
{
System.out.println("Name:");
str1[i]=br.readLine().trim();
}
System.out.println("Names for 2nd array:");
for(i=0;i< m;i++)
{
System.out.println("Name:");
str2[i]=br.readLine().trim();
}
sort();
merge();
display();
}
private void sort()
{
int flag;
for(i=0;i< n;i++)
{
flag=0;
for(j=0;j< n-i-1;j++)
{
if(str1[j].compareTo(str1[j+1])>0)
{
s=str1[j];
str1[j]=str1[j+1];
str1[j+1]=s;
flag=1;
}
}
if(flag==0)
break;
}
for(i=0;i< m;i++)
{
flag=0;
for(j=0;j< m-i-1;j++)
{
if(str2[j].compareTo(str2[j+1])>0)
{
s=str2[j];
str2[j]=str2[j+1];
str2[j+1]=s;
flag=1;
}
}
if(flag==0)
break;
}
}
private void merge()
{
int x=0;
i=0;
j=0;
while(i!=n && j!=m)
{
if(str1[i].compareTo(str2[j])<=0)
str3[x++]=str1[i++];
else
str3[x++]=str2[j++];
}
if(i==n)
{
for(;j< m;j++)
str3[x++]=str2[j];
}
else
{
for(;i< n;i++)
str3[x++]=str1[i];
}
}

private void display()
{
System.out.println("\nSorted Merged Names\n");
for(i=0;i< m+n;i++)
System.out.println(str3[i]);
System.out.println("\n*********\n");
System.out.println("\nFirst array names\n");
for(i=0;i< n;i++)
System.out.println(str1[i]);
System.out.println("\n*********\n");
System.out.println("\nSecond array names\n");
for(i=0;i< m;i++)
System.out.println(str2[i]);

}

public static void main(String args[])throws Exception
{
SortedNames obj=new SortedNames();
obj.take();
}
}


Program Number 3



A new advanced Operating System, incorporating the latest hi-tech features has been designed by Opera Computer System. The task of generating copy protection codes to prevent software piracy has been entrusted to the Security Department. The security department has decided to have codes containing a jumbled combination of alternate uppercase letters of the alphabet starting from A upto K (namely among A,C,E,G,I,K). The codes may or may not be in the consecutive series of alphabets.

Develop a program to input a code and its length. At the first instance of an error display “Invalid!” stating the appropriate reason. In case of no error, display the message “Valid!”

Test your program for the following data and some random data.

SAMPLE DATA
INPUT
N = 4
ABCE
OUTPUT
Invalid! Only alternate letters permitted!
INPUT
N = 4
AcIK
OUTPUT
Invalid! Only upper case letters permitted!
INPUT
N = 4
AAKE
OUTPUT
Invalid! Repetition of characters not permitted!
INPUT
N = 7
OUTPUT
Error! Length of string should not exceed 6 characters!
INPUT
N = 4
AEGIK
OUTPUT
Invalid! String length not the same as specified!
INPUT
N = 3
ACE
OUTPUT
Valid!
INPUT
N = 5
GEAIK
OUTPUT
Valid!

Codes of this program will be posted very soon.


Related Posts:
ISC 2007 Computer Practical Paper
ISC Computer Practical Paper - 2008
ISC 2010 Computer Practical

Wednesday, February 9, 2011

ISC Computer application practical paper – 2007

Program Number 1



Write a program to accept a date in the string format dd/mm/yyyy and accept
the name of the day on 1st of January of the corresponding year. Find the day for the given date.

Example: INPUT
Date : 5/7/2002
Day on 1st January of that year.

OUTPUT
Day on 5/7/2001 : THURSDAY

Codes of this program already posted in this blog.


Program Number 2



The input in this problem will consists of a number of lines of English text consisting of the letters of the English alphabet, the punctuation marks (‘) apostrophe, (.) full stop, (,) comma, (;)semicolon, (:) colon and white space characters (blank, newline). Your task is to print the word of the text in reverse order without a punctuation marks other than blanks.

For example consider the following input text:
This is a sample piece of text to illustrate this problem. If you are smart you
will solve this right.

The corresponding output would read as:

right this solve will you smart are you If problem this illustrate to text of piece

The first line of input contains a single integer N ( < = 20 ), indicating the
number of lines in the input. This is followed by N lines of input text. Each line should accept a maximum of 80characters.
except blanks illustrated above.

Test your program for the following data and some random data.

SAMPLE DATA
INPUT:
2
Emotions, controlled and directed to work, is character.
By Swami Vivekananda.
OUTPUT:
Vivekananda Swami by character is work to directed and controlled Emotions.
INPUT:
1
Do not judge a book by its cover.
OUTPUT
cover its by book a judge not Do.

Codes of this program already posted.


Program Number 3



A unique-digit integer is a positive integer (without leading zeros) with no
duplicates digits. For example 7, 135, 214 are all unique-digit integers whereas 33,
3121, 300 are not.
Given two positive integers m and n, where m < n, write a program to determine how many unique-digit integers are there in the range between m and n (both
inclusive) and output them.
The input contains two positive integers m and n. Assume m < 30000 and n <
30000. You are to output the number of unique-digit integers in the specified
range along with their values in the format specified below:

SAMPLE DATA:
INPUT:
m = 100
n = 120
OUTPUT:
THE UNIQUE-DIGIT INTEGERS ARE:
102, 103, 104, 105, 106, 107, 108, 109, 120.
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS : 9
INPUT:
m = 2500
n = 2550
OUTPUT:
THE UNIQUE-DIGIT INTEGERS ARE:
2501, 2503, 2504, 2506, 2507, 2508, 2509, 2510, 2513, 2514, 2516, 2517,
2518, 2517, 2530, 2519, 2530, 2531, 2534, 2536, 2537, 2538, 2539, 2540,
2541, 2543, 2546, 2547, 2548, 2549.
FREQUENCY OF UNIQUE-DIGIT INTEGERS IS: 28.

Codes of this program is in this blog.


Related Posts:
ISC Computer Practical Programs - 2006
ISC 2010 Computer Practical
ISC Computer Practical Paper - 2008

ISC Computer application practical paper – 2008

Program Number 1:



A smith number is a composite number, the sum of whose digits is the sum of
the digits of its prime factors obtained as a result of prime factorization
(excluding 1). The first few such numbers are 4, 22, 27, 58, 85, 94, 121 …

Example;
1. 666
Prime factors are 2, 3, 3 and 37
Sum of the digits are (6+6+6) = 18
Sum of the digits of the factors (2+3+3+(3+7) = 18
2. 4937775
Prime factors are 3, 5, 5, 65837
Sum of the digits are (4+9+3+7+7+7+5) = 42
Sum of the digits of the factors (3+5+5+(6+5+8+3+7) = 42

Write a program to input a number and display whether the number is a Smith number or not.

Sample data:
Input 94 Output SMITH Number
Input 102 Output NOT SMITH Number
Input 666 Output SMITH Number
Input 999 Output NOT SMITH Number

Codes of Smith Number Program is previously posted in this blog.



Program Number 2



A sentence is terminated by either “ . ” , “ ! ” or “ ? ” followed by a space. Input a piece of text consisting of sentences. Assume that there will be a maximum of 10 sentences in a block.

Write a program to:
(i) Obtain the length of the sentence (measured in words) and the frequency of vowels in each sentence.
(ii) Generate the output as shown below using the given data

Sample data:
INPUT
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF
LUCK.
OUTPUT
Sentence No. of Vowels No. of words
----------------------------------------------------------
1 2 1
2 5 3
3 8 4
4 3 3


Codes of the program



import java.io.*;
import java.util.*;
class Sentence
{
String str1,str2,str3[];
int number,i;
StringTokenizer stk;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeSentence()throws Exception
{
System.out.println("Enter the sentence:");
str1=br.readLine();
stk=new StringTokenizer(str1,"?.,");
number=stk.countTokens();
str3=new String[number];
i=0;

while(stk.hasMoreTokens())
{
str3[i++]=stk.nextToken();
}
System.out.println("\nSentence No No. of vowels No. of words\n");
for(i=0;i< number;i++)
{
str1=str3[i];
System.out.print((i+1)+" ");
System.out.print(vowel(str1)+ " ");
System.out.println(word(str1)+ " ");
}
}
private int vowel(String s)
{
int i,v=0,len;
len=s.length();
s=s.toUpperCase();
for(i=0;i< len;i++)
{
if(s.charAt(i)=='A'||s.charAt(i)=='E'||s.charAt(i)=='I'||s.charAt(i)=='O'||s.charAt(i)=='U')
v++;
}
return v;
}

private int word(String s)
{
int i,v=1,len;
len=s.length();
s=s.toUpperCase();
for(i=0;i< len;i++)
{
if(s.charAt(i)==' ')
v++;
}
return v;
}
public static void main(String args[])throws Exception
{
Sentence object=new Sentence();
object.takeSentence();
}
}



Program Number 3



Given a square matrix list [ ] [ ] of order ‘ n ’. The maximum value possible for ‘ n ’ is 20. Input the value for ‘ n ’ and the positive integers in the matrix and perform the following task:
1. Display the original matrix
2. Print the row and column position of the largest element of the matrix.
3. Print the row and column position of the second largest element of the
matrix.
4. Sort the elements of the rows in the ascending order and display the new matrix.

Sample data:
INPUT
N = 3
List [] [ ]
5 1 3
7 4 6
9 8 2
OUTPUT
5 1 3
7 4 6
9 8 2
The largest element 9 is in row 3 and column 1
The second largest element 8 is in row 3 and column 2
Sorted list
1 3 5
4 6 7
2 8 9

Codes of this program on array




import java.io.*;
class ArrayProgram
{
int array[][]=new int[3][3];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,j;
public void take() throws Exception
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print("Enter Number:");
array[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("\nValues as follows\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(" "+array[i][j]);
}
System.out.println();
}
sort();
System.out.println("\nValues as follows after sorting row wise\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(" "+array[i][j]);
}
System.out.println();
}
display();
}
private void sort()
{
int k,temp;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=j+1;k<3;k++)
{
if(array[i][j]>array[i][k])
{
temp=array[i][j];
array[i][j]=array[i][k];
array[i][k]=temp;
}
}
}
}
}
private void display()
{
int max1=0,max2=0,maxi=0,maxj=0;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(array[i][j]>max1)
{
max1=array[i][j];
maxi=i+1;
maxj=j+1;
}
}
}
System.out.println("Maximum value="+max1 + " and the row and column numbers are:"+maxi+","+maxj);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(array[i][j]>max2 && array[i][j]< max1)
{
max2=array[i][j];
maxi=i+1;
maxj=j+1;
}
}
}
System.out.println("2nd Maximum value="+max2 + " and the row and column numbers are:"+maxi+","+maxj);
}

public static void main(String args[])throws Exception
{
ArrayProgram object=new ArrayProgram();
object.take();
}
}



Similar Posts:
ISC Computer Practical Programs - 2006
ISC 2010 Computer Practical
ISC 2007 Computer Practical Paper

Tuesday, February 8, 2011

Abstract class and abstract function in BlueJ

In a simple class in BlueJ, the data members of the class are declared and function members are defined. The members can have any access specifiers, public, private, protected or default. Function definition means where function return type, name, argument list (if no argument, it is kept blank)and function body is defined. Function body of a function should have an opening and closing curly brace.

Example of function definition:



public void setData( int x, int y)
{
Statement 1;
Statement 2;
……………..

}

If in any class a function is not defined as shown above, its prototype is simply declared then the keyword abstract should be used with the function otherwise compiler will show error.
.

Example of abstract function



abstract void set();

This above function has no body, it is not defined. Thus we can say that this function is incomplete. In java, incomplete function means abstract function. If a single function of a class is abstract then the class also becomes abstract class. An abstract class can have more than one abstract function. For abstract class, the keyword abstract should be used before the class name while defining the class otherwise compiler will show compile time error.

Example of abstract class definition



abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

Abstract class can have instance members as well as static members. Abstract can define it’s own constructor also but the only difference with abstract class is that objects of abstract class can not be created. We have defined an abstract class ‘MyClass’ just above. If we try to create object of this class using the statement MyClass obj=new MyClass(), it will show compile time error. Abstract class can be inherited by other class but the sub class would either override the abstract functions of the abstract super class or declare itself abstract class.

Example of abstract class inheritance



abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

class MyClass2 extends MyClass
{

void show()
{
System.out.println(“Value=”+a);
}
}

Here the sub class MyClass2 inherites the abstract class MyClass and the abstract function is overridden in the sub class. If the sub class MyClass2 do not override the abstract function then the codes would be like

abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

abstract class MyClass2 extends MyClass
{

void showValue()
{
System.out.println(“Value=”+a);
}
}

Here in the above codes both the classes are abstract so objects of both the classes can not created. One point to be remembered that abstract class objects can be declared and it can refer its sub class object.

Sunday, February 6, 2011

Smith number and BlueJ program

What is a Smith number



Smith number a composite number in which the sum of its digits is equal to the sum of the digits in its prime factors. In 378 the sum of the digits is 3+7+8=18. The prime factors of 378 are 2, 3, 3, 3, 7. Here all the prime factors are single digit numbers and their sum is 2+3+3+3+7-18. So 378 is a smith number. Again if we take the case of 22, the sum of the digits is 2+2=4 and the prime factors are 2 and 11. Since 11 is a two digit number, the sum of the digits of the factors is 2+1+1=4. So 22 is a Smith number.

The first few Smith numbers are: 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562, 576, 588, 627, 634, 636, 645, 648, 654, 663, 666, 690, 706, 728, 729, 762, 778, 825, 852, 861, 895, 913, 915, 922, 958, 985, 1086

How to proceed on this program to check Smith number



Firstly sum of the digits of the entered number is to be stored in a variable. Next step is to find out the factors and checking the numbers whether they are prime or not. If found prime factor then the sum of the digits of the factor number is stored in another counter variable and the same process is followed for all prime factor numbers. Whenever any prime factor is found, the original entered number is tried with the same number and the original number is divided by the prime factor number.

Codes of the BlueJ program on Smith number checking



import java.io.*;
class smith1
{
int no,n,j,sum=0,sumfactors=0,i;
boolean bool;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeNumber() throws Exception
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine());
no=n;
sum=sumOfDigits(n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
bool=prime(i);
if(bool)
{
j=i;
System.out.print(" "+j);
while(j>0)
{
sumfactors=sumfactors+j%10;
j=j/10;
}
n=n/i;
i--;
}
}
}
if(sum==sumfactors)
System.out.println(no+ " is a smith number.");
else
System.out.println(no+ " is not a smith number.");
}
private int sumOfDigits(int n)
{
int s=0;
while(n>0)
{
s=s+n%10;
n=n/10;
}
return s;
}
private boolean prime(int n)
{
int i;
for(i=2;i< n;i++)
{
if(n%i==0)
break;
}
if(i==n)
return true;
else
return false;
}
public static void main(String args[])throws Exception
{
smith1 obj=new smith1();
obj.takeNumber();
}
}


Technical analysis of the Smith number checking program



Two variables ‘sum’ and ‘sumfactors’ are used in this program to store sum of the digits of the entered number and sum of the digits of the prime factors of the entered number. Three functions are defined in this program to perform the job of checking Smith number. Function ‘takeNumber()’ takes the number from user, invokes the other function ‘int sumOfDigits()’ which returns the sum of the digits and store in variable ‘sum’. Next the factors are generated and passed to another function ‘boolean prime()’ to check whether the number is prime or not. If any factor is not prime, the process of finding the next factor is continued. If the factor is found to be prime, sum of the digits of the factor number is calculated and stored in the other counter variable ‘sumfactors’. In such case, the process of finding prime factor number is continues with the same factor and the entered number is reduced by dividing the entered number by the prime factor. At the end both the entered number and the sum of the digits of prime factor numbers are checked .

Related posts:

Program on possible consecutive numbers
Program on Perfect Number
Program on Automorphic Number
Program on Saddle Number
Program on Armstrong Number

Friday, February 4, 2011

Finding all possible consecutive number combinations using BlueJ program

Amout the program on number of combination



We have to take a number and find out the sum of consecutive numbers within that entered number which is equal to the entered number itself. For example – if the entered number is 15 the consecutive number combinations will be
1 2 3 4 5
4 5 6
7 8

Codes of the program on number combination



import java.io.*;
class NumberCombonation
{
int no,sum=0,k,j,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

public void takeNumber()throws Exception
{
System.out.println("Enter the number:");
no=Integer.parseInt(br.readLine());
for(i=1;i< =no/2+1;i++)
{
sum=0;

for(j=i;j< =no/2+1;j++)
{
sum=sum+j;
if (sum==no)
break;
}
if(j<=no/2+1)
{
for(k=i;k< =j;k++)
System.out.print(" "+k);
System.out.println();
}
}
}

public static void main(String args[])throws Exception
{
NumberCombonation obj=new NumberCombonation ();
obj.takeNumber();
}
}

Technical analysis of the number combination program



The outer loop starts from 1 and this loop is generates the starting number of consecutive number combination series and the first inner loop checks if the number combination is possible with that starting number. If a series is found, which is checked just outside the first inner loop, the second inner loop prints the consecutive number combination.



Related posts:

Program on Perfect Number
Program on Automorphic Number
Program on Saddle Number
Program on Armstrong Number
Program on Smith Number

Tuesday, February 1, 2011

Perfect number checking program in BlueJ

What is perfect number



A number is considered as perfect number if the sum of its factors ( excepting the number itself) equals to the number. 6 is a perfect number as the factors of 6 are 1, 2, and 3 and sum of the factors is equal to 6.

How to check if a number is perfect or not



Take the number and find out the factors of the number using a loop. The sum of the factors are stored in a variable. At the end of the loop check the original number and the sum of the factors. If both the values are same, then the entered number is a perfect number otherwise not.

import java.io.*;
class PerfectNumber
{
int no,sum=0,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

public void takeNumber()throws Exception
{
System.out.println("Enter the number:");
no=Integer.parseInt(br.readLine());
for(i=1;i< no;i++)
{
if(no%i==0)
sum=sum+i;
}
if(sum==no)
System.out.println(no + " is a perfect number");
else
System.out.println(no + " is not a perfect number");
}
public static void main(String args[])throws Exception
{
PerfectNumber obj=new PerfectNumber ();
obj.takeNumber();
}
}



Related posts:

Program on possible consecutive numbers
Program on Automorphic Number
Program on Saddle Number
Program on Armstrong Number
Program on Smith Number

Friday, January 28, 2011

BlueJ program on string modification - displaying an entered full name in short form

This is BlueJ program on string modification. User entered name with middle name and surname which is stored in a string object will be displayed in short form. Initial alphabets of the name and middle name(s) and the complete surname will be displayed. The full name may have number of middle names. The initial alphabets of name, middle name and surname will be in capital letter and the rest of alphabets will be in lower case.

How to proceed on this string modification program



We have to recognize the initial alphabets of name, middlename and surname the entered name. The first alphabet of the string is the initial alphabet of the name and accessing it is not a tough job. Next initial alphabets should be just next to blank space as after name, middlename and surname there should be blank space. If user enters multiple consecutive blank spaces, removal of extra blank spaces from the string is necessary.

So, in this BlueJ program we need to access the blank spaces from the string and the alphabet following the blank spaces are to be taken which will be the initial alphabet of either name, middlename or surname. If these initial alphabets are in lower case, they should be converted in to upper case. All the alphabets of the last word means the surname should be taken and the alphabets excepting the first one should be changed to lower case if required.

Codes of the string modification program



import java.io.*;
class Words2
{
int sp;
BufferedReader br;
String text,text1="";
public static void main(String args[])throws IOException
{
Words2 ob=new Words2();
ob.accept();
ob.result();
}
Words2()
{
br=new BufferedReader(new InputStreamReader(System.in));
text="";
sp=0;
}
public void accept()throws IOException
{
System.out.println("Enter the Name:");
text=br.readLine().trim();
}
public void result()
{
int i=0,len,flag=0;
char ch;
System.out.println("The entered Name ="+text);
len=text.length();
do
{
if(text.charAt(i)==' ')
sp++;
i++;
}while(i
i=0;
do
{
ch=text.charAt(i);
if(i==0)
{
if(ch>=97 && ch<=122)
ch=(char)(ch-32);
text1=text1+ch;
}
else if(ch==' ')
{
flag=1;
text1=text1+".";
sp--;
}
else if(flag==1)
{
if(ch>=97 && ch<=122)
ch=(char)(ch-32);
text1=text1+ch;
flag=0;
}
else if(sp==0)
{
if(ch>=65 && ch<=90)
ch=(char)(ch+32);
text1=text1+ch;
}
i++;
}while(i< len);
text1=text1.trim();
System.out.println("Name in short form="+text1);
}
}

Technical analysis of the string modification program



Blank spaces of the entered string is counted first using a do while loop in this program. Again each apphabets are accessed using another do while loop where the required modification is done. The first alphabet of the string acceesed is the initial character of the name and the character is converted into upper case is necessary and concatenated with another string object. Whenever any blank space in the string is encountered, the variable containing the number of blank spaces in the string is decreased by 1, a dot (.) is concatenated with the string object containing the modified string and another variable ‘flag’ is set to 1. This value indicates that blank space is encountered just one character before. So the alphabets when the value of flag is 1, is concatenated to the modified string object. These alphabets are those initial alphabets of middlename and surname. When the value of the variable holding the number of blank spaces becomes zero, it indicates that surname alphabets excepting the initial character is accessed, so they are converted in to lower case if required and attached to the modified string object.

Related post:
Decoding encoded string

Monday, January 24, 2011

BlueJ program on checking Automorphic number and technical analysis of the program

Today I will show you how to check a number whether it is automorphic number or not in BlueJ program. Before I proceed further, few clarifications are needed.

What is automorphic number



For any number we have to find the number of digits in it. From the square value of the number take digits equal to the number of digits of the number from the right side. If the original number and the part of the number are found equal on checking then the entered number is an automorphic number.

For example, 25 is an automorphic number. Number of digits in 25 is 2 and square value of 25 is 625. We have to take 2 extreme right digits from 625 as there are 2 digits in the original entered number. Two extreme right digits of 625 is 25 which matches with original number 25. So 25 is an automorphic number. Similarly 5 is also an automorphic number.

Codes of the automorphic number program



import java.io.*;
class Automorphic
{
int i,n,no,sqnum,rev=0,digit=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void getNumber() throws Exception
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine());
no=n;
do
{
digit++;
no=no/10;
} while(no!=0);

sqnum=n*n;
}
public void showResult()
{
do
{
rev=rev*10+sqnum%10;
sqnum=sqnum/10;
digit--;
if(digit==0)
break;
} while(true);

rev=reverse(rev);
if(n==rev)
System.out.println(n+" is an Automorphic number");
else
System.out.println(n+" is not an Automorphic number");
}
private int reverse(int n)
{
int r=0;
while(n!=0)
{
r=r*10+n%10;
n=n/10;
}
return r;
}
public static void main(String args[])throws Exception
{
Automorphic obj=new Automorphic();
obj.getNumber();
obj.showResult();
}
}

Technical analysis of the automorphic number program



Three functions are defined in this program. The function ‘public void getNumber()’ takes the number from user, counts the digits in it using a do while loop and calculate the square value of the number.

Within the body of another function ‘public void showResult()’ in this program, the digits from the square value is retrieved with proper checking so that the digits retrieved is equal to the number of digits in the original number. This retrieval of digits is performed using do while loop in this program.

The third defined function in this program ‘private int reverse(int n)’ defined in this class is to reverse a number, as from 625 on extracting two digits we will get 52 but we need it as 25.



Related posts:

Program on possible consecutive numbers
Program on Perfect Number
Program on Saddle Number
Program on Armstrong Number
Program on Smith Number

Sunday, January 23, 2011

BlueJ program on decoding encoded string with removing extra blank spaces and modification on alphabet cases

The program is as stated below

An encoded string can be decoded by finding actual character for the given ASCII code in the encoded message. Write a program to input an encoded text having only sequence of ACSII values without any spaces.Any code or value which is not in the range(65-90 or 97-122 or 32 for space) will be ignored and should not appear in the output message.Decode the encoded text and print in the form of sentence.The first alphabet of each word must be in capitals and rest alphabets will be in lower case only. Any consecutive sets of code 32 will be taken as only one blank space.
The output should be exactly in the following format:

Input (encoded string) : 10665771011153266797868
Output(decoded string) : James Bond
Input (coded string) : 78487367421013232321006589
Output(decoded string) : Nice Day

This string program involves three steps.
1. Decoding the encoded text with only the alphabets and blank spaces, eliminating the others.
2. Elimination of extra blank spaces from the decoded text.
3. Changing the cases of the alphabets in the decoded text.

How to proceed on decoding the encoded text



Take the string of ASCII values in a string object. Firstly retrieve three characters from the left side of encoded text and check if is within the specified range, means it is the ASCII value of any alphabet or that of blank space. If the checking succeeds, concatenate the equivalent alphabet with another string object which will represent the decoded string and at the same time eliminate that ASCII substring from the original ASCII string. If the checking shows that the retrieved substring is not the ASCII value of the specified range then try the above process with two left most characters from the ASCII string and follow the same actions which are to be performed for three character substring. If the ASCII substring matches with any alphabet or blank space, remove the two left most characters from the original string.

If both the checkings with three left most characters and two left most characters shows that the substring is not the ASCII value of any alphabet or blank space remove two left most characters from the original string and continue the process until the length of the original string becomes less than 2.

At the end the second string object will represent the decoded string value with extra blank spaces in it if it were in the ASCII string and the case of the characters in the decoded string will be as per ASCII values in the entered encoded ASCII string.

How to proceed to remove extra blank spaces from the decoded string



Each character of the decoded string is to be accessed and appended to another string object excepting consecutive spaces. This process will eliminate all the extra blank spaces if any from the decoded text.

How to proceed to change the case of alphabets in decoded string



Here also loop is required. Access every alphabet from the decoded string using loop. Check the case of first character of the decoded string. If it is in lower case, change it in to upper case and whenever any blank space is found in the decoded string, perform the operation as the first alphabet of the decoded string. For the rest alphabets of the decoded string, checking is to be done and for upper case alphabets they should be converted to lower case alphabet.


Codes of the encoded and decoded string program



import java.io.*;
class Words2
{
int w;
BufferedReader br;
String text,text1="";
public static void main(String args[])throws IOException
{
Words2 ob=new Words2();
ob.accept();
ob.result();
}
Words2()
{
br=new BufferedReader(new InputStreamReader(System.in));
text="";
w=0;
}
public void accept()throws IOException
{
System.out.println("Enter the Coded value:");
text=br.readLine().trim();
}
public void result()
{
int i,len;
String ch;
System.out.println("The encoded text ="+text);

do
{
if(text.length()<3)
ch=text.substring(0,2);
else
ch=text.substring(0,3);
System.out.println(ch);
if( Integer.parseInt(ch)<=122 && Integer.parseInt(ch)>=97)
{
text1=text1+(char)(Integer.parseInt(ch));
text=text.substring(3);
}
else
{
ch=text.substring(0,2);
if( Integer.parseInt(ch)<=90 && Integer.parseInt(ch)>=65)
{
text1=text1+(char)(Integer.parseInt(ch));
text=text.substring(2);
}
else if( Integer.parseInt(ch)==32)
{
text1=text1+" ";
text=text.substring(2);
}
else
text=text.substring(2);
}
}while(text.length()>=2);
text1=removeSpace(text1);
System.out.println("Space removed="+text1);
text1=changeCase(text1);
System.out.println("Coded value="+text1);
}
String removeSpace(String s)
{
int j,len,flag=0;
String str="";
s=s.trim();
len=s.length();
for(j=0;j< len;j++)
{
if(s.charAt(j)==' ' && flag==1)
{
str=str+s.charAt(j);
flag=0;
}
else if(s.charAt(j)!=' ')
{
flag=1;
str=str+s.charAt(j);
}
}
return str;
}
String changeCase(String s)
{
int j,len,flag=0;
String str="";
s=s.trim();
len=s.length();
for(j=0;j< len;j++)
{
if(s.charAt(j)>=97 && j==0)
str=str+(char)(s.charAt(j)-32);
else if(s.charAt(j)==48)
{
str=str+" ";
flag=1;
}
else if(s.charAt(j)<=90 && flag==0)
str=str+(char)(s.charAt(j)+32);
else if(s.charAt(j)>=97 && flag==1)
{
str=str+(char)(s.charAt(j)-32);
flag=0;
}
else
{
str=str+s.charAt(j);
}
}
return str;
}
}

Thursday, January 20, 2011

BlueJ program on how to remove extra blank spaces from a string

Today I will discuss about a string modification program. String class has a function ‘String trim ()’ which removes leading and trailing spaces from a string value. But what happens if there are more than one blank space between two words in a text? The above ‘trim ()’ function can not remove such blank spaces from a string.

How to proceed on this string modification program

Firstly the leading and trailing space from the string is to be removed, if any. Function ‘String trim ()’ will perform this job. Next action is to access every character and check if there is consecutive blank spaces in the string. The characters and only one blank space following any character is to be concatenated in another string object. If there are multiple blank spaces, they should not be concatenated in the second string object which will hold the modified string.

Codes of removing extra blank spaces from a string object



import java.io.*;
class Words
{
int w;
BufferedReader br;
String text,modified="";
public static void main(String args[])throws IOException
{
Words ob=new Words();
ob.accept();
ob.result();
}
Words()
{
br=new BufferedReader(new InputStreamReader(System.in));
text="";
w=0;
}
public void accept()throws IOException
{
System.out.println("Enter the Sentence:");
text=br.readLine().trim();
}
public void result()
{
int i,len;
char ch;
System.out.println("The entered sentence ="+text);
len=text.length();
for(i=0;i
{
ch=text.charAt(i);
if(ch==' ' && w==1)
{
w=0;
modified=modified+ch;
}
else if(ch!=' ')
{
modified=modified+ch;
w=1;
}
}
System.out.println("The modified sentence ="+modified);
}
}

Technical analysis of the above string modification program



The job of removing extra blank spaces from the string is done within the ‘public void result ()’ function. Using a for loop each character of the string is accessed. An int type variable ‘w’ is used to notify if consecutive blank spaces are there in the string. Initial value of ‘w’ is set to ‘0’. Whenever any alphaber is found in the string, the value of the variable ‘w’ is set to ‘1’. On the process of checking each characters, if any blank space is found and the value of ‘w’ is ‘1’ at that time, the blank space is concatenated in the second string object. At the same time the value of ‘w’ is reset to ‘0’ so that consecutive two blank spaces are not taken in the modified string object.

Tuesday, January 18, 2011

Understanding the use of inner loop in BlueJ programs

Nested loop means there should be an outer loop and one or more inner loop. We have seen the use of inner loop in different type of programs. Whenever we use any nested loop, inner loop plays the most vital part. In sorting programs inner loop does the sorting job. In pattern printing programs, it is the inner loop which displays the pattern. So for any type of the above jobs, students should understand the inner loop properly.

Use of inner loop in nested loop



For any type of pattern, the inner loop is the main architech to display the design or pattern. Job of outer loop is simply to maintain the rows but the major job is performed by inner loop. Take any program on printing pattern, you would find that the construction of inner loop, the logical statements used in the inner loop are the main points to stydy and understand. Any change in the statements of inner loop will change the shape of the pattern.

Here is a program to print a pattern like

55555
55554
55543
55432
54321

Simply observe the checking done in inner loop

class Pat
{
int i,n,j;
public void show()
{
for(i=0;i<5;i++)
{
n=5;
for(j=0;j<5;j++)
{
if(i+j>=5)
n--;
System.out.print(n);
}
System.out.println();
}
}
public static void main(String args[])throws Exception
{
Pat obj=new Pat();
obj.show();
}
}

Use of inner loop in sorting programs



In any type of sorting programs, inner loop performs the major job. In slection sort programs, the checking job is performed by inner loop and the necessary exchange of values is also performed within inner loop.
In Bubble sort, the accessing the values, cheking the values and exchanging the values on requirements are done by inner loop only. The outer loop determines the maximum number of passes required.

Other uses of inner loop



Inner loop has many other countless uses. One of the very common use of inner loopis to store unique values in an array. Inner loop is used in such program to search a particular values from the list. Although normal searching program do not need inner loop but to store unique values in an array, inner loop is used to search if the value is already in the array.

Sunday, January 16, 2011

BlueJ program on storing unique values in an array

We have seen how to store values in array. While storing values in an array, situation may be such that all the values in the array should be unique. In such situation we have to develop our program in such a manner that it satisfies the need.

Why unique values in an array?



Suppose we are developing a program on array to store roll number of the students of a particular class and section. In such situation the roll number of students must be unique as in a class two or more students can not have the same roll number. Programmer can not expect operator to enter proper roll numbers. The operator may by mistake enter duplicate roll number but it’s the responsibily of the programmer to develop such a program that will never accept duplicate roll number.

How to proceed technically on this array program



We will create an array to store the values. The size of the array will be same as the number of values to be entered. Normally in array programs, we store the values directly in an array using a loop. In this program we will design a nested loop to take the values. Within the body of outer loop the values will be taken in a variable. The inner loop will check the array whether this current value is stored in the array. If the checking shows that the value is already present in the array, the value will be rejected as duplicate value otherwise it will be stored in the array. In case of rejection, the iteration will also be cancelled.

Codes of the array program on unique values



import java.io.*;
class UniqueValues
{
int arr[]=new int[10];
int i,n,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeData()throws Exception
{
for(i=0;i<10;i++)
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine().trim());
for(j=0;j
{
if(n==arr[j])
break;
}
if(j
{
System.out.println("Duplicate value...Re-enter:");
i=i-1;
}
else
arr[i]=n;
}
}
public void show()
{
System.out.println("Unique values are\n");
for(i=0;i<10;i++)
System.out.print(" "+ arr[i]);
}

public static void main(String args[])throws Exception
{
UniqueValues obj=new UniqueValues();
obj.takeData();
obj.show();
}
}

Friday, January 14, 2011

BlueJ program on finding saddle number

What is saddle number



Saddle number is related with numeric 2 d array. The number which is lowest in a particular row but at the same time the same number is greatest in its column. The size of 2 d array has no relation with saddle number. It may be of any number of rows and any number of columns. Again if the conditions of saddle number do not match in a 2 d array, there will be no saddle number in it.

How to proceed on this saddle number program



2 d array and nested loop is required for this saddle number finding program. Firstly store the values in the 2 d array. Next step is to find the saddle number. Find out the minimum value in a row and check whether that particular value is maximum in its column. If the checking confirms that it is the maximum value in that column then saddle number is found. Repeat the above steps for all the rows.

Codes of saddle number finding program



import java.io.*;
class Saddle
{
int arr[][]=new int[4][4];
int saddle,i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeNumbers ()throws Exception
{
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
System.out.println("Number:");
arr[i][j]=Integer.parseInt(br.readLine().trim());
}
}
System.out.println("\nThe list is as follows:\n");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
public void showResult ()
{
int flag=0,k,minr=0,minc=0;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
if(j==0)
{
minr=arr[i][j];
minc=j;
}
else if(arr[i][j]< minr)
{
minr=arr[i][j];
minc=j;
}
}
for(k=0;k<4;k++)
{
if(minr< arr[k][minc])
break;
}
if(k==4)
{
flag=1;
saddle=minr;
}
}
if(flag!=0)
System.out.println("Saddle number="+saddle);
else
System.out.println("No saddle number in the list");
}
public static void main (String args[])throws Exception
{
Saddle obj=new Saddle ();
obj.takeNumbers ();
obj.showResult ();
}
}

Technical analysis of the saddle number program



I think storing the values in 2 d array and displaying them is clear to all. The values are displayed so that user can check manually the correctness of the program. Within the function ‘showResult()’ the job of searching the saddle number is performed. The outer loop contains two inner loops within its body. The first inner loop is used to find the lowest number in that row and the other inner loop checks whether this lowest number is the greatest number in that particular column. A ‘flag’ variable is used to check if saddle number is present in the 2 d array.


Related posts:

Program on possible consecutive numbers
Program on Perfect Number
Program on Automorphic Number
Program on Armstrong Number
Program on Smith Number

Wednesday, January 12, 2011

BlueJ program on changing the case of characters of string

This program deals with changing the case of the characters of an entered string. Upper case characters will be changed to lower case characters and vice versa. We can do this program using different techniques.

How to proceed on this character case changing program



We have to extract each characters of the string. To perform this job, a loop is required and then the status of character is to be checked. This checking can be performed in different ways. We can use static functions of Charater class to check status of any character, whether it is in lower case or upper case. The second approach of checking is ASCII values of each character. Either of these techniques can be used to check the case of the characters and required changes can be done.

Here is the program which checks the character case using static function

import java.io.*;
class ChangeCase
{
String str1,str2="";
char ch;
int i,len;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void show()throws Exception
{
System.out.println("Enter the sentence:");
str1=br.readLine();
len=str1.length();

for(i=0;i< len;i++)
{
ch=str1.charAt(i);
if(Character.isUpperCase(ch))
ch=(char)(ch+32);
else if(Character.isLowerCase(ch))
ch=(char)(ch-32);
str2=str2+ch;
}
System.out.println("Modified string="+str2);
}
public static void main(String args[])throws Exception
{
new ChangeCase ().show();
}
}

Two unfamiliar functions are used in this program, ‘isUpperCase()’ and ‘isLowerCase()’. These are static functions of Character class. Character is a predefined wrapper class of java.lang package. Prototype of these two functions are ‘public boolean isUpperCase(char)’ and ‘public boolean isLowerCase(char)’. If the argument char value in ‘public boolean isUpperCase(char)’ is in upper case it return true otherwise false. The other function is just the reversed.

Here is the second program which checks the character case using ASCII values

import java.io.*;
class Pattern
{
String str1,str2="";
char ch;
int i,len;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void show()throws Exception
{
System.out.println("Enter the sentence:");
str1=br.readLine();
len=str1.length();

for(i=0;i< len;i++)
{
ch=str1.charAt(i);
if(ch>=65 && ch<=90)
ch=(char)(ch+32);
else if(ch>=97 && ch<=122)
ch=(char)(ch-32);
str2=str2+ch;
}
System.out.println("Modified string="+str2);
}
public static void main(String args[])throws Exception
{
new Pattern().show();
}
}

Monday, January 10, 2011

BlueJ program on string palindrome checking

what is string palindrome?



A word or sentence is said to be palindrome if it is same while read from the left to right and right to left. One example of palindrome word is ‘madam’.

How to proceed for this string palindrome checking program



Firstly user will enter a text value and it will be stored in a string object. Another string object should be in the program to store the reversed value of the entered text. At the end we will get two string objects and equality checking on these strings will confirm whether the string is palindrome or not.

Here is the program

import java.io.*;
class Palindrome
{
String str1, str2;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeString ()throws Exception
{
System.out.println("Enter a sentence:");
str1=br.readLine().trim();
}
public void showResult ()
{
int i,len;
str2=" ";
len=str1.length ();
for(i=len-1;i>=0;i--)
{
str2=str2+str1.charAt(i);
}
str2=str2.trim();
if(str1.equals(str2))
System.out.println(str1 +" is a palindrome string");
else
System.out.println(str1 +" is not a palindrome string");
}
public static void main (String args[])throws Exception
{
Palindrome obj=new Palindrome ();
obj.takeString ();
obj.showResult ();
}
}

Modification of the above string palindrome checking program



Our program is to check whether a string, it may be a word or sentence is a palindrome. In the above program, we have reversed the string and stored the reversed value in another string object. During reversing the string, the loop executed its full course of iteration. Actually the program is on string palindrome checking, not to reverse the string but we have reversed the string to check the equality. All the user entered strings would not be palindrome but our above program will reverse the string and will check the original string with its reversed version to reach the conclusion.

We can modify the above program so that it will reduce time complexity of the program. Take the string and execute a loop depending on the length of the string. Within the loop body our program will check characters from both end of the string, 1st character with the last character, 2nd character with the last but one character and so on for equality. If mismatch is found in the checking, the loop will be terminated to display that the string is not palindrome. If it happens that no mismatch is found during the entire checking process, the string will be palindrome.

Here is the modified program

import java.io.*;
class Palindrome
{
String str1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeString ()throws Exception
{
System.out.println("Enter a sentence:");
str1=br.readLine().trim();
}
public void showResult ()
{
int i,j=0,len;
len=str1.length ();
for(i=len-1;i>=0;i--)
{
if(str1.charAt(i)!=str1.charAt(j))
break;
j++;
}
if(i<0)
System.out.println(str1 +" is a palindrome string");
else
System.out.println(str1 +" is not a palindrome string");
}
public static void main (String args[])throws Exception
{
Palindrome obj=new Palindrome ();
obj.takeString ();
obj.showResult ();
}
}

Technical analysis of the palindrome checking program



Taking the string from user, calculating the length of string etc is same as previous program. One point to keep in mind that while taking any string from user always use trim () function to eliminate unnecessary leading or trailing spaces from the string object.

Modifications are in side the loop body. Two variables are used for palindrome checking. Initially loop control variable points the last character of the string and another variable ‘j’ points the 1st character of the string. On each iteration, two characters of opposite direction of the string are checked for equality and loop control variable moves towards end - the other variable moves towards the beginning. If any difference is found, the loop terminates.

Outside the loop body it is examined whether the loop terminates after full running or it’s a premature termination and accordingly result is displayed.

Saturday, January 8, 2011

Armstrong number checking program in BlueJ

What is Armstrong number?



From any number, the digits are to be separated and sum of the digit to the power number of digits of each digit is to be calculated. If the sum and number matches then the number is an Armstrong number.

For example if we enter 134 as the number then the number of digit in the number is 3. The sum would be 1^3+3^3+4^3 which is not equal to 134, so 134 is not an Armstrong number. Again if the number is 1234 then the sum would be 1^4+2^4+3^4+4^4. 153 is an Armstrong number as 1^3+5^3+3^3 equals to 153.

It is found that students always use 3 as the power but it is not correct way of checking Armstrong number although 3 digit numbers are Armstrong number only.

Codes of the Armstrong number checking program using 3 as power value




import java.io.*;
class Armstrong
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int p,sum=0,c,spy=0,i;

public void takeData() throws IOException
{
System.out.println("Enter the number:-");
i=Integer.parseInt(br.readLine());
p=i;
while(p>9)
{
spy=1;
c=p%10;
sum=sum+(int)Math.pow(c,3);
p=p/10;
}
if(spy==1)
{
sum=sum+(int)Math.pow(p,3);
if(sum==i)
System.out.println(i+ " is amstrong number");
else
System.out.println("Not amstrong number.");
}
else
System.out.println("Not possible.");
}
public static void main(String args[])throws IOException
{
Armstrong obj=new Armstrong();
obj.takeData();
}
}

Now I will do the same program using number of digits of the number as power value.

Variable description of the Armstrong number checking program



BufferedReader br is used to take the number from user.
int p is a variable is used as loop control variable in this program.
int digit counts the number of digits in the entered number
int sum stores the sum of the digit to the power number of digits value.
int c holds the individual digits of the number.
int spy is used for checking purpose, whether the number is single digit or not.
int i holds the original number entered by user.

How to proceed in the program



Firstly the number is stored in variable ‘i’ and using do while loop the number of digits is counted and stored in variable ‘digit’.
The second do while loop is used to extract the digits of the number one by one and the power value is stored in the variable ‘sum’. At the end of the loop, values of ‘sum’ and the number is compared to reach the conclusion.


Modified codes of the same program on Armstrong number checking



import java.io.*;
class Armstrong
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int p,digit=0,sum=0,c,spy=0,i;

public void takeNumber() throws IOException
{
System.out.println("Enter the number:-");
i=Integer.parseInt(br.readLine());
p=i;
do
{
digit++;
p=p/10;
}while(p!=0);
p=i;
do
{
spy=1;
c=p%10;
sum=sum+(int)Math.pow(c,digit);
p=p/10;
}while(p!=0);
if(spy==1)
{
if(sum==i)
System.out.println(i+ " is amstrong number");
else
System.out.println("Not amstrong number.");
}
else
System.out.println("Not possible.");
}
public static void main(String args[])throws IOException
{
Armstrong obj=new Armstrong();
obj.takeNumber();
}
}