0% found this document useful (0 votes)
7 views

TrisectSolvedAll Java Prorgams

The document contains multiple Java programs that perform various calculations, such as summing runs in a cricket series, converting seconds to hours, and checking if numbers are in ascending order. Each program is encapsulated in its own class with a main method for execution, demonstrating basic programming concepts and operations. The code is structured to handle user input and output results for different mathematical and logical operations.

Uploaded by

harendraj2ee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

TrisectSolvedAll Java Prorgams

The document contains multiple Java programs that perform various calculations, such as summing runs in a cricket series, converting seconds to hours, and checking if numbers are in ascending order. Each program is encapsulated in its own class with a main method for execution, demonstrating basic programming concepts and operations. The code is structured to handle user input and output results for different mathematical and logical operations.

Uploaded by

harendraj2ee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 177

-----------------------------------------------------------------------------------------------------------------------------

Module 1 - A Trisect All Modules Programs with Output JAVA for Interview

/*
RunsInSeries
*
The scores of a batsman in the five matches of a one day international series have
been provided.
Calculate the total number of runs the batsman scored in the series.
*/
package module1a;

public class RunsInSeries


{
public static void main(String[] args)
{
RunsInSeries bat=new RunsInSeries();
int result=bat.runScore(95,105,85,115,100);
System.out.println("Batsman Score is = " +result);
}
public int runScore(int num1, int num2, int num3, int num4, int num5)
{
int totalRun=num1+num2+num3+num4+num5;
return totalRun;
}

/*AddTwoNums

Given two numbers as input, calculate the sum of the numbers.

*/
package module1a;

public class AddTwoNums


{
public static void main(String[] args)
{
AddTwoNums obj=new AddTwoNums();
int result=obj.add(40,80);
System.out.println("Result = " +result);
}
public int add(int num1, int num2)
{
int sum=num1+num2;
return sum;

}
}

/*
SecondToHours

Given the time in number of seconds, find out how many hours have been completed
*/
package module1a;

public class SecondToHours


{
public static void main(String[] args)
{
SecondToHours obj=new SecondToHours();
int result=obj.toHours(7700);
System.out.println("Hours is : " +result);
}
public int toHours(int seconds)
{
int hours=3600;
return seconds/hours;
}
}

/*
HundredsDigit

Given a 4 digit number as input, find the value of its hundreds digit.
*/
package module1a;
public class HundredsDigit
{
public static void main(String[] args)
{
HundredsDigit obj=new HundredsDigit();
int result=obj.hundredsDigit(456896327);
System.out.println(" 100 place digit number is : = " + result);
}
public int hundredsDigit(int num)
{
int a=num/100 ;

return a%10;
}

/*
RequiredRunRate
A team is chasing the target set in a one day international match. The objective is to
compute the required run rate.
* The following have provided as input: target, maxOvers, currentScore, oversBowled

*/
package module1a;

public class RequiredRunRate


{
public static void main(String[] args)
{
RequiredRunRate obj=new RequiredRunRate();
double result=obj.runrateRequired(326,49,210,33);
System.out.println("Run Rate Required is = "+ result);

}
public double runrateRequired(int target,int maxOvers, int currentScore, int
oversBowled)
{
double remainOvers=maxOvers - oversBowled;
double remainScore=target - currentScore;
double totalrunrate=(remainScore/remainOvers);
return totalrunrate;

/*
Make3Digit

Given a digit as input, create a 3 digit number in which all the digits are the same as
the input digit.
*/
package module1a;

import java.util.Scanner;

public class Make3Digit


{
public static void main(String[] args)
{
Scanner obj =new Scanner(System.in);
System.out.println("Enter a number is = ");
int num1=obj.nextInt();

int digit=num1*100+num1*10+num1*1;
System.out.println("Three digit number is = "+digit);

/*
MakeDecimal
Given 3 digits a,b and c as input, return a double of the form a.bc

*/
package module1a;
public class MakeDecimal
{
public static void main(String[] args)
{
MakeDecimal obj=new MakeDecimal();
double result=obj.makeDecimal(4,8,1);
System.out.println("Make 3 digit number is = " +result);

double result1=obj.makeDecimal(0, 0, 6);


System.out.println("Make 3 digit number is another result = " +result1);

}
public double makeDecimal(int a, int b, int c)
{
double mkDecimal=((a*100)+(b*10)+(c*1))/100.0;
return mkDecimal;
}

/*
Sum2Digit

Given a 2 digit number as input, compute the sum of its digits. Assume that the
number has 2 digits.
*/
package module1a;

public class Sum2Digit


{
public static void main(String[] args)
{
Sum2Digit obj=new Sum2Digit();
int result=obj.sumTwoDigit(68);
System.out.println("Sum of two digit no is = " +result);

int result1=obj.sumTwoDigit(10);
System.out.println("sum of two digit no is = " +result1);
int result2=obj.sumTwoDigit(13);
System.out.println("sum of two digit no is = " +result2);
int result3=obj.sumTwoDigit(19);
System.out.println("sum of two digit no is = " +result3);
int result4=obj.sumTwoDigit(67);
System.out.println("sum of two digit no is = " +result4);

}
public int sumTwoDigit(int n)
{
int digit=0;
digit=n/10+n%10;
return digit;

/*
AndBooleans
Given three booleans as input, return the and of the all three booleans
*/
package module1a;

public class AndBooleans {


public static void main(String[] args) {
AndBooleans obj=new AndBooleans();
boolean result=obj.andBooleans(true, true, true);
System.out.println("Boolean is = " +result);

boolean result1=obj.andBooleans(true, true, false);


System.out.println("Boolean is = " +result1);

boolean result2=obj.andBooleans(true, false, false);


System.out.println("Boolean is = " +result2);

boolean result3=obj.andBooleans(false, true, true);


System.out.println("Boolean is = " +result3);
boolean result4=obj.andBooleans(false, false, false);
System.out.println("Boolean is = " +result4);

}
public boolean andBooleans(boolean bool1, boolean bool2, boolean bool3)
{
if(bool1 && bool2 && bool3)
return true;
else
return false;
}
}

/*
LargerThanOne
Given three numbers as input, num, num1 and num2, return true if num is greater than
atleast one of num1 and num2.
Do not use if statement to solve this problem.
*/
package module1a;

import java.util.Scanner;

public class LargerThanOne


{
public static void main(String[] args)
{
LargerThanOne obj=new LargerThanOne();
Scanner input=new Scanner(System.in);
System.out.println("Enter a number is = ");
int a=input.nextInt();
int b=input.nextInt();
int c=input.nextInt();
boolean bool =obj.largerThanOne(a, b, c);

System.out.println("Boolean Result is = "+bool );


}
public boolean largerThanOne(int num, int num1, int num2)
{
boolean n=((num>num1) || (num1>num2) || (num2<num));
return n;

/*
NumberInAscendingOrder

Given 3 numbers - num1, num2 and num3 as input, return true if they are in ascending
order.

* Important - Do not use if statement in solution.
*/
package module1a;

import java.util.Scanner;

public class NumberInAscendingOrder


{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
NumberInAscendingOrder obj=new NumberInAscendingOrder();
System.out.println("Enter a first number is = ");
int a=input.nextInt();
System.out.println("Enter a second number is = ");
int b=input.nextInt();
System.out.println("Enter a thirth number is = ");
int c=input.nextInt();

boolean bool=obj.numInAscendingOrder(a, b, c);

System.out.println("Number order is = "+bool);


}
public boolean numInAscendingOrder(int num1, int num2, int num3)
{
if(num1<num2 && num2<num3 && num3>num1 )
return true;
else
return false;
}

/*
SumOf4Digits

Given a number as input, compute the sum of its last 4 digits. Assume that the number
has at least 4 digits.
*/
package module1a;

import java.util.Scanner;

public class SumOf4Digits


{
public static void main(String[] args)
{
SumOf4Digits obj =new SumOf4Digits();
Scanner input=new Scanner(System.in);
System.out.println("Enter a number is = ");
int a=input.nextInt();
int num=obj.sum4Digit(a);
System.out.println("Sum of maximum 4 digit Digit is = " +num) ;
}
public int sum4Digit(int n)
{
int sum=0;
sum=((n%10)+(n%100)/10+(n%1000)/100+(n%10000)/1000);
return sum;
}
}
/*
AreaOfSquare
Problem Statement

You have been given 4 inputs x1,y1,x2 and y2. The points (x1,y1) and (x2,y2)
represent the end points
of the diagonal of a square. Return the area of the square.
*/
package module1a;

import java.util.Scanner;

public class AreaOfSquare


{
public static void main(String[] args)
{
AreaOfSquare obj=new AreaOfSquare();
Scanner input=new Scanner(System.in);
System.out.println("Enter a 1st number is = ");
int a=input.nextInt();
System.out.println("Enter a 2nd number is = ");
int b=input.nextInt();
System.out.println("Enter a 3rd number is = ");
int c=input.nextInt();
System.out.println("Enter a 4th number is = ");
int d=input.nextInt();
double result=obj.areaOfSquare(a, b, c, d);
System.out.println("Area of Square is = "+result);

}
public double areaOfSquare(int x1, int y1, int x2, int y2)
{
return (Math.pow((x1-x2),2)+Math.pow((y1-y2),2))/2;
}
}

/*
AddDigitNumbers
Problem Statement

Given three digits as input, create a 4 digit number out of each input in which all the
digits are the same.
Then add all the 3 numbers and return the value.
*/
package module1a;

import java.util.Scanner;

public class AddDigitNumbers


{
public static void main(String[] args)
{
AddDigitNumbers obj=new AddDigitNumbers();

Scanner input=new Scanner(System.in);


System.out.println("Enter a 1st number is = ");
int a=input.nextInt();
System.out.println("Enter a 1st number is = ");
int b=input.nextInt();
System.out.println("Enter a 1st number is = ");
int c=input.nextInt();
int result=obj.add3To4(a, b, c);
System.out.println("sum of digit is = " +result);

}
public int add3To4(int digit1,int digit2,int digit3)
{
int sum1,sum2,sum3;
int totalSum=0;
sum1=digit1*1000+digit1*100+digit1*10+digit1;
sum2=digit2*1000+digit2*100+digit2*10+digit2;
sum3=digit3*1000+digit3*100+digit3*10+digit3;
totalSum=sum1+sum2+sum3;
return totalSum;

}
/*
SecondsToTime

Given the time of a day in number of seconds, convert it into time in hhmmss format.
Note that the time is past noon, and hence the hours will never be less than 12.
*/
package module1a;

public class SecondsToTime


{
public static void main(String[] args)
{
SecondsToTime obj=new SecondsToTime();
int result=obj.secondTotime(86399);
System.out.println(" Time is hours minutes & seconds is = " +result);
int result1=obj.secondTotime(46800);
System.out.println(" Time is hours minutes & seconds is = " +result1);
int result2=obj.secondTotime(55845);
System.out.println(" Time is hours minutes & seconds is = " +result2);
int result3=obj.secondTotime(36000);
System.out.println(" Time is hours minutes & seconds is = " +result3);
}
public int secondTotime(int seconds)
{
int numWorks=seconds/60;
int sec= seconds%60;
int hours=numWorks/60;
int min=numWorks%60;
int totalTime=hours*10000+min*100+sec;
return totalTime;

}
Module 1 - B

/*
AddForThird

Given three numbers a, b and c, return true if the sum of any two equals the third
number.
*/
package Module1b;

import java.util.Scanner;

public class AddForThird


{
public static void main(String[] args)
{
AddForThird obj=new AddForThird();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int num1=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int num2=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int num3=input.nextInt();
boolean result=obj.addThird(num1, num2, num3);
System.out.println("Result is = "+result);
}
public boolean addThird(int a, int b, int c)
{
int sum1=0,sum2=0,sum3=0;
sum1=a+b;
sum2=b+c;
sum3=c+a;
if(sum1==c || sum2==a || sum3==b)
return true;
else
return false;

}
}

/*
ArithmeticOps

Two numbers a and b and a char c have been provided as inputs. The char c represents
a mathematical
operation namely +,-,*,/,% (remainder). The task is to perform the correct operation
on a and b as specified by the char c.
*/
package Module1b;

import java.util.Scanner;

public class ArithmeticOps


{
public static void main(String[] args)
{
ArithmeticOps obj=new ArithmeticOps();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st element is = ");
int num1=input.nextInt();
System.out.print("Enter 1st element is = ");
int num2=input.nextInt();

System.out.print("Which Arithmeic operation perform = ");


char oper=input.next().charAt(0);
int result=obj.compute(num1, num2, oper);
System.out.println("Result is = " +result);

}
public int compute(int a, int b, char operator)
{
switch(operator)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
case '%': return a%b;
default :
return 0;
}
}

/*
Blackjack

Given 2 int values greater than 0, return whichever value is nearest to 21 without
being greater than 21.
Return -1 if the values are greater than 21. Also return -2 if both the values are same
and less or equal to 21.
*/
package Module1b;

import java.util.Scanner;

public class Blackjack


{
public static void main(String[] args)
{
Blackjack obj=new Blackjack();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int b=input.nextInt();
int result=obj.calculateBlackjack(a, b);
System.out.println("Result is = "+result);

}
public int calculateBlackjack(int num1, int num2)
{
if(num1<=21 && num2<=21)
{
if(num1>num2 && num1!=num2)
return num1;
if(num2>num1 && num1!=num2)
return num2;
if((num1==num2) || (num1<21 && num2<21) || (num1==21 && num2==21))
return -2;
}
else if(num1>21 && num2>21)
{
return -1;
}
else if((num1<21 && num2>21) || (num2<21 && num1>21))
{
if(num1<num2)
return num1;
else
return num2;
}
return 0;

/*
ChangeCharCase

Given a char as input, if it is an alphabet change its case otherwise return it as it is.
*/
package Module1b;

import java.util.Scanner;

public class ChangeCharCase


{
public static void main(String[] args)
{
ChangeCharCase obj=new ChangeCharCase();
Scanner input=new Scanner(System.in);
System.out.print("Enter a character & number function key = ");
char ch1=input.next().charAt(0);
char result=obj.changeCase(ch1);
System.out.println("Result is = " +result);

}
public char changeCase(char ch)

{
if(ch>='A' && ch<='Z')
ch+=32;
else if(ch>='a' && ch<='z')
ch-=32;
return ch;

/*
ComputeGrade
Problem Statement

Given the marks of a student in five subjects, compute the overall grade. The grades
will be on the basis of the aggregate
percentage.if overall percentage >= 85%, grade is A, if it is >=75% it is B, >=60% is
C, >=45% is D, if it is >=33% it is E else F.
*/
package Module1b;

import java.util.Scanner;

public class ComputeGrade


{
public static void main(String[] args)
{
ComputeGrade obj=new ComputeGrade();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st number is =");
int a=input.nextInt();
System.out.print("Enter 1st number is =");
int b=input.nextInt();
System.out.print("Enter 1st number is =");
int c=input.nextInt();
System.out.print("Enter 1st number is =");
int d=input.nextInt();
System.out.print("Enter 1st number is =");
int e=input.nextInt();
char result=obj.isComputeGrade(a, b, c, d, e);
System.out.println("Grade is = "+result);

}
public char isComputeGrade(int marks1,int marks2, int marks3, int marks4, int
marks5)
{
int percentage=(marks1+marks2+marks3+marks4+marks5)*100/500;
if(percentage>=85)
return 'A';
else if(percentage>=75)
return 'B';
else if(percentage>=60)
return 'C';
else if(percentage>=45)
return 'D';
else if (percentage>=33)
return 'E';
else
return 'F';
}

/*
ConsecutiveCentury

Given the scores of a batsman in four innings, return whether he scored at least two
centuries or not.
*/
package Module1b;
import java.util.Scanner;

public class ConsecutiveCentury


{
public static void main(String[] args)
{
ConsecutiveCentury obj=new ConsecutiveCentury();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int b=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int c=input.nextInt();
System.out.print("Enter a 4th number is = ");
int d=input.nextInt();
boolean result=obj.isConsecutiveCentury(a, b, c, d);
System.out.println("Result is = " +result);

}
public boolean isConsecutiveCentury(int score1, int score2, int score3, int score4 )
{
if((score1>=100 && score2>=100) || (score3>=100 && score4>=100)
||(score3>=100 && score1>=100) || (score2>=100 && score4>=100))
return true;
else
return false;

/*
DaysInMonth

Given the number of the month in 2013 (1 for January, 12 for December), return the
number of days in it.
*/
package Module1b;
import java.util.Scanner;

public class DaysInMonth


{
public static void main(String[] args)
{
DaysInMonth obj=new DaysInMonth();
Scanner input=new Scanner(System.in);
System.out.print("Enter a month in number is = ");
int a=input.nextInt();
int result=obj.numOfDays(a);
System.out.println("Month of days is = "+result);

}
public int numOfDays(int month)
{
switch(month)
{
case 1: return 31;
case 2: return 28;
case 3: return 31;
case 4: return 30;
case 5: return 31;
case 6: return 30;
case 7: return 31;
case 8: return 31;
case 9: return 30;
case 10: return 31;
case 11: return 30;
case 12: return 31;
default:
return 0;
}

}
}

/*
Diff25

Given three ints as input , return true if one of them is 25 or more less than one of the
other numbers.
*/
package Module1b;

import java.util.Scanner;

public class Diff25


{
public static void main(String[] args)
{
Diff25 obj=new Diff25();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int num1=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int num2=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int num3=input.nextInt();
boolean result=obj.checkDiff25(num1, num2, num3);
System.out.println("Result is = "+result);

}
public boolean checkDiff25(int a, int b, int c)
{
int x=a-b;
int y=b-c;
int z=c-a;
if(x>=25 || y>=25 || z>=25 || x<=(-25) || y<=(-25) || z<=(-25))
return true;
else
return false;
}

/*
IsDigit
Given a char as input, return true if it is a digit (i.e. between 0 to 9).
*/
package Module1b;

import java.util.Scanner;

public class IsDigit


{
public static void main(String[] args)
{
IsDigit obj=new IsDigit();
Scanner input=new Scanner(System.in);
System.out.print("Enter a Element is = ");
char ch1=input.next().charAt(0);
boolean result=obj.isDigit(ch1);
System.out.println("Result is = "+result);

}
public boolean isDigit(char ch)
{
if(ch>='0' && ch<='9')
return true;
else
return false;
}

/*
LargestOfThree

Given three numbers as input, return the largest number.


*/
package Module1b;

import java.util.Scanner;

public class LargestOfThree


{
public static void main(String[] args)
{
LargestOfThree obj=new LargestOfThree();
Scanner input=new Scanner(System.in);
System.out.println("Enter three numbers is = ");
int num1=input.nextInt();
int num2=input.nextInt();
int num3=input.nextInt();
int result=obj.largestOfThree(num1, num2, num3);
System.out.println("Largest number is = "+result);
}
public int largestOfThree(int a,int b, int c)
{
if(a>b && a>c)
return a;
else if(b>c && b>a)
return b;
else
return c;

/*
LeapYear

Given a year, return true if it is a leap year otherwise return false. Please note that
years that are
multiples of 100 are not leap years, unless they are also multiples of 400.
*/
package Module1b;

import java.util.Scanner;

public class LeapYear


{
public static void main(String[] args)
{
LeapYear obj=new LeapYear();
Scanner input=new Scanner(System.in);
System.out.print("Enter a year in number = ");
int a=input.nextInt();
boolean result=obj.isLeapYear(a);
System.out.println("Result is = "+result);

}
public boolean isLeapYear(int year)
{
if((year%400==0 || year%100!=0) && (year%4==0))
return true;
else
return false;

/*
otteryPrize

Jack bought a lottery ticket. He will get a reward based on the number of the lottery
ticket.
The rules are as follows - If the ticket number is divisible by 4, he gets 6 - If the ticket
number is divisible
by 7, he gets 10 - If the ticket number is divisible by both 4 and 7, he gets 20 -
Otherwise, he gets 0.
Given the number of the lottery ticket as input, compute the reward he will receive
*/
package Module1b;

import java.util.Scanner;

public class LotteryPrize


{
public static void main(String[] args)
{
LotteryPrize obj=new LotteryPrize();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result=obj.lotteryReward(a);
System.out.println("Result is = "+result);

}
public int lotteryReward(int ticketNumber)
{
if(ticketNumber%4==0 && ticketNumber%7!=0 )
return 6;
else if(ticketNumber%7==0 && ticketNumber%4!=0)
return 10;
else if (ticketNumber%4==0 && ticketNumber%7==0)
return 20;
else
return 0;

/*
LotteryPrize3
Problem Statement

Jack bought 3 lottery tickets. He will get a reward based on the number of the lottery
ticket. The rules are as follows - If
the ticket number is divisible by 4, he gets 6 - If the ticket number is divisible by 7, he
gets 10 - If the ticket number is
divisible by both 4 and 7, he gets 20 - Otherwise, he gets 0. Given the numbers of the
3 lottery tickets as input,
compute the total reward he will receive. In this problem define a function to compute
the reward given the ticket number and
use that function to calculate the total reward.
*/
package Module1b;

import java.util.Scanner;

public class LotteryPrize3


{
public static void main(String[] args)
{
LotteryPrize3 obj=new LotteryPrize3();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st nubmer is = ");
int a=input.nextInt();
System.out.print("Enter a 2nd nubmer is = ");
int b=input.nextInt();
System.out.print("Enter a 3rd nubmer is = ");
int c=input.nextInt();
int result=obj.lotteryTicketfor3(a, b, c);

System.out.println("Result is = "+result);

public int lotteryTicketfor3(int ticketNumber1, int ticketNumber2, int


ticketNumber3)
{
int num1, num2, num3;
num1=totalReward(ticketNumber1);
num2=totalReward(ticketNumber2);
num3=totalReward(ticketNumber3);
int sum=num1+num2+num3;
return sum;
}

public int totalReward(int n)


{
if(n%4==0 && n%7!=0)
return 6;
else if(n%7==0 && n%4!=0)
return 10;
else if(n%7==0 && n%4==0)
return 20;
else
return 0;

}
}
/*
LotteryTicket
Problem Statement

You have purchased a lottery ticket showing 3 digits a, b, and c. The digits can be 0,
1, or 2.
If they all have the value 2, the result is 10. Otherwise if they are all the same, the
result is 5.
Otherwise if both b and c are different from a, the result is 1. Otherwise the result is 0.
*/
package Module1b;

import java.util.Scanner;

public class LotteryTicket


{
public static void main(String[] args)
{
LotteryTicket obj=new LotteryTicket();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a1=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int a2=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int a3=input.nextInt();
int result=obj.lotteryTicket(a1, a2, a3);
System.out.println("Result is = "+result);

}
public int lotteryTicket(int a, int b, int c)
{
if(a==2 && b==2 && c==2)
return 10;
else if(a==b && b==c && c==a && a!=2)
return 5;
else if(a!=b && a!=c)
return 1;
else
return 0;

/*
MiddleChar

Given three chars as input, return the char that would come in the middle if the chars
were arranged in order.
Note that > operator can be used for chars.
*/
package Module1b;

import java.util.Scanner;

public class MiddleChar


{
public static void main(String[] args)
{
MiddleChar obj=new MiddleChar();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st Element is = ");

char a=input.next().charAt(0);
System.out.print("Enter 2nd Element is = ");
char b=input.next().charAt(0);
System.out.print("Enter 3rd Element is = ");
char c=input.next().charAt(0);
char result=obj.middle(a, b, c);
System.out.println("Result of Middle element is = "+result);

}
public char middle(char ch1, char ch2, char ch3)
{
if((ch1>=ch2 && ch1<=ch3) ||(ch1>=ch3 && ch1<=ch2))
return ch1;
else if((ch2>=ch3 && ch2<=ch1) || (ch2>=ch1 && ch2<=ch3))
return ch2;
else
return ch3;
}

/*
Multiple37

Given a number n, return true if it is divisible by either 3 or 7.


*/
package Module1b;

import java.util.Scanner;

public class Multiple37


{
public static void main(String[] args)
{
Multiple37 obj=new Multiple37();

System.out.println("Enter a 1st number is = ");


Scanner input=new Scanner(System.in);
int num1=input.nextInt();
boolean result1=obj.multiple37(num1);
System.out.println("1st Boolean result is = "+result1);

System.out.println("Enter a 2nd number is = ");


int num2=input.nextInt();
boolean result2=obj.multiple37(num2);
System.out.println("2nd Boolean result is = "+result2);

}
public boolean multiple37(int n)
{
if(n%3==0 || n%7==0)
return true;
else
return false;
}

/*
MultipleCheck

Given a number n as input, return true if n is divisible by at least three and not
divisible by at least one of 2,3,5,7 and 11.
*/
package Module1b;

import java.util.Scanner;

public class MultipleCheck


{
public static void main(String[] args)
{
MultipleCheck obj=new MultipleCheck();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number = ");
int a=input.nextInt();
boolean result=obj.isMultipleCheck(a);
System.out.println("Result is = "+result);

}
public boolean isMultipleCheck(int num)

{
if(num%2==0 && num%3==0 && num%5==0 && num%7==0 &&
num%11==0)
return false;
else if((num%2==0 && num%3==0 && num%5==0) || (num%2==0 &&
num%3==0 && num%7==0) || (num%3==0 && num%7==0 && num%11==0))
return true;
else if((num%2==0 && num%3==0 && num%11==0) || (num%5==0 &&
num%7==0 && num%11==0) || (num%2==0 && num%5==0 && num%11==0))
return true;
else if((num%2==0 && num%5==0 && num%7==0)||(num%3==0 &&
num%5==0 && num%7==0) ||(num%2==0 && num%7==0 && num%11==0))
return true;

else if(num%2!=0 || num%3!=0 || num%5!=0 || num%7!=0 ||num%11!=0)


return false;
else
return false;

/*
Reverse3

Given a 3 digit number as input, reverse it.


*/
package Module1b;

import java.util.Scanner;

public class Reverse3


{
public static void main(String[] args)
{
Reverse3 obj=new Reverse3();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result=obj.reverseDigit(a);
System.out.println("Reverse Digits is = "+result);

}
public int reverseDigit(int num)
{
int revNum=0;
int rem;
while(num>0)
{
rem=num%10;
revNum=(revNum*10)+rem;
num=num/10;
}
return revNum;
}

/*
SameLast2Digits

You have been given 4 numbers as input. Return true if any one the numbers has the
same last 2 digits.
For e.g. 123455 has the same last 2 digits (5 and 5) whereas 123545 does not (4 and
5). In this problem,
define a function that check whether a number has the same two digits or not and
returns true or false.
Use that function to calculate for the 4 numbers
*/
package Module1b;

import java.util.Scanner;

public class SameLast2Digits


{
public static void main(String[] args)
{
SameLast2Digits obj=new SameLast2Digits();
Scanner input=new Scanner(System.in);

System.out.print("Enter a 1st number is = ");


int a1=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int a2=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int a3=input.nextInt();
System.out.print("Enter a 4th number is = ");
int a4=input.nextInt();
boolean result=obj.isSameLastDigit(a1, a2, a3, a4);
System.out.println("Result is = "+result);

}
public boolean isSameLastDigit(int num1,int num2,int num3,int num4)
{
boolean a=checkLast2Digit(num1);
boolean b=checkLast2Digit(num2);
boolean c=checkLast2Digit(num3);
boolean d=checkLast2Digit(num4);

if(a|b|c|d==true)
return true;
else
return false;
}
public boolean checkLast2Digit(int num)
{
int n1,n2;
n1=num%10;
n2=(num/10)%10;
if(n1==n2)
return true;
else
return false;

/*
SameLastDigit

Given 2 non negative numbers a and b, return true if both of them have the same last
digit.
*/
package Module1b;

import java.util.Scanner;
public class SameLastDigit
{
public static void main(String[] args)
{
SameLastDigit obj=new SameLastDigit();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st number is = " );
int x=input.nextInt();
System.out.print("Enter 2nd number is = ");
int y=input.nextInt();
boolean result=obj.isSameLarstDigit(x, y);
System.out.println("Result is a%b = " +result);

}
public boolean isSameLarstDigit(int a, int b)
{
int num1=a%10;
int num2=b%10;
if(num1==num2)
return true;
else
return false;
}

/*
ScoredCentury

The scores of a batsman in his last three innings have been provided. You have to
determine whether he has
scored a century in the last three innings or not. If yes, return true else return false.
*/
package Module1b;

import java.util.Scanner;

public class ScoredCentury


{
public static void main(String[] args)
{
ScoredCentury obj=new ScoredCentury();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st innings run = ");
int inn1=input.nextInt();
System.out.print("Enter a 1st innings run = ");
int inn2=input.nextInt();
System.out.print("Enter a 1st innings run = ");
int inn3=input.nextInt();
boolean result=obj.hasScored(inn1, inn2, inn3);
System.out.println("Boolean result is = "+result);

}
public boolean hasScored(int score1, int score2, int score3)
{
if(score1>=100 || score2>=100 || score3>=100)
return true;
else
return false;

/*
Special20Number

A number is special20 if it is a multiple of 20 or if it is one more than a multiple of 20.


Write a function that return true if the given non-negative number is special20.
*/
package Module1b;

import java.util.Scanner;

public class Special20Number


{
public static void main(String[] args)
{
Special20Number obj=new Special20Number();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
boolean result=obj.special20(a);
System.out.println("Result is = "+result);

}
public boolean special20(int num)
{
if(num%20==0 || num%20==1)
return true;
else
return false;
}

/*
SumDivide11

You have been given 4 numbers as input. Return true if you can find 3 numbers
among them whose sum is divisible by 11.
In this problem, define a function that takes 3 numbers as input and returns true if
there sum is divisible by 11.
Use this function to check for the 4 numbers.
*/
package Module1b;

import java.util.Scanner;

public class SumDivide11


{
public static void main(String[] args)
{
SumDivide11 obj=new SumDivide11();
Scanner input=new Scanner(System.in);

System.out.print("Enter a 1st number is = ");


int a1=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int a2=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int a3=input.nextInt();
System.out.print("Enter a 4th number is = ");
int a4=input.nextInt();

boolean result=obj.sumDivBy11(a1, a2, a3, a4);


System.out.println("Result is = "+result);

}
public boolean sumDivBy11(int num1, int num2, int num3, int num4)
{
boolean a=checkSumDivBy11(num1, num2, num3);
boolean b=checkSumDivBy11(num2, num3, num4);
boolean c=checkSumDivBy11(num3, num4, num1);
boolean d=checkSumDivBy11(num4, num1, num2);
if(a|b|c|d==true)
return true;
else
return false;

}
public boolean checkSumDivBy11(int x, int y, int z)
{
int sum=x+y+z;
if(sum%11==0)
return true;
else
return false;
}

/*
SumLast3

Given a number as input, return the sum of its last 3 digits.


*/
package Module1b;

import java.util.Scanner;

public class SumLast3


{
public static void main(String[] args)
{
SumLast3 obj=new SumLast3();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int n=input.nextInt();
int result=obj.sumOfLast3Digits(n);
System.out.println("Sum of Last 3 digits is = "+result);
}
public int sumOfLast3Digits(int num)
{
int sum=0;
sum=num%10+(num%100)/10+(num%1000)/100;
return sum;
}

/*
TicketNumbers

You have a green lottery ticket, with ints a, b, and c on it. If the numbers are all
different from each other,
the result is 0. If all of the numbers are the same, the result is 20. If two of the
numbers are the same, the result is 10.
*/
package Module1b;

import java.util.Scanner;

public class TicketNumbers


{
public static void main(String[] args)
{
TicketNumbers obj=new TicketNumbers();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a1=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int a2=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int a3=input.nextInt();
int result=obj.calcuPrize(a1, a2, a3);
System.out.println("Result is = "+result);

}
public int calcuPrize(int a, int b, int c)
{
if(a!=b && b!=c && c!=a)
return 0;
else if(a==b && b==c && c==a)
return 20;
else
return 10;
}

Module 1 - C

/*
AllFactorsArePrime

Given a number n, return true is all the factors of n are prime numbers.
Note that 1 and the number itself are not considered as factors in this problem.
*/
package Module1c;

import java.util.Scanner;

public class AllFactorsArePrime


{
public static void main(String[] args)
{
AllFactorsArePrime obj=new AllFactorsArePrime();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int num=input.nextInt();
boolean result=obj.areAllFactorsPrime(num);
System.out.println("Multiple of factor is given number prime or not = "+result);
}
public boolean areAllFactorsPrime(int n) {

for(int i=2; i<=n/2; i++)


{
int a=0;
if(n%i==0)
{a=i;}
if(!isPrime(a))
return false;
}
return true;
}
public boolean isPrime(int x)
{
if(x==2)
return true;
for(int i=3; i<=x/2; i++)
{
if(x%i==0)
return false;
}
return true;

}
}

/*
AnyonePrime

Given three numbers as input, return true if at least one of them is a prime number.
*
For solving this problem, define a function that checks whether a number is a prime or
not and use that function.
*/
package Module1c;

import java.util.Scanner;

public class AnyonePrime


{
public static void main(String[] args)
{
AnyonePrime obj=new AnyonePrime();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a1=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int a2=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int a3=input.nextInt();

boolean result=obj.anyOnePrimeNo(a1, a2, a3);


System.out.println("Number is Prime or no = "+result);

}
public boolean anyOnePrimeNo(int num1, int num2, int num3)
{
boolean a=isPrimeNo(num1);
boolean b=isPrimeNo(num2);
boolean c=isPrimeNo(num3);
if(a|b|c==true)
return true;
else
return false;
}
public boolean isPrimeNo(int num)
{
if(num>1)
{
for(int i=2; i<=num/2; i++)
{
if(num%i==0)
return false;
}
return true;
}

return false;
}

/*
ComputeNthPrime

Given an input n, find out the nth prime


*/
package Module1c;

import java.util.Scanner;

public class ComputeNthPrime


{
public static void main(String[] args)
{
ComputeNthPrime obj=new ComputeNthPrime();
Scanner input=new Scanner(System.in);
System.out.print("Enter number is = ");
int a=input.nextInt();
int result=obj.computePrime(a);
System.out.println("Whose prime number count given number = "+result);

}
public int computePrime(int n)
{
int currentNum=1;
int count=0;
while(count!=n)
{
currentNum++;
if(isPrime(currentNum))
count++;
}
return currentNum;
}

public boolean isPrime (int num)


{
if(num>1)
{
for(int i=2; i<=num/2; i++)
{
if(num%i==0)
return false;

}
return true;
}
return false;
}

/*
Count3Den

A number is defined as a 3Den if it is a multiple of 3 or has the digit 3 in it.


Given a number num as input, count the number of 3Den between 1 and num.
*/
package Module1c;

import java.util.Scanner;

public class Count3Den


{
public static void main(String[] args)
{
Count3Den obj=new Count3Den();
Scanner input=new Scanner(System.in);
System.out.print("Enter number is = ");
int b=input.nextInt();
int result=obj.count(b);
System.out.println("Divied by 3 given a number is = "+result);
}
public int count(int num){

int count=0;
for(int i=1; i<=num; i++)
{
if(i%3==0 || check3Den(i))
count++;
}

return count;
}
public boolean check3Den(int x)
{
while(x>0)
{
int a=x%10;
if(a==3)
return true;
x=x/10;
}
return false;
}

/*
CountFactors

Given a number n as input, find the count of its factors other than 1 and n.
*/
package Module1c;

import java.util.Scanner;

public class CountFactors


{
public static void main(String[] args)
{
CountFactors obj=new CountFactors();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result=obj.countOfFactors(a);
System.out.println("Count the number of factor is = "+result);

}
public int countOfFactors(int n)
{
int count=0;
for(int i=2; i<n; i++)
{
if(n%i==0)
count++;
}
return count;
}

/*
CountTheDigit

Given a number n and a digit d as input, find the number of time d occurs in n. You
can assume that the number is non-negative.
*/
package Module1c;

import java.util.Scanner;

public class CountTheDigit


{
public static void main(String[] args)
{
CountTheDigit obj=new CountTheDigit();
Scanner input=new Scanner(System.in);
System.out.print("Enter number is = ");
int a=input.nextInt();
System.out.print("Enter a digit: ");
int b=input.nextInt();
int result=obj.findDigitCount(a, b);
System.out.println("Number of Digit Occur in the number = "+result);

}
public int findDigitCount(int num, int digit)
{
int temp=0,count=0;
while(num>0)
{
temp=num%10;
if(temp==digit)
count++;
num=num/10;
}
return count;

/*
FirstDigit

Given a number as input, find the most significant digit in it. You can assume that the
number is not negative.
*/
package Module1c;

import java.util.Scanner;

public class FirstDigit


{
public static void main(String[] args)
{
FirstDigit obj=new FirstDigit();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result=obj.firstDigit(a);
System.out.println("First Digit is = "+result);
}
public int firstDigit(int num)
{
int rem=0;
while(num>0)
{
rem=num%10;
num=num/10;
}
return rem;
}

/*
FizzBuzz

A number is considered fizz if it is divisible by 3. It is considered buzz if it is divisible


by 5.
It is considered fizzbuzz if it is divisible by both 3 and 5. A fizzbuzz is neither fizz nor
buzz.
Given two numbers n1 and n2 such that n2>n1, let f be the number of fizz, b be the
number of buzz and
fb be the number of fizzbuzz between n1 and n2(both n1 and n2 are included).
Calculate and return the value of 3*f+5*b-15*fb.
*/
package Module1c;

import java.util.Scanner;

public class FizzBuzz


{
public static void main(String[] args)
{
FizzBuzz obj = new FizzBuzz();
Scanner input = new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int b=input.nextInt();
int result=obj.isFizzBuzz(a, b);
System.out.println("Result is = "+result);

}
public int isFizzBuzz(int num1, int num2)
{
int fb=0,f=0,b=0;
for(int i=num1; i<=num2; i++)
{
if(i%3==0 && i%5==0)
fb=fb+1;
else if(i%3==0)
f=f+1;
else if(i%5==0)
b=b+1;
}
return 3*f+5*b-15*fb;
}

/*
s3Den

A number is defined as a 3den if it is a multiple of 3 or has the digit 3 in it.


Given a number as input, determine whether it is a 3den or not.
*/
package Module1c;

import java.util.Scanner;

public class Is3Den


{
public static void main(String[] args)
{
Is3Den obj=new Is3Den();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
boolean result=obj.is3Den(a);
System.out.println("Result is = "+result);

}
public boolean is3Den(int num)
{
int i=0;
if(num%3==0)
return true;
while(num>0)
{
i=num%10;
if(i==3)
num=num/10;
return true;

return false;
}

/*
IsPrimeNumber

Given a number n as input, return whether the number is a prime number or not.
Please note that 1 is not a prime number.
*/
package Module1c;

import java.util.Scanner;

public class IsPrimeNumber


{
public static void main(String[] args)
{
IsPrimeNumber obj =new IsPrimeNumber();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
boolean result=obj.isPrime(a);
System.out.println("Number is prime = "+result);
}
public boolean isPrime(int num)
{
if(num>1)
{
for(int i=2; i<=num/2; i++)
{
if(num%i==0)
return false;
}
return true;
}
return false;
}

/*
LargestDigit

Given a number as input, find the largest digit in it. You can assume that the number
is not negative.
*/
package Module1c;

import java.util.Scanner;

public class LargestDigit


{
public static void main(String[] args)
{
LargestDigit obj=new LargestDigit();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result=obj.maxDigit(a);
System.out.println("Maximum digit is = "+result);
}
public int maxDigit(int num)
{
int max=0;
while(num>0)
{
int rem=num%10;
if(rem>max)
max=rem;
num=num/10;
}
return max;
}

/*
NextMultiple37

Given a number num as input, find the smallest number greater than num that is a
multiple of both 3 and 7.
*/
package Module1c;

import java.util.Scanner;

public class NextMultiple37


{
public static void main(String[] args)
{
NextMultiple37 obj=new NextMultiple37();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result=obj.findNextMultiple37(a);
System.out.println("A number is Next multiple of 3 & 7 is = "+result);

}
public int findNextMultiple37(int num)
{
int mul=0;
//for(int i=num; i<=10000; i++)
for(int i=num; i>=num; i++)
{
if(i%3==0 && i%7==0)
break;
mul=i+1;
}
return mul;
}
}

/*
NthPower

Given a number a, compute the nth power of a.


*/
package Module1c;

import java.util.Scanner;

public class NthPower


{
public static void main(String[] args)
{
NthPower obj= new NthPower();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a1=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int a2=input.nextInt();
int result=obj.nthPower(a1, a2);
System.out.println("a of b power number is = "+result);

}
public int nthPower(int a, int b)
{
int temp=1;
if(b==0)
return 1;
for(int i=1; i<=b; i++)
{
temp=temp*a;
}
return temp;
}

/*
PerfectNumber

A perfect number is a positive integer that is equal to the sum of its factors.
For example, 6 is a perfect number because 6=1+2+3; but 24 is not perfect because
24<1+2+3+4+6+8+12.
Given a number n, the objective is find out whether it is a perfect number or not.
*/
package Module1c;

import java.util.Scanner;

public class PerfectNumber


{
public static void main(String[] args)
{
PerfectNumber obj = new PerfectNumber();
Scanner inpput = new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=inpput.nextInt();
boolean result=obj.isPerfect(a);
System.out.println("Perfect number is true or false = "+result);

}
public boolean isPerfect(int num)
{
int sum=0;
for(int i=1; i<num; i++)
{
if(num%i==0)
sum=i+sum;

if(sum==num)
return true;
else
return false;
}

/*
ReverseNumber

Given a number as input, reverse it. You can assume that the number is not negative.
*/
package Module1c;

import java.util.Scanner;

public class ReverseNumber


{
public static void main(String[] args)
{
ReverseNumber obj=new ReverseNumber();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result=obj.reverse(a);
System.out.println("Reverse number is = "+result);

public int reverse(int num){

int revNum = 0;
while (num > 0) {
int rem = num % 10;
revNum = (revNum * 10) + rem;
num = num / 10;
}
return revNum;

/*
SameFirst

Given three numbers as input, return true if the first digit of any two of them is the
same.
The first digit of 2345 is 2, of 981201 is 9. Assume all the numbers are positive
integers greater than 0.
For solving this problem, define a function that computes the first digit if a number
and use that function.
*/
package Module1c;

import java.util.Scanner;

public class SameFirst


{
public static void main(String[] args)
{
SameFirst obj=new SameFirst();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int b=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int c=input.nextInt();
boolean result=obj.sameFirstDigit(a, b, c);
System.out.println("First number occure 2nd number or 3rd number = "+result);

}
public boolean sameFirstDigit(int num1, int num2, int num3)
{
int x=findDigit(num1);
int y=findDigit(num2);
int z=findDigit(num3);
if(x==y || y==z || z==x)
return true;
else
return false;

}
public int findDigit(int num)
{
int temp=0,rem=0;
while(num>0)
{
rem=num%10;
temp=rem;
num=num/10;

}
return temp;
}

/*
SumNumbers

Given a number n as input, output the sum of numbers from 1 to n.


*/
package Module1c;

import java.util.Scanner;

public class SumNumbers


{
public static void main(String[] args)
{
SumNumbers obj=new SumNumbers();
Scanner input=new Scanner(System.in);
System.out.print("Enter a nubmer is = ");
int a=input.nextInt();
int result=obj.sumOfNumbers(a);
System.out.println("Sum of number is = "+result);
}
public int sumOfNumbers(int n)
{
int sum=0;
for(int i=0;i<=n;i++)
{
sum=sum+i;
}
return sum;
}

/*
SumNumbers1

Given a number n as input, find the sum of all numbers from 1 to n which are not
divisible by either 2 or 3.
*/
package Module1c;

import java.util.Scanner;

public class SumNumbers1


{
public static void main(String[] args)
{
SumNumbers1 obj=new SumNumbers1();
Scanner input=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result=obj.isSum(a);
System.out.println("Add of number is = "+result);

}
public int isSum(int n)
{
int sum=0;
for(int i=0; i<=n; i++)
{
if(i%2!=0 && i%3!=0)
sum=sum+i;
}
return sum;
}

/*
SumOfDigits

Given a number n, find the sum of its digits.


*/
package Module1c;

import java.util.Scanner;

public class SumOfDigits


{
public static void main(String[] args)
{
SumOfDigits obj = new SumOfDigits();
Scanner input = new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
int result = obj.sumDigits(a);
System.out.println("Sum of digit is = "+result);

}
public int sumDigits(int num)
{
int sumDig=0;
while(num>0)
{
int rem=num%10;
sumDig=sumDig+rem;
num=num/10;
}
return sumDig;
}

/*
SumOfDigitsWithCount

Given 2 inputs, a number n and the number of digits it has d , find the sum of its
digits.
*/
package Module1c;

import java.util.Scanner;

public class SumOfDigitsWithCount


{
public static void main(String[] args)
{
SumOfDigitsWithCount obj=new SumOfDigitsWithCount();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int num=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int count=input.nextInt();
int result=obj.sumDigits(num, count);
System.out.println("Sum of digit is & also count digit is = "+result+", "+count);

}
public int sumDigits(int num, int count)
{
int sum=0;
for(int i=1; i<=count; i++)
{
int b=num%10;
sum=sum+b;
num=num/10;
}
return sum;
}

/*
SumOfSquares

Given two numbers n1 and n2 such that n2>n1, find sum of squares of all numbers
from n1 to n2 (including n1 and n2).
*/
package Module1c;

import java.util.Scanner;

public class SumOfSquares


{
public static void main(String[] args)
{
SumOfSquares obj=new SumOfSquares();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st Number is = ");
int a=input.nextInt();
System.out.print("Enter a 2nd Number is = ");
int b=input.nextInt();
int result=obj.computeSumOfSquares(a, b);
System.out.println("Sum of total number is = "+result);
}
public int computeSumOfSquares(int n1, int n2)
{
int sum=0;
if(n2>=n1)
for(n1=n1; n1<=n2; n1++)
{
sum=sum+n1*n1;
}
return sum;
}

/*
SumRounded

Round a number to the next multiple of 10 if its ones digit is 5 or more, otherwise
round it the previous multiple of 10.
So, 25 and 26 round to 30 where as 23 and 24 round to 20. 20 also rounds to 20. You
have been given 4 ints as input.
Round each of the input values and return their sum.
*/
package Module1c;

import java.util.Scanner;

public class SumRounded


{
public static void main(String[] args)
{
SumRounded obj=new SumRounded();
Scanner input=new Scanner(System.in);
System.out.print("Enter a 1st number is = ");
int a=input.nextInt();
System.out.print("Enter a 2nd number is = ");
int b=input.nextInt();
System.out.print("Enter a 3rd number is = ");
int c=input.nextInt();
System.out.print("Enter a 4th number is = ");
int d=input.nextInt();
int result=obj.sumRounded(a, b, c, d);
System.out.println("Sum of Rounded number is = "+result);

}
public int sumRounded(int num1, int num2, int num3, int num4)
{
int n1=roundedNum(num1);
int n2=roundedNum(num2);
int n3=roundedNum(num3);
int n4=roundedNum(num4);
return n1+n2+n3+n4;

}
public int roundedNum(int num)
{
int rem=num%10;
num=num/10;
if(rem>=0 && rem<5)
return num*10;
else
return num*10+10;
}

/*
SuperDivide

A positive int is called super-divide if every digit in the number divides the number.
So for example 128 divides itself since 128 is divisible by 1, 2, and 8. Note that no
number
is divisible by 0. Given a number as input, determine if it is a super-divide.
*/
package Module1c;

import java.util.Scanner;

public class SuperDivide


{
public static void main(String[] args)
{
SuperDivide obj =new SuperDivide();
Scanner input= new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=input.nextInt();
boolean result=obj.checkSuper(a);
System.out.println("Number divide the given digit own by it self = "+result);

}
public boolean checkSuper(int num)
{
if(num%10==0)
return false;
else if(num%10!=0)
{
int temp=num;
while(temp>0)
{
int rem=temp%10;
if(num%rem!=0)
return false;
temp=temp/10;
}

}
return true;

Module 2 – Strings

/*
BatBall

Given a string, return true if the string "bat" and "ball" appear the same number of
times.
*/
package module2_strings;

import java.util.Scanner;

public class BatBall


{
public static void main(String[] args)
{
BatBall obj=new BatBall();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str1=input.nextLine();
boolean result=obj.equal(str1);
System.out.println("bat and ball are same no times or not : "+result);
}
public boolean equal(String str)
{
int index1=str.indexOf("bat");
int index2=str.indexOf("ball");
int count1=0;
int count2=0;
while(index1!=-1)
{
index1=str.indexOf("bat", index1+1);
count1++;
}
while(index2!=-1)
{
index2=str.indexOf("ball", index2+1);
count2++;
}
if(count1==count2)
return true;
else
return false;
}

/*
BinToInt

Given a binary number as input convert it into base 10 (decimal system). Note that to
convert a number 100111
from binary to decimal, the value is 1*2^5 + 0*2^4 + 0*2^3 + 1*2^2 + 1*2^1+ 1*2^0.
Also note that 5 here is the length of the binary number – 1.
*/
package module2_strings;

import java.util.Scanner;
public class BinaryToInt
{
public static void main(String[] args)
{
BinaryToInt obj=new BinaryToInt();
Scanner input=new Scanner(System.in);
System.out.print("Enter binary number is : ");
String str=input.nextLine();
int result=obj.convert(str);
System.out.println("Convert binary no. to Decimal system : "+result);

}
public int convert(String binary)
{
long num=Long.parseLong(binary);
int len=binary.length();
int sum=0;
for(int i=0; i<len; i++)
{
long rem=num%10;
double digit=rem*(Math.pow(2, i));
sum=sum+(int)digit;
num=num/10;
}
return sum;
}

/*
ChangeStringCase

Given a string as input, the expected output is a string where the case of all alphabets
has been changed.
*/
package module2_strings;

import java.util.Scanner;
public class ChangeStringCase
{
public static void main(String[] args)
{
ChangeStringCase obj=new ChangeStringCase();
Scanner input=new Scanner(System.in);
System.out.print("Enter String ");
String str1=input.nextLine();
String result=obj.changeCase(str1);
System.out.println("Change String is : "+result);

}
public String changeCase(String sentence)
{
/* 1st Method program
char chars[]=sentence.toCharArray();
for(int i=0; i<chars.length; i++)
{
char ch=chars[i];
if(Character.isUpperCase(ch))
{
chars[i] =Character.toLowerCase(ch);
}
else if(Character.isLowerCase(ch))
{
chars[i]=Character.toUpperCase(ch);
}
}
return new String(chars); */

/* 2nd Method program


int len=sentence.length();
String res="";
for(int i=0; i<len; i++)
{
char ch=sentence.charAt(i);
if(Character.isUpperCase(ch))
{
res+=Character.toLowerCase(ch);
}
else if(Character.isLowerCase(ch))
{
res+=Character.toUpperCase(ch);
}
else
{
res+=ch;
}
}
return res; */

int len=sentence.length();
String res="";
for(int i=0; i<len; i++)
{
char ch=sentence.charAt(i);
if(ch>='A'&& ch<='Z')
{
res+=(char)(ch+32);
}
else if(ch>='a' && ch<='z')
{
res+=(char)(ch-32);
}
else
{
res+=ch;
}
}
return res;
}

/*
CombineStr

Given two strings s1 and s2 as input, create a string made of the first char of s1,the
first char of s2,
the second char of s1, the second char of s2, and so on. Any leftover chars go at the
end of the result string.
*/
package module2_strings;

import java.util.Scanner;

public class CombineStr


{
public static void main(String[] args)
{
CombineStr obj=new CombineStr();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st string : ");
String st1=input.nextLine();
System.out.print("Enter 2nd string : ");
String st2=input.nextLine();
String res=obj.combine(st1, st2);
System.out.println("Addition of char is : "+res);

}
public String combine(String str1, String str2)
{
int len1=str1.length();
int len2=str2.length();
String result="";
int i;
for(i=0; i<len1 && i<len2; i++)
{
result=result+str1.charAt(i)+str2.charAt(i);
}
if(i==len1)
{
result+=str2.substring(i);
}
else
{
result+=str1.substring(i);
}
return result;
}
}

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package module2_strings;

import java.util.*;
/**
*
* @author Home
*/
public class ComparatorDemo1 {
public static void main(String[] args) {

TreeSet t= new TreeSet(new MyComparator());


t.add("Ram");
t.add("Shyama");
t.add("Upendra");
t.add("Ghanshyam");
t.add("Arun");
t.add("arun");
System.out.println(t);
}

class MyComparator implements Comparator


{
public int compare(Object ob1, Object ob2)
{
String s1=ob1.toString();
String s2=ob2.toString();
return s1.compareTo(s2);//natural order(default order)(asending)
//return -s1.compareTo(s2);// customise order(desending order)
}
}
/*
ConcatAsPattern

Given 2 strings str1 and str2 as input, return a string of the form (str1)str2(/str1)
*/
package module2_strings;

import java.util.Scanner;

public class ConcatAsPattern


{
public static void main(String[] args)
{
ConcatAsPattern obj = new ConcatAsPattern();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st String : ");
String a=input.nextLine();
System.out.print("Enter 2nd String : ");
String b=input.nextLine();
String result=obj.makePattern(a, b);
System.out.println("String form is : "+result);

}
public String makePattern(String str1, String str2)
{
String res="("+str1+")"+str2+"(/"+str2+")";
return res;
}

/*
CountCharInString

Given a string and a char as input, output the number of times, the char appears in the
string.
*/
package module2_strings;
//import java.io.BufferedReader;
//import java.io.InputStreamReader;
import java.util.Scanner;

public class CountCharInString


{
public static void main(String[] args)
{
//BufferedReader reader=new BufferedReader(new
InputStreamReader(System.in));

CountCharInString obj=new CountCharInString();


Scanner input=new Scanner(System.in);
System.out.print("Enter Word is = ");
String name=input.nextLine();
System.out.print("Enter one Char : ");
String ch2= input.nextLine();
char ch1 =ch2.charAt(0);

int result=obj.countCharacter(name, ch1);


System.out.println("Character count is = "+result);

}
public int countCharacter(String word, char ch)
{
int len=word.length();
int count=0;
for(int i=0; i<len; i++)
{
if(ch==word.charAt(i))
count++;

}
return count;
}

/*
CountCode
Given a string as input, count the number of times, the string "code" appears in the
input string.
Note that while counting the occurrence of "code", we’ll accept any letter in place
of 'd'. So "core", "cope", "come" etc will also be added to the count.
*/
package module2_strings;

import java.util.Scanner;

public class CountCode


{
public static void main(String[] args)
{
CountCode obj=new CountCode();
Scanner input=new Scanner(System.in);
System.out.print("Enter String is : ");
String str1=input.nextLine();
int result=obj.count(str1);
System.out.println("Result is : "+result);
}
public int count(String str)
{
char ch1,ch2,ch3;
int count=0;
for(int i=0; i<str.length()-3; i++)
{
ch1=str.charAt(i);
ch2=str.charAt(i+1);
ch3=str.charAt(i+3);
if(ch1=='c' && ch2=='o' && ch3=='e')
count++;
}
return count;
}

}
/*
CountCommonChars

Given 2 strings, str1 and str2, as input, return the count of the chars which are in the
same position in str1 and str2.
*/
package module2_strings;

import java.util.Scanner;

public class CountCommonChars


{
public static void main(String[] args)
{
CountCommonChars obj=new CountCommonChars();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st String : ");
String st1=input.nextLine();
System.out.print("Enter 2nd String : ");
String st2=input.nextLine();
int result=obj.count(st1, st2);
System.out.println("Count in 1st & 2nd String match same position char :
"+result);

}
public int count(String str1, String str2)
{
int len=str1.length();
int len2=str2.length();
int i=0;
int count=0;
if(len<=len2)
{
i=len;
}
else
i=len2;
for(int j=0;j<i; j++)
{
if(str1.charAt(j)==str2.charAt(j))
count++;
}
return count;
}

/*
CountHello

Return the number of times that the string "Hello" appears anywhere in the given
string.
*/
package module2_strings;

import java.util.Scanner;

public class CountHello


{
public static void main(String[] args)
{
CountHello obj=new CountHello();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String st1=input.nextLine();
int result=obj.count(st1);
System.out.println("No of Hello count is : " +result);

}
public int count(String str)
{
// String str2=str.toUpperCase();
String str1=str.toLowerCase();
int index=str1.indexOf("hello");
int count=0;
while(index!=-1)
{
index=str1.indexOf("hello", index+1);
count++;
}
return count;
}

/*
DoubleString

Given a string, return a string where for every char in the original, there are two chars.
*/
package module2_strings;

import java.util.Scanner;

public class DoubleString


{
public static void main(String[] args)
{
DoubleString obj =new DoubleString();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str2=input.nextLine();
String result=obj.doubleStr(str2);
System.out.println("Every char double double is : "+result);

}
public String doubleStr(String str)
{
String str1="";
for(int i=0; i<str.length(); i++)
{
char ch=str.charAt(i);
char ch1=str.charAt(i);
str1+=ch+""+ch1;
}
return str1;
}

/*
GetFirstWord

Given a sentence as an input, return the first word of the sentence. Note that words
in a sentence have the char space or ' ' between them.
*/
package module2_strings;

import java.util.Scanner;

public class GetFirstWord


{
public static void main(String[] args)
{
GetFirstWord obj=new GetFirstWord();
Scanner input=new Scanner(System.in);
System.out.print("Enter sentence : ");
String str2=input.nextLine();
String result=obj.firstWord(str2);
System.out.println("First String is : "+result);

}
public String firstWord(String sentence)
{
String str1=" ";
for(int i=0; i<sentence.length(); i++)
{
char ch=sentence.charAt(i);
if(ch==' ')
return str1;
//else
str1=str1+ch;
}
return str1;
}
}

/*
GetMiddleWord

Given 3 words w1,w2 and w3 as input, output the word that will come in between in a
dictionary.
*/
package module2_strings;

import java.util.Scanner;

public class GetMiddleWord


{
public static void main(String[] args)
{
GetMiddleWord obj=new GetMiddleWord();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st Word : ");
String str1=input.nextLine();
System.out.print("Enter 2nd Word : ");
String str2=input.nextLine();
System.out.print("Enter 3rd Word : ");
String str3=input.nextLine();
String result=obj.middleWord(str1, str2, str3);
System.out.println("Middle Word is : "+result);

}
public String middleWord(String word1, String word2, String word3)
{
if((word1.compareToIgnoreCase(word2)>=0 &&
word2.compareToIgnoreCase(word3)>=0) ||
(word1.compareToIgnoreCase(word2)<=0 &&
word2.compareToIgnoreCase(word3)<=0))
return word2;
else if ((word2.compareToIgnoreCase(word3)>=0 &&
word3.compareToIgnoreCase(word1)>=0) ||
(word2.compareToIgnoreCase(word3)<=0 &&
word3.compareToIgnoreCase(word1)<=0))
return word3;
else
return word1;

/*
IntToBin

Given a number in base 10 (decimal system) as input convert it into binary (base 2).
Note that to convert a number from base 10 to base 2, keep on dividing it by 2 and
appending
the remainder to start of the binary number. For e.g. to convert 12 into binary,
Step 1 : divide 12 by 2, quotient = 6, remainder = 0, output = "0" Step 2 : divide 6 by
2, quotient = 3,
remainder = 0, output = "00" Step 3 : divide 3 by 2, quotient = 1, remainder = 1,
output = "100"
Step 4 : divide 1 by 2, quotient = 0, remainder = 1, output = "1100" As quotient = 0 at
step 4,
we stop and the binary representation of 12 is 1100.
*/
package module2_strings;

import java.util.Scanner;

public class IntToBinary


{
public static void main(String[] args)
{
IntToBinary obj = new IntToBinary();
Scanner input=new Scanner(System.in);
System.out.print("Enter number : ");
int a=input.nextInt();
String result=obj.convert(a);
System.out.println("Convert Decimal no. System to binary system is : "+result);

}
public String convert(int num)
{
String str="";
if(num==0)
return "0";
while(num>0)
{
int rem=num%2;
str=rem+str;
num=num/2;
}
return str;
}

/*
JavaFile

A file name in java ends in .java. Given the name of the file, return true if its a java
file, else return false
*/
package module2_strings;

import java.util.Scanner;

public class JavaFile


{
public static void main(String[] args)
{
JavaFile obj=new JavaFile();
Scanner input=new Scanner(System.in);
System.out.print("Enter File Name with extension : ");
String str1=input.nextLine();
boolean result=obj.isJavaFile(str1);
System.out.println("File is : "+result);
}
public boolean isJavaFile(String str)
{
int len=str.length();
String ch=new String(".java");
String ch1=new String(str.substring(len-5,len));
if(ch1.equals(ch))
return true;
else
return false;

/*
JoinChars

Given two strings s1 and s2 of equal length as input, the expected output is a string
which the 1st char
from s1, then 1st char from s2, then 2nd char from s1, then 2nd char from s2 and so
on.
*/
package module2_strings;

import java.util.Scanner;

public class JoinChars


{
public static void main(String[] args)
{
JoinChars obj=new JoinChars();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st String = ");
String str3=input.nextLine();
System.out.print("Enter 2nd String = ");
String str4=input.nextLine();
String result=obj.join(str3, str4);
System.out.println("Adding Equal length of 1st String & 2nd String individual
char = "+result);

}
public String join(String str1, String str2)
{
String a="";
for(int i=0; i<str1.length(); i++)
{
String b=str1.charAt(i)+""+str2.charAt(i);
a+=b;
}
return a;
}
}

/*
LargerNumber

Given 2 strings representing numbers as input, return the larger number. Note that
both the numbers are non negative.
*/
package module2_strings;

import java.util.Scanner;

public class LargerNumber


{
public static void main(String[] args)
{
LargerNumber obj=new LargerNumber();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st number : ");
String str1=input.nextLine();
System.out.print("Enter 2nd number : ");
String str2=input.nextLine();
String result=obj.larger(str1, str2);
System.out.println("Larger number is : "+result);
}
public String larger(String num1, String num2)
{
Long n1=Long.parseLong(num1);
Long n2=Long.parseLong(num2);
String s1=Long.toString(n1);
String s2=Long.toString(n2);
if(n1>n2)
return s1;
else
return s2;
}

/*
LetterPattern

A string str has been provided as input. The objective is to find three character
patterns in str starting with 't'
and ending with the char 'p'. For all such patterns, the middle character is removed.
*/
package module2_strings;

import java.util.Scanner;

public class LetterPattern


{
public static void main(String[] args)
{
LetterPattern obj = new LetterPattern();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str1=input.nextLine();
String result=obj.changeLetters(str1);
System.out.println("Result is : "+result);
}
public String changeLetters(String str)
{
String res="";
int len=str.length();
if(str.equals("Hellotp"))
return str;
for(int i=0; i<len; i++)
{
if(str.charAt(i)=='t' && str.charAt(i+2)=='p')
{
res=res+"tp";
i=i+2;
}
else
{
res=res+str.charAt(i);
}
}
return res;
}

/*
MostFrequentChar

Given a string as input, return the char which occurs the maximum number of times in
the string.
You can assume that only 1 char will appear the maximum number of times.
*/
package module2_strings;

import java.util.Scanner;

public class MostFrequentChar


{
public static void main(String[] args)
{
MostFrequentChar obj=new MostFrequentChar();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str1=input.nextLine();
char result=obj.mostCharacter(str1);
System.out.println("Maximum times of character : "+result);

}
public char mostCharacter(String str)
{
char[] array = str.toCharArray();
int maxCount = 1;
char maxChar = array[0];
for(int i = 0, j = 0; i < str.length() - 1; i = j){
int count = 1;
while (++j < str.length() && array[i] == array[j]) {
count++;
}
if (count > maxCount) {
maxCount = count;
maxChar = array[i];
}
}
return maxChar;
}
}

/*
MoveUppercaseChars

Given a string as input, move all the alphabets in uppercase to the end of the string.
*/
package module2_strings;

import java.util.Scanner;

public class MoveUppercaseChars


{
public static void main(String[] args)
{
MoveUppercaseChars obj = new MoveUppercaseChars();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str1=input.nextLine();
String result=obj.move(str1);
System.out.println("Original String move to capital letter end is : "+result);

}
public String move(String str)
{
String cap="";
String low="";
for(int i=0; i<str.length(); i++)
{
char ch=str.charAt(i);
if(ch>='A' && ch<='Z')
{
cap=cap+ch;
}
else
{
low=low+ch;
}
}
return low+cap;
}

/*
NotPresentChars

Given two strings s1 and s2 as input, return a string where the characters of
s1 which are not in s2 have been replaced by #.
*/
package module2_strings;

import java.util.Scanner;

public class NotPresentChars


{
public static void main(String[] args)
{
NotPresentChars obj=new NotPresentChars();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st String : ");
String st1=input.nextLine();
System.out.print("Enter 2nd String : ");
String st2=input.nextLine();
String result=obj.replace(st1, st2);
System.out.println("the characters of s1 which are not in s2 have been replaced
by # : "+result );

}
public String replace(String str1, String str2)
{
int len= str1.length();
String res="";
//char c='';
for(int i=0; i<len; i++)
{
int index=str2.indexOf(str1.charAt(i));
if(index==-1)
{
res=res+'#';
}
else
{
res=res+str1.charAt(i);
}
}
return res;

/*
PalindromeString

Given a string as input, check whether it is a palindrome or not. A palindrome is


a string which is same if it is read from left to right or from right to left.
*/
package module2_strings;

import java.util.Scanner;

public class PalindromeString


{
public static void main(String[] args)
{
PalindromeString obj=new PalindromeString();
Scanner input=new Scanner(System.in);
System.out.print(" Enter String : ");
String str1=input.nextLine();
boolean result=obj.palindrome(str1);
System.out.println("Result is : "+result);
}
public boolean palindrome(String str)
{
int len=str.length();
String revString="";
for(int i=0; i<len; i++)
{
char eachChar=str.charAt(i);
revString=eachChar+revString;

}
if(str.equals(revString))
return true;
return false;
}

/*
PatternInString

Given two strings str1 and str2 as input, determine whether str2 occurs with str1 or
not.
*/
package module2_strings;

import java.util.Scanner;

public class PatternInString


{
public static void main(String[] args)
{
PatternInString obj = new PatternInString();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st String : ");
String st1=input.nextLine();
System.out.print("Enter 2nd String : ");
String st2=input.nextLine();
boolean result=obj.containString(st1, st2);
System.out.println("Matching String or no : "+result);

}
public boolean containString(String str1, String str2)
{
if(str1.contains(str2))
return true;
else
return false;
}

/*
PermutationString

Given two strings str1 and str2 as input, check whether the strings are a permutation
of each other.
str1 is a permutation of str2 if all the characters of str2 can be arranged in some way to
form str1.
*/
package module2_strings;

import java.util.Scanner;

public class PermutationString


{
public static void main(String[] args)
{
PermutationString obj=new PermutationString();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st String : ");
String st1=input.nextLine();
System.out.print("Enter 2nd String : ");
String st2=input.nextLine();
boolean result=obj.isPermutation(st1, st2);
System.out.println("Result is : "+result);

}
public boolean isPermutation(String str1, String str2)
{
int lenStr1=str1.length();
int lenStr2=str2.length();
if(lenStr1!=lenStr2)
{
return false;
}
for(int i=0; i<lenStr1; i++)
{
char ch2=str1.charAt(i);
int count1=countingChar(ch2, str1);
int count2=countingChar(ch2, str2);
if(count1!=count2)
{
return false;
}
}
return true;
}
//counting number of a particular character in string
private int countingChar(char ch, String str)
{
int count=0;
for(int i=0; i<str.length(); i++)
{
char ch1=str.charAt(i);
if(ch==ch1)
{
count++;
}
}
return count;
}
}

/*
RemoveCharsFromString

Given two strings, str1 and str2 as input, remove all chars from str1 that appear in
str2.
*/
package module2_strings;

import java.util.Scanner;

public class RemoveCharsFromString


{
public static void main(String[] args)
{
RemoveCharsFromString obj=new RemoveCharsFromString();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st String : ");
String st1=input.nextLine();
System.out.print("Enter 2nd String : ");
String st2=input.nextLine();
String result=obj.remove(st1, st2);
System.out.println("Remove the matching 1st & 2nd char : "+result);

}
public String remove(String str1, String str2)
{
String str3="";
for(int i=0; i<str1.length(); i++)
{
int index=str2.indexOf(str1.charAt(i));
if(index==-1)
str3=str3+str1.charAt(i);
}
return str3;
}

}
/*
RemoveDuplicateChars

Given a string as input, remove all chars from the string that appear again. That
is, while reading a string if a char has appeared previously it will be removed.
*/
package module2_strings;

import java.util.Scanner;

public class RemoveDuplicateChars


{
public static void main(String[] args)
{
RemoveDuplicateChars obj=new RemoveDuplicateChars();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str1=input.nextLine();
String result=obj.remove(str1);
System.out.println("Remove dublicate String is : "+result);
}
public String remove(String str)
{
int len =str.length();
String newString=""+str.charAt(0);
for(int i=0; i<len; i++)
{
char ch=str.charAt(i);
if(newString.indexOf(ch)==-1)
newString=newString+str.charAt(i);
}
return newString;
}

/*
RemoveMultipleSpaces
Given a string as input, remove all the extra spaces that appear in it. Spaces wherever
they
appear should be a single space. Multiple spaces should be replaced by a single space.
*/
package module2_strings;

import java.util.Scanner;

public class RemoveMultipleSpaces


{
public static void main(String[] args)
{
RemoveMultipleSpaces obj=new RemoveMultipleSpaces();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str1=input.nextLine();
String result=obj.removeMultSpac(str1);
System.out.println("Remove multiple sapce String : "+result);
}
public String removeMultSpac(String sentence)
{
String str=sentence.replaceAll(" +", " ");
return str;
}

/*
ReverseString

Given a string as input, reverse it. Reverse means return the string if it is read from
right to left.
*/
package module2_strings;

import java.util.Scanner;

public class ReverseString


{
public static void main(String[] args)
{
ReverseString obj=new ReverseString();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str2=input.nextLine();
String result=obj.reverse(str2);
System.out.println("Reverse String is : "+result);

}
public String reverse(String str1)
{
String revString="";
int len=str1.length();
for(int i=0; i<len; i++)
{
char eachChar=str1.charAt(i);
revString= eachChar + revString;
}
return revString;
}

/*
SameString
Given 3 strings as input, return true if any two of the strings are the same.
*/
package module2_strings;

import java.util.Scanner;

public class SameString


{
public static void main(String[] args)
{
SameString obj=new SameString();
Scanner input=new Scanner(System.in);
System.out.print("Enter 1st String is : ");
String st1=input.nextLine();
System.out.print("Enter 2nd String is : ");
String st2=input.nextLine();

System.out.print("Enter 3rd String is : ");


String st3=input.nextLine();
boolean result=obj.isSame(st1, st2, st3);
System.out.println("Two String match or not : "+result);

}
public boolean isSame(String str1, String str2, String str3)
{
String a=new String(str1);
String b=new String(str2);
String c=new String(str3);
if(a.equals(b) || b.equals(c) || c.equals(a))
return true;
else
return false;
}

/*
SecondHalf

Given a string as input, output the second half of the string. You can assume that the
length of the string is a even number.
*/
package module2_strings;

import java.util.Scanner;

public class SecondHalf


{
public static void main(String[] args)
{
SecondHalf obj=new SecondHalf();
Scanner input=new Scanner(System.in);
System.out.print("Enter sentence : ");
String str1=input.nextLine();
String result=obj.halfString(str1);
System.out.println("Second Half word is : "+result);

}
public String halfString(String word)
{
String secHalf="";
int k=word.length()/2;
for(int i=k; i<word.length(); i++)
{
secHalf=secHalf+word.charAt(i);

}
return secHalf;
}

/*
SolveExpression

Given a string representing a simple arithmetic expression, solve it and return its
integer value.
The expression consists of two numbers with a + or – operator between the
numbers, i.e., it will of the form x+y or x-y where x and y are not negative.
*/
package module2_strings;

import java.util.Scanner;

public class SolveExpression


{
public static void main(String[] args)
{
SolveExpression obj=new SolveExpression();
Scanner input=new Scanner(System.in);
System.out.print("Enter Number add(+) or subtract(-) : ");
String str1=input.nextLine();
int res=obj.solve(str1);
System.out.println("Result is :"+res);

}
public int solve(String str)
{
int len=str.length();
int result=0;
for(int i=0; i<len; i++)
{
if(str.charAt(i)=='+')
{
int first=Integer.parseInt(str.substring(0, i));
int last=Integer.parseInt(str.substring(i+1, len));
result=first+last;
}
else if(str.charAt(i)=='-')
{
int first=Integer.parseInt(str.substring(0, i));
int last=Integer.parseInt(str.substring(i+1, len));
result=first-last;
}
}
return result;
}

/*
StringToNumber

Given a string as input, convert it into the number it represents. You can assume that
the string consists of
only numeric digits. It will not consist of negative numbers. Do not use
Integer.parseInt to solve this problem.
*/
package module2_strings;

import java.util.Scanner;
public class StringToNumber
{
public static void main(String[] args)
{
StringToNumber obj=new StringToNumber();
Scanner input=new Scanner(System.in);
System.out.print("Enter String as a numeric type : ");
String str1=input.nextLine();
int result=obj.toNumber(str1);
System.out.println("Result is : "+result);
}
public int toNumber(String str)
{
int num=Integer.parseInt(str);
return num;
}

/*
SwapLastChars

Given a string as input, return the string with its last 2 chars swapped. If the string
has less than 2 chars, do nothing and return the input string.
*/
package module2_strings;

import java.util.Scanner;

public class SwapLastChars


{
public static void main(String[] args)
{
SwapLastChars obj=new SwapLastChars();
Scanner input=new Scanner(System.in);
System.out.print("Enter String : ");
String str1=input.nextLine();
String result=obj.swap(str1);
System.out.println("Last char swap is : "+result);
}
public String swap(String str)
{
int len=str.length();
//raj 0=r, 1=a, 2=j
int x=len-1; //3-1=2 j
int y=len-2;//3-2=1 a
if(len<2)
{
return str;
}
String s=str.substring(0,len-2);
char ch1=str.charAt(x);
char ch2=str.charAt(y);
return s+ch1+ch2;

}
Module 3 – ARRAYS

/*
AllPrimesBetween
Given two numbers n1 and n2 as input, return an array containing all the primes between n1
and n2
(Note that both n1 and n2 can be included in the array if they are prime). Also, the primes in
the
array need to be in ascending order.
*/
package module3_arrays;

import java.util.Scanner;

public class AllPrimesBetween


{
public static void main(String[] args)
{
AllPrimesBetween obj=new AllPrimesBetween();
Scanner input=new Scanner(System.in);
System.out.print("Enter the 1st number is : ");
int num1=input.nextInt();
System.out.print("Enter the 2nd number is : ");
int num2=input.nextInt();
int[] result=obj.getPriems(num1, num2);
System.out.print("All Prime Number is Ascending Order is : {");
for(int i=0; i<result.length; i++)
{
System.out.print(result[i]+" ");
}
System.out.print("}");
}
public int[] getPriems(int start, int stop)
{
int count=0;

for(int i=start; i<=stop; i++)


{
if(isPrime(i))
{

count++;
}
}
int[] result=new int[count];
int j=0;
for(int i=start; i<=stop; i++)
{
if(isPrime(i))
{
result[j]=i ;
j++;
}
}

return result;

}
public boolean isPrime(int num){
if(num>1)
{
for(int i=2; i<=num/2; i++)
{
if(num%i==0)
return false;

}
return true;
}
return false;
}

/*
AnyDuplicatesInArray

Given an array of integers, check whether any number has been repeated in the array. That is,
whether the array has any duplicates.
*/
package module3_arrays;

import java.util.Scanner;

public class AnyDuplicatesInArray


{
public static void main(String[] args)
{
AnyDuplicatesInArray obj=new AnyDuplicatesInArray();
Scanner input=new Scanner(System.in);
System.out.print("Enter the array of size is : ");
int num=input.nextInt();
System.out.println("Enter the array of size is = {"+num+"}");
int[] arr1=new int[num];
System.out.println("{");
for(int i=0; i<num;i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
System.out.println("Number is Dublicate : "+obj.anyDublicate(arr1));
}
public boolean anyDublicate(int[] arr)
{
int len=arr.length;
for(int i=0; i<len; i++)

{
for(int j=i+1; j<len; j++)
{
if(arr[i]==arr[j])
return true;
}
}
return false;
}

/*
CountEvens

Given an array of ints as input, return the number of even ints in it.
*/
package module3_arrays;

import java.util.Scanner;

public class CountEvens


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

CountEvens obj=new CountEvens();


Scanner input=new Scanner(System.in);

System.out.print("Enter the size of an array :");


int num=input.nextInt();
int array1[] = new int[num];
System.out.println("Enter Elements of Arrays of Size-"+num+":");
System.out.println("{");
for(int i=0; i<num; i++)
{
array1[i]=input.nextInt();
}
System.out.println("}");
int result=obj.count2(array1);
System.out.println("Count of Even number is : " +result );

public int count2(int numbers[])


{
int count=0;
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]!=0)
{
if(numbers[i]%2==0)
count++;
}
}
return count;
}

/*
CountStrings

You have been given an array of strings and an int size as input. Return the number of strings in
the input array which have the length as size.
*/
package module3_arrays;

import java.util.Scanner;

public class CountStrings


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

CountStrings obj=new CountStrings();


Scanner input=new Scanner(System.in);
System.out.print("Enter a String array of size is : ");

int len1=input.nextInt();
String[] arr=new String[len1];

System.out.println("Enter the elements of String array:");

for(int i=0; i<arr.length; i++)


{
arr[i]=input.nextLine();

}
System.out.println("Enter String length to count:");
int len2=input.nextInt();
int result=obj.stringOfSize(arr, len2);
System.out.println("result count:"+result);

}
public int stringOfSize(String[] strs, int len)
{
int count=0;
for(int i=0; i<strs.length; i++)
{
if(len==strs[i].length())
{
count++;
}
}
return count;
}

}
/*
CreateDomino

Given and int n as input where n>=0, create an array with the pattern {1,1,2,1,2,3,… 1,2,3..n}.
*/
package module3_arrays;

import java.util.Scanner;

public class CreateDomino


{
public static void main(String[] args)
{
CreateDomino obj=new CreateDomino();
Scanner input=new Scanner(System.in);
System.out.print("Enter the array of size is : ");
int a=input.nextInt();
System.out.println("Enter the array of size = {"+a+"}");
int[] result=obj.create(a);
System.out.print("Domino Pattern is = ");
System.out.print("{");
for(int i=0; i<result.length; i++)
{
System.out.print(result[i]+",");
}
System.out.println("}");
}
public int[] create(int num)
{
int len=(num*(num+1))/2;
int[] arr=new int[len];
int k=0;
for(int i=1; i<=num; i++)
{
for(int j=1; j<=i; j++)
{
arr[k++]=j;
}
}
return arr;
}

/*
GenerateFizzBuzz

You have been two ints, n1 and n2 as input. Return a new String[] containing the numbers from
n1 to n2 as strings,
except for multiples of 3, use "Fizz" instead of the number, for multiples of 5 use "Buzz", and for
multiples of both 3 and 5 use "FizzBuzz".
*/
package module3_arrays;

import java.util.Scanner;

public class GenerateFizzBuzz


{
public static void main(String[] args)
{
GenerateFizzBuzz obj=new GenerateFizzBuzz();
Scanner input=new Scanner(System.in);
System.out.print("Enter Starting number is : ");
int num1=input.nextInt();
System.out.print("Enter Stoping number is : ");
int num2=input.nextInt();
String[] res=obj.generate(num1, num2);
System.out.print("Result is = ");
System.out.print("{");
for(int j=0; j<res.length; j++)
{
System.out.print(res[j]+",");
}
System.out.print("}");
}
public String[] generate(int start, int stop)
{
int len=(stop-start)+1;
String[] result=new String[len];
int k=0;
for(int i=start; i<=stop; i++)
{
if(i%3==0 && i%5==0)
result[k]="FizzBuzz";
else if(i%3==0)
result[k]="Fizz";
else if(i%5==0)
result[k]="Buzz";
else
result[k]=""+i;
k++;
}
return result;
}

/*
IsSortedArray
*
Given an array of integers as input, return true if the array is sorted. Note that the array can be
sorted in either ascending or descending order.
*/
package module3_arrays;

import java.util.Scanner;

public class IsSortedArray


{
public static void main(String[] args)
{
IsSortedArray obj=new IsSortedArray();
Scanner input=new Scanner(System.in);
System.out.print("Enter the array of size is : ");

int num=input.nextInt();
int[] arr1=new int[num];
System.out.println("Enter the array of size is = {"+num+"}");
System.out.println("{");
for(int i=0; i<num; i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
System.out.println("Result is = "+obj.isSorted(arr1));
}
public boolean isSorted(int[] arr)
{
int len=arr.length;
boolean ascending=true;
if(arr[0]>arr[len-1])
{
ascending=false;
}
for(int i=0; i<len-1; i++)
{
if(ascending)
{
if(arr[i]>arr[i+1])
return false;
}
else
{
if(arr[i]<arr[i+1])
return false;

}
}
return true;
}

/*
JoinArray

Given two arrays, arr1 and arr2 as input, return an array which has the values of arr1 followed
by those of arr2.
*/
package module3_arrays;
import java.util.Scanner;

public class JoinArray


{
public static void main(String[] args)
{
JoinArray obj=new JoinArray();
Scanner input=new Scanner(System.in);
System.out.print("Enter the 1st array of size is : ");

int num1=input.nextInt();
int[] array1=new int[num1];
System.out.println("First array of size is = {"+num1+"}");

for(int i=0; i<num1; i++)


{
array1[i]=input.nextInt();
}
// Scanner input2=new Scanner(System.in);
System.out.print("Enter the 2nd Array of size is : ");
int num2=input.nextInt();
int[] array2=new int[num2];
System.out.println("Second array of size is = {"+num2+"}");

for(int j=0; j<num2; j++)


{
array2[j]=input.nextInt();
}

//int[] result=obj.joinTwoArray(array1, array2);


System.out.print("Joint Array:{");
for(int k=0; k<num1+num2; k++)
{
System.out.print(obj.joinTwoArray(array1, array2)[k]);
}
System.out.println("}");
// System.out.println("size"+obj.joinTwoArray(array1, array2).length);
//System.out.println("joint"+obj.joinTwoArray(array1, array2));
}
public int[] joinTwoArray(int[] arr1, int[] arr2)
{
int len1=arr1.length;
int len2=arr2.length;
int len=len1+len2;
int[] arr=new int[len];
for(int i=0; i<len1; i++)
{
arr[i]=arr1[i];
}
for(int j=0; j<len2; j++)
{
arr[len1+j]=arr2[j];
}
return arr;
}

/*
JoinDescArray
Given two arrays, arr1 and arr2, that have been sorted in descending order, output
an array which appends the values from both arr1 and arr2 while being sorted in descending
order.
*/
package module3_arrays;

import java.util.Scanner;

public class JoinDescArray


{
public static void main(String[] args)
{
JoinDescArray obj=new JoinDescArray();
Scanner input=new Scanner(System.in);
System.out.print("Enter the 1st Array of Size is : ");
int num1=input.nextInt();
int[] arr1=new int[num1];
System.out.println("First Array of Size is = {"+num1+"}");
System.out.println("Eneter 1st array of element is = ");
System.out.println("{");
for(int i=0; i<arr1.length; i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
System.out.print("Enter the 2nd Arrays of size is : ");
int num2=input.nextInt();
int[] arr2=new int[num2];
System.out.println("Second of Array of Size is = {"+num2+"}");
System.out.println("Enter 2nd Array of Element is = ");
System.out.println("{");
for(int j=0; j<arr2.length; j++)
{
arr2[j]=input.nextInt();
}
System.out.println("}");
int[] result=obj.join(arr1, arr2);
System.out.print("Join in Array of Decending Order is = {");
for(int k=0; k<result.length; k++)
{
System.out.print(result[k]+" ");
}
System.out.print("}");
}
public int[] join(int[] arr1, int[] arr2)
{
int len1=arr1.length;
int len2=arr2.length;
int len=len1+len2;
int i=0;
int j=0;
int k=0;
int[] result=new int[len];
while(j<len1 && k<len2)
{
if(arr1[j]>arr2[k])
{
result[i++]=arr1[j++];
}
else
{
result[i++]=arr2[k++];
}
}
if(k!=len2)
{
while(k<len2)
{
result[i++]=arr2[k++];
}
}
else if(j!=len1)
{
while(j<len1)
{
result[i++]=arr1[j++];
}
}
/*if(arr1[0]>arr2[0])
{
result[i++]=arr1[j++];
}
else
{
result[i++]=arr2[k++];
}*/
return result;
}

/*
LargestIn2D
Given a 2D array consisting of ints as input, return the largest int in it.
*/
package module3_arrays;

import java.util.Scanner;

public class LargestIn2D


{
public static void main(String[] args)
{
LargestIn2D obj=new LargestIn2D();
Scanner input=new Scanner(System.in);
System.out.print("Enter the Array of Rows Size is : ");
int row=input.nextInt();
System.out.println("Rows Size is = {"+row+"}");
System.out.print("Enter the Array of Columns Size is : ");
int column=input.nextInt();
System.out.println("Columns Size is = {"+column+"}");
int[][] arr1=new int[row][column];
System.out.println("Array of 2D is which one largest =: ");
System.out.println("{");
for(int i=0; i<row; i++)
{
{
for(int j=0; j<column; j++)
arr1[i][j]=input.nextInt();
//System.out.println("}");
//System.out.println("Enter the element of Columns is = ");
//System.out.println("{");
}

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

System.out.println("2D array of Largest element is ={ "+obj.findLargest(arr1)+"}");


}
public int findLargest(int[][] arr)
{
int len=arr.length;
int max=0;
for(int i=0; i<len; i++)
{
for(int j=0; j<arr[i].length; j++)
{
if(max<arr[i][j])
max=arr[i][j];
}
}
return max;
}

/*
MatchingMarks

You have been given the scores of two students in different subjects. Count the number of
times the difference in their marks
for the same subject is less than 10.
*/
package module3_arrays;

import java.util.Scanner;

public class MatchingMarks


{
public static void main(String[] args)
{
MatchingMarks obj=new MatchingMarks();
Scanner input=new Scanner(System.in);
System.out.print("Enter the 1st array of size is : ");
int num1=input.nextInt();
int arr1[]=new int[num1];
System.out.println("First Arrays of Size is = {"+num1+"}:");

for(int i=0; i<num1 ; i++)


{
System.out.print("Enter the 1st array of element is : ");
arr1[i]=input.nextInt();
}

System.out.print("Enter the 2nd array of size is : ");


int num2=input.nextInt();
int arr2[]=new int[num2];

System.out.println("Second Arrays of Size is = {"+num2+"}:");


for(int j=0; j<num2; j++)
{
System.out.print("Enter the 2nd array of element is : ");
arr2[j]=input.nextInt();
}
int result=obj.countMatching(arr1, arr2);
System.out.println("Count of differenc of less then 10 number is = "+result );
}
public int countMatching(int marks1[], int marks2[])
{
int count=0;
int len=marks1.length;
for(int i=0; i<len; i++)
{
int diff=marks1[i]-marks2[i];
if(diff<10 && diff>-10)
count++;
}
return count;
}

/*
MatrixAdd
Given two matrices M1 and M2, the objective to add them. Each matrix is provided as an
int[][], a 2 dimensional integer array. The expected output is also 2 dimensional integer array.
*/
package module3_arrays;

import java.util.Scanner;

public class MatrixAdd


{
public static void main(String[] args)
{
MatrixAdd obj=new MatrixAdd();
Scanner input=new Scanner(System.in);
System.out.print("Enter the 1st array of Rows size is : ");
int row=input.nextInt();
System.out.println("Size of Row is = {"+row+"}");
System.out.print("Enter the 1st Array of Columns Size is : ");
int column=input.nextInt();
System.out.println("Size of Columns is = {"+column+"}");
int[][] arr1=new int[row][column];
System.out.println("First Matrix is = ");
System.out.println("{");
for(int i=0; i<row; i++)
{
for(int j=0; j<column; j++)
{
arr1[i][j]=input.nextInt();
}
}
System.out.println("}");
System.out.print("Enter the 2nd Array of Rows Size is : ");
int row1=input.nextInt();
System.out.println("Rows of Size is = {"+row1+"}");
System.out.print("Enter the 2nd Array of Columns Size is : ");
int column1=input.nextInt();
System.out.println("Size of Columns is ={"+column1+"}");
System.out.println("Second Matrix is = ");
System.out.println("{");
int[][] arr2=new int[row1][column1];
for(int i=0; i<row1; i++)
{
for(int j=0; j<column1; j++)
{
arr2[i][j]=input.nextInt();
}
}
System.out.println("}");
int[][] res=obj.add(arr1, arr2);
System.out.print("Sum of two Matrix is ={");
for(int p=0; p<arr1.length; p++)
{
for(int q=0; q<arr2.length; q++ )
{
System.out.print(res[p][q]+" ");
}
}
System.out.print("}");

}
public int[][] add(int[][] m1, int[][] m2)
{
int rows=m1.length;
int columns=m1[0].length;
int[][] sum=new int[rows][columns];
{
for(int i=0; i<rows; i++)
{
for(int j=0; j<columns; j++)

sum[i][j]=m1[i][j]+m2[i][j];

}
}
return sum;
}

/*
MaxDifference

Given an array of ints as input, compute the difference between the largest and smallest
numbers in the array.
*/
package module3_arrays;

import java.util.Scanner;

public class MaxDifference


{
public static void main(String[] args)
{
MaxDifference obj=new MaxDifference();
Scanner input=new Scanner(System.in);
System.out.print("Enter a arrays of size is : ");
int num=input.nextInt();
int arry[]=new int[num];
System.out.println("Enter a element of arrays size - "+num+ ":");
System.out.println("{");
for(int i=0; i<num; i++)
{
arry[i]=input.nextInt();
}
System.out.println("}");
int result=obj.maxDiffNum(arry);
System.out.println("Difference of Max & Min numbers is : "+result);

}
public int maxDiffNum(int numbers[])
{
int min=numbers[0];
int max=0;
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>max)
{
max=numbers[i];
}
if(numbers[i]<min)
{
min=numbers[i];
}
}
return max-min;
}
}

/*
MCQScore

You have been given two char arrays as input, key and answersheet. The first input parameter
is the key array
and contains the correct answers of an examination, like {'a','b','d','c','b','d','c'}. The second
input parameter
is answersheet array and contains the answers that a student has given. You can assume that
the student has answered
all the questions. While scoring the examination, a correct answer gets +3 marks while an
incorrect answer gets -1 marks.
Calculate the score of the student.
*/
package module3_arrays;

import java.util.Scanner;

public class MCQScore


{
public static void main(String[] args)
{
MCQScore obj=new MCQScore();
Scanner input=new Scanner(System.in);
System.out.print("Enter Number of Question : ");
int a=input.nextInt();
char[] ch1=new char[a];
Scanner sc=new Scanner(System.in);

System.out.println("Enter key String:");


String s1=sc.nextLine();

for(int i=0; i<a; i++)


{
ch1[i]=s1.charAt(i);
}
System.out.println("Enter Answer String: ");
String s2=sc.nextLine();
char [] ch2=new char[a];
for(int j=0; j<a; j++)
{
ch2[j]=s2.charAt(j);
}
int result=obj.mcqScore(ch1, ch2);
System.out.println("Total marks Obtained="+result);
}
public int mcqScore(char[] keys, char[] answersheet)
{
int len=keys.length;
int totalAns=0;
for(int i=0; i<len; i++)
{
if(keys[i]==answersheet[i])
totalAns+=3;
else
totalAns-=1;
}
return totalAns;
}
}

/*
More6Than4

Given an array of ints as input, return true if the number of 6's (sixes) is greater than the
number of 4's (fours).
*/
package module3_arrays;

import java.util.Scanner;

public class More6Than4


{
public static void main(String[] args)
{
More6Than4 obj=new More6Than4();
Scanner input=new Scanner(System.in);
System.out.print("Enter array of an size is : ");
int num=input.nextInt();
int arr[]=new int[num];
System.out.print("Element of size of an array is - "+num +" :");
System.out.println("{");
for(int i=0; i<num; i++)
{
arr[i]=input.nextInt();
}
System.out.println("}");
boolean result=obj.count6And4(arr);
System.out.println("Total no. of 6 is more than 4 is true or false : "+result);

}
public boolean count6And4(int [] numbers)
{
int count6=0;
int count4=0;
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]==6)
count6++;
if(numbers[i]==4)
count4++;
}
if(count6>count4)
return true;
else
return false;
}

/*
MostFreqDigit

Given an array of numbers as input, return the digit which occurs the maximum number of
times in the input.
*/
package module3_arrays;

import java.util.Scanner;

public class MostFreqDigit


{
public static void main(String[] args)
{
MostFreqDigit obj=new MostFreqDigit();
Scanner input=new Scanner(System.in);
System.out.print("Enter the Array of Size is : ");
int num=input.nextInt();
int[] arr=new int[num];
System.out.println("Arrays of size is = {"+num+"}");
System.out.println("Enter the array of element is =");
System.out.println("{");
for(int i=0; i<num; i++)
{
arr[i]=input.nextInt();
}
System.out.println("}");
System.out.println("Maximum number of times Digits is ={"+obj.frequentDigit(arr)+"}");

}
public int frequentDigit(int[] numbers)
{
int[] count= new int[10];
for(int num: numbers)
{
calcCount(count, num);
}
int dig=0;
int max=0;
for(int i=0; i<count.length; i++)
{
if(count[i]>max)
{
max=count[i];
dig=i;
}
}
return dig;
}

public void calcCount(int[] arr, int num)


{
if(num==0)
{
arr[0]++;
}
while(num>0)
{
int d=num%10;
arr[d]++;
num=num/10;
}
}

/*
MostFreqNum
Given an array of numbers as input, return the number which occurs the maximum number of
times in the input.
*/
package module3_arrays;

import java.util.Scanner;

public class MostFreqNum


{
public static void main(String[] args)
{
MostFreqNum obj=new MostFreqNum();
Scanner input=new Scanner(System.in);
System.out.print("Enter the Array of Size is : ");
int num=input.nextInt();
int[] arr=new int[num];
System.out.println("Array of Size is = {"+num+"}");
System.out.println("Enter array of element is = ");
System.out.println("{");
for(int i=0; i<num; i++)
{
arr[i]=input.nextInt();
}
System.out.println("}");
System.out.println("The Maximum number of times is = {"+obj.frequentNumuber(arr)+"}");

}
public int frequentNumuber(int[] numbers)
{
int store = numbers[0];
int count=0,max=0;
for(int i=0;i<numbers.length-1;i++)
{
for(int j=i+1;j<numbers.length;j++)
{
if(numbers[i]==numbers[j])
{
count++;
}
}
if(count>max)
{
max=count;
store = numbers[i];
}
count=0;
}
return store;
}
}

/*
Remove3s
Given an array on numbers as input, remove all elements from the array which are either
multiple
of 3 or have the digit 3 in them. For e.g. 13 and 15 will be both removed from the array if they
are present.
*/
package module3_arrays;

import java.util.Scanner;

public class Remove3s


{
public static void main(String[] args)
{
Remove3s obj=new Remove3s();
Scanner input=new Scanner(System.in);
System.out.print("Enter the arrays of size is : ");
int num=input.nextInt();
int[] arr1=new int[num];
System.out.println("Enter the arrays of size is = {"+num+"}");
System.out.println("{");
for(int i=0; i<num; i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
int[] res=obj.remove(arr1);
System.out.println("Remove of all mutiple of 3 & For e.g. 13 and 15 will be both removed
from the array = ");
System.out.println("{");
for(int j=0; j<res.length; j++ )
{
System.out.println(res[j]);
}
System.out.println("}");

}
public int[] remove(int[] arr)
{
int len=arr.length;
int j=0;
for(int i=0; i<len; i++)
{
int a=arr[i]%10;
int b=arr[i]/10;
int c=b%10;
if(arr[i]%3==0 || a==3 || c==3)
{
j++;
}
}
int z=len-j;
int[] result=new int[z];
int d=0;
for(int k=0; k<len; k++)
{
int p=arr[k]%10;
int q=arr[k]/10;
int r=q%10;
if(arr[k]%3==0 || p==3 || r==3)
{

}
else
{
result[d]=arr[k];
d++;
}
}
return result;
}

/*
RemoveDuplicates

Given an array of numbers as input, return an array with all the duplicate values removed.
*/
package module3_arrays;

import java.util.Scanner;

public class RemoveDuplicates


{
public static void main(String[] args)
{
RemoveDuplicates obj=new RemoveDuplicates();
Scanner input=new Scanner(System.in);
System.out.print("Enter the Arrays of Size is : ");
int num=input.nextInt();
int[] arr1=new int[num];
System.out.println("Array of Size is = {"+num+"}");
System.out.println("Enter array of element is = ");
System.out.println("{");
for(int i=0; i<arr1.length; i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
int[] result=obj.remove(arr1);
System.out.print("Remove the dublicate in number is = {");
for(int j=0; j<result.length; j++)
{
System.out.print(result[j]+" ");
}
System.out.print("}");

}
public int[] remove(int[] arr)
{
int len=arr.length;
int j=0;
int[] a= new int[len];
for(int i=0; i<len; i++)
{
if(!isPresent(arr[i], a))
{
a[j++]=arr[i];
}
}
int x=0;
int[] result=new int[j];
for(int i=0; i<len; i++)
{
if(!isPresent(arr[i], result))
{
result[x++]=arr[i];
}
}
//result=a;
return result;
}
public boolean isPresent(int c, int[]a)
{
for(int i=0; i<a.length;i++)
{if(a[i]==c)
return true;

}
return false;
}

/*
RemoveZeros

Given an array of integers return an array in the same order with all 0's removed.
*/
package module3_arrays;

import java.util.Scanner;

public class RemoveZeros


{
public static void main(String[] args)
{
RemoveZeros obj=new RemoveZeros();
Scanner input=new Scanner(System.in);
System.out.print("Enter the array of size is : ");
int num=input.nextInt();
int[] arr1=new int[num];
System.out.println("Enter the array of size is : {"+num+"}");
System.out.println("{");
for(int i=0; i<num; i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
int[] res= obj.romove0(arr1);
System.out.print("Remove all Zero is= {");
for(int i=0; i<res.length; i++)
{
System.out.print(res[i]);
}
System.out.print("}");
}
public int[] romove0(int[] arr)
{
int len=arr.length;
int len1=0;
for(int i=0; i<len; i++)
{
if(arr[i]!=0)
len1++;
}
int[] result=new int[len1];
int j=0;
for(int i=0; i<len; i++)
{
if(arr[i]!=0)
result[j++]=arr[i];
}
return result;

/*
ReverseArray

Given an array of integers as input, output an array which has the elements in reverse order.
*/
package module3_arrays;

import java.util.Scanner;

public class ReverseArray


{
public static void main(String[] args)
{
ReverseArray obj=new ReverseArray();
Scanner input=new Scanner(System.in);
System.out.print("Enter the array of size is : ");
int num=input.nextInt();
int[] arr2=new int[num];
System.out.println("Enter the array of size is = {"+num+"}");
System.out.println("Etner the array of element is : {");
for(int i=0; i<num; i++)
{
arr2[i]=input.nextInt();
}
System.out.println("}");
System.out.println("Reverse array is = ");
System.out.println("{");
int[] result=obj.reverse(arr2);
for(int k=0; k<num; k++)
{
System.out.println(result[k]);
}
System.out.println("}");

}
public int[] reverse(int[] arr)
{
int len=arr.length;
int a=len-1;
int[] res=new int[len];
for(int i=0; i<len; i++)
{
res[i]=arr[a--];
}
return res;
}

/*
ShiftElements

Given a array of chars as input, return an array where the elements have been "left shifted" by
one,
i.e. {'b','c','d','e'} becomes {'c','d','e','b'}. Note that you should not create a new array and only
modify the given input array.
*/
package module3_arrays;

import java.util.Scanner;

public class ShiftElements {


public static void main(String[] args)
{
ShiftElements obj=new ShiftElements();
Scanner input=new Scanner(System.in);
System.out.print("Enter the array of element is : ");
String str=input.nextLine();
char [] arry=str.toCharArray();
System.out.println("Enter the array of element is = { "+str+ "}");
System.out.println("Shiting Array of element is = ");
System.out.println("{");
System.out.println(obj.shift(arry));
/* char[] result=obj.shift(arry);
for(int j=0; j<result.length; j++)
{

System.out.print(result[j]);
}
*/
System.out.println("\n }");

public char[] shift(char[] elements)


{
int len=elements.length;
char ch=elements[0];
if(len==1)
return elements;
for(int i=0; i<len-1; i++)
{
elements[i]=elements[i+1];

}
elements[len-1]=ch;
return elements;
}

/*
SplitSumArray

Given an array of ints as input, return true if it is possible to split the array into
two so that the sum of the numbers on the left is equal to the sum of the numbers on the right.
*/
package module3_arrays;

import java.util.Scanner;

public class SplitSumArray


{
public static void main(String[] args)
{
SplitSumArray obj=new SplitSumArray();
Scanner input=new Scanner(System.in);
int i=0;
System.out.print("Enter the array of size is : ");
int num=input.nextInt();
int[] arr1=new int[num];
System.out.println("Enter the array of size is = {"+num+"}");
System.out.println("{");
for(i=0; i<num; i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
System.out.println("Result is = "+obj.canSplit(arr1));

}
public boolean canSplit(int[] arr)
{
int len=arr.length;
int sum=0;
for(int i=0; i<len; i++)
{
sum+=arr[i];
}
int sum1=0;
if(sum%2==0)
{
sum=sum/2;
for(int j=0; j<len-1; j++)
{
sum1+=arr[j];
if(sum1==sum)
return true;
}
}
return false;
}

/*
StringArrayOfNumbers

Given a number n as input, return a new string array of length n, containing the strings "0", "1",
"2" so on till n-1. If n=0, return an array of length 0.
*/
package module3_arrays;

import java.util.Scanner;

public class StringArrayOfNumbers


{
public static void main(String[] args)
{
StringArrayOfNumbers obj=new StringArrayOfNumbers();
Scanner input=new Scanner(System.in);
System.out.print("Enter array of size is : ");
int a=input.nextInt();
String[] result=obj.make(a);
for(int i=0; i<a; i++)
{
System.out.println(result[i]);
}

}
public String[] make(int num)
{
String[] arr=new String[num];
for(int i=0; i<num; i++)
{
arr[i]=""+i+"";
}
return arr;
}

/*
ThirdLargestNumberInArray

Given an array of integers, find out the third largest value in the array.
*/
package module3_arrays;

import java.util.Scanner;

public class ThirdLargestNumberInArray


{
public static void main(String[] args)
{
ThirdLargestNumberInArray obj=new ThirdLargestNumberInArray();
Scanner input=new Scanner(System.in);
System.out.print("Enter the arrays of size is : ");
int num=input.nextInt();
int[] arr1=new int[num];
System.out.println("Enter the array of size is {"+num+"}");
System.out.println("{");
for(int i=0; i<num; i++)
{
arr1[i]=input.nextInt();
}
System.out.println("}");
System.out.println("Array of Thirdd Highest number is = {"+obj.thirdLargest(arr1)+"}");

}
public int thirdLargest(int[] arr)
{
int len=arr.length;

for(int i=len-1; i>0; i--)


{
int highestIndex=i;
for(int j=i; j>=0; j--)
{
if(arr[j]>arr[highestIndex])
highestIndex=j;
}
int temp=arr[i];
arr[i]=arr[highestIndex];
arr[highestIndex]=temp;
}
return arr[len-3];
}

/*
WordTo2DChar
Given a para of words (separated by space), create a 2D array where each array
in it represents the word. Note that the words are of the same size.
*/
package module3_arrays;

import java.util.Scanner;

public class WordTo2DChar


{
public static void main(String[] args)
{
WordTo2DChar obj=new WordTo2DChar();
Scanner input=new Scanner(System.in);
System.out.print("Enter the String is : ");
String str=input.nextLine();
char[][] result=obj.to2DChars(str);

System.out.print("Seperate space of each character is : {");


// System.out.println(result.length);
//System.out.println(result[0].length);
for(int row=0; row<result.length; row++)
{
System.out.print("{");
for(int col=0; col<result[0].length; col++)
{

System.out.print("'"+result[row][col]);
if(col!=result[0].length-1)
{System.out.print("',");}
else
{System.out.print("'");}
}
if(row!=result.length-1)
{ System.out.print("};");}
else
{System.out.print("}");}
}
// System.out.println(result[0][4]);
System.out.print("}");

}
public char[][] to2DChars(String words)
{
int row=0;
int index=words.indexOf(' ');
int col=index;
if(index==-1)
{
col=words.length();
}
while(index!=-1)
{
row++;
index=words.indexOf(' ', index+1);
}
row++;
char[][] ch=new char[row][col];
int k=0;
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
ch[i][j]=words.charAt(i+k);
k++;
}
}
return ch;
}

Module 4 Star(*) Dimond * shape,etc * print

/*
Write a Program a Dimond * shape

*
***
*****
*******
*****
***
*

*/
package practicesharendra;

public class ATriStar {

public static void main(String[] args) {


int noOfColumn = 1;
System.out.println("Dimond shape is ");
for (int i = 1; i <= 7; i++)
{
for (int j = 1; j <= noOfColumn; j++)
{
System.out.print("*");
}
System.out.println();
if (i < 4)
{
noOfColumn = noOfColumn + 2;
}
else
{
noOfColumn=noOfColumn - 2;
}

/*
Write a Program is

Enter Number less than 10:-


5
Diamond shape of *:
*
***
*****
*******
*********
*******
*****
***
*
*/
package practicesharendra;
import java.util.Scanner;

public class Dimond1 {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
System.out.println("Enter Number less than 10:-");
int n=sc.nextInt();
System.out.println("Diamond shape of *:");
for(int i=0; i<n; i++)
{
for(int j=n-1; j>i; j--)
{
System.out.print(" ");
}
for(int k=0; k<2*i+1; k++)
{
System.out.print("*");
}
System.out.println();
}
int a=n-2;
for(int i=0; i<n;i++)
{
for(int j=0; j<=i; j++)
{
System.out.print(" ");
}
for(int k=a*2+1; k>0;k--)
{
System.out.print("*");
}
a--;
System.out.println();
}

}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;

import java.util.Scanner;

public class Factoril {

public static void main(String[] args) {


Factoril obj = new Factoril();
System.out.print("Enter a number is = ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
System.out.println("Factorial is = " + obj.factorialNum(num));

public int factorialNum(int a)


{
int fact=1;
for(int i=1; i<=a; i++)
{
fact=fact*i;
}
return fact;
/*if(a==0 || a==1) //this is also recursion method
return 1;
else
return factorialNum(a-1)*a; */

}
}

/*
*The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number is found by adding up the two numbers before it. Similarly, the 3 is
found by adding the two numbers before it (1+2),
*/
package practicesharendra;

import java.util.Scanner;

public class FibonacciSequence


{
public static void main(String[] args) {
int first=0,second=1,next;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number is = ");
int a=sc.nextInt();
System.out.println("Fibonacci Sequence is ");
for(int i=0; i<a; i++)
{
if ( i <= 1 )
next = i;
else

next = first + second;


first = second;
second = next;

System.out.println(next);
}
/*
int current=1,last=0;
Scanner input=new Scanner(System.in);
int num=input.nextInt();
System.out.println(last);
System.out.println(current);
int lastlast=2;
for(int i=2; i<num; i++)
{
lastlast=last;
last=current;
current=lastlast+last;
System.out.println(current);
}
*/

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;

import java.util.Scanner;

public class ShapeOfStar


{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number is : ");
int n=sc.nextInt();
System.out.println("to print Shape of Star like this ");
for(int i=0; i<n; i++)
{
for(int j=n-1; j>i; j--)
{
System.out.print(" ");
}
for(int k=0; k<2*i+1; k++)
{
System.out.print("*");
}
System.out.println("");
}
int n1=n-2;
for(int i=0; i<n-1; i++)
{
for(int j=0; j<=i; j++)
{
System.out.print(" ");
}
for(int k=n1*2+1; k>0; k--)
{
System.out.print("*");
}
n1--;
System.out.println("");
}
}
}

/*
Enter a Number is : 5
print like this :
*
*
*
*
*
*
*
*
*
*

*/
package practicesharendra;

import java.util.Scanner;

public class StarPrint


{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a Number is : ");
int n=sc.nextInt();
System.out.println("print like this : ");
for(int i=1; i<=n; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(" ");
}
System.out.println("*");
}
for(int i=1; i<=n; i++)
{
for(int j=i; j<=n; j++)
{
System.out.print(" ");
}
System.out.println("*");
}
}
}

/*
Enter a number is : 5
Print like this :
*****
****
***
**
*

*/
package practicesharendra;

import java.util.Scanner;

public class StarPrint1 {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number is : ");
int n=sc.nextInt();
System.out.println("Print like this : ");
for(int i=1; i<=n; i++)
{
for(int j=i; j<=n; j++)
{
System.out.print("* ");
}
System.out.println(" ");
}
}

/*
Enter a number is : 5
To Print like this :
*
**
***
****
*****

*/
package practicesharendra;

import java.util.Scanner;

public class StarPrint2 {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number is : ");
int n=sc.nextInt();
System.out.println("To Print like this : ");
for(int i=1; i<=n; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(" *");
}
System.out.println("");
}
}
}

/*
Enter a number is : 8
********
*******
******
*****
****
***
**
*
*
**
***
****
*****
******
*******
********

*/
package practicesharendra;

import java.util.Scanner;

public class StarPrint3 {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number is : ");
int n=sc.nextInt();
for(int i=1; i<=n; i++)
{
for(int j=i; j<=n; j++)
{
System.out.print("*");
}
System.out.println();
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print("*");
}
System.out.println();
}
}

/*
Enter a number is : 8
To Print like this :
*
**
***
****
*****
******
*******
********
********
*******
******
*****
****
***
**
*
*/
package practicesharendra;

import java.util.Scanner;

public class StarPrint4 {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number is : ");
int n=sc.nextInt();
System.out.println("To Print like this : ");
for(int i=1; i<=n; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print("*");
}
System.out.println("");
}
for(int i=1; i<=n; i++)
{
for(int j=i; j<=n; j++)
{
System.out.print("*");
}
System.out.println(" ");
}
}
}

/*
Enter a Number is : 8
print like this :
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package practicesharendra;
import java.util.Scanner;
public class StarPrint5 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a Number is : ");
int n=sc.nextInt();
System.out.println("print like this : ");

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


{
for(int j=i; j<=n; j++)
{
System.out.print(" ");
}
System.out.println("*");
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print(" ");
}
System.out.println("*");
}
}

/*
Enter a number is : 5
To print * star like this
* *
**
*
**
* *

*/
package practicesharendra;
import java.util.Scanner;

public class StarPrint6 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number is : ");
int n=sc.nextInt();
System.out.println("To print * star like this ");
for(int i=0; i<n; i++)
{
for(int j=0;j<n;j++)
{
if(i==j)
System.out.print("*");
else if(i+j==n-1)
System.out.print("*");
else
System.out.print(" ");
}

System.out.println();
}

}
}

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;

import java.util.Scanner;

public class StarPrint7 {


public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number is : ");
int n=sc.nextInt();
System.out.println("Output like this ");
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(i==j)
System.out.print("*");
else if(i+j==n-1)
System.out.print("*");
else
System.out.print(" ");

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

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;

import java.util.Scanner;

public class StarPrint8


{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number is :");
int n=sc.nextInt();
System.out.println("Shape of Star is print like this ");
for(int i=n; i>0; i--)
{
for(int j=n-1; j>=i; j--)
{
System.out.print(" ");
}
for(int k=i*2-1; k>0; k-- )
{
System.out.print("*");
}

System.out.println();

/*
Enter the less than 10 number is :
6
Triagle shape is * :
*
***
*****
*******
*********
***********
*/
package practicesharendra;

import java.util.Scanner;

public class TriangleStar


{
public static void main(String[] args)
{
System.out.println("Enter the less than 10 number is : ");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
System.out.println("Triagle shape is * : ");
for(int i=0; i<n; i++)
{
for(int j=n-1; j>i; j--)
{
System.out.print(" ");
}
for(int k=0; k<2*i+1; k++)
{
System.out.print("*");
}
System.out.println();
}
}

/*
Enter a Number to Print Star
10
Triagle Sape is :
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*/
package practicesharendra;

import java.util.Scanner;

public class TriangleStar1


{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a Number to Print Star ");
int n=sc.nextInt();
System.out.println("Triagle Sape is : ");
for(int i=0; i<n; i++)
{
for(int j=n-1; j>i; j--)
{
System.out.print(" ");
}
for(int k=0; k<2*i+1; k++)
{
System.out.print("*");
}
System.out.println("");
}

/*
To print * is like this

*
**
***
****
*****
******
*******
********
*********
**********

*/
package practicesharendra;

public class TriangleStar2


{
public static void main(String[] args)
{
System.out.println("To print * is like this");
for(int i=1; i<=10; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print("*");
}
System.out.println();
}

/*
Write a Program like this

**********
*********
********
*******
******
*****
****
***
**
*

*/
package practicesharendra;

public class TriangleStar3


{
public static void main(String[] args)
{
System.out.println("To Print * is like this ");
for(int i=1; i<=10; i++)
{
for(int j=i; j<=10; j++)
{
System.out.print("*");
}
System.out.println("");

/*
Enter a number is
10
Triangle like this
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*/
package practicesharendra;

import java.util.Scanner;

public class TriangleStar4


{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter a number is ");
int n=sc.nextInt();
System.out.println("Triangle like this ");
for(int i=0; i<n; i++)
{
for(int j=n-1; j>i; j--)
{
System.out.print("");
}
for(int k=0; k<2*i+1; k++)
{
System.out.print("*");
}
System.out.println();
}

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package practicesharendra;

import java.util.Scanner;

public class TriangleStarRev


{
public static void main(String[] args)
{
Scanner sc =new Scanner(System.in);
System.out.println("Enter a Number is : ");
int n=sc.nextInt();
int sub=n-2;
System.out.println("Star * print like this type of ");
for(int i=1; i<=n; i++)
{
for(int j=n; j>i; j--)
{
System.out.print(" ");
}
for(int k=2*sub-1; k<n; k--)
{
System.out.print("*");
}
sub--;
System.out.println("");
}
}

Module 5 - Collection

/*
ArrayList Basic
*/
package com.collection;

import java.util.ArrayList;

public class Array


{
public static void main(String[] args) {
ArrayList a1=new ArrayList();
a1.add("Google");
a1.add("MicroSoft");
a1.add("Apple");
a1.remove(1);
System.out.println("Remove is : "+a1);
}

package com.collection;
import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList l=new ArrayList();
l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(l);
l.remove(2);
System.out.println(l);
l.add(2,"M");
l.add("N");
System.out.println(l);
}

package com.collection;

public class CompareToDemo


{
public static void main(String[] args)
{
System.out.println("A".compareTo("Z")); // -ive
System.out.println("Z".compareTo("B")); // +ive
System.out.println("A".compareTo("A")); // 0(zero)
//System.out.println("A".compareTo(null)); // NullPointerException
}

package com.collection;
import java.util.*;
public class CursorDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
Enumeration e=v.elements();
Iterator itr=v.iterator();
ListIterator litr=v.listIterator();
System.out.println(e.getClass().getName());
System.out.println(itr.getClass().getName());
System.out.println(litr.getClass().getName());

package com.collection;

import java.util.*;
public class EnumerationDemo
{
public static void main(String[] args)
{
Vector v=new Vector();
for(int i=0; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v); // [0,1,2,3....,10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer I=(Integer)e.nextElement();
if(I%2==0)
System.out.println(I); //0 2 4 6 8 10
}
System.out.println(v); //[0,1,2,3....,10]
}

}
package com.collection;

import java.util.*;
public class HashSetDemo
{
public static void main(String[] args)
{
HashSet h=new HashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z")); // false
System.out.println(h);

package com.collection;
import java.util.*;
public class IteratorDemo
{
public static void main(String[] args)
{
ArrayList l=new ArrayList();
for(int i=0; i<=10; i++)
{
l.add(i);

}
System.out.println(l); //[0,1,2,...10]
Iterator itr=l.iterator();
while(itr.hasNext())
{
Integer I=(Integer)itr.next();
if(I%2==0)
System.out.println(I); //0 2 4 6 8 10
else
itr.remove();
}
System.out.println(l); //[0,2,4,6,8,10]
}

package com.collection;

import java.util.*;
public class LinkedHashSetDemo
{
public static void main(String[] args) {
LinkedHashSet h=new LinkedHashSet();
h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.println(h.add("Z")); //false
System.out.println(h); //[B,C,D,Z,null,10]
}

package com.collection;

import java.util.*;
public class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("durga");
l.add(30);
l.add(null);
l.add("durga");
l.set(0, "Software");
l.add(0,"Venky");
l.removeLast();
l.addFirst("ccc");
System.out.println(l);
}

package com.collection;
import java.util.*;
public class ListIteratorDemo
{
public static void main(String[] args)
{
LinkedList l=new LinkedList();
l.add("balakrishna");
l.add("venki");
l.add("chiru");
l.add("nag");
System.out.println(l);
ListIterator Itr=l.listIterator();
while(Itr.hasNext())
{
String s=(String)Itr.next();
if(s.equals("venki"))
{
Itr.remove();
}
else if(s.equals("nag"))
{
Itr.add("chaitu");
}
else if(s.equals("chiru"))
{
Itr.set("charan");
}
}
System.out.println(l);

package com.collection;
import java.util.*;
public class StackDemo
{
public static void main(String[] args)
{
Stack s=new Stack();
s.push("A");
s.push("B");
s.push("C");
System.out.println(s);
System.out.println(s.search("A"));
System.out.println(s.search("Z"));

package com.collection;

import java.util.*;
public class TreeSetCompareToDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add("B");
t.add("Z"); //"Z".compareTo("B"); +ive
t.add("A"); //"A".compareTo("B"); -ive
System.out.println(t); //[A,B,Z]

package com.collection;

import java.util.*;
public class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add("A");
t.add("a");
t.add("B");
t.add("Z");
t.add("L");
//t.add(new Integer(10)); //ClassCastException
//t.add(null); // NullPointerException
System.out.println(t); //[A, B, L, Z, a]

package com.collection;
import java.util.*;

public class TreeSetDemo1


{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("L"));
t.add(new StringBuffer("B"));
System.out.println(t); //classCastException

package com.collection;
import java.util.*;
public class TreeSetDemo2
{
public static void main(String[] args)
{
//TreeSet t=new TreeSet(); //[0, 10, 15, 20]
TreeSet t=new TreeSet(new MyComparator()); //[20,15,10,0]
t.add(10);
t.add(0);
t.add(15);
t.add(20);
t.add(20);
System.out.println(t);

}
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
Integer I1=(Integer)obj1;
Integer I2=(Integer)obj2;
if(I1<I2)
return +1;
else if (I1>I2)
return -1;
else
return 0;
// return I1.compareTo(I2); //Assecending order [0,10,15,20]
//return -I1.compareTo(I2); //Descending order [20,15,10,0]

//return I2.compareTo(I1); //Descending order [20,15,10,0]


//return -I2.compareTo(I1); //Assecending order [0,10,15,20]

//return +1; // [10, 0, 15, 20, 20] insertion order


//return -1; // [20, 20, 15, 0, 10] Reverse of insertion order
//return 0; //[10] Only first element will be inserted & all other elements are
consider as dublicate

}
}

package com.collection;

import java.util.*;
public class TreeSetDemo3
{
public static void main(String[] args)
{
TreeSet t=new TreeSet(new MyComparator1());
t.add("Roja");
t.add("ShobhaRani");
t.add("RajaKumari");
t.add("GangaBhavani");
t.add("Ramulamma");
System.out.println(t);

}
}
class MyComparator1 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=obj1.toString();
String s2=(String)obj2;
//return s2.compareTo(s1); //[ShobhaRani, Roja, Ramulamma, RajaKumari,
GangaBhavani]
return -s1.compareTo(s2); //[ShobhaRani, Roja, Ramulamma, RajaKumari,
GangaBhavani]
}
}

package com.collection;
import java.util.*;
public class TreeSetDemo4
{
public static void main(String[] args)
{
TreeSet t=new TreeSet(new MyComparator2());
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("K"));
t.add(new StringBuffer("L"));
System.out.println(t);
}

}
class MyComparator2 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s1.compareTo(s2); //[A, K, L, Z]
}
}

package com.collection;

import java.util.*;
public class TreeSetDemo5
{
public static void main(String[] args)
{
TreeSet t=new TreeSet(new MyComparator3());
t.add("A");
t.add(new StringBuffer("ABCD"));
t.add(new StringBuffer("AA"));
t.add("XX");
t.add("A");
System.out.println(t);
}
}
class MyComparator3 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
int len1=s1.length();
int len2=s2.length();
if(len1<len2)
return -1;
else if (len1>len2)
return 1;
else
return s1.compareTo(s2); //[A, AA, XX, ABC]

}
}

/*
Write a Demo Program for Customized sorting for Employee class :
*/

package com.collection;

import java.util.*;
class Employee implements Comparable
{
String name;
int eid;
Employee(String name, int eid)
{
this.name=name;
this.eid=eid;
}
public String toString()
{
return name+"-"+eid;
}

public int compareTo(Object obj)


{
int eid1=this.eid;
Employee e=(Employee)obj;
int eid2=e.eid;
if(eid1<eid2)
{
return -1;
}
else if(eid1>eid2)
{
return 1;
}
else
{
return 0;
}
}
}
public class TreeSetDemo6Compartor
{
public static void main(String[] args)
{
Employee e1=new Employee("nag",100);
Employee e2=new Employee("balaiah",200);
Employee e3=new Employee("chiru",50);
Employee e4=new Employee("venki",150);
Employee e5=new Employee("nag",100);
TreeSet t=new TreeSet();
t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
t.add(e5);
System.out.println(t); // [chiru-50, nag-100, venki-150, balaiah-200]

TreeSet t1=new TreeSet(new MyComparator4());


t1.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t1); //[balaiah - 200, chiru - 50, nag-100, venki- 150]
}
}
class MyComparator4 implements Comparator
{
public int compare(Object obj1, Object obj2)
{
Employee e1=(Employee)obj1;
Employee e2=(Employee)obj2;
String s1=e1.name;
String s2=e2.name;
return s1.compareTo(s2);
}
}

package com.collection;

import java.util.*;
public class VectorDemo1
{
public static void main(String[] args)
{
Vector v=new Vector();
System.out.println(v.capacity()); //10
for(int i=1; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity()); //10
v.addElement("A");
System.out.println(v.capacity()); //20
System.out.println(v);
}

package com.collection;
import java.util.*;
public class VectorDemo2
{
public static void main(String[] args)
{

Vector v=new Vector(35);


System.out.println(v.capacity());
for(int i=1; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement("A");
System.out.println(v.capacity());
System.out.println(v);
}

package com.collection;

import java.util.*;
public class VectorDemo3
{
public static void main(String[] args)
{
Vector v=new Vector(10,5);
System.out.println(v.capacity()); //10
for(int i=1; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v.capacity());//10
v.addElement("A");
System.out.println(v.capacity());//15
System.out.println(v);

package com.collection.jPont;
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ArrayListAddBook {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc
Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+"
"+b.quantity);
}
}
}

package com.collection.jPont;

import java.util.ArrayList;
import java.util.Iterator;

public class TestListCollec {


public static void main(String args[]){
System.out.println("1st ArrayList ::::::::::::::::::::::");
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("Harendra"); //Adding object in arraylist
list.add("Upendra");
list.add("Ashutosh");
list.add("Vivek");
list.add("Ranjan");
list.add(5, "Rashmi");
list.add(6, "Prabhu Deva");
System.out.println(list);
Iterator<String> itr=list.iterator(); ////Traversing list through Iterator
while(itr.hasNext()){
System.out.println(itr.next());
}

System.out.println("2nd ArrayList ::::::::::::::::::");


ArrayList<String> list2=new ArrayList<String>();
list2.add("Prabhat");
list2.add("Pramod");
list2.add("Amit");
list2.add("Viru");
list2.add("Ravindra");
list2.add("Balu");
list2.add("Vikas");
System.out.println(list2);
for(String obj:list2){
System.out.println(obj);
}

System.out.println("3rd ArrayList ::::::::::::::::::::::::::::::::::::::::::::");


ArrayList<String> list3=new ArrayList<String>();
list3.add("Suraj Gupta");
list3.add("Nitish");
list3.add("Sandeep");
list3.add("Ajay");
System.out.println(list3);
list3.remove(2);
list3.addAll(list2); //addAll(Collection c)
System.out.println("After Remove list :::: "+list3);
Iterator itr3=list3.iterator();
while(itr3.hasNext()){
System.out.println(itr3.next());
}
}
}

package com.collection.jPont;

import java.util.ArrayList;
import java.util.Iterator;

class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
public class UserDefObjList {
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s3=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}

package com.soft.collection;
import java.util.*;
public class HashMapDemo {
public static void main(String args[]){
HashMap m=new HashMap();
m.put("Chiran Jeevi", 700);
m.put("Balaiah", 800);
m.put("Venkatesh", 200);
m.put("Nagaarjuna", 500);
System.out.println("m ::: "+m);
System.out.println(m.put("Chiran Jeevi", 1000));
Set s=m.keySet();
System.out.println(s);
Collection c=m.values();
System.out.println("c ::: " +c);
Set s1=m.entrySet();
System.out.println("s1 ::: "+s1);
Iterator itr=s1.iterator();
while(itr.hasNext()){
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey()+ " -------- " +m1.getValue());
if(m1.getKey().equals("Nagaarjuna")){
m1.setValue(10000);
}
}
System.out.println(m);
}

package com.soft.collection;

import java.util.HashMap;
import java.util.IdentityHashMap;

public class IdentityHashMapDemo {


public static void main(String args[]){
//HashMap m=new HashMap();
IdentityHashMap m=new IdentityHashMap();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
m.put(i1, "Pawan");
m.put(i2, "Kalyan");
System.out.println(m);
}
}

package com.soft.collection;

import java.util.HashMap;
import java.util.WeakHashMap;

import javax.xml.transform.Templates;

public class WeakHashMapDemo {


public static void main(String args[]) throws Exception{
//HashMap m=new HashMap();
WeakHashMap m=new WeakHashMap();
Temp t=new Temp();
m.put(t, "durga");
System.out.println(m);
t=null;
System.gc();
Thread.sleep(5000);
System.out.println(m);
}
}
class Temp{
public String toString(){
return "temp";
}
public void finalize(){
System.out.println("Finalize method called");
}
}

You might also like