0% found this document useful (0 votes)
32 views43 pages

Java 2

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 43

I/O

1. Hello World
class Main
{
public static void main(String args[])
{
System.out.println("\"Hello, World!\"");
}
}

2. Hello World with tab


class Main
{
public static void main(String args[])
{
//Try out your code here
System.out.println("Hello World\tHello World");
}
}

3. Hello world with new line


class Main
{
public static void main(String args[])
{
//Try out your code here
System.out.println("Hello World\nHello World");
}
}

4. Student Details
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = sc.nextInt();
Float cgpa = sc.nextFloat();
char grade = sc.next().charAt(0);
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("CGPA: "+Math.floor(cgpa*100)/100);
System.out.println("Grade: "+grade);
}
}
5. ASCII 1
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0);
int ascii = (char)ch;
System.out.println(ascii);
}
}

6. ASCII 2
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int ascii = sc.nextInt();
char ch = (char)ascii;
System.out.println(ch);
}
}

7. Round off
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
float n = sc.nextFloat();
int a = (int)n;
int b = (int)Math.ceil(n);
int c = (int)Math.floor(n);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
OPERATORS
1. Fencing the ground
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int l = sc.nextInt();
int b = sc.nextInt();
int length = 2*(l+b);
int area = l*b;
System.out.println("The required length is "+length+" m");
System.out.println("The required area of carpet is "+area+" sqm");
}
}

2. Newspaper agency
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int profit = a*(b-c)-100;
System.out.println(profit);
}
}

3. Harry potter
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
n = Math.abs(n);
int d1 = n / 1000;
int d4 = n % 10;
System.out.println(d1+d4);
}
}
4. Splitting into teams
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int frnds = sc.nextInt();
int teams = sc.nextInt();
int frndsPerTeam = frnds / teams;
int frndsLeft = frnds % teams;
System.out.println("The number of friends in each team is "+ frndsPerTeam +" and left
out is "+frndsLeft);
}
}

5. Debt repay
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Float principal = sc.nextFloat();
Float rate = sc.nextFloat();
Float year = sc.nextFloat();
Float interest = (principal*rate*year)/100;
Float totalamt = principal + interest;
Float discount = 0.02f * interest;
Float finalval = totalamt - discount;
System.out.printf("%.2f%n",interest);
System.out.printf("%.2f%n",totalamt);
System.out.printf("%.2f%n",discount);
System.out.printf("%.2f%n",finalval);
}
}

6. 3 psychos
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x1 = sc.nextInt();
int y1 = sc.nextInt();
int x2 = sc.nextInt();
int y2 = sc.nextInt();
double mp1 = (x1+x2)/2.0;
double mp2 = (y1+y2)/2.0;
System.out.println("Arun's house is located at("+mp1+","+mp2+")");
}
}

7. Hop n hop
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
double distance = Math.sqrt(Math.pow(x - 3, 2) + Math.pow(y - 4, 2));
System.out.println(Math.floor(distance));
}
}

8. Dollars and cents


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int d1 = sc.nextInt();
int c1 = sc.nextInt();
int d2 = sc.nextInt();
int c2 = sc.nextInt();
int csum = (c1+c2)/100;
int rem = (c1+c2) % 100;
int dsum = (d1+d2)+((c1+c2)/100);
System.out.println(dsum);
System.out.println(rem);

}
}

9. Treasure Hunter
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int coins = sc.nextInt();
int ben = sc.nextInt();
int black = sc.nextInt();
int benShare = (ben * coins)/100; //473
int rem = coins - benShare; //256
int blackShare = (black * rem)/100; //222
int rems = rem - blackShare; //34
int otherShare = (rems/3);
System.out.println(benShare);
System.out.println(blackShare);
System.out.println(otherShare);
}
}

10. Reverse a 3 digit


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d1 = n / 100;
int d2 = n / 10 % 10;
int d3 = n % 10;
System.out.println((d3*100)+(d2*10)+d1);
}
}

11. Tic tac toe


import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n < 1 || n > 9){
System.out.println("Error");
}
int index = n - 1;
int row = index / 3;
int col = index % 3;
System.out.println(row + " " + col);
}
}
DECISION MAKING
1. Checking alphabets
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0);
if((ch>='a' && ch<='z')|| (ch>='A' && ch<='Z'))
{
if( ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' ||
ch=='I' || ch=='O' || ch=='U' )
{
System.out.println("Vowel");
}
else
{
System.out.println("Consonant");
}
}
else
{
System.out.println("Not an alphabet");
}
}
}

2. Electricity bill
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int units=sc.nextInt();
if(units<=200){
System.out.println( "Rs."+units*5/10);
}
else{
System.out.println("Rs."+((units*65/100)+100));
}
}}

3. Online shopping
4. Hotel traffic
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int month = scanner.nextInt();
int roomRentPerDay = scanner.nextInt();
int daysStayed = scanner.nextInt();
if (month < 1 || month > 12) {
System.out.println("Invalid Input");
return;
}
boolean isPeakSeason = (month >= 4 && month <= 6) || (month >= 11 &&
month <= 12);
int totalTariff = roomRentPerDay * daysStayed;
if (isPeakSeason) {
totalTariff *= 1.20;
}
System.out.println(totalTariff);
}
}

5. Gift for bday


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if((n%4 == 0) && (n%100!=0))
System.out.println(n+" is a leap year");
else
System.out.println(n+" is not a leap year");
}
}

6. Trendy number
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n>=100 && n<=999)
{
int mid = n / 10 % 10;
if(mid % 3 == 0)
{
System.out.println("Trendy Number");
}
else
{
System.out.println("Not a Trendy Number");
}
}
else
{
System.out.println("Invalid Number");
}
}
}

7. Time sheet
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int sun = sc.nextInt();
int mon = sc.nextInt();
int tues = sc.nextInt();
int wed = sc.nextInt();
int thur = sc.nextInt();
int fri = sc.nextInt();
int sat = sc.nextInt();
int ans=0;
ans=(mon+tues+wed+thur+fri)*100;
int satBonus = 125;
int sunBonus = 150;
if(mon>8)
ans=ans+(mon-8)*15;
if(tues>8)
ans=ans+(tues-8)*15;
if(wed>8)
ans=ans+(wed-8)*15;
if(thur>8)
ans=ans+(thur-8)*15;
if(fri>8)
ans=ans+(fri-8)*15;
ans=ans+(sat*satBonus)+(sun*sunBonus);
System.out.println(ans);
}
}

8. No of days
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
int month = sc.nextInt();
if(month==2)
{
if ((year%4==0 && year%100!=0) || year%400==0)
System.out.println("29 Days");
else
System.out.println("28 Days");
}
else if(month==4 || month==6 || month==9 || month==11)
System.out.println("30 Days");
else
System.out.println("31 Days");
}
}

9. Scholarship
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
int year = sc.nextInt();
int famIncome = sc.nextInt();
int arrear = sc.nextInt();
Float marks = sc.nextFloat();
Float attendance = sc.nextFloat();
if((age <=21) && (age >=18) && (year >=2021) && (famIncome <= 200000) &&
(arrear <2) && (marks >= 60) && (attendance >= 80))
{
System.out.println("Eligible");
}
else if((arrear >=2) && (marks >=80) && (attendance >=90) && (famIncome >=
200000) && (famIncome <= 250000))
{
System.out.println("Partially Eligible");
}
else
{
System.out.println("Not Eligible");
}
}
}

10. Mango tree


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
int c = sc.nextInt();
int t = sc.nextInt();
if(t<=c || t%c==1 || t%c==0)
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}

11. Cricket
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int totalBalls = scanner.nextInt();
int totalRuns = scanner.nextInt();
int runsScored = scanner.nextInt();
int ballsBowled = scanner.nextInt();
float overs,oversFinished,currentRR,totalRR;

overs = totalBalls/6;
int z1= ballsBowled / 6;
int z2= ballsBowled % 6;
oversFinished = z1 + z2 * 0.1f;
currentRR = runsScored / oversFinished;
totalRR = totalRuns/overs;

System.out.println((int)overs);
System.out.printf("%.1f\n", oversFinished);
System.out.printf("%.1f\n", currentRR);
System.out.printf("%.1f\n", totalRR);

if (currentRR>totalRR)
{
System.out.println("Eligible to Win");
}
else
{
System.out.println("Not Eligible to Win");
}
}
}
CONTROL STATEMENTS
1. Multiplication table
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc =new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int val=n;
System.out.println("Enter n");
System.out.println("Enter m");
System.out.println("The multiplication table of "+n+" is");
for(int i=1;i<=m;i++)
{
System.out.println(i+"*"+n+"="+val);
val=val+n;
}
}
}

2. Prime num
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=2;i<=n;i++)
{
boolean isPrime = true;
for(int j=2;j<=i/2;j++)
{
if(i%j==0)
{
isPrime = false;
break;
}
}
if(isPrime)
{
System.out.print(i+" ");
}
}
}
}
3. Special number
import java.util.*;
class Main
{

public static void fun(int n)


{
int a = n%10;
int b = n/10;
int ans = (a*b)+(a+b);
if(ans==n)
System.out.println(n);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int e = sc.nextInt();
for(int i=s;i<=e;i++)
fun(i);
}
}

4. Amoeba multiplication
import java.util.*;
class Main
{
public static int fib(int n)
{
if(n==1)
return 0;
else if(n==2)
return 1;
else
return (fib(n-1)+fib(n-2));
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(fib(n));
}
}

5. Number series
import java.util.*;
class Main
{
public static int fun(int n)
{
if(n%2==0)
return (n*n)-2;
else
return (n*n)-1;
}

public static void main(String args[])


{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=1;i<=n;i++)
System.out.print(fun(i)+" ");
}
}

6. Hollow square
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==1 || i==n || j==1 || j==n)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}

7. Treasure finder
import java.util.*;
class Main
{
public static int min(int a,int b,int c)
{
if(a>b && b>c)
return a;
else if(b>a && b>c)
return b;
else
return c;
}
public static int find(int a,int b,int c)
{
for(int i=min(a,b,c);i>=1;i--)
{
if(a%i==0 && b%i==0 && c%i==0)
return i;
}
return 1;
}
public static int max2(int a,int b,int c)
{
if((a>b && a<c) || (a<b && a>c))
return a;
else if((b > a && b < c) || (b < a && b > c))
return b;
else
return c;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int ans = max2(a,b,c);
int ans1 = find(a,b,c);
System.out.println("The treasure is in the box which has the number "+ans);
System.out.println("The code to open the box is "+ans1);
}
}

8. Collatz problem
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int steps = generateCollatzSequence(n);
System.out.println(steps);
}
public static int generateCollatzSequence(int n)
{
int steps = 0;
while(n!=1)
{
System.out.println(n);
if(n%2 == 0)
{
n=n/2;
}
else
{
n=3*n+1;
}
steps++;
}
System.out.println(n);
return steps;
}
}

9. Strong number
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int temp = n;
int sum=0;
while(n!=0)
{
int i=1;
int fact=1;

int rem=n%10;
while(i<=rem)
{
fact=fact*i;
i++;
}
sum=sum+fact;
n=n/10;
}
if(temp == sum)
System.out.println("Yes");
else
System.out.println("No");
}
}

10. Inverted right angle triangle


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i,j;
for(i=n;i>0;i--)
{
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}
}
}

11. Sum of digits


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int number = Integer.parseInt(input);
int result = sumOfDigits(number);
System.out.println(result);
}
public static int sumOfDigits(int number)
{
while(number>=10)
{
number = digitalSum(number);
}
return number;
}

public static int digitalSum(int number)


{
int sum=0;
while(number > 0){
sum +=number%10;
number /=10;
}
return sum;
}
}

12. Kaprekar number


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int count = 0;
int temp = n;
int sq = n*n;
while(n!=0)
{
n = n/10%10;
count++;
}
int p = (int)Math.pow(10,count);
int r = sq % p;
int q = sq/p;
int sum= r+q;
if(temp==sum)
{
System.out.println("Kaprekar Number");
}
else
{
System.out.println("Not a Kaprekar Number");
}
}
}

13. Trapezium pattern


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int l = 1;
int r = n*n+1;
for(int i=n;i>0;i--)
{
for(int j=n;j>i;j--)
{
System.out.print("--");
}
for(int k=i;k>0;k--)
{
System.out.print(l++ +"*");
}
for(int k=i;k>1;k--)
{
System.out.print(r++ +"*");
}
System.out.println(r);
r = r-2*(i-1);
}
}
}
ARRAYS 1D
1. Same or not
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size1 = scanner.nextInt();
int size2 = scanner.nextInt();
if (size1 != size2) {
System.out.println("Not Same");
return;
}
int[] array1 = new int[size1];
int[] array2 = new int[size2];
for (int i = 0; i < size1; i++) {
array1[i] = scanner.nextInt();
}
for (int i = 0; i < size2; i++) {
array2[i] = scanner.nextInt();
}
int sum1 = 0;
int sum2 = 0;
for (int num : array1) {
sum1 += num;
}
for (int num : array2) {
sum2 += num;
}
if (sum1 == sum2) {
System.out.println("Same");
} else {
System.out.println("Not Same");
}
}
}

2. Count distinct elements


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[] array = new int[size];
for(int i=0;i<size;i++){
array[i] = sc.nextInt();
}
Set<Integer>distinctElements = new HashSet<>();
for(int num : array){
distinctElements.add(num);
}
System.out.println("There are "+distinctElements.size()+" distinct element in the array.");
}
}

3. Compatible arrays
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int n1=sc.nextInt();
int[] array1 = new int[n1];
for(int i=0;i<n1;i++){
array1[i]=sc.nextInt();
}
int n2=sc.nextInt();
int[] array2 = new int[n2];
for(int i=0;i<n2;i++)
{
array2[i] = sc.nextInt();
}
boolean compatible = true;
if(n1 != n2){
compatible = false;
}
else
{
for(int i=0;i<n1;i++){
if(array1[i] < array2[i]){
compatible = false;
break;
}
}
}
if(compatible)
{
System.out.println("Compatible");
}
else{
System.out.println("Incompatible");
}
}
}

4. Sum of even and odd


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
for(int i=0;i<n;i++){
array[i] = sc.nextInt();
}
int sumEven =0;
int sumOdd = 0;
for(int num:array){
if(num%2==0){
sumEven +=num;
} else{
sumOdd +=num;
}
}
System.out.println("The sum of the even numbers in the array is " + sumEven);
System.out.println("The sum of the odd numbers in the array is " + sumOdd);
}
}

5. Ascending order
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

System.out.println("The Sorted array is:");


for (int i = 0; i < size; i++) {
System.out.println(arr[i]);
}
}
}
6. Queue
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[] groups = new int[n];
for(int i=0;i<n;i++)
{
groups[i] = sc.nextInt();
}
int buses = 0;
int passengers = 0;
for(int i=0;i<n;i++)
{
if(passengers + groups[i] <= m)
{
passengers += groups[i];
}
else
{
buses++;
passengers = groups[i];
}
}
if(passengers > 0)
{
buses++;
}
System.out.println(buses);
}
}

7. Array insertion
8. Remove duplicate elements
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
Set<Integer> set = new LinkedHashSet<>();
for (int num : array) {
set.add(num);
}
for (int num : set) {
System.out.println(num);
}
scanner.close();
}
}
9. Online game
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
segregateArray(arr);
System.out.println("Array after Segregation");
for (int num : arr) {
System.out.print(num + " ");
}
scanner.close();
}
public static void segregateArray(int[] arr) {
int left = 0, right = arr.length - 1;

while (left < right) {


while (arr[left] % 2 == 0 && left < right) {
left++;
}
while (arr[right] % 2 != 0 && left < right) {
right--;
}
if (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
}
10. Largest house
import java.util.*;
public class Main
{
static class House implements Comparable<House>
{
int num;
int pos;
public House(int num, int pos)
{
this.num = num;
this.pos = pos;
}
@Override
public int compareTo(House other)
{
return this.pos - other.pos;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
House[] houses = new House[num];
for (int i = 0; i < num; i++)
{
int houseNum = sc.nextInt();
int pos = sc.nextInt();
houses[i] = new House(houseNum, pos);
}
Arrays.sort(houses);
int maxDistance = Integer.MIN_VALUE;
int house1 = -1, house2 = -1;
for (int i = 0; i < num - 1; i++)
{
int distance = houses[i+1].pos - houses[i].pos;
if (distance > maxDistance)
{
maxDistance = distance;
house1 = houses[i].num;
house2 = houses[i+1].num;
}
}
System.out.println(Math.min(house1, house2) + " " + Math.max(house1, house2));
}
}

11. Pair the container


import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int numContainers = sc.nextInt();
int[] capacities = new int[numContainers];
for(int i=0;i<numContainers;i++){
capacities[i] = sc.nextInt();
}
Arrays.sort(capacities);
int left=0,right = numContainers-1;
while(left<right){
System.out.println(capacities[right] + " " + capacities[left]);
left++;
right--;
}
if(left == right){
System.out.println(capacities[left] + " 0");
}
}
}

12. Smallest positive missing


import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
int missingNumber = findMissingNumber(a);
System.out.println(missingNumber);
}
public static int findMissingNumber(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
while (a[i] > 0 && a[i] <= n && a[a[i]-1] != a[i]) {
int temp = a[a[i]-1];
a[a[i]-1] = a[i];
a[i] = temp;
}
}
for (int i = 0; i < n; i++) {
if (a[i] != i+1) {
return i + 1;
}
}
return n + 1;
}
}
ARRAYS 2D
1. Transpose Matrix
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[][] matrix = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
matrix[i][j] = scanner.nextInt();
}
}
System.out.println("Original matrix is:");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
int[][] transpose = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
transpose[j][i] = matrix[i][j];
}
}
System.out.println("Transpose matrix is:");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}

2. Upper triangular matrix


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}
boolean isUpperTriangular = true;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (matrix[i][j] != 0) {
isUpperTriangular = false;
break;
}
}
if (!isUpperTriangular) {
break;
}
}
if (isUpperTriangular) {
System.out.println("Upper triangular matrix");
} else {
System.out.println("Not an Upper triangular matrix");
}
scanner.close();
}
}

3. Max element in each col


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
int[][] matrix = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}
for (int j = 0; j < n; j++) {
int max = matrix[0][j];
for (int i = 1; i < m; i++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
System.out.println(max);
}
scanner.close();
}
}

4. Matrix multiplication
5. Sum of zigzag
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int r = scanner.nextInt();
int c = scanner.nextInt();
int[][] a = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
a[i][j] = scanner.nextInt();
}
}
int sum = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (i == 0 || i == r - 1 || i == j) {
sum += a[i][j];
}
}
}
System.out.println("Sum of Zig-Zag pattern is " + sum);
}
}

6. Move all zeros


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();

while (T-- > 0) {


String input = scanner.next();
StringBuilder result = new StringBuilder();
int countZeroes = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '0') {
countZeroes++;
} else {
result.append(input.charAt(i));
}
}
for (int i = 0; i < countZeroes; i++) {
result.append('0');
}
System.out.println(result);
}
scanner.close();
}
}

7. Uniformity matrix
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}
boolean isUniform = true;
int firstElement = matrix[0][0] % 2;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] % 2 != firstElement) {
isUniform = false;
break;
}
}
if (!isUniform) {
break;
}
}
if (isUniform) {
System.out.println("Yes");
} else {
System.out.println("No");
}
scanner.close();
}
}

8. Magic square
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = scanner.nextInt();
}
}
int s1 = 0, s2 = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
s1 += a[i][j];
}
if (i + j == n - 1) {
s2 += a[i][j];
}
}
}
if (s1 == s2) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
9. Sum of rows and columns
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] fruits = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
fruits[i][j] = scanner.nextInt();
}
}
int maxRowSum = Integer.MIN_VALUE;
int maxRowIndex = -1;
System.out.print("The Sum of rows is ");
for (int i = 0; i < rows; i++) {
int rowSum = 0;
for (int j = 0; j < cols; j++) {
rowSum += fruits[i][j];
}
System.out.print(rowSum + " ");
if (rowSum > maxRowSum) {
maxRowSum = rowSum;
maxRowIndex = i + 1;
}
}
System.out.println("\nRow " + maxRowIndex + " has a maximum sum");
int maxColSum = Integer.MIN_VALUE;
int maxColIndex = -1;
System.out.print("The Sum of columns is ");
for (int j = 0; j < cols; j++) {
int colSum = 0;
for (int i = 0; i < rows; i++) {
colSum += fruits[i][j];
}
System.out.print(colSum + " ");
if (colSum > maxColSum) {
maxColSum = colSum;
maxColIndex = j + 1;
}
}
System.out.println("\nColumn " + maxColIndex + " has the maximum sum");
scanner.close();
}
}

10. Spiral pattern


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[][] matrix = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = scanner.nextInt();
}
}
spiralTraversal(matrix);
scanner.close();
}
public static void spiralTraversal(int[][] matrix) {
int topRow = 0, bottomRow = matrix.length - 1;
int leftCol = 0, rightCol = matrix[0].length - 1;
while (topRow <= bottomRow && leftCol <= rightCol) {
for (int i = leftCol; i <= rightCol; i++) {
System.out.print(matrix[topRow][i] + " ");
}
topRow++;
for (int i = topRow; i <= bottomRow; i++) {
System.out.print(matrix[i][rightCol] + " ");
}
rightCol--;

if (topRow <= bottomRow) {


for (int i = rightCol; i >= leftCol; i--) {
System.out.print(matrix[bottomRow][i] + " ");
}
bottomRow--;
}
if (leftCol <= rightCol) {
for (int i = bottomRow; i >= topRow; i--) {
System.out.print(matrix[i][leftCol] + " ");
}
leftCol++;
}
}
}
}

11. Matrix rotation


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int[][] matrix = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
matrix[i][j] = scanner.nextInt();
}
}
rotateMatrix(matrix);
printMatrix(matrix);
scanner.close();
}
public static void transpose(int[][] matrix) {
int N = matrix.length;
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
public static void reverseRows(int[][] matrix) {
int N = matrix.length;
for (int i = 0; i < N; i++) {
int start = 0;
int end = N - 1;
while (start < end) {
int temp = matrix[i][start];
matrix[i][start] = matrix[i][end];
matrix[i][end] = temp;
start++;
end--;
}
}
}
public static void rotateMatrix(int[][] matrix) {
transpose(matrix);
reverseRows(matrix);
}
public static void printMatrix(int[][] matrix) {
int N = matrix.length;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
RECURSION
1. Factorial of a number
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
scanner.close();
int factorial = computeFactorial(number);
System.out.println("The factorial of " + number + " is " + factorial);
}
public static int computeFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * computeFactorial(n - 1);
}
}
}

2. Number of digits
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a non-negative integer:");
int number = scanner.nextInt();
scanner.close();

int numDigits = countDigits(number);

System.out.println("The number of digits in " + number + " is " + numDigits);


}

public static int countDigits(int n) {


if (n < 10) {
return 1;
} else {
return 1 + countDigits(n / 10);
}
}
}

3. Sum of array elements


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
scanner.close();
int sum = calculateSum(arr, n);
System.out.println(sum);
}
public static int calculateSum(int[] arr, int n) {
if (n <= 0) {
return 0;
} else {
return arr[n - 1] + calculateSum(arr, n - 1);
}
}
}

4. Fibonacci Series
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n, t1 = 0, t2 = 1, nextTerm = 0, i;
n = sc.nextInt();
if(n == 0 || n == 1)
System.out.println(n);
else
nextTerm = t1 + t2;
for (i = 3; i <= n; ++i)
{
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
System.out.println("The term "+n+" in the Fibonacci series is "+t2);
}
}

5. Compute a^n
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int n = scanner.nextInt();
scanner.close();
long result = power(a, n);
System.out.println("The value of " + a + " power " + n + " is " + result);
}
public static long power(int a, int n) {
if (n == 0) {
return 1;
} else if (n % 2 == 0) {
long temp = power(a, n / 2);
return temp * temp;
} else {
long temp = power(a, n / 2);
return a * temp * temp;
}
}
}

6. Sum of positive odd numbers


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
scanner.close();
int sum = sumPositiveOdd(arr, n);
System.out.println("Sum = " + sum);
}
public static int sumPositiveOdd(int[] arr, int n) {
if (n <= 0) {
return 0;
}
int currentSum = 0;
if (arr[n - 1] > 0 && arr[n - 1] % 2 != 0) {
currentSum = arr[n - 1];
}
return currentSum + sumPositiveOdd(arr, n - 1);
}
}

7. Max element in an array


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
scanner.close();
int max = findMax(array, size);
System.out.println("Maximum element in the array is " + max);
}
public static int findMax(int[] array, int size) {
if (size == 1) {
return array[0];
}
int maxRest = findMax(array, size - 1);
return Math.max(maxRest, array[size - 1]);
}
}

8. Prime number
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
scanner.close();
if (isPrime(number, 2)) {
System.out.println("Prime Number");
} else {
System.out.println("Not a Prime Number");
}
}
public static boolean isPrime(int n, int divisor) {
if (n <= 2) {
return (n == 2) ? true : false;
}
if (n % divisor == 0) {
return false;
}
if (divisor * divisor > n) {
return true;
}
return isPrime(n, divisor + 1);
}
}

9. GCD of 2 numbers
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
scanner.close();
int gcdResult = gcd(num1, num2);
System.out.println(gcdResult);
}
public static int gcd(int num1, int num2) {
if (num2 == 0) {
return num1;
}
return gcd(num2, num1 % num2);
}
}

10. Decimal to binary


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int decimal = scanner.nextInt();
scanner.close();
String binary = convertToBinary(decimal);
System.out.println(binary);
}
public static String convertToBinary(int decimal) {
if (decimal == 0) {
return "0";
}
return convertToBinaryHelper(decimal, "");
}
public static String convertToBinaryHelper(int decimal, String binary) {
if (decimal == 0) {
return binary;
}
binary = (decimal % 2) + binary;
return convertToBinaryHelper(decimal / 2, binary);
}
}
STRINGS
1. Count the vowels
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
int c = 0, vc = 0;
for (int i = 0; i < a.length(); i++) {
char z = a.charAt(i);
if (z == 'a' || z == 'e' || z == 'i' || z == 'o' || z == 'u' || z == 'A' || z == 'E' || z == 'I' || z == 'O'
|| z == 'U')
vc++;
}
System.out.printf("Number of vowels: %d", vc);
scanner.close();
}
}

2. Palindrome
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
int c = a.length();
int i = 0, j = c - 1, f = 0;
while (i < j) {
if (a.charAt(i) != a.charAt(j))
f = 1;
i++;
j--;
}
if (f == 0)
System.out.println("Palindrome");
else
System.out.println("Not a Palindrome");
scanner.close();
}
}

3. First non repeating


4. Sorting
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
char[] charArray = a.toCharArray();
for (int i = 0; i < charArray.length; i++) {
for (int j = i + 1; j < charArray.length; j++) {
if (charArray[i] > charArray[j]) {
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
}
}
System.out.println(new String(charArray));
scanner.close();
}
}

5. Wordakshari
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] a = new String[10];
int n = 0;
while (true) {
a[n] = scanner.next();
if (a[n].equals("####"))
break;
n++;
}
System.out.println(a[0]);
int i = 0, j = 1;
while (i < n - 1) {
char l = a[i].charAt(a[i].length() - 1);
if (l == a[j].charAt(0)) {
System.out.println(a[j]);
} else {
break;
}
i++;
j++;
}
scanner.close();
}
}

6. Reverse each word


import java.util.Scanner;
public class Main {
public static void reverseSentence(String A) {
int len = A.length();
int count = 0;
for (int i = len - 1; i >= 0; i--) {
if (A.charAt(i) != ' ') {
count++;
} else {
for (int j = i + 1; j <= (i + count); j++) {
System.out.print(A.charAt(j));
}
count = 0;
System.out.print(" ");
}
}
for (int i = 0; i < count; i++) {
System.out.print(A.charAt(i));
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String A = scanner.nextLine();
reverseSentence(A);
scanner.close();
}
}

7. String subsequence
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.nextLine();
String b = scanner.nextLine();
int s1 = a.length();
int s2 = b.length();

int i = 0, j = 0;
while (i < s1 && j < s2) {
if (a.charAt(i) == b.charAt(j)) {
j++;
}
i++;
}
if (j >= s2) {
System.out.println("1");
} else {
System.out.println("0");
}
scanner.close();
}
}

8. Anagram
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String firstString = scanner.nextLine();
String secondString = scanner.nextLine();
if (areAnagrams(firstString, secondString)) {
System.out.println("Anagram");
} else {
System.out.println("Not Anagram");
}
scanner.close();
}
public static boolean areAnagrams(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}
}

9. Encrypted string
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int c = (int) (Math.log10(n) + 1);
int[] a = new int[c];
int i = c - 1;
while (n > 0) {
a[i--] = n % 10;
n = n / 10;
}
for (i = 0; i < c - 1; i++) {
int t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
i++;
}
int ans = 0;
for (i = 0; i < c; i++) {
ans = ans * 10 + a[i];
}
System.out.println(ans);
}
}
10. Count the sum
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.nextLine();
int ans = 0, fans = 0;
for (int i = 0; i < a.length(); i++) {
if (Character.isDigit(a.charAt(i))) {
ans = ans * 10 + (a.charAt(i) - '0');
} else {
fans += ans;
ans = 0;
}
}
fans += ans;
System.out.println(fans);
}
}

11. Remove all char


import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
StringBuilder result = new StringBuilder();
for (int i = 0; i < b.length(); i++) {
boolean found = false;
for (int j = 0; j < a.length(); j++) {
if (b.charAt(i) == a.charAt(j)) {
found = true;
break;
}
}
if (!found) {
result.append(b.charAt(i));
}
}
System.out.println(result.toString());
}
}
STRUCTURE AND UNION
1. Student details
2. Add two distances
3. Time differences
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int h1, m1, s1, h2, m2, s2;
h1 = scanner.nextInt();
m1 = scanner.nextInt();
s1 = scanner.nextInt();
h2 = scanner.nextInt();
m2 = scanner.nextInt();
s2 = scanner.nextInt();
int s = s1 - s2;
int m = m1 - m2;
int h = h1 - h2;
System.out.printf("TIME DIFFERENCE: %d:%d:%d - %d:%d:%d = %d:%d:%d", h1, m1, s1, h2,
m2, s2, h, m, s);
}
}

You might also like