java programs

71
PROGRAMS:- 1./* * Contract:calAerCyl:double,double->double * * Purpose:To compute the area of a cylinder * * Header:double calAerCyl(dradius,dheight){...} * * Program Example:calAerCyl->(2,3) * * Algorithm: * CalAerCyl(dradius,dheight) * BEGIN * RETURN 2(3.142*dradius*dradius) +2*3.142*dradius*dheight * END * * */ public class calAerCyl { public static double calAerCyl(double r,double h) { return (2*(3.142*r*r)+2*3.142*r*h); } } 2./* * Contract:calculateBalance:double,double,double->double * * Purpose:To compute the balance at the end of that time * * Header:double calculateBalance(double dprincipal,double drateofintrest,double dnoofmonths){...} * * Program Example:calculateBalance(2,3,4)-> * * Algorithm: * calculateBalance(double dprincipal,double drateofintrest,double dnoofmonths) * BEGIN

Transcript of java programs

Page 1: java programs

PROGRAMS:-1./* * Contract:calAerCyl:double,double->double * * Purpose:To compute the area of a cylinder * * Header:double calAerCyl(dradius,dheight){...} * * Program Example:calAerCyl->(2,3) * * Algorithm: * CalAerCyl(dradius,dheight) * BEGIN * RETURN 2(3.142*dradius*dradius)+2*3.142*dradius*dheight * END * * */public class calAerCyl{ public static double calAerCyl(double r,double h) { return (2*(3.142*r*r)+2*3.142*r*h); }}2./* * Contract:calculateBalance:double,double,double->double * * Purpose:To compute the balance at the end of that time * * Header:double calculateBalance(double dprincipal,double drateofintrest,double dnoofmonths){...} * * Program Example:calculateBalance(2,3,4)-> * * Algorithm: * calculateBalance(double dprincipal,double drateofintrest,double dnoofmonths) * BEGIN * RETURN (p+(p*r*(n/12))/100) * END * * */public class calculateBalance{public static double calculateBalance(double p,double r,double n){return (p+(p*r*(n/12))/100);

Page 2: java programs

}}3./* * Contract:calHgtRckt:double,double->double * * Purpose:To compute the height of rocket * * Header:double calHgtRckt(dtime,daccrate){...} * * Program Example:calHgtRckt-> * * Algorithm: * CalHgtRckt(dtime,daccrate) * BEGIN * RETURN 0.5*daccrate*dtime*dtime * END * * */public class calHgtRckt{ public static double calHgtRckt(double t,double g ) { return(0.5*9.8*t*t); }}4./* * Contract:calTileSum:double,double,double->double * * Purpose:To compute the whole number of tiles needed to cover the floor completely * * Header:double calTileSum(dlength,dwidth,dedgelength){...} * * Program Example:calTileSum->(2,3,4) * * Algorithm: * CalTileSum(dlength,dwidth,dedgelength) * BEGIN * RETURN (int)(dlength*dwidth)/(dedgelength*dedgelength) * END * * */public class calTileSum{ public static double calTileSum(double l,double w,double e) { return (int)(l*w)/(e*e);

Page 3: java programs

}}5./*Contract:calculateSimpleIntrest:double,double,double->double * * Purpose:To compute the simpleintrest using the formula * p*n*r/100 given principal p,number of years of n,rate of intrest r * * Header:double calculateSimpleIntrest(double dprinciple,double dnoofyears,double drateofintrest){....} * * Program Example:calculateSimpleIntrest(100.55,3.5,12.5)->43.990625 * * Algorithm: * calculateSimpleIntrest(dprinciple,dnoofyears,drateofintrest) * BEGIN * DECLARE SIMPLEINTREST * IF(dpriciple<0 OR dnoofyears<0 OR drateofintrest<0) * RETURN -1 * ELSE * SIMPLEINTREST=(dprinciple*dnoofyears*drateofintrest)/100 * RETURN SIMPLEINTREST * END IF * END * */class IntrestCalculator{ public static double calcSimpleIntrest(double dprincipal,double dnoofyears,double drateofintrest) { double simpleintrest=0; if(dprincipal<0||dnoofyears<0||drateofintrest<0) return -1; else { simpleintrest=dprincipal*dnoofyears*drateofintrest/100; return simpleintrest; } } }6./* * Contract:calAerPipe:double,double,double->double * * Purpose:To compute the area of a pipe * * Header:double calAerPipe(dradius,dheight,dthickness){...} *

Page 4: java programs

* Program Example:calAerPipe->(2,3,4) * * Algorithm: * CalAerPipe(dradius,dheight,dthickness) * BEGIN * RETURN 2*3.142*(dradius*dthickness)*dheight-2*3.142*dradius*dheight * END * * */public class calAerPipe{ public static double calAerPipe(double r,double h,double t) { return 2*3.142*(r*t)*h-2*3.142*r*h; }}7./* * Contract:calTotalInch:double,double->double * * Purpose:To compute the total length in inches * * Header:double calTotalInch(dradius,dheight){...} * * Program Example:calTotalInch->(2,3) * * Algorithm: * CalTotalInch(dnumber1,dnumber2) * BEGIN * RETURN dnumber1*12+dnumber2 * END * * */public class calTotalInch{ public static double calTotalInch(double n1,double n2) { return n1*12+n2; }}8.public class Conversion{ public static double convInchTocm(double i) { return i*2.54; } public static double convFeetToinch(double f)

Page 5: java programs

{ return f*12; } public static double convYardsTofeet(double y) { return y*3; } public static double convRodsToyards(double r) { return r*5.5; } public static double convFurlongsTorods(double fu) { return fu*40; } public static double convMilesTofurlongs(double m) { return m*8; } public static double convYardsTocm(double y) { double ft=convYardsTofeet(y); double in=convFeetToinch(ft); return convInchTocm(in); } public static double convRodToInch(double r) { double y=convRodsToyards(r); double ft=convYardsTofeet(y); return convFeetToinch(ft); } public static double convFeetTocm(double f) { double in=convFeetToinch(f); return convInchTocm(in); } public static double convMileToFeet(double m) { double fr=convMilesTofurlongs(m); double r=convFurlongsTorods(fr); double y=convRodsToyards(r); return convYardsTofeet(y); } public static double enterChoice(int ch,double d) {

Page 6: java programs

switch(ch) { case 1: return convInchTocm(d); case 2: return convFeetToinch(d); case 3: return convYardsTofeet(d); case 4: return convRodsToyards(d); case 5: return convFurlongsTorods(d); case 6: return convMilesTofurlongs(d); case 7: return convYardsTocm(d); case 8: return convRodToInch(d); case 9: return convFeetTocm(d); case 10: return convMileToFeet(d); default: return 0; } }}9./* * Contract:calcNetPay:int->double * * Purpose:To compute the netpay of an employee from the number of hour worked * * Header:double calcNetPay(int ihrswrkd){...} * * Program Example:calcNetPay->(9) * * Algorithm: * CalcNetPay(int ihrswrkd) * BEGIN * DECLARE grosspay=ihrswrkd*12 * DECLARE netpay=0 * netpay=grosspay-calTax(grosspay) * RETURN netpay * END

Page 7: java programs

* CalTax(grosspay) * BEGIN * RETURN grosspay*.15 * END * * */public class NetPaycalculator{ public static double calNetPay(int ihrswrkd) { double gp=ihrswrkd*12; double np=0; np=gp-calTax(gp); return np; } public static double calTax(double gp) { return gp*.15; } }10./* * Contract:calIncome:int->double * * Purpose:To compute howmuch income the attends produce * * Header:double calIncome(int noofcustomer){...} * * Program Example:calIncome->(40) * * Algorithm: * CalIncome(inoofcustomer) * BEGIN * RETURN (inoofcustomer*5-(20+inoofcustomer*.50)) * END * * */public class calIncome{ public static double calIncome(int cus) { return(cus*5-(20+cus*.50)); }}11./* * Contract:calDistBall:double->double

Page 8: java programs

* * Purpose:To compute how far the ball travels by the time it hits the ground for the third time * * Header:double calDistBall(dheight){...} * * Program Example:calDistBall-> * * Algorithm: * CalDistBall(dheight) * BEGIN * RETURN height+(2/3*height*2)+(2/3*(2/3*height*height)*2) * END * * */public class calDistBall{ public static double calDistBall(double h) { return h+(2/3*h*2)+(2/3*(2/3*h*h)*2); }}12./* * Contract:calAerPoly:double,double->double * * Purpose:To compute the area of a polygon * * Header:double calAerPoly(dlength,dside){...} * * Program Example:calAerPoly * * Algorithm: * CalAerPoly(dlength,dside) * BEGIN * RETURN 1/4*n*s*s*1/(tan 3.14/n). * END * * */public class calAerPoly{ public static double calAerPoly(double s,double n) { return .25*n*s*s*1/(Math.tan (3.14/n)); }}13./*

Page 9: java programs

* Contract:calDistBoat:double,double,double->double * * Purpose:To compute the distance a boat travels across a river * * Header:double calDistBoat(dwidth,dboatspeed,driverspeed){...} * * Program Example:calDistBoat-> * * Algorithm: * CalDistBoat(dwidth,dboatspeed,driverspeed) * BEGIN * RETURN Math.sqrt(Math.pow(((bs+rs)*(w/bs)),2)+Math.pow(w,2)) * END * * */public class calDistBoat{ public static double calDistBoat(double w,double bs,double rs ) { return Math.sqrt(Math.pow(((bs+rs)*(w/bs)),2)+Math.pow(w,2)); }}14./* * Contract:calPeriSqr:double->double * * Purpose:To compute the perimeter of a square * * Header:double calPeriSqr(dside){...} * * Program Example:calPeriSqr->(22) * * Algorithm: * CalPeriSqr(dside) * BEGIN * RETURN (Math.sqrt(dside)*4) * END * * */public class calPeriSqr{ public static double calPeriSqr(double ds) { return (Math.sqrt(ds)*4); }}15./*

Page 10: java programs

* Contract:calVolCyl:double,double->double * * Purpose:To compute the volume of a cylinder * * Header:double calVolCyl(dradius,dheight){...} * * Program Example:calVolCyl->(2,3) * * Algorithm: * CalVolCyl(dradius,dheight) * BEGIN * RETURN 3.142*dradius*dradius*dheight * END * * */public class calVolCyl{ public static double calVolCyl(double r,double h) { return(3.142*r*r*h); }}16./* * Contract:calculateDiffCalculator:int,int->int * * Purpose:To compute the difference between sum of the squares and the square of the sums of 2 numbers * * Header:int DiffCalculator(int inumber1,int inumber2){...} * * Program Example:DiffCalculator(2,3)->-12 * * Algorithm: * DiffCalculator(int inumber1,int inumber2) * BEGIN * RETURN(inumber1*inumber1+inumber2*inumber2)-((inumber1+inumber2)*(inumber1+inumber2)) * END * * */public class DiffCalculator{public static int calcdiff(int in1,int in2){return (in1*in1+in2*in2)-((in1+in2)*(in1+in2));}

Page 11: java programs

}17./* * Contract:calGcd:int,int->int * * Purpose:To calculate the greatest common divisor of two positive numbers a and b. *gcd(a,b) is recursively defined as *gcd(a,b) = a if a =b *gcd(a,b) = gcd(a-b, b) if a >b *gcd(a,b) = gcd(a, b-a) if b > a * *Header:int calGcd(int number1,int number2){...} * * Program Example:GcdCal.calGcd(2,45)->1 * **/public class GcdCal{ public static int calGcd(int a,int b) { int ans=0; if(a>b) ans=calGcd(a-b,b); else if(b>a) ans=calGcd(a,b-a); else return a; return ans; }}18./* * Contract:findAscend:String->String * * Purpose:To find whether the alphabets in a word (string) are in the ascending order. * * Header:String findAscend(String word){...} * * Program Example:AscendFind.findAscend("abcef")->"Ascending order" * * */public class AscendFind{ public static String findAscend(String w) { int i=0; boolean value=false;

Page 12: java programs

while(i<w.length()-1) { char ch=w.charAt(i); if(ch>w.charAt(i+1)) { value=false; break; } i++; value=true; } if(value) return "Ascending order"; else return "Descending order"; }}19./* * * Contract:calSeqNo:int->String * * Purpose:To find the sequence based on an input number as below * if the number is even : the next number = number / 2 *if the number is odd : the next number = (number * 3) + 1 *display a sentence that says how many numbers there are in the sequence. *eg. input = 17, output = 17 52 26 13 40 20 10 5 16 8 4 2 1 * * Header:String calSeqNO(int number){...} * * Program Example:CalcSeqNo.calSeqNo(10)->"There are 7 numbers in the sequence" * */public class CalcSeqNo{ public static String calSeqNo(int num) { int tot=1; String s1="There are "; while(num!=1) { if(num%2==0) num=num/2; else num=num*3+1; tot++; } return s1+tot+" numbers in the sequence";

Page 13: java programs

}}20./* * Contract:sumFibo:int->int * * Purpose:To find the sum of all the * a) even-valued terms and * b) numbers divisible by three *in the Fibonacci sequence which do not exceed n. * * Header:int sumFibo(int number){...} * * Program Example:CalcSumFibo.sumFibo(9)->34 * */public class CalcSumFibo{ public static int sumFibo(int n) { int i=0,n1=0,n2=1,n3=0,sum=0; while(i<n-2) { n3=n1+n2; if(n3%2==0||n3%3==0) sum=sum+n3; n1=n2; n2=n3; i++; } return sum; }}21./* * Contract:findtribona:int->int * * Purpose:To find the nth term in Tribonacci series (0,1,1,2,4,7,13……) * * Header:int findTribonac(int number){...} * * Program Example:Tribonac.findTribonac(8)->24 * * */public class Tribonac{ public static int findTribonac(int n) { int n1=0,n2=1,n3=1,i=0,n4=0;

Page 14: java programs

if(n>3) while(i<n-3) { n4=n1+n2+n3; n1=n2; n2=n3; n3=n4; i++; } else if(n==3||n==2) n4=1; else n4=0; return n4; }}22./* * Contract:findOccrStr:String,String->int * * Purpose:To find the number of occurrences of given word in a sentence. * *Header:int fidOccrStr(String word,String sentence){...} * * Program Example:OccrWard.findOccrStr("ab","a ab ab ab ")->3 * * */public class OccrWard{ public static int findOccrStr(String w,String s) { int i=0,p=0; String sub=""; int occr=0; while(i<s.length()) { if(s.charAt(i)==32) { sub=s.substring(p,i); p=i+1; } else if(i==(s.length()-1)) sub=s.substring(p,i+1); if(sub.equals(w)) occr++; sub="";

Page 15: java programs

i++; } return occr; }}23./* * Contract:findOccrWrd:String->String * * Purpose:To find the number of occurrences of each word in a sentence * * Header:String findOccrWrd(String sentence){...} * * Program Example:OccuranceOfWord.findOccrWrd("hi himan himan")->"hi-1 times, himan-2 times, himan-2 times," * */public class OccuranceOfWord{ static String findOccrWrd(String s) { int i=0,p=0,t=0; String sub="",s1=""; while(i<s.length()) { if(s.charAt(i)==32) { sub=s.substring(p,i); p=i+1; t=find(sub,s); s1=s1+sub+"-"+t+" times, "; } else if(i==(s.length()-1)) { sub=s.substring(p,i+1); t=find(sub,s); s1=s1+sub+"-"+t+" times, "; } i++; } return s1; } public static int find(String w,String s) { int i=0,p=0; String sub=""; int occr=0; while(i<s.length())

Page 16: java programs

{ if(s.charAt(i)==32) { sub=s.substring(p,i); p=i+1; } else if(i==(s.length()-1)) sub=s.substring(p,i+1); if(sub.equals(w)) occr++; sub=""; i++; } return occr; }}

24./* *Contract:findMostOccr:int->String * *Purpose:To find the digit that occurs most in a given number. * *Header:String findMostOccr(int number) {...} * *Program Example:findMostOccr(3333888) ->"3- maximum occresand it is 4 times" * * * */public class MostOccr{ public static String findMostOccr(int num) { int max=0; int n1=0,val=0; while(num!=0) { n1=num%10; int temp1=num,i=0; while(temp1!=0) { if(n1==temp1%10) i++; temp1=temp1/10; } if(i>max)

Page 17: java programs

{ max=i; val=n1; } num=num/10; } return (val+"- maximum occres"+"and it is "+max+" times"); }}

25./* *Contract:isMetro:boolean,int,double->boolean * * Purpose:To evalute if the city entered is metropolis or not,given * iscapitalcity,numberof citizen and taxpercitizen * * Header:boolean isMetro(boolean iscapitalCity,int numberOfCitizens,double taxPerCitizen){...} * * Program Example: Metropoli.calMetro(true,230000,2500)->true * * **/public class Metropoli{ public static boolean isMetro(boolean iscapitalCity,int numberOfCitizens,double taxPerCitizen) { if((iscapitalCity && numberOfCitizens>100000)|| (!iscapitalCity && numberOfCitizens>200000 && (taxPerCitizen*numberOfCitizens>720000000))) return true; else return false; }}26./* * Contract:calPayback:double->double * * Purpose:To calculate the payback by the credit card company given the amount * * Header:double calPayback(double amount){...} * * Program Example:calPayback(9000)->4527.5 *

Page 18: java programs

* Test Cases: * * Amount Payback * 15500 11027.5 * 5000 30.0 * 400 1.0 * 1400 5.75 * */public class PaybackCalc{ public static double calPayback(double am) { double ch=0; while(am>0) { if(am/500<=1||am/500>1) { if(am>=500) { ch=ch+500*.0025; } else ch=ch+am*.0025; am=am-500; } if(am/500>1) { if(am>=1500) ch=ch+1500*.0050; else ch=ch+am*.0050; am=am-1500; } if(am/1500>1) { if(am>=2500) ch=ch+2500*.0075; else ch=ch+am*.0075; am=am-2500; } if(am/2500>1) { ch=ch+am*1; am=0; }

Page 19: java programs

} return ch; }}27./* *Contract:calDay:int,int,int->String * * Purpose:To calculate the day of the week given the day,months,year * * Header:String calDay(int day,int months,int year){...} * * Program Example:calDay(20,1,2011)->"Thusday" * * Test Cases: * Day Month Year DayofWeek * 20 1 2011 Thusday * 21 1 2011 Friday * 22 2 2011 Saturday * * */public class DayofWeek{ public static String calDay(int d,int m,int y) { int td=0,day=0; for(int i=1;i<=(m-1);i++) if((i%2==0&&i<=6)||((i%2!=0&&i>6)&&(i!=7))) day=day+30; else day=day+31; if(m>2) day=day-2; td=day+d+(y-1900)*365+(y-1900)/4; td=td%7; if(m<=2&&(y%4==0||y%400==0)) td=td-1; switch(td) { case 0: return "Sunday"; case 1: return "Monday"; case 2: return "Tueday"; case 3:

Page 20: java programs

return "Wednesday"; case 4: return "Thusday"; case 5: return "Friday"; case 6: return "Saturday"; default: return "null"; } }}28./* * Contract : calculateBill(String, double) ? double * * Purpose:To Compute a function which accepts name of the plan and total outgoing call duration as input arguments * and this function should return the bill as per the rules mentioned below: * * For "best value" plan: * Monthly rent= Rs 249 * Call rates: * For first 200 minutes – 0 * For talk time > 200 minutes and up to 500 minutes – Re 1 / minute * For talk time > 500 minutes and up to 1000 minutes – Rs 0.75 / minute * For talk time > 1000 minutes – Rs 0.50 / minute * For "true value 99" plan: * Monthly rent= Rs 99 * Call rates: * For first 200 minutes – Rs 1.75 / minute * For talk time > 200 minutes and up to 500 minutes – Rs 1.5 / minute * For talk time > 500 minutes – Re 1 / minute * * Header:double calculateBill(String splan,double doutcallduration)->double * * Program Example : Test1.calculateBill("best value",600)= 249 + (200 * 0) + (300 * 1) + (100 *0.75) = 624.0 * Test1.calculateBill("true value 99" ,700) = 99 + (200 * 1.75) + (300 * 1.5) + (200 * 1) = 1099.0 * * */public class Test1{ public static double calculateBill(String splan,double doutcall) { double dcalcost=0;

Page 21: java programs

if(splan.equals("best value")||splan.equals("true value 99")) { if(splan.equals("best value")) { if(doutcall<=200||doutcall>200) dcalcost=249+200*0; if(doutcall>200||doutcall<500) { if(doutcall>=500) dcalcost=dcalcost+300*1; else dcalcost=dcalcost+(doutcall-200)*1; } if(doutcall>500||doutcall<=1000) { if (dcalcost>=1000) dcalcost=dcalcost+500*.75; else dcalcost=dcalcost+(doutcall-500)*.75; } if(doutcall>1000) { dcalcost=dcalcost+(doutcall-1000)*.50; } } else { if(doutcall<=200||doutcall>200) { if(doutcall<200) dcalcost=99+1.75*doutcall; else dcalcost=99+1.75*200; } if(dcalcost>200) { if(dcalcost>=500) dcalcost=dcalcost+1.5*300; else dcalcost=dcalcost+(doutcall-200)*1.5; } if(doutcall>500) { dcalcost=dcalcost+(doutcall-500)*1;

Page 22: java programs

} } } else return 1; return dcalcost; } } 29./* * Contract:checkAlph:char->String * * Purpose:To check if the input alphbet entered is vowel or consonant * given the alphabet * * Header:String checkAlph(char ch){...} * * Program Example:checkAlph('j')->"Alphabet enter is Consonant" * * Algorithm: * checkAlph(alphabet) * BEGIN * IF(alphabet=='a'OR alphabet=='A'OR alphabet=='e' OR alphabet=='E' OR * alphabet=='I' OR alphabet=='i' OR alphabet0=='O' OR alphabet=='o'OR alphabet=='u' OR alphabet=='U') * RETURN "Alphabet is Vowel" * ELSE * RETURN "Alphabet is Consonant" * END IF * END * * * */public class CheckAlpha{ public static String checkAlph(char ch) { if(ch=='a'||ch=='A'||ch=='e'||ch=='E'||ch=='I'||ch=='i'||ch=='O'||ch=='o'||ch=='u'||ch=='U') return "Alphabet is Vowel"; else return "Alphabet is consonant"; }}30./* *

Page 23: java programs

* Construct:calInterest:double->double * * Purpose:To calculate the amount of interest that is generated in one year * according to certain company rate of interest ,given the amount of money that is * deposted * * Header:double calInterest(double amount){...} * * Program Example:calInterest(2000)->90.0 * * Algorithm: * calInterest(amount) * BEGIN * DECLARE rate=0; * IF(amount<=1000) * THEN rate=4 * ELSE IF(amount<=5000) * THEN rate=4.5; * ELSE * rate=5; * END IF * END * */public class InterestCal{ public static double calInterest(double p) { double rate=0; if(p<=1000) rate=4; else if(p<=5000) rate=4.5; else rate=5.0; return p*1*rate/100; }}31./* * * Contract:library:char->String * * Purpose:To return a msg according to a given module name given * * Header:String library(char character){...} * * Program Example:library('J')->"Magazine Addition function opened"

Page 24: java programs

* * Algorithm: * library(char chararcter) * BEGIN * IF(chararcter=='M') * RETURN "Member Registration "+"funcion opened"; * END IF * IF(chararcter=='B') * RETURN "Book Addition "+"funcion opened" * END IF * IF(chararcter=='J') * RETURN "Magazine Adddition "+"funcion opened" * END IF * IF(chararcter=='I') * RETURN "Book Issue "+"funcion opened" * END IF * IF(chararcter=='S') * RETURN "Book section addition "+"funcion opened" * END IF * RETURN "invalid input" * END * * * */public class LibraryEval{ public static String library(char ch) { if(ch=='M') return "Member Registration "+"funcion opened"; if(ch=='B') return "Book Addition "+"funcion opened"; if(ch=='J') return "Magazine Adddition "+"funcion opened"; if(ch=='I') return "Book Issue "+"funcion opened"; if(ch=='S') return "Book section addition "+"funcion opened"; return "invalid input"; }}32./* * Contract:calMaxno:int,int,int->int * * Purpose:To calculate the greatest of 3 numbers given 3 numbers *

Page 25: java programs

* Header:int calMaxno(int number1,int number2,int number2){...} * * Program Example:calMaxno(1000,12392,5699)->12392 * * Algorithm: * calMaxno(number1,number2,number3) * BEGIN * DECLARE LARGE * IF (number1>number2 AND number1>number3) * LARGE=number1 * ELSE IF(number3>number1 AND number3>number2) * LARGE=number3 * ELSE * LARGE=number2 * RETURN LARGE * END * * */public class Max3NO{ public static int calMaxno(int n1,int n2,int n3) { int large=0; if(n1>n2 && n1>n3) large=n1; else if(n3>n1&&n3>n2) large=n3; else large=n2; return large; }}33./* * Contract:netPay:double->double * * Purpose:To calculate the netPay given the grosspay and company tax varies according to the grosspay * * Header:double netPay(double grosspay){...} * * Program Example:netPay(250)->212.5 * * Algorithm: * netPay(grosspay)

Page 26: java programs

* BEGIN * RETURN (grosspay-grosspay*calltax(grosspay)/100) * END * caltax(double grosspay) * BEGIN * DECLARE tax * IF(grosspay<=240) * tax=0; * ELSE IF(grosspay>240&&grosspay<=480) * tax=15 * ELSE * tax=28 * END IF * RETURN tax * END * * * */public class TaxCalc{ public static double caltax(double gp) { double tax=0; if(gp<=240) tax=0; else if(gp>240&&gp<=480) tax=15; else tax=28; return tax; } public static double netPay(double gp) { double tax=(caltax(gp))/100; return (gp-tax*gp); } }34./* * Contract:checkPalidrome:String->boolean * * Purpose:To determine whether a string is a palindrome or not. Display the output as yes or no. * * Header:boolean checkPalidrome(String word){...}

Page 27: java programs

* * Program Example:checkPalidrome("abcba")->true * */public class PalidmCheck{ public static boolean checkPalidrome(String s) { String s2=""; for(int i=0;i<s.length();i++) { s2=s2+s.charAt(s.length()-i-1); } if(s2.equals(s)) return true; else return false; }}35./* * Contract:calQuantity:int[],int[]->String * * Purpose:To finding the total quantity of each kind of fruit(represented by an integer number) *sold from an ordered list containing fruits and the quantity sold. * * Header:String calQuantity(int fruitarray[],int quantity[]){...} * * Program Example:calQuantity(new int[]{1,2,1,2},new int[]{1,9,1,5})-> * " Quntitye of 1- type no.-2 Quntitye of 9- type no.-14" * * * */public class QuantityCalc{ public static String calQuantity(int fr[],int q[]) { for(int i=0;i<fr.length-1;i++) for(int j=0;j<fr.length-i-1;j++) if(fr[j]>fr[j+1]) { int temp=fr[j]; fr[j]=fr[j+1]; fr[j+1]=temp; int temp1=q[j]; q[j]=q[j+1]; q[j+1]=temp1;

Page 28: java programs

} int val=fr[0],add=0; String sum=""; for(int j=0;j<fr.length;j++) { if(fr[j]==val) add=add+q[j]; else { sum=sum+" Quntitye of "+q[j-1]+"- type no.-"+add; val=fr[j]; add=q[j]; } if(j==fr.length-1) sum=sum+" Quntitye of "+q[j-1]+"- type no.-"+add; } return sum; }} 36./* * Contract:arrangeStudent:int[]->String * * Purpose:To find the taller half of students and arrange them in the *ascending order of their height and the shorter half in the descending order of *their height. * * Header:String arrangeStudent(int array[]){...} * * Program Example:StudentArrange.arrangeStudnent(new int[]{1,2,3,4,5,6,7,90,78})->" 5 4 3 2 1 6 7 78 90 " * */public class StudentArrange{ public static String arrangeStudent(int arr[]) { int sortarr[]=sort(arr); int taller[],shorter[],val=0,k=0; taller=new int[arr.length/2]; shorter=new int[arr.length-arr.length/2]; String sum=" "; for(int i=0;i<arr.length;i++) { if(i<(arr.length-arr.length/2)) val=shorter[i]=sortarr[(arr.length-arr.length/2)-i-1]; else

Page 29: java programs

val=taller[k++]=sortarr[i]; sum=sum+val+" "; } return sum; } static int [] sort(int arr[]) { for(int i=0;i<arr.length-1;i++) for(int j=0;j<arr.length-i-1;j++) if(arr[j]>arr[j+1]) { int temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } return arr; }}

37./* * Contract:findRank:int[],int->int * * Purpose:To find the marks for a rank from a series of marks. * * Header:int findRank(int markarrary[],int rank){...} * * Program Example:findRank(new int[]{12,34,10,90,100},2)->90 * */

public class RankMark{ public static int findRank(int m[],int r) { for(int i=0;i<m.length-1;i++) for(int j=0;j<m.length-i-1;j++) if(m[j]>m[j+1]) { int temp=m[j]; m[j]=m[j+1]; m[j+1]=temp; } return m[m.length-r]; }}38/* * Contract:findRoll:int[],String[],int->String

Page 30: java programs

* * Purpose:To find the roll numbers for a rank from a given series of roll numbers and marks. * * Header:String findRoll(int marksarrary[],String rollarray[],int rank){...} * * Program Example: * findRoll(new int[]{12,20,10,54,90},new String[]{"roll-1","roll-2","roll-3","roll-4","roll-5"},2)->"roll-4" * * */ public class RollRankMark{ public static String findRoll(int m[],String rl[],int r) { for(int i=0;i<m.length-1;i++) for(int j=0;j<m.length-i-1;j++) if(m[j]>m[j+1]) { int temp=m[j]; m[j]=m[j+1]; m[j+1]=temp; String temp1=rl[j]; rl[j]=rl[j+1]; rl[j+1]=temp1; } return rl[rl.length-r]; }}39./* * Contract:calMaxStr:String[]->String * * Purpose:To return the String having first alphabet greater in the string * * Header:String calMaxStr(String []stringarray){...} * * Program Example:MaxStrAll.calMaxStr(new String[]{"bc","def","dea","b"})"b" * */public class MaxStrAll{ public static String calMaxStr(String []ws) { char max=(ws[0]).charAt(0); String smax=ws[0];

Page 31: java programs

for(int i=1;i<ws.length;i++) { if((ws[i]).charAt(0)<max) { max=(ws[i]).charAt(0); smax=ws[i]; } else if(ws[i].charAt(0)==max) { for(int j=0;j<smax.length();j++) { if(smax.charAt(j)<=ws[i].charAt(j)) smax=ws[i]; } } } return smax; }}40./* * Contract:checkAlpha:char[],char->true * * Purpose:To write a program to accept an array of alphabets and an alphabet and check whether the alphabet *is present in the array. Return “Yes” if alphabet is present in the array. * * Header:boolean checkAlpha(char []charArray,char character){...} * * Program Example:checkAlpha(new char[]{'a','b','c'},'c')->true * A. * */public class AlphaCheck{ public static boolean checkAlpha(char []cha,char ch) { for(int i=0;i<cha.length;i++) { if(ch==cha[i]) return true; } return false; }}

Page 32: java programs

41./* * Contract:calMaxStr:String[]->String * * Purpose:To return the String having first alphabet greater in the string * * Header:String calMaxStr(String []stringarray){...} * * Program Example:MaxStrAll.calMaxStr(new String[]{"bc","def","dea","b"})"b" * */public class MaxStrAll{ public static String calMaxStr(String []ws) { char max=(ws[0]).charAt(0); String smax=ws[0]; for(int i=1;i<ws.length;i++) { if((ws[i]).charAt(0)<max) { max=(ws[i]).charAt(0); smax=ws[i]; } else if(ws[i].charAt(0)==max) { for(int j=0;j<smax.length();j++) { if(smax.charAt(j)<=ws[i].charAt(j)) smax=ws[i]; } } } return smax; }}42./* * Contract:doMerge:int[],int[],int[]->String * * Purpose:To combine 3 sorted lists into 1 sorted list and remove the duplicate elements in the * resultant array. * * Header:String doMerge(int array1[],int array2[],int array3[]){...}

Page 33: java programs

* * Program Example:doMerge(new int[]{1,2,3},new int[]{1,2,3},new int[]{1,2,3,22,3,1})->"1 2 3 22" * */public class MergeSort{ public static String doMerge(int []a1,int []a2,int[] a3) { int size=a1.length+a2.length+a3.length; int r[]=new int[size]; for(int i=0;i<size;i++) { if(i<a1.length) { r[i]=a1[i]; } else if(i<(a1.length+a2.length)) r[i]=a2[i-a1.length]; else r[i]=a3[i-(a1.length+a2.length)]; } for(int i=0;i<size-1;i++) for(int j=0;j<size-i-1;j++) if(r[j]>r[j+1]) { int temp=r[j]; r[j]=r[j+1]; r[j+1]=temp; } String sum=""+r[0]; for(int i=0;i<size-1;i++) { if(r[i]!=r[i+1]) sum=sum+" "+r[i+1]; } return sum; }}43./* * * Contract:checkName:String,String->boolean * * Purpose:To write a program to accept an array of names and a name and check whether the name is present * in the array. Return “Yes” if the name is present in the array.

Page 34: java programs

* * Header:boolean checkName(String []arrofname,String name){...} * * Program Example:checkName(new String[]{"aa","def","abc"},"aa")->true * */public class NameCheck{ public static boolean checkName(String []namearr,String name) { for(int i=0;i<namearr.length;i++) { if(namearr[i].equals(name)) return true; } return false; }}44./* * Contract:calQuantity:int[],int[]->String * * Purpose:To finding the total quantity of each kind of fruit(represented by an integer number) *sold from an ordered list containing fruits and the quantity sold. * * Header:String calQuantity(int fruitarray[],int quantity[]){...} * * Program Example:calQuantity(new int[]{1,2,1,2},new int[]{1,9,1,5})-> * " Quntitye of 1- type no.-2 Quntitye of 9- type no.-14" * * * */public class QuantityCalc{ public static String calQuantity(int fr[],int q[]) { for(int i=0;i<fr.length-1;i++) for(int j=0;j<fr.length-i-1;j++) if(fr[j]>fr[j+1]) { int temp=fr[j]; fr[j]=fr[j+1]; fr[j+1]=temp; int temp1=q[j]; q[j]=q[j+1]; q[j+1]=temp1; }

Page 35: java programs

int val=fr[0],add=0; String sum=""; for(int j=0;j<fr.length;j++) { if(fr[j]==val) add=add+q[j]; else { sum=sum+" Quntitye of "+q[j-1]+"- type no.-"+add; val=fr[j]; add=q[j]; } if(j==fr.length-1) sum=sum+" Quntitye of "+q[j-1]+"- type no.-"+add; } return sum; }} 45. /* * Contract:findRoll:int[],String[],int->String * * Purpose:To find the roll numbers for a rank from a given series of roll numbers and marks. * * Header:String findRoll(int marksarrary[],String rollarray[],int rank){...} * * Program Example: * findRoll(new int[]{12,20,10,54,90},new String[]{"roll-1","roll-2","roll-3","roll-4","roll-5"},2)->"roll-4" * * */ public class RollRankMark{ public static String findRoll(int m[],String rl[],int r) { for(int i=0;i<m.length-1;i++) for(int j=0;j<m.length-i-1;j++) if(m[j]>m[j+1]) { int temp=m[j]; m[j]=m[j+1]; m[j+1]=temp; String temp1=rl[j]; rl[j]=rl[j+1];

Page 36: java programs

rl[j+1]=temp1; } return rl[rl.length-r]; }}46./* *Contract:revSentence:String->String * * Purpose:To write a program that reverses a sentence. * * Header:String revSentece(String sentence){...} * * Program Example: * */public class SentenceRev{ public static String revSentence(String s) { String s1=""; for(int i=0;i<s.length();i++) { s1=s1+s.charAt(s.length()-i-1); } return s1; } }47./* *Contract:occrOfName:String[],String->int * * Purpose:To write a program to accept an array of names and a name and check whether the name is present *in the array. Return the count of occurrence. Use the following array as input *{“Dave”, “Ann”, “George”, “Sam”, “Ted”, “Gag”, “Saj”, “Agati”, “Mary”, “Sam”, “Ayan”, *“Dev”, “Kity”, “Meery”, “Smith”, “Johnson”, “Bill”, “Williams”, “Jones”, “Brown”, “Davis”, *“Miller”, “Wilson”, “Moore”, “Taylor, “Anderson”, “Thomas”, “Jackson”} * Header:int occrOfName(String []namearr,String name){...} * *Program Example:occrOfName(new String[]{"Dave","Dave","man"},"Dave")->2 * * */public class NoOfOccr{ public static int occrOfName(String []namearr,String name)

Page 37: java programs

{ int occr=0; for(int i=0;i<namearr.length;i++) { if(namearr[i].equals(name)) occr++; } return occr; }} 48./* * Contract:findOccrLen:String->String; * * Purpose:To accept a sentence ad display the number of occurrences of words of different *lengths * * Header:String findOccrLen(String sentence){...} * * Program Example:OccrLen.findOccrLen("i am a boy")->" i-1 am-2 a-1 boy-3 " * */public class OccrLenF{ public static String findOccrLen(String s) { int i=0,p=0,k=0; int arr[]=new int[s.length()]; String sub="",sum=" "; while(i<s.length()) { if(s.charAt(i)==32) { sub=s.substring(p,i); p=i+1; arr[k++]=sub.length(); } else if(i==(s.length()-1)) { sub=s.substring(p,i+1); arr[k++]=sub.length(); } i++; }

Page 38: java programs

return sum; } }49./* * Contract:oprAlphaArray:char[],char[],String->char[] * * Purpose:Write a program to accept two arrays of alphabets and combine the arrays as per *the input flag – “merge”, “append”, “common” *If “merge” is given, create the result array with {<1st element in 1st *array>, <1st element in second array>,<2nd element in first array>,<2nd element in *second array>…….,<last element in first array>,<last element in last array>} *If “append” is given, the result array appending second array to the end of first *arrayIf “common” is given, the result array should only have elements common in both arrays * * Header:char[] oprAlphaArray(char[] arr1,char[] arr2,String operation){...} * * Program Example:oprAlphaArray(new char[]{'a','b','c','e','f','g'},new char[]{'a','b','c','d'},"merge") *->{ a, a, b, b, c, c, e, d, f, g } * * */public class AlphaOperation{ public static char[] oprAlphaArray(char[] arr1,char[] arr2,String op) { char arr3[]=new char[arr1.length+arr2.length]; int size=0,k=0; if(op.equals("append")) { arr3=funap(arr1,arr2); return arr3; } if(op.equals("merge")) { if(arr1.length<=arr2.length) size=arr2.length; else size=arr1.length; for(int i=0,j=0;i<size;i++,j++) { if(i<arr1.length&&i<arr2.length)

Page 39: java programs

{ arr3[k++]=arr1[i]; arr3[k++]=arr2[i]; } else if(i<arr1.length) arr3[k++]=arr1[i]; else arr3[k++]=arr2[i]; } return arr3; } if(op.equals("common")) { for(int i=0;i<arr1.length;i++) for(int j=0;j<arr2.length;j++) if(arr1[i]==arr2[j]) arr3[k++]=arr1[i]; } char charr[]=new char[k]; for(int i=0;i<k;i++) charr[i]=arr3[i]; return charr; } static char[] funap(char []arr1,char[] arr2) { int size=arr1.length+arr2.length,k=0; char arr3[]=new char[size]; for(int i=0;i<size;i++) { if(i<arr1.length) arr3[i]=arr1[i]; else arr3[i]=arr2[k++]; } return arr3; } }50./* *Contract:findOccr:String->String * * Purpose:To accept a sentence and display the number of occurrences of words of different * lengths *

Page 40: java programs

* Header:String findOccr(String sentence){...} * * Program Example:NoofOcrOfWord.findOccr("hi hi abc h hai") * "2 word length:2- times * 3 word length:2- times * 1 word length:1- times " * * */public class NoofOcrOfWord{ public static String findOccr(String s) { String snew[]=convToArray(s); String sum=""; for(int i=0;i<snew.length;i++) { int count=1; if(snew[i]!="") for(int j=i+1;j<snew.length;j++) { if(snew[i].length()==snew[j].length()) { count++; snew[j]=""; } } if(snew[i]!="") sum=sum+snew[i].length()+" word length:"+count+"- times \n"; } return sum; } //convert string to an array of string; static String[] convToArray(String s) { int noofSpace=0,j=1; String sn=s+" "; while(j<sn.length()) { if(sn.charAt(j)==32&&sn.charAt(j-1)!=32) noofSpace++; j++; } String sarr[]=new String [noofSpace]; int i=0,p=0,k=0; while(i<s.length()) {

Page 41: java programs

i=sn.indexOf(" ",p); if(sn.charAt(p)!=32) sarr[k++]=sn.substring(p,i); p=i+1; } return sarr; }}

51./* * Contract:findLarge2nd:int[]->int * * Purpose:To write a program to find the second * largest number in an array of unsorted numbers * * Header:findLarge2nd(int array[]){...} * * Program Example:LargeSecond.findLarge2nd(new int[]{1,2,3})->2 * */public class LargeSecond{ public static int findLarge2nd(int arr[]) { int val=2,max2=0,max1=0; max1=fmax(arr); max2=fmax(arr); if(max1!=max2) return max2; else return -1; } //The below function finds the maximum number in an array static int fmax(int arr[]) { int max=0,j=0; for(int i=0;i<arr.length;i++) if(arr[i]>max) { max=arr[i]; j=i; } arr[j]=0; return max; }}

Page 42: java programs

52./* *Contract:caountValue:int[],int->int * * Purpose:To write a program to find the count of a particular value in a array of integers. * * Header:int countValue(int array[],int value){...} * * Program Example:ValueCount.countValue(new int[]{1,2,3,1,2,333,3},3)->2 * */public class ValueCount{ public static int countValue(int arr[],int val) { int count=0; for(int i=0;i<arr.length;i++) { if(arr[i]==val) count++; } return count; }}53./* *Contract:replaceString:String[],String,String->String[] * * Purpose:To write a program to replace a particular string if it is there in an array of strings. * * Header:String[] replaceString(String []stringarray,String string_name,String replace){...} * * Program Example:StringReplace.replaceString(new String []{"abc","def"},"abc","abcde")->{ abcde, def } * */public class StringReplace{ public static String[] replaceString(String []as,String s,String r) { for(int i=0;i<as.length;i++) { if(as[i].equals(s)) as[i]=r; } return as; }

Page 43: java programs

}54/* *Contract:concatString:String[]->String * * Purpose:To write a program to concatenate an array of string into a single string and return the string. * * Header:String concatString(String[] strarray){...} * * Program Example:StringConcat.concatString(new String[]{"welcome","to","tcs"})->"welcome to tcs " * * */public class StringConcat{ public static String concatString(String[] str) { String sum=""; for(int i=0;i<str.length;i++) { sum=sum+str[i]+" "; } return sum; }}

55./* * Contract:insertDelimeter:String[]->String[]; * * Purpose:To write a program to insert a delimter (e.g “$”) on every 3 rd position in an array of strings. * * Header:String[] insertDelimter(String []strarry){...} * * Program Example:DelimterInsert.insertDelimter(new String[]{"abc","def","abdeee"})->{ ab$c, de$f, ab$deee } * * */public class DelimterInsert{ public static String[] insertDelimter(String []sa) { int pos=3; for(int i=0;i<sa.length;i++) {

Page 44: java programs

if(sa[i].length()>=3) sa[i]=sa[i].substring(0,2)+'$'+sa[i].substring(2,(sa[i].length())); } return sa; }}56./* * Contract:replaceAlpha:char[]->char[] * * Purpose:To write a program to replace an array of alphabets (A – J) in upper case * with corresponding lower case alphabets. * * Header:char[] replaceAlpha(char[] chararray){...} * * Program Example:AlphaReplace.replaceAlpha(new char[]{'A','B','J','M'})->{ a, b, j, m } * * */public class AlphaReplace{ public static char[] replaceAlpha(char[] ch) { for(int i=0;i<ch.length;i++) { ch[i]=(char)(ch[i]+32); } return ch; }}57./* *Contract:calMarkSub:double[],double[],double[],double[],double[]->String * * Purpose:To write a program to store the marks in 4 subjects(English, Science, Maths, Social, *Arts) of 5 students. The program should have two functions to *1) To calculate the average marks for each subject *2) To calculate the total marks for each student. *3) Assume arrays of marks for each student in the predefined subject *order(e.g { <marks for English>, <marks for Science>,<marks for *Maths>,<marks for Social>,<marks for Arts>} * * Header:String calMarkSub(double mark1[],double mark2[],double mark3[],double mark4[],double mark5[]){...} * * Program Example:calMarkSub(new double[]{1,2,3,4,5},new double[]{1,2,3,4,5},new double[]{1,2,3,4,5}

Page 45: java programs

* ,new double[]{1,2,34,5},new double[]{1,2,3,4,15}),4,5},new double[]{1,2,3,4,15})-> *"English: 1.0 Science: 2.0 Maths: 3.0 Social: 4.0 Arts: 7.0 *student1: 15.0 : student2: 15.0 : student3: 15.0 : student4: 15.0 : student5: 25.0 : " * * */public class MarkCalc{ public static String calMarkSub(double mark1[],double mark2[],double mark3[],double mark4[],double mark5[]) { String s[]={"English", "Science", "Maths","Social","Arts"}; String sum=""; for(int i=0;i<5;i++) { s[i]=s[i]+": "+(mark1[i]+mark2[i]+mark3[i]+mark4[i]+mark5[i])/5; sum=sum+s[i]+" "; } return sum+"\n"+calMarkStu(mark1,mark2,mark3,mark4,mark5); } static String calMarkStu(double mark1[],double mark2[],double mark3[],double mark4[],double mark5[]) { String s[]={"student1","student2","student3","student4","student5"}; String sum=""; double val=0; double arr[]=new double[5]; for(int i=0;i<5;i++) { switch(i) { case 0: arr=mark1; break; case 1: arr=mark2; break; case 2: arr=mark3; break; case 3: arr=mark4; break; case 4: arr=mark5; break; }

Page 46: java programs

val=calmark(arr); sum=sum+s[i]+": "+val+" : "; } return sum; } static double calmark(double []arr) { double sum=0; for(int i=0;i<5;i++) { sum=arr[i]+sum; } return sum; } }58./* * Contract:oprAlphaArray:char[],char[],String->char[] * * Purpose:Write a program to accept two arrays of alphabets and combine the arrays as per *the input flag – “merge”, “append”, “common” *If “merge” is given, create the result array with {<1st element in 1st *array>, <1st element in second array>,<2nd element in first array>,<2nd element in *second array>…….,<last element in first array>,<last element in last array>} *If “append” is given, the result array appending second array to the end of first *arrayIf “common” is given, the result array should only have elements common in both arrays * * Header:char[] oprAlphaArray(char[] arr1,char[] arr2,String operation){...} * * Program Example:oprAlphaArray(new char[]{'a','b','c','e','f','g'},new char[]{'a','b','c','d'},"merge") *->{ a, a, b, b, c, c, e, d, f, g } * * */public class AlphaOperation{ public static char[] oprAlphaArray(char[] arr1,char[] arr2,String op) { char arr3[]=new char[arr1.length+arr2.length]; int size=0,k=0; if(op.equals("append")) { arr3=funap(arr1,arr2); return arr3;

Page 47: java programs

} if(op.equals("merge")) { if(arr1.length<=arr2.length) size=arr2.length; else size=arr1.length; for(int i=0,j=0;i<size;i++,j++) { if(i<arr1.length&&i<arr2.length) { arr3[k++]=arr1[i]; arr3[k++]=arr2[i]; } else if(i<arr1.length) arr3[k++]=arr1[i]; else arr3[k++]=arr2[i]; } return arr3; } if(op.equals("common")) { for(int i=0;i<arr1.length;i++) for(int j=0;j<arr2.length;j++) if(arr1[i]==arr2[j]) arr3[k++]=arr1[i]; } char charr[]=new char[k]; for(int i=0;i<k;i++) charr[i]=arr3[i]; return charr; } static char[] funap(char []arr1,char[] arr2) { int size=arr1.length+arr2.length,k=0; char arr3[]=new char[size]; for(int i=0;i<size;i++) { if(i<arr1.length) arr3[i]=arr1[i]; else arr3[i]=arr2[k++]; } return arr3;

Page 48: java programs

} }59./* *Contract:favTask:String[]->String[] * * Purpose:To write a program to store the names of favourite tasks (say ‘painting’, ‘reading’, *‘writing’…..) and return the string “My favourite tasks are <task1>, <task2>, *<task3>,…..and <task 4> .” (tasks listed in ascending order). * * Header:String[] favTask(String[] taskarray){...} * * Program Example:FavoriteTask.favTask(new String []{"painting","reading","writing"})->{ painting, reading, writing } * * * */public class FavoriteTask{ public static String[] favTask(String []task) { int size=1; for(int i=0;i<task.length-1;i++) { for(int j=0;j<task.length-i-1;j++) { if(task[j].length()<task[j+1].length()) size=task[j].length(); else size=task[j+1].length(); for(int k=0;k<size;k++) { if(task[j].charAt(k)>task[j+1].charAt(k)) { String stemp=task[j]; task[j]=task[j+1]; task[j+1]=stemp; break; } else break; } }

Page 49: java programs

} return task; } }QUESTIONS:- A.1.1Grade calculationWrite a program to store the marks in 4 subjects(English, Science, Maths, Social, Arts) of 5 students. The program should have two functions to 1)To calculate the average marks for each subject2)To calculate the total marks for each student.3)Assume arrays of marks for each student in the predefined subject order(e.g { <marks for English>, <marks for Science>,<marks for Maths>,<marks for Social>,<marks for Arts>}A.1.2Stack Implementation – Chocolate box problemYou have a set chocolates of different makes (KitKat,Cadbury, Toblerone). There is one box where all the chocolates need to be placed. Only one chocolate can be placed inside the box at one instance and only one can be retrieved at any instance. The chocolate which is placed last will be at the top of the box while the chocolate which is place first will be at the bottom of the box. Write a program to insert a set of chocolates in the order in which is it received (random) into a box (that can hold 10 chocolates) and retrieve specific chocolates from the box.A.1.3Find second largest numberWrite a program to find the second largest number in an array of unsorted numbers. If there is no second largest number, return -1A.1.4Insert Strings Write a program to insert Strings to an array of size 10. If the string is already present in the array, return a message saying “<String>, already exist”. After the 10th element, for any insert action, return a message “No more Strings can be stored”.A.1.5Find occurrence of an integerWrite a program to find the count of a particular value in a array of integers.A.1.6Replace a stringWrite a program to replace a particular string if it is there in an array of strings.A.1.7Concatenate a stringWrite a program to concatenate an array of string into a single string and return the string.A.1.8Introduce a delimiterWrite a program to insert a delimter (e.g “$”) on every 3 rd position in an array of strings.A.1.9Replace stringsWrite a program to replace an array of alphabets (A – J) in upper case with corresponding lower case alphabets. A.1.1Favorite tasks

Page 50: java programs

Write a program to store the names of favourite tasks (say ‘painting’, ‘reading’, ‘writing’…..) and return the string “My favourite tasks are <task1>, <task2>, <task3>,…..and <task 4> .” (tasks listed in ascending order).A.1.2Array additionWrite a program to accept two arrays of alphabets and combine the arrays as per the input flag – “merge”, “append”, “common” If “merge” is given, create the result array with {<1st element in 1st array>, <1st element in second array>,<2nd element in first array>,<2nd element in second array>…….,<last element in first array>,<last element in last array>} If “append” is given, the result array appending second array to the end of first arrayIf “common” is given, the result array should only have elements common in both arrays.A.1.3Batch gradeWrite a program to calculate the exam pass percentage of a batch consisting of 4 students (each having 5 marks entered in order) based on the following rule.Weigtage of mark1, mark2 is 25%Weightage of mark3, mark4 is 20%Weightage of mark5 is 10% Maximum marks is 100 for each subject.Batch grade is A if, batch percentage is above 80% and B if between 40% and 80% and C if less than 40%If a student didn’t appear for an exam(that is marks = 0), then his other marks should not be considered for the batch grade calculationA.1.4Batch strength distributionWrite a program to accept an array of count of participants in batches and a reference count so that the if any batch has additional participants, the extra participants are distributed among those batches with a lower value(so as to make the other close to the reference value). A return message with defiecent(-) /surplus(+) participant count should be returnede.g Input can be { 10, 45, 50, 15, 20} and value 30. The result array can be{30, 30,30,30,20} and the -10 is returned.A.1.5Coins requiredWrite a program to accept an array of count of coins of denomination 10,25 and 50 respectively and an amount(in paise). The program will find the least number of coins required to satisfy this amount and return the array. Eg. Accept {5,10,5}, 300 will return {0,2,5}A.1.6Items procurementWrite a program to accept three arrays, Product Type(“Cosmetic”, “Household”, “Medicinal” ), product quantity and product price and return the total amount required for procurement. Cosmetic items have a tax of 12%, for Household 4% and no tax for medicinal goods. A.1.7Room allocationWrite a program to accept three arrays – Room numbers, room capacity and an array of size 3 representing number of gents,ladies and familes(which consists of a male and a female). The program should return an array of unallocated room numbers

Page 51: java programs

The room number is a 3 digit number(e.g 123) and “1” represents the floor number. The program should ensure to allocate the rooms in lower floors first.Unless a family, a male and female should not be allocated to a room.A.1.8Loan selectionWrite a program to automate the following loan policy.Age categoryGenderProfessionPersonal assetsLoan amount eligible16 -25M /FSelf-Employed>2500010000

Professional1500026 - 40M SelfEmployed / Professional> 4000025000F

3000041 - 60M / FSelfEmployed / Professional> 5000040000> 60M/FSelf Employed> 2500035000 – Age * 100

Retired25000 – Age * 100

The loan selection program should accept the age, gender, jobstatus and assets and return the eligible loan amount.

A.1.9Shopping ListWrite a program to accept item list from 3 users and prepare an array with items and total count (store it as string instead of integer). The result array can have the format

Page 52: java programs

{<item1 name>, <item1 count>,<item2 name>,<item2 count>,<item3 name>, <item4 count>….}

A.Design the following programs by developing the Contract, Purpose, Header, Example and Algorithm. Validate your algorithm by doing a dry run.Exercise 1Find the maximum of three numbers Exercise 2Find the maximum of a series of numbers Exercise 3What is the difference between sum of the squares and the square of the sums of n numbers? Exercise 4Utopias tax accountants always use programs that compute income taxes even though the tax rate is a solid, never-changing 15%. Define the program tax, which determines the tax on the gross pay.Also define netpay. The program determines the net pay of an employee from the number of hours worked. Assume an hourly rate of $12.Exercise 5An old-style movie theater has a simple profit program. Each customer pays $5 per ticket. Every performance costs the theater $20, plus $.50 per attendee. Develop the program total-profit. It consumes the number of attendees (of a show) and produces how much income the attendees produce.Exercise 6The United States uses the English system of (length) measurements. The rest of the world uses the metric system. So, people who travel abroad and companies that trade with foreign partners often need to convert English measurements to metric ones and vice versa. Here is a table that shows the six major units of length measurements of the English system:Develop the programs inches->cm, feet->inches, yards->feet, rods->yards, furlongs->rods, and miles->furlongs. Then develop the programs feet->cm, yards->cm, rods->inches, and miles->feet. Develop the programs inches->cm, feet->inches, yards->feet, rods->yards, furlongs->rods, and miles->furlongs. Then develop the programs feet->cm, yards->cm, rods->inches, and miles->feet. Hint: Reuse programs as much as possible. Use variable definitions to specify constants.Exercise 7Develop the program volume-cylinder. It consumes the radius of a cylinders base disk and its height; it computes the volume of the cylinder.

Exercise 8Develop area-cylinder. The program consumes the radius of the cylinders base disk and its height. Its result is the surface area of the cylinder.Exercise 9

Page 53: java programs

Develop the program area-pipe. It computes the surface area of a pipe, which is an open cylinder. The program consumes three values: the pipes inner radius, its length, and the thickness of its wall.Develop two versions: a program that consists of a single definition and a program that consists of several program definitions. Which one evokes more confidence?Exercise 10Develop the program height, which computes the height that a rocket reaches in a given amount of time. If the rocket accelerates at a constant rate g, it reaches a speed of g • t in t time units and a height of 1/2 * v * t where v is the speed at t.

Exercise 11Develop the program interest. Like interest-rate, it consumes a deposit amount. Instead of the rate, it produces the actual amount of interest that the money earns in a year. The bank pays a flat 4% for deposits of up to $1,000, a flat 4.5% per year for deposits of up to $5,000, and a flat 5% for deposits of more than Rs.5, 000. Exercise 12Develop the program tax, which consumes the gross pay and produces the amount of tax owed. For a gross pay of $240 or less, the tax is 0%; for over Rs. 240 and Rs. 480 or less, the tax rate is 15%; and for any pay over $480, the tax rate is 28%.Also develop netpay. The program determines the net pay of an employee from the number of hours worked. The net pay is the gross pay minus the tax. Assume the hourly pay rate is Rs.12. Remember to develop auxiliary programs when a definition becomes too large or too complex to manage.Exercise 13Some credit card companies pay back a small portion of the charges a customer makes over a year. One company returns 1. .25% for the first Rs500 of charges, 2. .50% for the next Rs1000 (that is, the portion between Rs500 and Rs1500), 3. .75% for the next Rs1000 (that is, the portion between Rs1500 and Rs2500), 4. and 1.0% for everything above Rs2500. Thus, a customer who charges Rs. 400 a year receives Rs.1.00, which is 0.25 • 1/100 • 400, and one who charges Rs1, 400 a year receives Rs. 5.75, which is 1.25 = 0.25 • 1/100 • 500 for the first Rs. 500 and 0.50 • 1/100 • 900 = 4.50 for the next Rs. 900. Determine by hand the pay-backs for a customer who

A.1.7Room allocationWrite a program to accept three arrays – Room numbers, room capacity and an array of size 3 representing number of gents,ladies and familes(which consists of a male and a female). The program should return an array of unallocated room numbersThe room number is a 3 digit number(e.g 123) and “1” represents the floor number. The program should ensure to allocate the rooms in lower floors first.Unless a family, a male and female should not be allocated to a room.A.1.8Loan selectionWrite a program to automate the following loan policy.Age categoryGender

Page 54: java programs

ProfessionPersonal assetsLoan amount eligible16 -25M /FSelf-Employed>2500010000

Professional1500026 - 40M SelfEmployed / Professional> 4000025000F

3000041 - 60M / FSelfEmployed / Professional> 5000040000> 60M/FSelf Employed> 2500035000 – Age * 100

Retired25000 – Age * 100

The loan selection program should accept the age, gender, jobstatus and assets and return the eligible loan amount.

A.1.9Shopping ListWrite a program to accept item list from 3 users and prepare an array with items and total count (store it as string instead of integer). The result array can have the format{<item1 name>, <item1 count>,<item2 name>,<item2 count>,<item3 name>, <item4 count>….} I.A.1.1Improve the understandability of the codeclass Problem1 {

Page 55: java programs

int[] a; int nElems; public ArrayBub(int max) { a = new int[max]; } public void insert(int value) { a[nElems] = value; nElems++; } public void Sort() { int out, in; for(out=nElems-1; out>1; out--) for(in=0; in<out; in++) if( a[in] > a[in+1] ) swap(in, in+1); } public void swap(int one, int two) { long temp = a[one]; a[one] = a[two]; a[two] = temp; }A.1.2Refactor the codeclass marks {public static int total (int mark1, int mark2, int mark3, int mark4, int mark5, int mark6) { int totalMarks = 0; totalMarks = mark1 + mark2 + mark3 + mark4 + mark5 + mark6 ; percentagemark = totalMarks / 600; return percentagemark;}}A.1.3Refactor the codeimport java.util.*;class problem3 { int[] numArray = new int[10];public static void incrementElements (int[] integerArray) { int arraylen = integerArray.length; for (int i = 0; i < arraylen; i ++) { System.out.println(integerArray[i]);

Page 56: java programs

} for (int i = 0; i < arraylen; i ++) { integerArray[i] = integerArray[i] + 10; } for (int i=0; i < arraylen; i ++) { System.out.println(integerArray[i]); }}}