Wednesday, February 23, 2011

Collection

BlueJ Program on displaying day name from the entered date in specific format

Here is the BlueJ Program for ISC Students.

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

Example:
Input:
Enter the date ( in dd/mm/yyyy) format: 5/7/2001
Enter the Day on 1st January in this year: Monday

Output:
5/7/2001 : Thursday


import java.io.*;
class Date1
{
int arr[]={31,28,31,30,31,30,31,31,30,31,30,31};
BufferedReader br;
String str1,day,day1;
int x,i,dayno,mon,yr,leap1;
public static void main(String args[])throws IOException
{
Date1 ob=new Date1 ();
ob.take();
ob.show();
}
Date1 ()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public void take()throws IOException
{

System.out.println("Enter the date ( in dd/mm/yyyy) format:");
day=br.readLine().trim();
day1=day;
i=day.indexOf("/");
dayno=Integer.parseInt(day.substring(0,i));
day=day.substring(i+1);
i=day.indexOf("/");
mon=Integer.parseInt(day.substring(0,i));
day=day.substring(i+1);
yr=Integer.parseInt(day);
leap1=0;
if(mon>2)
leap1=leap(yr);
System.out.println("Enter the Day on 1st January in this year:");
str1=br.readLine().trim();
}
int leap(int p)
{
if(p%100==0 && p%400==0)
return 1;
else if(p%100!=0 && p%4==0)
return 1;
else
return 0;
}
void show ()
{
if (str1.equalsIgnoreCase("Sunday"))
x=1;
else if (str1.equalsIgnoreCase("Monday"))
x=2;
else if (str1.equalsIgnoreCase("Tuesday"))
x=3;
else if (str1.equalsIgnoreCase("Wednesday"))
x=4;
else if (str1.equalsIgnoreCase("Thursday"))
x=5;
else if (str1.equalsIgnoreCase("Friday"))
x=6;
else if (str1.equalsIgnoreCase("Saturday"))
x=7;
for(i=0;i< mon-1;i++)
dayno=dayno+arr[i];
dayno=dayno+leap1;
for(i=0;i< dayno-1;i++)
{
x++;
if(x==8)
x=1;
}


System.out.println(day1+ ":");
switch(x)
{
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
}
}
}


Here in this BlueJ program the array ‘arr’ holds the number of days of each month. ‘take()’ function takes the date and day name of 1st January of the specific year. It also breaks the date into day, month and year. If the month is greater than 2 ( Means minimum March), from the end of the body of the function it calls a function ‘leap()’. It returns ‘1’ if the year is leap year other wise returns ‘0’.

Within ‘show()’ function we initialize a variable ‘x’ with 1 if the day name is Sunday, 2 if the day name is Monday and so on. That means in our BlueJ program ‘x’ holds the day number of the 1st January of the specific year. Then using a for loop, count the total number of days from 1st January to the specified date and ‘x’ is utilized to hold the day number of the specific date.
.

Wednesday, November 17, 2010

Banking program using BlueJ

This is the Banking program on transaction.

About the program



Initially Name, Account Number, Account type ( Savings / Current etc) and Initial Balance are taken for number of clients from user.
Minimum balance amount is Rs. 500.
In case of transaction Account number, mode of transaction (withdrwal or deposit), amount are taken from user. If it is withdrwal checking is done whether the balance permits the transaction.

User can enter any Account number and the current status of the Account will be displayed.


import java.io.*;
class Bank
{
String name[],amount[],ac[],acno[],particulars[],tran[][];
/* 'name' to hold names, 'amount' will hold initial amount, 'ac' will hold type of account
( savings / current etc) and 'acno' will hold account number, 'tran' will hold the transactions
'particulars' will hold the details of trasaction */
double dep; String actype;
/* 'dep' will hold the transaction amount and 'actype' will hold account type */
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int index=0;
/* it will be the index of the above declared arrays */
int tranindex=0;
/* it will be used in the transaction array */
Bank()
{
name=new String[50];
tran=new String[50][6];
particulars=new String[50];
amount=new String[50];
ac=new String[50];
acno=new String[50];
}
void initial()throws IOException
{
int i;
String date1;
String op="Yes";
while(!op.equalsIgnoreCase("No"))
{
System.out.println("Date:");
date1=br.readLine().toUpperCase();
System.out.println("Name:");
name[index]=br.readLine().toUpperCase();
//particulars[index]="B/F";
System.out.println("A/c No.:");
acno[index]=br.readLine().trim();
System.out.println("Initial Amount:");
amount[index]=br.readLine().trim();
System.out.println("Which type of A/c -(Press 'S' for Savings,'C' for Current,'R' for Recurring,'F' for Fixed deposit):");
ac[index]=br.readLine().trim().toUpperCase();
tran[tranindex][0]=date1;
tran[tranindex][1]="B/F";
tran[tranindex][2]=acno[index];
tran[tranindex][3]="d";
tran[tranindex][4]=amount[index];
tran[tranindex][5]=amount[index];
tranindex++;
System.out.println("Any More(Yes/No:):");
op=br.readLine().trim();
index++;
}
}
void transaction()throws IOException
{
int i;
double amount1; String date1,dep1,account;
String pat;
/* 'amount1' will hold the transaction amount, 'date1' to hold the transaction date,'dep1' will hold mode of transaction, 'account' will hold account number
'pat' will hold the particulars */
System.out.println("Enter the transaction type(d for deposit/w for withdrawal):");
dep1=br.readLine().trim().toLowerCase();
System.out.println("Enter the amount:");
amount1=Double.parseDouble(br.readLine());
System.out.println("Enter the Particulars:");
pat=br.readLine().trim();
System.out.println("A/c No.:");
account=br.readLine().trim();
System.out.println("Date of transaction:");
date1=br.readLine().trim();
for( i=0;i
{
if(account.equals(acno[i]))
break;
}
if(i==index)
System.out.println("This A/c No.does not exist:");
else
{
if(dep1.equals("w"))
{
if(Double.parseDouble(amount[i])-amount1<500)
{
System.out.println("Insufficient Balance");
}
else
{
amount[i]=String.valueOf(Double.parseDouble(amount[i])-amount1);
tran[tranindex][0]=date1;
tran[tranindex][1]=pat;
tran[tranindex][2]=account;
tran[tranindex][3]="w";
tran[tranindex][4]=String.valueOf(amount1);
tran[tranindex][5]=String.valueOf(amount[i]);
tranindex++;
}
}
else if(dep1.equals("d"))
{
amount[i]=String.valueOf(Double.parseDouble(amount[i])+amount1);
tran[tranindex][0]=date1; // date of transaction
tran[tranindex][1]=pat;// particulars
tran[tranindex][2]=account;// account number
tran[tranindex][3]="d";// mode of transaction
tran[tranindex][4]=String.valueOf(amount1); // transaction amount
tran[tranindex][5]=String.valueOf(amount[i]);// balance
tranindex++;
}
}
}
void display(String s1)
{
int i,j;
for(i=0;i
{
if(s1.equals(acno[i]))
break;
}
if(i==index)
System.out.println("A/C No. does not exist:");
else
{
System.out.println("Name of the A/C holder="+name[i]);
System.out.println("A/c No.:"+s1);
System.out.println("A/c type:"+ac[i]);
System.out.println("Balance Rs:"+amount[i]);
System.out.println("*******************\n");
System.out.println("Date Particulars Withdrawn Deposited Balance\n");
for(j=0;j
{
if(s1.equals(tran[j][2]))
{
if(tran[j][1].equals("B/F"))
System.out.println(tran[j][0]+ " " + tran[j][1]+ " "+ tran[j][5]);
else if(tran[j][3].equals("w"))
System.out.println(tran[j][0]+ " " + tran[j][1]+ " "+tran[j][4]+" "+ tran[j][5]);
else if(tran[j][3].equals("d"))
System.out.println(tran[j][0]+ " " + tran[j][1]+ " "+tran[j][4]+" "+ tran[j][5]);
}
}

}
}
public static void main(String args[])throws IOException
{
String ans="yes";
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
Bank ob=new Bank();
ob.initial();
while(!ans.equalsIgnoreCase("No"))
{
ob.transaction();
System.out.println("Any More(Yes/No:):");
ans=br1.readLine().trim();
}
System.out.println("A/C Number to search:");
String s=br1.readLine().trim();
ob.display(s);
}
}

Saturday, November 13, 2010

Binary addition using BlueJ program

How to proceed in the binary addition program



This BlueJ program is on addition of two binary numbers. In this program, we will take two binary numbers in two string objects. The smaller string object will be stored on 'bin1' and the greater or same string object will be stored on 'bin2'. Here length of the strings are considered for smaller or greater strings.

Then characters from the end of both string objects are extracted and numeric addition is done on both of them. If the result exceeds 1, it will be reset on 0,1 will be carried forward and the result will be concatenated with another string object 'str'. Ultimately 'str' will be displayed from reverse direction..

import java.io.*;
class Blue
{
public static void main(String args[])throws IOException
{
Blue ob=new Blue();
ob.take();
}
public void take()throws IOException
{
String bin1,bin2;
int i,a,b,c,len1,len2,flag=0;
String str=" ",str1;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter 1st binary Number:");
bin1=br.readLine().trim();
System.out.println("Enter 2nd binary Number:");
bin2=br.readLine().trim();
if(bin1.length()>bin2.length())
{
str1=bin1;
bin1=bin2;
bin2=str1;
}
len1=bin1.length()-1;
len2=bin2.length()-1;
for(i=len1;i>=0;i--)
{
a=bin1.charAt(i)-48;
b=bin2.charAt(len2)-48;
len2--;
c=a+b+flag;
flag=0;
if(c>1)
{
c=0;
flag=1;
}
str=str+c;
}
if(len2==-1 && flag==1)
str=str+flag;
else
{
for(i=len2;i>=0;i--)
{
a=bin2.charAt(i)-48;
c=a+flag;
flag=0;
str=str+c;
}
}
str=str.trim();
len1=str.length()-1;
System.out.println("Sum of the binary numbers are:");
for(i=len1;i>=0;i--)
System.out.print(str.charAt(i));
}
}

Wednesday, October 27, 2010

File Handling in Java

The following program is on file handling in java. Names of several persons are to be written in a text file in the format name-middlename-surname. In case there is no middle name, record is entered as name and surname. Records are displayed as Middle name, Name and SurName. If there is no middle name then 'XX' is displayed in middle name part.

import java.io.*;
import java.util.*;
class BlueJx
{
public static void main(String args[]) throws IOException
{
byte barr[];
StringTokenizer stk;
String name,mname,sname;
int pos;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fout;
FileInputStream fin;
fout=new FileOutputStream("record.txt",true);
String str;
/*2nd argument true means the values will be appended in the file*/

System.out.println("Enter the Name with middle Name and Surname");
str=br.readLine();
str="*"+str;
barr=str.getBytes();
fout.write(barr);
// for reading
fin=new FileInputStream("record.txt");
pos=fin.available();
barr=new byte[pos];
System.out.println("\nRecords as follows\n");
fin.read(barr);
str=new String(barr);
stk=new StringTokenizer(str,"*");
while(stk.hasMoreTokens())
{
str=stk.nextToken();
pos=str.lastIndexOf(" ");
sname=str.substring(pos).trim();
str=str.substring(0,pos).trim();
pos=str.lastIndexOf(" ");
if(pos!=-1)
{
mname=str.substring(pos).trim();
name=str.substring(0,pos).trim();
}
else
{
mname="XX";
name=str;
}
System.out.println(mname + " "+ name+" "+ sname);
}
}
}

Friday, October 15, 2010

BlueJ Pattern

Using BlueJ print the pattern

12345678910
13579
14710
159
16
17
18
19
110
1


class BlueJx
{
public void show()
{
int j,x=1,y=0;
for(int i=0;i<10;i++)
{
x=1;
while(x<=10)
{
System.out.print(x);
x=x+y+1;
}
y=y+1;
System.out.println();
}
}
public static void main(String args[])
{
BlueJx ob=new BlueJx();
ob.show();
}
}


In this above program, 10 rows of numbers are printed. The numbers are generated with some interval. The interval starts with '0' and gradually increases by '1' after each increase in row. The maximum number in a row can be 10.

Thursday, October 14, 2010

Fibonacci numbers Using Recursive Function and its Algorithm

BlueJ program to display fibonacci numbers using recursive function.

import java.io.*;
class BlueJRecursive
{
public void show(int p,int c,int n)
{
int next;
if(n==0)
return;
next=p+c;
System.out.print(" "+next);
p=c;
c=next;
show(p,c,n-1);
}

public static void main(String args[])throws IOException
{
BlueJRecursive ob=new BlueJRecursive();
int p=0,c=1,n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of elements in the series:");
n=Integer.parseInt(br.readLine());
System.out.print("The Fibonacci series is= "+p+" "+c);
ob.show(p,c,n-2);
}
}


Algorithm of this program is as follows:

Step 1: Take variables ‘p’,’c’,’n’ of int type.
Step 2: Initialize ‘p’ with 0 and ‘c’ with 1.
Step 3: Take the number of elements in the series in ‘n’
Step 4: Display ‘p’ and ‘c’.
Step 5: Repeat upto Step 11 until ‘n’ becomes 0
Step 6: Assign the sum of ‘p’ and ‘c’ on another variable ‘next’
Step 7: Display next
Step 8: Assign the value of ‘c’ on ‘p’
Step 9: Assign the values of ‘next’ on ‘c’
Step 10: Reduce ‘n’ by 1
Step 11: Again go to Step 5.

Tuesday, October 12, 2010

Lots of pattern programs in BlueJ

Program in BlueJ using nested loop to print the following Pattern.

-----------1234567--------
------------23456--------
-------------345----------
--------------4-----------
-------------345----------
------------23456---------
-----------1234567---------



class BlueJx
{
public void show()
{
int j,x;
for(int i=0;i< 4;i++)
{
x=1;
for(j=0;j< i;j++)
{
x++;
System.out.print(" ");
}
for(int k=i+j;k< 7;k++)
System.out.print(x++);
System.out.println();
}
for(int i=0;i< 3;i++)
{
x=1;
for(j=i;j< 2;j++)
{
x++;
System.out.print(" ");
}
for(int k=0;k< 3+i*j;k++)
System.out.print(x++);
System.out.println();
}
}
}


Write Program in BlueJ using nested loop to print the following Pattern

.

------------1--------
-----------2_2-------
----------3_3_3------
---------4_4_4_4------
--------5_5_5_5_5-----
---------4_4_4_4------
----------3_3_3-------
-----------2_2--------
------------1----------


class BlueJx
{
public void show()
{
int j,x=1;
for(int i=1;i< =5;i++)
{
for(j=1;j< =5-i;j++)
{
System.out.print(" ");
}
for(int k=0;k< x;k++)
{
if(k%2==0)
System.out.print(i);
else
System.out.print(" ");
}
System.out.println();
x=x+2;
}

x=1;
for(int i=4;i >=1;i--)
{
for(j=i;j< =4;j++)
{
System.out.print(" ");
}
for(int k=0;k< =7-x;k++)
{
if(k%2==0)
System.out.print(i);
else
System.out.print(" ");
}
System.out.println();
x=x+2;
}

}
}

In the above program, two separate outer loops are used. For the first outer loop, again two inner loops are used. First inner loop prints the left side spaces and the second inner loop prints the values. The outer loop continues upto the line 5 5 5 5 5 5 …
With the iteration of the outer loop the iteration of the loop printing the space of the pattern is decreased and iteration of the loop printing the digits is increased.

This is just the reverse for the second loop.

Another pattern printing program in BlueJ



--------------1----------
-------------333---------
------------55555--------
-----------7777777-------
----------999999999------
-----------7777777-------
------------55555--------
-------------333---------
--------------1----------



class BlueJx
{
public void show()
{
int j,x=1;
for(int i=1;i< =5;i++)
{

for(j=1;j< =5-i;j++)
{

System.out.print(" ");
}
for(int k=0;k< x;k++)
{
System.out.print(x);

}
System.out.println();
x=x+2;
}

x=x-4;
for(int i=4;i >=1;i--)
{
for(j=i;j< =4;j++)
{
System.out.print(" ");
}
for(int k=0;k< x;k++)
{
System.out.print(x);
}
System.out.println();
x=x-2;
}

}
}

Program to print the following pattern.

6
6 12
6 12 18
6 12 18 24

The codes of the above pattern are as follows

class BlueJx
{
public void show(int n)
{
int j,x;
for(int i=0;i< n;i++)
{
x=6;
for(j=0;j< =i;j++)
{

System.out.print(" "+x);
x=x+6;
}
System.out.println();
}
}
}

Sunday, October 10, 2010

Few programs in BlueJ

Program to print prime numbers



class BlueJ
{
public void show()
{
System.out.println("\nPrime numbers between 2 and 100 are as follows:");
for( int i=2;i< =100;i++)
{
if(prime(i))
System.out.print(" " + i);
}
}
public 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;
}
}

Display largest odd and even number from a list




import java.io.*;
class BlueJ1
{
int arr[],n,max,min;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeData()throws IOException
{
System.out.println("\nEnter the number of values to be stored:");
n=Integer.parseInt(br.readLine());
arr=new int[n];
for( int i=0;i< n;i++)
{
System.out.print("Enter value: " );
arr[i]=Integer.parseInt(br.readLine());
}
}
public void show()
{
max=1;
min=2;
for(int i=0;i< n;i++)
{
if(arr[i]%2==0 && max==1)
max=arr[i];
else if(arr[i]%2!=0 && min==2)
min=arr[i];
else if(arr[i]%2==0 && arr[i]>max)
max=arr[i];
else if(arr[i]%2!=0 && arr[i] < min)
min=arr[i];
}
System.out.println("Minimum odd Number="+min);
System.out.println("Maximum even Number="+max);
}
}

Write program in BlueJ to display the prime palindromes



class BlueJ2
{
public void show()
{
System.out.println("The numbers which are prime and palindrome are:");
for( int i=100;i< =500;i++)
{
if(palin(i) && prime(i))
System.out.print(i+ " " );
}
}
public 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 boolean palin(int n)
{
int r=0;
for(int i=n;i >0;i=i/10)
{
r=r*10+i%10;
}
if(r==n)
return true;
else
return false;
}
}


Write program in BlueJ to print the multiplication table from 11-15




class BlueJ3
{
public void show()
{
System.out.println("The Multiplication Table from 11 to 15 as follows:");
for( int i=11;i< =15;i++)
{
for(int j=1;j< =10;j++)
{
System.out.print(i*j+ " " );
}
System.out.println();
}
}
}

Sunday, October 3, 2010

Few programs on Pattern in BlueJ

Program: Find the sum of the following series using BlueJ.

x/2!+x/4!+x/6!+....n terms



class BlueJS
{
public void show(int x,int n)
{
double sum=0;
int f;
for(int i=2; i<=n; i=i+2)
{
f=fact(i);
sum=sum+(double)x/f;
}
System.out.println("Sum of the series=" + sum);
}

int fact(int n)
{
int f=1;
for( int i=2 ; i<= n; i++)
{
f=f*i;
}
return f;
}
}





Display the pattern using BlueJ program.


1
333
55555
7777777
999999999
7777777
55555
333
1


class BlueJS
{
public void show()
{
int x=1;
for(int i=0; i< 5; i++)
{
for(int j=0; j< i*2+1; j++)
{
System.out.print( x );
}
x=x+2;
System.out.println ( );
}
x=x-4;
for(int i=0; i< 4; i++)
{
for(int j=0; j< 7 - i*2; j++)
{
System.out.print( x );
}
x=x-2;
System.out.println ( );
}
}
}



Display the pattern using BlueJ program.


1
2_2
3_3_3
4_4_4_4
5_5_5_5_5
4_4_4_4
3_3_3
2_2
1




class BlueJS
{
public void show()
{
int x=1;
for(int i=0; i< 5; i++)
{
for(int j=0; j< i*2+1; j++)
{
if(j%2==0)
System.out.print( x );
else
System.out.print(" ");

}
x=x+1;
System.out.println ( );
}
x=x-2;
for(int i=0; i< 4; i++)
{
for(int j=0; j< 7 - i*2; j++)
{
if(j%2==0)
System.out.print( x );
else
System.out.print(" ");

}
x=x-1;
System.out.println ( );
}
}
}

Monday, September 27, 2010

Few fundamental question answers in ICSE BlueJ

Define an object



Object is the instance of a class. Class is the template and object is the real entity which can be used to perform specific type of jobs as defined in the class. An object consists of data members and function / method members. Data member hold values and function members of the object acts on the data members.
Data members may be of primitive type variables or objects of other predefined classes.

What is a method?



Method or function means statement or statements kept within a block. In java block is defined by curly braces [{…}]. A name is assigned to the block which is known as function name. The name must start with any alphabet and by convention, function name starts with lower case character. A function should have a return type which indicates what type of values the function should return to the calling program while invoked. If a function does not return any value, its return type should be ‘void’. The return type may be any primitive type or user defined type, i.e. class. The function name is followed by parenthesis which is known as argument or parameter zone which is utilized to pass values to the function from outside. If a function is defined in such a way that it does not take any value or argument from outside, a blank parenthesis is a must. Function body is executed while invoked. Functions of an object actually define the behaviour of an object.

Can there be objects without having any methods?



We can define a class without methods also. In such case the data members should be either declared with public specifier or default specifier as they are to be accessed from outside the class.
e.g.

class BlueJ
{
int height,width,length;
}


Why are methods so important for the description of objects?



As per encapsulation, methods or functions hide the data members from unauthorized access and it is the methods which manipulates the data members of an object. Normally an object contains number of methods which acts on its data members. Each function is normally assigned different jobs. This concept reduces the complexity of a program and the same time reduces the space complexity of a program.

Simply think about your mobile set. It has number of functions and without knowing the complex working of the functions we simply invoke functions get the desired result.

What is a class?



Class can be defined as user defined new data type. Every programming language has number of predefined types which are known as primitive data types. Data types define the nature and behavious of its instance. For example, a declaration ‘int a;’ denotes that ‘a’ is the instance of the predefined type ‘int’ and ‘int’ defines that ‘a’ can hold whole number of a specific range and different operators like ‘+’,’-‘ etc can act on this variable.
Similarly by defining a class we can create a new type with specific nature and behaviour. After defining the class we can create instance of a class which is known as object.

What is an abstraction?



In program language, abstraction means managing complexity without going in details of any working. In real life also we perform lot of work through abstraction. For example a driver drives the car through abstraction. Using the brake, he can stop the car. The complex gearing arrangement behind this operation is unknown to him.
Similarly in programming language, we can work with a predefined object without knowing the details of its methods and data members. We should know how the methods of the object can be invoked and what would be the result. This is called abstraction.

Can there be multiple abstractions of a real world entity



In real life there is lot of examples on abstraction. During fever we take medicine without knowing how this medicine will work. We operate our television set using the remote without knowing how a simple press on remote button changes the channel.

How are classes and abstraction linked?



In every class, number of methods is defined. These methods use number of data members and act on these data members. While using any object of a predefined class, we simply invoke methods of the object to get our work done without knowing the detail operation of the method. This is abstraction. For example while calling ‘print()’ or ‘println()’ method we know that it will display the argument as a string but the codes executed by these methods to perform the job is not known to us.

What is an object factory?



Class is known as object factory, as after defining any class we can create number of instances of that class. These instances are known as objects. Objects are created following the nature and behaviour defined by the class.

Tuesday, September 7, 2010

Application of user defined functions in BlueJ programs - part II

In this post I will try to show how we can utilize our own defined functions to manage the program effectively. In every program we call different predefined or library class functions from the body of another function. Here in the following programs of today’s post I will call different own defined functions from the body of another own defined function. This technique helps to organize the program is a better shape.

Program is to check whether a number is palprime number or not



A palprime number is a number which is a prime number and at the same time a palindrome.


class palprime
{
public void show(int n)
{
if(prime(n) && palin(n))
System.out.println("the number is palprime");
else
System.out.println("the number is not palprime");
}
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;
}

boolean palin(int n)
{
int x;
int rev=0;
for(int i=n;i >0;i=i/10)
{
x=i%10;
rev=rev * 10 + x;
}
if(rev==n)
return true;
else
return false;
}

public static void main(String args[])
{
palprime ob=new palprime();
ob.show(195);
}
}

Brief stydy of the functions of the program



We can reat ‘public void show(int n)’ as the pivot function in this program. User will call this function with value and this function in tern call two other user defined functions, ‘boolean prime(int n)’ and ‘boolean palin(int n)’ and pass the value to the function argument. Both are return type functions and return boolean value. The functions checks whether the number is prime and palindrome recpectively and return boolean value accordingly.

Programs to check the prime factors of a number



In this program also I have defined two functions to display the result. The codes of the program are as follows:-

class PrimeFactors
{
public void show(int n)
{
for(int i=1;i< n;i++)
{
if(n%i==0 && prime(i))
System.out.println(i);
}
}
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[])
{
PrimeFactors ob=new PrimeFactors();
ob.show(195);
}
}

Brief stydy of the user defined functions of the program



Initially the number is passed as argument to the function ‘public void show(int n)’. This function genarates the factors and pass the factor as argument to another boolean return type function ‘boolean prime(int n)’ which checks whther the argument value is prime of not.

Programs to display twin prime numbers within a specified range



Twin prime numbers means two consecutive prime numbers with a gap of 1.

class TwinPrime
{
public void show(int n,int m)
{
for(int i=n;i< =m-2;i++)
{
if(prime(i) && prime(i + 2))
System.out.println(i +" "+(i + 2));
}
}
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[])
{
TwinPrime ob=new TwinPrime();
ob.show(10,159);
}
}

Functions of the program


‘public void show (int n,int m)’ function is the pivotal function of this program. The range is passed to the function and it displays the twin prime numbers within the range. ‘boolean prime (int n)’ is another defined function in this program which is called from the show function twice on each iteration of the loop inside show() function. The values passed as argument are consecutive values with a gap of 1 and from the return value of the prime () function it is decided whether the numbers are twin prime or not.

Friday, September 3, 2010

BlueJ program on combination of digits

Here is a BlueJ program which displays the different combination of 3 digits - 1,2 and 3.
The combination of the digits will be 123,132,213,231,312,321

class BlueJP
{

public void show()
{

int i, x=1,y=2,z=3,t,n=3,j;

for (i=1; i<=n; i++)
{

t=x;
x=y;
y=z;
z=t;

for(j=1;j
{
t=y;
y=z;
z=t;
System.out.println( x+ y+ z);
}
}

}
}

Friday, August 27, 2010

BlueJ Program on rearranging the words of a text in reverse order

Here is a string program on which changes the position of the words but not the alphabets. Details of the program are given below.


The input here 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, new line). Your task is to print the words of the text in reverse order without a punctuation mark 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 sample a is This’.
That is, the lines are printed in reverse order. Note: Individual words are not reversed. 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 80 characters.


import java.io.*;
import java.util.*;
class ReverseSentence
{
String str;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stk;
String arr[]=new String[60];
int index=0;
String s1;
public void take() throws IOException
{

System.out.println("Enter the sentence:");
str=br.readLine();
str=str.substring(0,str.length()-1);

stk=new StringTokenizer(str);

while(stk.hasMoreTokens())
{
s1=stk.nextToken();
if((s1.charAt(s1.length()-1)>=65 && s1.charAt(s1.length()-1)<=90)||(s1.charAt(s1.length()-1)>=97 && s1.charAt(s1.length()-1)<=122))

arr[index++]=s1;
else
arr[index++]=s1.substring(0,s1.length()-1);
}
str=" ";
for(int i=index-1;i>=0;i--)
{
str=str+ arr[i]+" ";
}
str=str.trim();
str=str+".";
}
public void display()
{
System.out.println("Output="+str);
}
public static void main(String args[]) throws IOException
{
ReverseSentence ss=new ReverseSentence();
ss.take();
ss.display();
}
}

Variable description of the program



String str – Initial text is stored in this string objecty.
BufferedReader br – Used to take input from user.
StringTokenizer stk – break the input text into tokens.
String arr[] – The words of the text are stored here.
int index= - index of the string array.

Brief study of the program



This program is little bit simple one. The input text is broken into words using StringTokenizer class. The punctuations of the text are eliminated from the words and ultimately they are stored in a string array.
The values are accessed from the end location of the array and are concatenated in another string object and displayed as a text with the words reversed.

BlueJ program on String array - arranging the words in ascending order

Today’s program is on string manipulation. This type of program is very much essential for ISC students. In practical examination of ISC Computer Science every year, programs on string manipulation using string array object is a common feature.

Here is the program on string array



Accept a paragraph of text consisting of sentences that are terminated
by either “.”, “,”, “!” or a “?” followed by a space. Assume that there can be a maximum of 05 sentences in a paragraph.
Design a program to perform the following :
(a) Arrange the sentences in alphabetical order of words, sentence by sentence.
(b) Separate the words which begin with a vowel.
Sample data 1:
INPUT: HELLO ! HOW ARE YOU ? WHEN ARE YOU COMING ? HOPE TO SEE YOU SOON.
OUTPUT: HELLO ! ARE HOW YOU ? ARE COMING WHEN YOU ? HOPE SEE SOON TO YOU.
VOWELS: ARE
Sample data 2 :
INPUT : THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.
OUTPUT : BROWN DOG FOX JUMPED LAZY OVER QUICK THE THE.
VOWELS: OVER


Here are the codes of the string array program




import java.io.*;
import java.util.*;
class String1
{
String str,str3;
BufferedReader br;
StringTokenizer stk;
String str1[];
String str2[];
String vowel[];
int i,j,k,len,x=0,y=0,z=0;
String1()
{
str1=new String [10];
str2=new String [10];
vowel=new String [200];
br=new BufferedReader(new InputStreamReader(System.in));
}
public void take()throws IOException
{
System.out.println("Enter the paragraph of sentences:");
str=br.readLine();
str=str.substring(0,str.length()-1);
stk=new StringTokenizer(str,"!?",true);
while(stk.hasMoreTokens())
{
str1[x++]=stk.nextToken();
}
for(i=0;i< x;i++)
{
str=str1[i];
stk=new StringTokenizer(str," ");
y=0;
while(stk.hasMoreTokens())
{
str2[y++]=stk.nextToken();
}

for(j=0;j< y-1;j++)
{
for(k=j+1;k< y;k++)
{
if(str2[j].compareTo(str2[k])>0)
{
str3=str2[j];
str2[j]=str2[k];
str2[k]=str3;
}
}
}
for(j=0;j< y;j++)
{
vowel[z++]=str2[j];
System.out.print(" "+str2[j]);
}

y=0;
}
System.out.println(".");
System.out.println("\nVowels:");
for(j=0;j< z;j++)
{
str=vowel[j].trim().toUpperCase();
if(str.charAt(0)=='A' ||str.charAt(0)=='E' ||str.charAt(0)=='I' ||str.charAt(0)=='O' ||str.charAt(0)=='U')
System.out.print(vowel[j]+" ");
}
}
public static void main(String args[])throws IOException
{
String1 ob=new String1();
ob.take();
}
}


Brief study of the program



The paragraph is entered in a string object firstly. StringTokenizer class is used in this program to break the text into tokens in respect of punctuations as it is given in the program that paragraph is to be broken into sentences in respect of punctuation and stored in a string array object ‘str1’. This step ensures that all sentences are stored in the string array. Next step is to break the sentences again in words and stored in another string array ‘str2’. These words are then sorted in ascending order and displayed. Another very interesting job is performed here, all the words of ‘str2’ are stored in the third string array ‘vowel’ from which words starting with vowels will be searched. This step is required as values of the string array ‘str2’ will be changed every time a new sentence from the string array ‘str1’ is broken into words.

Sunday, August 15, 2010

BlueJ program on validation of date

BlueJ Program to verify the correctness of date



Write program which inputs a date in six digit number format i.e. 141296 . Test the validation of the date and print the date in full form . If date is invalid then print a message as “ Invalid Date“
1. Example :
INPUT : 141296
OUTPUT : 14th December , 96
: VALID DATE
2. Example :
INPUT : 230488
OUTPUT : 23rd April , 88
: VALID DATE
3. Example :
INPUT : 300284
OUTPUT : INVALID DATE


import java.io.*;
class NumToWord
{

public void show() throws IOException
{
int flag,leap,i,num,mon1,day1,year1;
int dpm[]={31,28,31,30,31,30,31,31,30,31,30,31};
leap=0;
flag=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
clrscr();
System.out.println("\nInput:");
num=Integer.parseInt(br.readLine());
year1=num%100;
num=num/100;
mon1=num%100;
num=num/100;
day1=num;
if(year1%100==0 && year1%400==0)
leap=1;
else if(year1%100!=0 && year1%4==0)
leap=1;
if(mon1==2 && leap==1 && dpm[mon1-1]>28)
flag=1;
else if(mon1==2 && leap==0 && dpm[mon1-1]>28)
flag=1;
else if(day1>dpm[mon1-1])
flag=1;

if(flag==1)
{
System.out.println("\nInvalid Date...");
return;
}
leap=day1%10;
System.out.println("\nOUTPUT: "+ day1);
switch(leap)
{
case 0:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.print(" th");
break;
case 1:
System.out.print(" st");
break;
case 2:
System.out.print(" nd");
break;
case 3:
System.out.print(" rd");
break;
}

switch(mon1)
{
case 1:
System.out.print(" January,");
break;
case 2:
System.out.print(" February,");
break;
case 3:
System.out.print(" March,");
break;
case 4:
System.out.print(" April,");
break;
case 5:
System.out.print(" May,");
break;
case 6:
System.out.print(" June,");
break;
case 7:
System.out.print(" July,");
break;
case 8:
System.out.print(" August,");
break;
case 9:
System.out.print(" September,");
break;
case 10:
System.out.print(" October,");
break;
case 11:
System.out.print(" November,");
break;
case 12:
System.out.print(" December,");
break;
}
System.out.print(year1);

}
}

Brief study of the Program



In this above program user has to enter the date in ‘ddmmyyyy’ format from which date, month and year are separated. The first checking point is whether the year is leap year or not. Total number of days of each month is stored in a one dimensional array and from there validation of date is confirmed using else if ladder.

After the validation job, it is displayed in proper format using switch statement. Another switch statement is used in this program to display the month name. Year number is displayed at the end.

Thursday, August 12, 2010

Sample paper on BlueJ

Sample question and answer on BlueJ



1. Write any two rules for naming variable.

Variable names must start with alphabet and keywords can not be used in variable names. These are two rules for naming variable.

2.Write any two differences in Implicit Type Casting and Explicit Type Casting.

In implicit type casting, variables of different types are converted into one type if they are used in any expression where as in explicit casting, variables of one type are to be converted to other type using coding.

3. Write a main difference between while loop and do while loop in BlueJ.

While loop is an entry controlled loop where do while is an exit control loop. This is the main difference between while and do-while loop.

4. Give an example of conditional operator.
If (a>b)
{
max=a;
}
else
{
max=b;
}

This above statement can be written as
max=(a>b)?a:b;


5. Read the following program and answer the given questions :
class demo{
public void main( ) {
int a,b,i,j;
for(i=1;i<5;i=i+1)
{
for(j=1;j<=I;j=j+1)
{
System.out.print(“ “+j);
}
System.out.println( );
}}}
( i ) How many times the first loop of i will perform? Ans: 4 times (ii) How many times the first print statement work ? Ans: 10 times
(iii) What will be the output of program ?

Output would be like:
1
1 2
1 2 3
1 2 3 4

6. Write the output of following statements :

class output
{
public void fmn( )
{
int a=12,b=10;
System.out.println (“a++=”+a++);
System.out.println (“a>b=”+a>b);
System.out.println (“++a=”+++a);
System.out.println (“--a=”+--a);
System.out.println (“a!=(a+b)=”+a!=(a+b));
}
}

Ans: a++=12
a>b=true
++a=14
--a=13
a!=(a+b)=true


7.Find the errors if any in the following program :

class 12design
{
public void mn ()
{
byte 1a=10;
int b=20;
int c=a>b?a,b;
System.out.println(‘The value of c is :’+c);
}
}

Ans: Class name should start with alphabet, so class name 12design will generate compile time error.
byte 1a; variable name must start with alphabet.
int c=a>b?a,b; this should be int c=a>b?a:b;
The value of c is: should be kept within “ “.

8. Explain the bubble sort technique in array with an example.

Bubble sort technique compares consecutive values and if necessary exchange the values between them. In every pass it starts from the first location (starting index of the array) . This technique arranges the values from the last location, so on every pass it reduces the checking from right end. The main advantage of this sorting process is that if no exchange is found in any pass, the process is terminated.

Suppose the values in an array of size 5 are as follows:
4 2 3 66 5 and we want to arrange them ascending orer.
In the first pass
array[0]>array[1] exchange. Now the array is 2 4 3 66 5
array[1]>array[2] No exchange
array[2]>array[3] No exchange
array[3]>array[4] exchange. Now the array is 2 4 3 5 66
This is the end of first pass and the highest value is set in the last location. In the second pass array[3] and array[4] will not be compared.

In the start of second pass the array is 2 4 3 5 66
array[0]>array[1] No exchange
array[1]>array[2] exchange. Now the array is 2 3 4 5 66
array[2]>array[3] No exchange
End of second pass and the array is now 2 3 4 5 66

Third pass
array[0]>array[1] No exchange
array[1]>array[2] No exchange
End of third pass and as there is no exchange, the process is terminated.

Thursday, August 5, 2010

User defined function in BlueJ programs - Part I

What is function



Function means a block where number of statement(s) are kept. These statement(s) are to be executed when required. In structured programming, a program is divided into different modules. Another reason of using functions in a program is to reduce the size of the program. In programs there may be situations when same set of statements will be required to be executed in different parts of the same program. In such case create, a function with the statements. In BlueJ and other Object oriented programming languages, user defined function is a must.

In Icse and Isc computer applications question papers, you will find BlueJ programs to write with using specific user defined functions as written in question paper. You have to do the program with the guide line provided. So a clear concept on user defined function is very much needed for students.

Components of a function



1.Function name (user defined)—Function should have a name.

2.Return type of the function (should be placed before the function name)– function which returns value must have a return type equivalent to the type of value returned (e.g. int, float etc). If a function does not return any value then it’s return type should be void.

3.parentheses [()] follow the function name. Functions can take values or arguments when invoked .If a function takes any argument then it must be declared inside the parentheses.

Two steps required for function



1. Function definition – next comes the function definition. The function definition of the above declared functions would look like: -
void add ()
{
From this point the function body starts
The statement(s), which form the unit
Should be placed within this body
} Function body ends here.

Note that there is no semicolon after void add (). In case of function definition there should be no semicolon. A function definition must have a function body and inside the body the function statements should be placed. In BlueJ programs, sometimes we have to define a function with empty body, means no statement inside the function body. In such case also we have to define the block of function body. On calling the function the statements will be executed. void main () is an example of function definition.

2.Calling the function – To execute the statements of a function body, the function is to be called. At the time of calling a function no return type should be used. Suppose we want to call the previously defined function then the syntax should be: - add ();

In BlueJ programs, we normally define function and call function. Declaring a function in BlueJ means something different. In such case, the class would be abstract class. In inheritance we will discuss it abstract class in details. Where as in C Language and C++ programs we can declare functions in normal situation.

Saturday, July 31, 2010

For the beginners in BlueJ

I got one comment on this site from one visitor that he wants to learn BlueJ and his query is - from where to start and how to start. For those who don’t have any previous knowledge of language and want to learn BlueJ through this site from the beginning are advised to go through my other site on C Language. C Language is the mother language of any modern programming language. Java is object oriented programming, so before starting java one should have knowledge on variables, array, structure and user defined function very clearly. In C Language we have the scope to learn the necessity of array and ultimately necessity of structure. Actually structure is the platform of object oriented program. Then comes function, user defined functions. In BlueJ we have to define our own functions in each and every program. So without a clear cut conception on user defined function, one cann’t apply it in BlueJ perfectly.

So, my advice to the beginners, please go through C Language first, Find out the advantages of structure in C language. Then find out the limitations of structure, for these limitations object oriented programming languages are developed.

Try to have a clear idea about user defined function. In BlueJ you have to juggle with functions.

Happy Journey through C.

Friday, July 30, 2010

Program on Pattern

Few days back I got one comment to design a pattern using program that will will looks like:

7654321
66
55
44
33
22
11

I forgot to publish the comment. Anyway here is the codings of the program.

class BlueJ
{
int i,j,x;
public void show()
{
x=7;
for(i=0;i<7;i++)
{
for( j=0;j<7;j++)
{
System.out.print(x+" ");
if (i==0)
x--;
else if(i!=0 && j==1)
break;

}
System.out.println();
x=7-i-1;
}
}
}

Wednesday, July 21, 2010

2 d or Two-Dimensional arrays in BlueJ

2 d array plays a vital role in computer programs. Many type of programs needs 2 d array. In my previous post I have given few programs. This is a continuation of 2 d array programs.

BlueJ program on Marks-sheet of students using 2 d array



The annual examination results of 10 students are tabulated as follows
Roll No. sub1 sub2 sub3
--------------------------------
Write program to read data and determine the following
1. Total marks obtain by each student
2. The highest marks in each subject with Roll number
3. The student who obtained the highest total marks

import java.io.*;
class Student

{
int result[][]=new int[10][5];
int i,j,k,total,maxr,maxm;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeData() throws IOException
{

for(i=0;i< 10;i++)
{
total=0;
for(j=0;j< 4;j++)
{
if(j==0)
System.out.println("Enter Roll number\t");
else if(j==1)
System.out.println ("Enter 1st subject marks\t");
else if(j==2)
System.out.println ("Enter 2nd subject marks\t");
else if(j==3)
System.out.println ("Enter 3rd subject marks\t");
result[i][j]=Integer.parseInt(br.readLine());
if(j!=0)
total+=result[i][j];
}
result[i][j]=total;
}
}
public void showResult()
{

System.out.println ("Mark sheet");
System.out.println ("\nRoll 1st 2nd 3rd Total");
for(i=0;i<10;i++)
{
for(j=0;j< 5;j++)
{
System.out.println (" "+result[i][j]);
}
System.out.println ();
}
System.out.println (“\n\n”);
System.out.println ("Roll number with total");
printf("\nRoll Total");
for(i=0;i<10;i++)
{
for(j=0;j<5;j++)
{
if((j==0)||(j==4))
System.out.println (" “+result[i][j]);
}
System.out.println ();
}
for(i=1;i< 4;i++)
{
for(j=0;j< 10;j++)
{
if(j==0)
{
maxm=result[j][i];
maxr=result[j][0];
}
else if(result[j][i]>maxm)
{
maxm=result[j][i];
maxr=result[j][0];
}
}
if(i==1)
System.out.println ("\nMaximum marks in sub1 is :”+maxm + “ “+maxr);
else if(i==2)
System.out.println ("\nMaximum marks in sub2 is :”+maxm + “ “+maxr);
else if(i==3)
System.out.println ("\nMaximum marks in sub3 is :”+maxm + “ “+maxr);

}
for(i=0;i< 10;i++)
{
for(j=0;j< 5;j++)
{
if(j==4)
{
if(i==0)
{
maxm=result[i][j];
maxr=result[i][0];
}
else if(result[i][j]>maxm)
{
maxm=result[i][j];
maxr=result[i][0];
}
}
}
}
System.out.println ("\nMaximum total is :”+maxm + “ “+maxr);
}
}

Program on sparse matrix



Write program to display a 5 by 5 array with the following output
Upper left traingle with +1
Lower left traingle with -1
Right to left diagonal with 0

class Arr

{
int result[][]=new int[5][5];
int i,j;
public void show()
{

for(i=0;i< 5;i++)
{
for(j=0;j< 5;j++)
{
if(i+j==4)
result[i][j]=0;
else if(i+j<4)
result[i][j]=1;
else
result[i][j]=-1;
}
}
for(i=0;i< 5;i++)
{
for(j=0;j< 5;j++)
{
System.out.print(" "+result[i][j]);
}
System.out.print ();
}
}
}

Tuesday, July 13, 2010

Two dimensional or 2 d array in BlueJ programs

What is 2 d array



2 d array is actually array of arrays. To declare a 2 d array variable, specify each additional index using another set of square brackets. For example, to create a 2 d integer array named arr, the syntax is:int arr [][]=new int[x][y]; Unlike C Programming Language , Java arrays are dynamic.

This means that an array of size 'x' will be created, while within each index there will be another array of size 'y'.

Consider the following program on 2 d array:-

Marks obtained in three subjects by three students is

Roll no. 1
Math 78
Physics 65
Chemistry 60

Roll no. 2
Math 87
Physics 56
Chemistry 65


Roll no. 3
Math 77
Physics 78
Chemistry 70

If we were asked to store the marks obtained by Roll no.1, then we can simply create an one dimensional array of size 4. Then the Roll no and three subject marks can be stored in the array variable. But here the case is different. We have to store the values in the tabular form in a variable. Here comes the utility of two-dimensional array. We have to declare a 3 by 4 array.

2 d array program on students marks



import java.io.*;
class Arr
{
int result [][]=new int[3][4];
int i, j;
BufferedReader br=new BufferedReader(new InputStreamReader(Systm.in));
public void take() throws IOException
{
for (i=0;i<3;i++)
{
j=0;
System.out.println ("Enter the Roll number:-");
result [i][j]=Integer.parseInt(br.readLine());
for (j=1;j<4;j++)
{
System.out.println ("Enter the marks of subject no “ + j + “:”);
result [i][j]=Integer.parseInt(br.readLine());

}
}

System.out.println ("The stored values are:");
for (i=0;i<3;i++)
{
for (j=0;j<4;j++)
{
System.out.println (" "+ result [i][j]);
}
System.out.println();
}
}
}


2 d array program on temperature of number of cities for number of days



The daily maximum temperature of 4 cities for 5 dates are recorded during the month of January. Write a program to find the day and city corresponding to @. highest temperature and @. lowest temperature


import java.io.*;
class Arr
{
int temp [][]=new int[5][4];
int i, j;
BufferedReader br=new BufferedReader(new InputStreamReader(Systm.in));
int maxc,minc,maxd,mind,maxt,mint,i,j;
public void take() throws IOException
{

for(i=0;i<5;i++)
{
for(j=0;j<4;j++)
{
if(j==0)
System.out.println ("Enter temp. of Calcutta on “ + (i+1) + “ January:”);
else if(j==1)
System.out.println ("Enter temp. of Chennai on “ + (i+1) + “ January:”);
else if(j==2)
System.out.println ("Enter temp. of Mumbai on “ + (i+1) + “ January:”);

else if(j==3)
System.out.println ("Enter temp. for Delhi on “ + (i+1) + “ January:”);
temp [i][j]=Integer.parseInt(br.readLine());

}
}
System.out.println ("The recorded temperature:-");
System.out.println ("Calcutta Madras Mumbai Delhi");
for(i=0;i<5;i++)
{
for(j=0;j<4;j++)
{
System.out.println (" ",temp[i][j]);
}
System.out.println ();
}
System.out.println ("**************");
for(i=0;i<5;i++)
{
for(j=0;j<4;j++)
{
if((i==0)&&(j==0))
{
maxt=temp[i][j];
maxd=i;
maxc=j;
mint=temp[i][j];
mind=i;
minc=j;
}
else
{
if(maxt
{
maxt=temp[i][j];
maxd=i+1;
maxc=j+1;
}
if(mint>temp[i][j])
{
mint=temp[i][j];
mind=i+1;
minc=j+1;
}
}
}
}
System.out.println ("The maximum temperature is :" + maxt);
System.out.println ("And the corresponding date is :"+ maxd);
System.out.println ("City number: "+ maxc);
System.out.println ("The minimum temperature is :" + mint);
System.out.println ("And the corresponding date is: " + mind);
System.out.println ("City number: " +minc);
}
}

Sunday, July 4, 2010

BlueJ numeric array programs

This is a continuation of array in BlueJ for ICSE Schools.

Program on voting using array in BlueJ



An election is contested by 5 candidates numbered from 1 to 5 and the voting is done by marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast for each candidate using an array variable count. In case the number read is outside the range 1 to 5 , the ballot should be considered as 'spoilt ballot' and the program should also count the number of spoilt ballots

import java.io.*;
class Arr
{
int count[] =new int[1000];
int one,two,three,four,five,spoilt,n,i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void takeDate() throws IOException
{

one=two=three=four=five=spoilt=0;
System.out.println("Enter the number of voters\t");
n=Integer.parseInt(br.readLine());
for(i=0;i < n;i++)
{
System.out.println ("Choice\t");
count[i]=Integer.parseInt(br.readLine());
}
for(i=0;i < n;i++)
{
if(count[i]==1)
one++;
else if(count[i]==2)
two++;
else if(count[i]==3)
three++;
else if(count[i]==4)
four++;
else if(count[i]==5)
five++;
else
spoilt++;
}
System.out.println ("\nNumber of votes for first candidate\t%d",one);
System.out.println ("\nNumber of votes for second candidate\t%d",two);
System.out.println ("\nNumber of votes for third candidate\t%d",three);
System.out.println ("\nNumber of votes for 4rth candidate\t%d",four);
System.out.println ("\nNumber of votes for 5th candidate\t%d",five);
System.out.println ("\nNumber of spoilt ballot\t%d",spoilt);
}
}

Program on merging two arrays in a single array



Given two one-dimensional array A and B which are sorted in accending order. Write program on BlueJ to merge them into a single sorted array C that contains every elements of A and B

class Arr
{
int A[]={1,5,7,9,80},B[]={3,6,8,10,14},C[]=new int[10];
int i,j,x=0,t;
public void show()
{
for(i=0;i<5;i++)
{
C[x]=A[i];
x++;
}
for(i=0;i<5;i++)
{
C[x]=B[i];
x++;
}
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(C[i]>C[j])
{
t=C[i];
C[i]=C[j];
C[j]=t;
}
}
}
System.out.println ("\nThe final array after merge is:\n");
for(i=0;i<10;i++)
{
System.out.print (" " + C[i]);
}
}
}


Deletion of an element from an array



Another program on BlueJ to delete an element of array (location to be taken from the user)

import java.io.*;
class Arr
{
int arr[]=new int[50];
int i,n,loc;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void take() throws IOException
{
System.out.println ("How many elements:");
n=Integer.parseInt(br.readLine());

for(i=0;i< n;i++)
{
System.out.println ("Value:");
arr[i]=Integer.parseInt(br.readLine());

}
System.out.println ("The values are:");
for(i=0;i< n;i++)
{
System.out.print (" " + arr[i]);
}
System.out.println ("Enter the location which value is to be deleted:");
loc=Integer.parseInt(br.readLine());
for(i=loc-1;i< n;i++)
{
arr[i]=arr[i+1];
}
System.out.println ("Now the array is(after deletion).\n");
for(i=0;i< n-1;i++)
System.out.println (" " + arr[i]);
}
}

Thursday, June 24, 2010

Another lot of array programs in BlueJ

This is a continuation of array in BlueJ. Previously we have seen some programs on array in java. Few common programs on array are given below.

Program on generate series and store in array



This type of program is very common in icse Computer papers. Generate the series 1,4,7,10.....50th element and generate the values of the element of 18th,49th,27th (print series)


class Arr
{
int num[] new int[50];
int i,no=1;
public void show()
{
for(i=0;i<50;i++)
{
num[i]=no;
no=no+3;
}
System.out.println ("The series is: -\n");
for(i=0;i<50;i++)
{
System.out.println num[i]);
}
System.out.println ("\n*************\n");
System.out.println ("Value of the element at 18th position:" + num[17]);
System.out.println ("Value of the element at 49th position:" + num[48]);
System.out.println ("Value of the element at 27th position:” + num[26]);
}
}
}

Program on searching values in array




In this program on searching different types of values from an array. Input an array of 20 integers, they can be +ve, -ve or zero . i) count the number of +ve, -ve and zero values ii) count the number of even numbers and odd numbers iii) prime numbers in the array

import java.io.*;
class Count
{
int a[] new int[20];
int i,j,odd=0,even=0, pos=0,neg=0,zero=0,prime=0,flag;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void take() throws IOException
{
for(i=0;i<20;i++)
{
System.out.println("enter a value:-");
a[i]=Integer.parseInt(br.readLine());
}

for(i=0;i<20;i++)
{
System.out.println(a[i]);
}
for(i=0;i<20;i++)
{
flag=0;
if(a[i]>0)
pos++;
else if(a[i]<0)
neg++;
else
zero++;
if(a[i]%2==0)
even++;
else
odd++;
for(j=2;j
{
flag=1;
if(a[i]%j==0)
break;
}
if(((j==a[i])||(flag==0))&&(a[i]>0)&&(a[i]!=0))
prime++;
}
System.out.println(" (+)ve="+pos );
System.out.println(" (-)ve=" + neg );
System.out.println(" Odd="+ odd);
System.out.println(" Even=" + even);
System.out.println("Zero=" + zero);
System.out.println("Prime=" + prime);

}
}

If you have any doubt in any program, pl. feel free to put your comments. I am here to clear your doubts.

Tuesday, June 15, 2010

Array programs in BlueJ

We will go through few program on array in java. I think it would help students of ICSE and ISC in their computer application paper.

Suppose we want to enter ages of 'n' number of persons in an array. Here the user will decide the array size.

import java.io.*;
class Arr
{
int arr [ ], n;
BufferedReader br=new BufferedReader(new InputStreamReader ( System.in));
void takeAge() throws IOException
{
System.out.println(“ How many Persons:”);
n=Integer.parseInt(br.readLine());
arr=new int[n];
for (i=0;i < n;i++)
{
System.out.println(“ How many persons ");
arr[i]=Integer.parseInt(br.readLine());
}
System.out.println(“Entered Ages are as follows “);
for (i=0;i < n;i++)
{
System.out.println(“ “+ arr[i]);
}
}
}

From the above BlueJ program on array, it is clear that the user decides the size of the array and it is possible as java array is dynamic. But consider another case. Suppose the user don’t know how many values he has to store at the start of the program. As he continues entering values, at some point he has to stop.

In such case we will create an array with maximum size. For example if we want to ages of students of a particular class of a school, the number of students in a class can’t be more than 500 in any case. So user can go on entering values without any risk.


import java.io.*;
class Arr
{
int arr [ ], [500], n;
BufferedReader br=new BufferedReader(new InputStreamReader ( System.in));
arr=new int[500];
char ch=’y’;
void takeAge() throws IOException
{
while (ch !=’n’)
{
System.out.println(“ Enter age:”)
arr[n++]=Integer.parseInt(br.readLine());
System.out.println(“Any more student (y/n):”);
ch=(char)br.readLine();
}
System.out.println(“Entered Ages are “);
for (i=0;i < n;i++)
{
System.out.println(“ “+ arr[i]);
}
}
}

Here is another program . Take 'n' number of integer values from the user; display the value of 'n' and the average of the numbers.

import java.io.*;
class Arr
{
int number [];
char ch='y';
number=new int[500];
void takedata() throws IOException
{
int i=0, sum=0;

while (ch!='n')
{
System.out.println ("Enter the number:");
number[i++]=Integer.parseInt(br.readLine());
sum=sum+number [i];

System.out.println ("Any more? (y/n)");
ch=(char)br.readLine();
}
System.out.println ("The total is :”+ sum);
System.out.println ("Average is :"+(float) sum/counter);
}
}

Program on counting number days from the start of the year



Our next program on array is an interesting one. The user will enter the month number (1 to 12), date and year. Our program will display the total number days from the start of the year.

import java.io.*;
class MyDay
{
int month,day,tday,year,i,lip=0;
boolean a=true,b=true;
int dpm[12]={31,28,31,30,31,30,31,31,30,31,30,31};
void take() throws IOException
{

while(a)
{
System.out.println ("enter the month(1to12):-");
month=Integer.parseInt(br.readLine());
if(month>12)
{
System.out.println ("Enter the proper month:-");
continue;
}
a=false;
}
while(b)
{
System.out.println ("Enter the day(1to31):-\n");
day=Integer.parseInt(br.readLine());
if(day>31)
{
System.out.println ("enter the proper day:-\n");
continue;
}
b=false;
}
tday=day;
System.out.println ("Enter the year:-");
year=Integer.parseInt(br.readLine());
for(i=0;i < month-1;i++)
{
tday=tday+dpm[i];
}
for(i=0;i<2;i++)
{
if(year%10!=0)
break;
year=year/10;
}if(i==2)
{
if(year%400==0)
lip=1;
}
else if(year%4==0)lip=1;if((lip==1)&&(month>2))
tday=tday+1;
System.out.println("total days from start of the year is:”+tday);
}
}

If you have any doubt in any program, pl. feel free to put your comments. I am here to clear your doubts.

1 comment: