0% found this document useful (0 votes)
78 views133 pages

External Training JAVA Training - 01.07.2024 - 11.07.2024

Java Advanced Practice questions

Uploaded by

Santhose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views133 pages

External Training JAVA Training - 01.07.2024 - 11.07.2024

Java Advanced Practice questions

Uploaded by

Santhose
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 133

External JAVA Training

01.07.2024 – 11.07.2024

2024 – 2025
Final Year Placement

External Trainer(s)
1. Batch I - Mr. Eshwar, Enbott – Codechef.
2. Batch II - Mr. Dinesh, Top Freshers (Terv).
3. Batch III - Mr. Puzhal, Innate Talent.
External JAVA Training
Batch I
10 DAY ADVANCED JAVA TRAINING
Batch 1
TRAINER: MR.ESHWAR, ENBOTT TECHNOLOGIES, CHENNAI
Day 1:
Basics of OOPs
Problems in codeChef – Learn OOPS Module
Day 2:
Constructor and Sta c members
Problems in codeChef – Learn OOPS Module
Day 3:
Inheritance and Polymorphism
Zoho – Train Ticket Booking
Day 4:
Interface and Abstract class
Zoho – Train Ticket Booking
Day 5:
Parameters and Aggrega on
Codechef – Odd Sum, Rooks Checkboard Placement, Smallest Number Digit Product
Day 6:
Excep on Handling
Problems – String Compression
Day 7:
File Handling
Problems – K Palindrome Integers, Prin ng prime numbers from 1 to N.
Day 8:
Queue and Stack
CodeChef – GoldMine, Super ASCII Character Checker
Day 9:
Singly Linked List and Doubly Linked List
Problem – Maximum Tips Money
Day 10:
Graphs and Trees
Problem – Christmas Tree Pa ern
External JAVA Training
Batch II
Day 1

1. Prime numbers
public class primenumbers{
public static void main(String [] args){
int n=50;
boolean[] p=test(n);
System.err.println("To be printed "+n+":");
for(int i=2;i<=n;i++){
if(p[i]){
System.out.print(i+" ");
}
}
}
public static boolean[] test(int n){
boolean []p=new boolean[n+1];
for(int i=0;i<=n;i++){
p[i]=true;
}
p[0]=p[1]=false;
for(int p1=2;p1*p1<=n;p1++){
if(p[p1]){
for(int i=p1*p1;i<=n;i=i+p1){
p[i]=false;
}
}
}
return p;
}}

2. GCD using recursion


public class recursion{
public static int ab(int a,int b){
if(b==0){
return a;
}
else{
return ab(b,a%b);
}
}
public static void main(String [] args){
int a=12;
int b=15;
int result=ab(a,b);
System.out.println("The result of a "+a+ " b "+b+" is:"+result);
}
}
3. Left rotation in the position of 2
public class Leftrotation {
public static void main(String[] args) {
int d = 2;
int n =3 ;
int[] arr = new int [n];
for (int i = 0; i < d; i++){
int temp = arr[0];
for (int j=0; j<n-1;j++)
{
arr[j] = arr[j+1];

}
arr[n-1] = temp;

}
System.out.println("Arrays.toString[()");

}
}

Assessment Problem
Question1
Get the monthly salary and loss of pay of employees and find salary to be credit to the employee in
java
input format
first line represents monthly salary of an employee
second line represents total number of days leave taken
input constraints
1<=salary <= 100000
1<= Days <=30
output format
salary credited to the employee
sample input
25000
4
sample output
21668
Code
import java.util.Scanner;
public class SalaryCalculation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read the monthly salary


int monthlySalary = scanner.nextInt();

// Read the number of days leave taken


int leaveDays = scanner.nextInt();

// Assuming 30 days in a month


int daysInMonth = 30;

// Calculate daily salary


double dailySalary = (double) monthlySalary / daysInMonth;

// Calculate loss of pay


double lossOfPay = dailySalary * leaveDays;

// Calculate salary to be credited


double creditedSalary = monthlySalary - lossOfPay;

// Print the salary to be credited


System.out.printf("%.0f%n", creditedSalary);

// Close the scanner


scanner.close();
}
}
Question 2
you are choreographing a circus show with various animals. For one act, you are given two
kangaroos on a number line ready to jump in the positive direction (i.e toward positive infinity).
The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump . The second
kangaroo starts at location x2 and moves at a rate of v2 meters per jump. You have to figure out a
way to get both kangaroos at the same time as part of the show. If it is possible, return YES
otherwise return NO
Input format
A single line of four space-separated integers denoting the respective values of x1, v1, x2, v2
input constraints
0<=x1<x2<=10000
1<=v1<=10000
1<=v2<=10000
Output format
string: either YES or NO
Sample input
0342
sample output
YES
Code
import java.util.Scanner;
public class Kangaroo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Read inputs
int x1 = scanner.nextInt();
int v1 = scanner.nextInt();
int x2 = scanner.nextInt();
int v2 = scanner.nextInt();

// Check if they will meet


String result = willMeet(x1, v1, x2, v2) ? "YES" : "NO";

// Print the result


System.out.println(result);

// Close the scanner


scanner.close();
}

public static boolean willMeet(int x1, int v1, int x2, int v2) {
// If the first kangaroo jumps faster but starts behind, they will never meet
// If the second kangaroo jumps faster but starts behind, they will never meet
if (v1 == v2) {
return x1 == x2;
} else {
return (x2 - x1) % (v1 - v2) == 0 && (x2 - x1) / (v1 - v2) >= 0;
}
}
}

Day 2

1. longest common subsequence in string

X = "AGGTAB"

Y = "GXTXAYB"

output : 4(GTAB)

2. vowels reverse

input: "Apple"

output: "epplA"

3. bmountains higest Peak Element :

Input: array = [1, 2, 1, 3, 5, 6, 4]

Output: 6

4. subarray :

Input: array = [1, 2, 3]

Output: [1],[1, 2],[1, 2, 3],[2],[2, 3],[3]


ASSESMENT

Question -1

Food festival is when we get to taste multiple cuisines at one place. There is a chef called Victor
from Eastern Europe. He is specialized in making noodles.

Noodle is tastier with how long it is. This noodle is a special type of noodle, each meter of noodle
weighs 100 grams. Victor conducts small games, and the game will be conducted in multiple levels,
and each level of game, the person will be awarded one meter of this special noodle. If a person
looses at a particular level, then he will be giving the noodle which he won, and paying an amount
to him for cooking that quantity of noodle which he won during the contest. At the end of each
level the person must be given the particular amount of noodle as the reward. As you know, noodle
is longer the better. So, brake the noodles for minimum number of times so that it will be tastier
while cooking it but at the same time at the end of each level the particular reward must be given to
the participant.

N meters of noodle is available with the chef, so he can conduct a game which has N levels, so that
he can give a meter of noodle as a gift for successfully completing each level. Help Victor with the
minimum number of times he must brake the noodles.

Sample Input 283746827373832

Sample Output 44

Code

import java.util.Scanner;

public class NoodleBreaker {


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

// Read the input value for N


String input = scanner.nextLine().trim();

// The number of breaks required is one less than the number of levels
int breaks = input.length() - 1;

// Output the result


System.out.println(breaks);

scanner.close();
}
}

Question 2
what coin will he gift? in java
Rohit is a stingy person, he does not like spending money. He had a friend by the name Kamal, and
he invited Rohit for his daughter's birthday party. he was happy to go to the party but a sad that he
had to spend some money to buy a gift for her.He didn't want to spend much in buying the gift. he
know that kamal's daughter had a coin collection, so he thought he can give a coin which she didn't
have and that too a least possible value as possible. But he didn't wanna look that much obviously
stingy, so he decided not to give a coin of any denomination that she also already and also the coin
value must not be equal to sum of any coins she has already, but also least value coin as possible .
So you can help Rohit to find the least value coin as possible.
Note: Lets assume there are coins of all denominations.

input format
the first line of input has one single integer N denoting the various denominations of coins Kamal's
daughter has
the second line of input has N spaced integer denoting each domination

Input constraints
1<=N<=10^3
1<=a[i ] <=10^9
N - number of denominations
a[ i ] - value of denominations

Output format
the least possible value of the coin

Sample input
3
125

sample output
4

Code

import java.util.*;

public class LeastPossibleCoin {


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

int N = sc.nextInt(); // Read the number of denominations


int[] denominations = new int[N];

// Read the denominations


for (int i = 0; i < N; i++) {
denominations[i] = sc.nextInt();
}

// Sort the denominations


Arrays.sort(denominations);
// Variable to keep track of the smallest sum we can't form
int smallestMissingSum = 1;

for (int coin : denominations) {


// If the current coin is greater than the smallestMissingSum, we found the answer
if (coin > smallestMissingSum) {
break;
}
smallestMissingSum += coin;
}

// Print the smallest missing sum which is the answer


System.out.println(smallestMissingSum);

sc.close();
}
}

Day 3

QUESTION 1:

Print test cases

In the online judge system, a judge file may include multiple datasets to check whether the
submitted program outputs a correct answer for each test case. This task is to practice solving a
problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are
given for this problem.

Input
The input consists of multiple datasets. Each dataset consists of an
integer x in a line.

The input ends with an integer 0. You program should not process (print)
for this terminal symbol.

Output
For each dataset, print x in the following format:

Case i: x
where i is the case number which starts with 1. Put a single space between
"Case" and i. Also, put a single space between ':' and x.

Constraints
1 ≤ x ≤ 10000
The number of datasets ≤ 10000
Sample Input
3
5
11
7
8
19
0
Sample Output
Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19

ANSWER:

import java.util.*;

public class Judge{

public static void main(String[] args){

Scanner scan=new Scanner(System.in);

int[] a=new int[10000];

int i;

int count = 1;

for(i=0;i<10000;i++){

a[i]=scan.nextInt();

if(a[i]==0){

break;

for(int j=0;j<i;j++){
if(a[j] != 0) {

System.out.println("case "+count+":"+a[j]);

count++;

QUESTION 2:

A subarray of an n-element array is an array composed from a contiguous block of the


original array's elements.

For example, if array =[1,2,3], then the subarrays are [1],[2] ,[3] ,[1,2] ,[2,3] , and [1,2,3].

Something like [1,3] would not be a subarray as it's not a contiguous subsection of the
original array.

The sum of an array is the total sum of its elements.

An array's sum is negative if the total sum of its elements is negative.

An array's sum is positive if the total sum of its elements is positive.

Given an array of n integers, find and print its number of negative subarrays on a new line.

Input Format

The first line contains a single integer,n , denoting the length of array A=[a0,a1,...an-1] .

The second line contains space-separated integers describing each respective

element, ai, in array A .


Constraints

1<=n<=100

-10 power 4 <=ai <=10 power 4

Output Format

Print the number of subarrays of A having negative sums.

Sample Input

1 -2 4 -5 1

Sample Output

ANSWER:

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();

int count = 0;

for (int i = 0; i < n; i++) {

int sum = 0;

for (int j = i; j < n; j++) {

sum += arr[j];

if (sum < 0) {
count++;

System.out.println(count);

QUESTION 3:

Jack and Daniel are friends. Both of them like letters, especially uppercase ones.They are cutting
uppercase letters from newspapers, and each one of them has his collection of letters stored in a
stack.

One beautiful day, Morgan visited Jack and Daniel. He saw their collections.
He wondered what is the lexicographically minimal string made of those two collections. He can
take a letter from a collection only when it is on the top of the stack. Morgan wants to use all of the
letters in their collections. As an example, assume Jack has collected and Daniel has . The example
shows the top at index for each stack of letters.
Assemble the string as follows:

Jack Daniel result


ACA BCF
CA BCF A
CA CF AB
A CF ABC
A CF ABCA
F ABCAC
ABCACF

Note the choice when there was a tie at CA and CF.

Function Description

Complete the morganAndString function in the editor below.

morganAndString has the following parameter(s):

string a: Jack's letters, top at index


string b: Daniel's letters, top at index
Returns
- string: the completed string
Input Format

The first line contains an integer,the number of test cases.

The next pairs of lines are as follows:


- The first line contains string
- The second line contains string .

Constraints
1<=T<=5
1<=|a|,|b|<=10 power 5

a and b contain upper-case letters only, ascii[A-Z].

Sample Input
2
JACK
DANIEL
ABACABA
ABACABA
Sample Output

DAJACKNIEL
AABABACABACABA

ANSWER:

import java.util.Scanner;

import java.util.Stack;

public class Letter {

public static String mergeStrings(String a, String b) {

Stack<Character> stackA = new Stack<>();

Stack<Character> stackB = new Stack<>();

for (int i = a.length() - 1; i >= 0; i--) {

stackA.push(a.charAt(i));

}
for (int i = b.length() - 1; i >= 0; i--) {

stackB.push(b.charAt(i));

StringBuilder result = new StringBuilder();

while (!stackA.isEmpty() || !stackB.isEmpty()) {

if (stackA.isEmpty()) {

result.append(stackB.pop());

} else if (stackB.isEmpty()) {

result.append(stackA.pop());

} else if (stackA.peek() <= stackB.peek()) {

result.append(stackA.pop());

} else {

result.append(stackB.pop());

return result.toString();

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int T = scanner.nextInt();

scanner.nextLine(); // Consume the newline character

for (int t = 0; t < T; t++) {


String a = scanner.nextLine();

String b = scanner.nextLine();

System.out.println(mergeStrings(a, b));

Day 4
Question 1 : Finding Intersection and union
Code
import java.util.Scanner;

public class Inun {


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

System.out.println("Enter size of the first array:");


int n1 = sc.nextInt();
int[] arr1 = new int[n1];
System.out.println("Enter elements of the first array:");
for (int i = 0; i < n1; i++)
arr1[i] = sc.nextInt();

System.out.println("Enter size of the second array:");


int n2 = sc.nextInt();
int[] arr2 = new int[n2];
System.out.println("Enter elements of the second array:");
for (int i = 0; i < n2; i++)
arr2[i] = sc.nextInt();

int[] unionArr = new int[n1 + n2];


int k = 0;
for (int i = 0; i < n1; i++)
unionArr[k++] = arr1[i];
for (int i = 0; i < n2; i++) {
boolean found = false;
for (int j = 0; j < n1; j++) {
if (arr2[i] == arr1[j]) {
found = true;
break;
}
}
if (!found)
unionArr[k++] = arr2[i];
}

int[] intersectionArr = new int[Math.min(n1, n2)];


int l = 0;
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
if (arr1[i] == arr2[j]) {
intersectionArr[l++] = arr1[i];
break;
}
}
}

System.out.print("Union: ");
for (int i = 0; i < k; i++)
System.out.print(unionArr[i] + " ");
System.out.println();

System.out.print("Intersection: ");
for (int i = 0; i < l; i++)
System.out.print(intersectionArr[i] + " ");
System.out.println();

sc.close();
}
}

Question 2 :
(Stack based question)

Jack and Daniel are friends. Both of them like letters, especially uppercase ones. They are cutting
uppercase letters from newspapers, and each one of them has his collection of letters stored in a
stack.

One beautiful day, Morgan visited Jack and Daniel. He saw their collections. He wondered what is
the lexicographically minimal string made of those two collections. He can take a letter from a
collection only when it is on the top of the stack. Morgan wants to use all of the letters in their
collections.
As an example, assume Jack has collected and Daniel has.The example shows the top at index for
each stack of letters.
Assemble the string as follows:

Jack Daniel result


ACA BCF
CA BCF A
CA CF AB
A CF ABC
A CF ABCA
F ABCAC
ABCACF
Note the choice when there was a tie at CA and CF.

Function Description

Complete the morganAndString function in the editor below.

morganAndString has the following parameter(s):

string a: Jack's letters, top at index


string b: Daniel's letters, top at index
Returns
- string: the completed string

Input Format

The first line contains an integer,the number of test cases.

The next pairs of lines are as follows:


- The first line contains string
- The second line contains string .

Constraints
1<=T<=5
1<=|a|,|b|<=10 power 5

a and b contain upper-case letters only, ascii[A-Z].

Sample Input
2
JACK
DANIEL
ABACABA
ABACABA
Sample Output

DAJACKNIEL
AABABACABACABA
Explanation

Code
import java.util.Scanner;
import java.util.Stack;

public class Letter {

public static String mergeStrings(String a, String b) {


Stack<Character> stackA = new Stack<>();
Stack<Character> stackB = new Stack<>();

for (int i = a.length() - 1; i >= 0; i--) {


stackA.push(a.charAt(i));
}
for (int i = b.length() - 1; i >= 0; i--) {
stackB.push(b.charAt(i));
}

StringBuilder result = new StringBuilder();

while (!stackA.isEmpty() || !stackB.isEmpty()) {


if (stackA.isEmpty()) {
result.append(stackB.pop());
} else if (stackB.isEmpty()) {
result.append(stackA.pop());
} else if (stackA.peek() <= stackB.peek()) {
result.append(stackA.pop());
} else {
result.append(stackB.pop());
}
}

return result.toString();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
scanner.nextLine();

for (int t = 0; t < T; t++) {


String a = scanner.nextLine();
String b = scanner.nextLine();
System.out.println(mergeStrings(a, b));
}
}
}

Question 3:

Chef is looking to buy a TV and has shortlisted two models. The first one costs 𝐴A rupees, while the
second one costs 𝐵B rupees.

Since there is a huge sale coming up on Chefzon, Chef can get a flat discount of 𝐶C rupees on the
first TV, and a flat discount of 𝐷D rupees on the second one.

Help Chef determine which of the two TVs would be cheaper to buy during the sale.

Input Format

· The first line contains a single integer 𝑇T — the number of test cases. Then the test cases follow.
· The first and only line of each test case contains four space-separated integers 𝐴A, 𝐵B, 𝐶C and 𝐷D
— the marked price (in rupees) of the first TV, the marked price (in rupees) of the second TV, the flat
discount (in rupees) of the first TV, and the flat discount (in rupees) of the second TV.

Output Format

For each test case, print a single line containing the string First if the first TV is cheaper to buy with
discount, or Second if the second TV is cheaper to buy with discount. If both of them cost the same
after discount, print Any.

You may print each character of the string in uppercase or lowercase (for example, the strings first,
First, fIRSt, and FIRST will all be treated as identical).

Constraints

· 1≤𝑇≤5000

· 1≤𝐴,𝐵≤100

· 0≤𝐶≤𝐴

· 0≤𝐷≤𝐵

Code
import java.util.Scanner;

public class CheaperTV {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int T = sc.nextInt();

if (T < 1 || T > 5000) {

throw new IllegalArgumentException("Number of test cases T must be between 1 and


5000.");

for (int t = 0; t < T; t++) {

int A = sc.nextInt();

int B = sc.nextInt();

int C = sc.nextInt();

int D = sc.nextInt();
if (A < 1 || A > 100 || B < 1 || B > 100) {

throw new IllegalArgumentException("Prices A and B must be between 1 and 100.");

if (C < 0 || C > A) {

throw new IllegalArgumentException("Discount C must be between 0 and A.");

if (D < 0 || D > B) {

throw new IllegalArgumentException("Discount D must be between 0 and B.");

int effectivePrice1 = A - C;

int effectivePrice2 = B - D;

if (effectivePrice1 < effectivePrice2) {

System.out.println("First");

} else if (effectivePrice1 > effectivePrice2) {

System.out.println("Second");

} else {

System.out.println("Any");

sc.close();

Self- assessment

Question 1
Arun is an ice cream seller. He sells only 2 flavors of icecream Chocolate and Vennila. He will give
one kid a free ice cream with one quiz. He will tell the kid the total number of ice-creams he has
initially. The chocolate flavor is numbered as odd values and vanilla is numbered as even values.
Initially, the n ice-creams are arranged in ascending order. Now Arun will give the kid a number K.
The kid has to sort Chocolate flavored ice-creams first and Vanilla flavored ice- creams next.

The kid has to tell the value of ice-cream in the kth place. Help a kid get free ice-cream.

Input Format

The only line of input contains integers n and k

Input Constraints

1<=n,k<=10^12

Output Format

Single integer

Sample Input

11

Sample Output

Code
import java.util.*;

public class Icecream{

public static void main(String[] args){

Scanner ns=new Scanner(System.in);

int n=ns.nextInt();

int k=ns.nextInt();

int x=n/2;

if(n==1||k==1)

System.out.print(1:1);

else if(k>x)
System.out.print(2);

else if(k<=x)

System.out.print(1);

Question 2

Yalini is a small girl and loves coin collection. She has a collection of coins whose value is from 1 to
n (n distinct coins). She gifted her elder brother coins on his birthday. But her brother knows it took a
long time for yalu to collect those coins. So her brother refused to get it from her. But she turns out to
take certain coins only from the coin bag. She took out the coin which has only one digit repeated 1 or
more times. Write the program to count the number of coins yalini took out from the bag.

INPUT FORMAT

The first line contains an integer t, number of test cases.

Each test case consists of one line, which contains a positive integer n

OUTPUT FORMAT

Print t integers

INPUT CONSTRAINTS

1<=t<=10^4

1<=n<=10^9

Input Format

The first line contains an integer t, number of test cases.

Each test case consists of one line, which contains a positive integer n

Input Constraints

1<=t<=10^4

1<=n<=10^9

Output Format

Print t integers
Sample Input

18

100500

33

1000000000

Sample Output
10
1
9
45
12
81
Code
public class Coins
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int[] test=new int[a];
for(int i=0;i<a; i++)
{
test[i]=sc.nextInt();
}
for(int t=0;t<a;t++)
{
int count=0;
int n=test[t];
for(int i=0;i<n;i++)
String numStr=Integer.toString(i);
char firstdigit=numStr.charAt(0);
boolean rep=true;
for(int j=1;j<numStr.length();j++)
{
if(numStr.charAt(j)!=firstdigit)
{
rep=false;
break;
}
}
if(rep){
count++;
}
}
System.out.print(count+" ");
}
}
}

Question 3

Every year December 23, Farmers used to celebrate Farmers Day by playing a game. Farmer Surya,
places 'n' number of baskets with 'ni' apples in it. Not all the baskets are filled with same number of
apples and only one basket will be removed before the game starts.
The number of apples in each basket follows a specific pattern. After removing exactly one basket,
any other Farmer can approach Surya and play the game by telling the number of apples in the
removed basket. If anyone tells the correct answer then that many apples will be given for free.
Arjun is now playing the game. Help Arjun find the correct number of apples in the removed basket
Input Format
The First line consist of a single integer 'n' which corresponds to the total number of baskets after
removing one basket
The Second line consists of 'n' space separated integers.
Input Constraints
3<=n<=100
1<=a[i]<=10^4
Output Format
Single integer denoting the number of removed apples
Sample Input
76
2595
2621 2647 2673 2699 2725 2751
2777
2803
2829
28552881
2907
2933
2959
2985
3011
3037
3063
3089 3115 3141 3167 3193 3219 3245 3271 3297 3323 3349 3375 3401 3427 3453 3479 3505
35313557
3583 3609 36353661 3687 3713 3739 376537913817 3843 38693895 3921 3947 3973 3999 4025
4077
4103 4129 4155 4181 4207 4233 4259 4285 4311 4337
4363 4389 4415 4441 4467 4493 4519 4545
4571
Sample Output
4051

Code

import java.util.Scanner;

public class FarmersGame {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] apples = new int[n];
for (int i = 0; i < n; i++) {
apples[i] = scanner.nextInt();
}
int diff1 = apples[1] - apples[0];
int diff2 = apples[2] - apples[1];
int commonDifference = Math.min(diff1, diff2);

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


int currentDifference = apples[i] - apples[i - 1];
if (currentDifference != commonDifference) {
if (i == 1 || currentDifference < commonDifference) {
commonDifference = currentDifference;
} else {
commonDifference = apples[i] - apples[i - 2];
break;
}
}
}
for (int i = 1; i < n; i++) {
if (apples[i] - apples[i - 1] != commonDifference) {
System.out.println(apples[i - 1] + commonDifference);
break;
}
}

scanner.close();
}
}
DAY 5

Question 1
Reverse the Queue Array
Code
import java.util.*;
public class Queue {
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;

Queue() {
front = -1;
rear = -1;
}

boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}

void enQueue(int element) {

if (isFull()) {
System.out.println("Queue is full");
} else {
if (front == -1) {
front = 0;
}

rear++;
items[rear] = element;
System.out.println("Insert " + element);
}
}

int deQueue() {
int element;
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
} else {
element = items[front];
if (front >= rear) {
front = -1;
rear = -1;
} else {
front++;
}
System.out.println(element + " Deleted");
return (element);
}
}

void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
} else {

System.out.println("\nFront index-> " + front);


System.out.println("Items -> ");
for (i = front; i <= rear; i++)
System.out.print(items[i] + " ");
System.out.println("\nRear index-> " + rear);

void reverse() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
} else {
System.out.println("Reverse list");
for(int j=rear;j>=front;j--){
System.out.print(items[j]+" ");
}

public static void main(String[] args) {


Queue q = new Queue();
q.deQueue();
for (int i = 1; i < 6; i++) {
q.enQueue(i);
}
q.enQueue(6);
q.display();
q.deQueue();
q.display();
q.reverse();

}
}
Question 2
Using 2D array, calculate the total marks across all subjects for each student, and then find the
average marks and grade
Code
import java.util.*;

public class StudentGrade2D {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of students:");
int numstud = s.nextInt();
System.out.println("Enter the number of subjects:");
int numsubj = s.nextInt();

// Consume the newline character left by nextInt()


s.nextLine();

String[] namestud = new String[numstud];


String[] namesub = new String[numsubj];

System.out.println("Enter the names of the students:");


for (int i = 0; i < numstud; i++) {
System.out.print("Student " + (i + 1) + ": ");
namestud[i] = s.nextLine();
}

System.out.println("Enter the names of the subjects:");


for (int i = 0; i < numsubj; i++) {
System.out.print("Subject " + (i + 1) + ": ");
namesub[i] = s.nextLine();
}

int marks[][] = new int[numstud][numsubj];

for (int i = 0; i < numstud; i++) {


System.out.println("Enter the marks for " + namestud[i] + " :");
for (int j = 0; j < numsubj; j++) {
System.out.print(namesub[j] + " : ");
marks[i][j] = s.nextInt();
}
// Consume the newline character left by nextInt()
s.nextLine();
}

// Calculate total marks for each student


System.out.println("\nTotal marks and Average Marks:");
for (int i = 0; i < numstud; i++) {
int total = 0;
System.out.print(namestud[i] + ": ");
for (int j = 0; j < numsubj; j++) {
total += marks[i][j];
}
double average = (double) total / numsubj;
System.out.print(" | Total: " + total);
System.out.printf(" | Average: %.2f", average);

// Determine grade based on average marks


char grade = calculateGrade(average);
System.out.println(" | Grade: " + grade);
}

s.close();
}

// Method to calculate grade based on average marks


public static char calculateGrade(double average) {
if (average >= 90) {
return 'A';
} else if (average >= 80) {
return 'B';
} else if (average >= 70) {
return 'C';
} else if (average >= 60) {
return 'D';
} else {
return 'F';
}
}
}
Output
Enter the number of students:
3
Enter the number of subjects:
3
Enter the names of the students:
Student 1: Alice
Student 2: Bob
Student 3: Charlie
Enter the names of the subjects:
Subject 1: Math
Subject 2: Science
Subject 3: History
Enter the marks for Alice :
Math : 85
Science : 78
History : 92
Enter the marks for Bob :
Math : 76
Science : 85
History : 88
Enter the marks for Charlie :
Math : 90
Science : 92
History : 85

Total marks and Average Marks:


Alice: | Total: 255 | Average: 85.00 | Grade: A
Bob: | Total: 249 | Average: 83.00 | Grade: B
Charlie:| Total: 267 | Average: 89.00 | Grade: B

Question 3
Swapping near by elements in array
Code
import java.util.*;
public class Swaparray{
public static void main(String[] args){
Scanner s=new Scanner(System.in);
int lim=s.nextInt();
int a[]=new int[lim];

for(int i=0;i<lim;i++){
a[i]=s.nextInt();
}
int c=a.length;

if(c%2!=0){
for(int i=0;i<lim;i=i+2){
int temp=a[i];
a[i]=a[i+1];
System.out.print(a[i]+" "+temp+" ");
if(a[i]==lim-1){
System.out.print(a[lim-1]);
break;
}}}
else{
for(int i=0;i<lim;i=i+2){
int tem=a[i];
a[i]=a[i+1];
System.out.print(a[i]+" "+tem+" ");
}

}
}
}
Output
5 //limit
1
2
3
4
5
21435
Self assessment
Question 1
code

import java.util.Scanner;
public class TwistedPrime {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isPrime = true;
if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
int reversedNumber = 0;
int tempNumber = number;
while (tempNumber != 0) {
int digit = tempNumber % 10;
reversedNumber = reversedNumber * 10 + digit;
tempNumber /= 10;
}
boolean isReversedPrime = true;
if (reversedNumber <= 1) {
isReversedPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(reversedNumber); i++) {
if (reversedNumber % i == 0) {
isReversedPrime = false;
break;
}
}
}
if (isPrime && isReversedPrime) {
System.out.println(number + " is a twisted prime.");
} else {
System.out.println(number + " is not a twisted prime.");
}

scanner.close();
}
}
Question 2
Unhappy number
Code
import java.util.Scanner;

public class UnhappyNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
int slow = number;
int fast = number;
do {
slow = sumOfSquaresOfDigits(slow);
fast = sumOfSquaresOfDigits(sumOfSquaresOfDigits(fast));
} while (slow != fast);
if (slow == 1) {
System.out.println(number + " is a happy number.");
} else {
System.out.println(number + " is an unhappy number.");
}

scanner.close();
}

private static int sumOfSquaresOfDigits(int num) {


int sum = 0;
while (num != 0) {
int digit = num % 10;
sum += digit * digit;
num /= 10;
}
return sum;
}
}

Question 3
John and Dytto are close friends in college. After college, they don't get a chance to meet each other.
John got married and has twin babies. Dytto wants to meet his friend. Dytto decided to buy chocolate
(with n pieces) for the babies. She wants to buy one chocolate and divide it into two (a and b) so that
the number of pieces in a and b are the same. The shopkeeper suggested 'm' number of chocolate
boxes and Dytto is so confused about which box to buy. Can you help her?
Input Format

The first line contains an integer n, the number of chocolate boxes.

The second line contains n integers ala2 an where ai is the number?


Input
3
211
output
1

Code

import java.util.Scanner;

public class ChocolateDivider {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of chocolate boxes: ");
int n = scanner.nextInt();
int[] chocolateBoxes = new int[n];
System.out.println("Enter the number of pieces in each chocolate box:");
for (int i = 0; i < n; i++) {
chocolateBoxes[i] = scanner.nextInt();
}
int count = 0;
for (int i = 0; i < n; i++) {
if (chocolateBoxes[i] % 2 == 0) {
count++;
}
}
System.out.println(count);
scanner.close();
}
}
Day 6

Question 1
Triangle Pattern
import java.util.*;
public class Tripattern{
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter the no.of.rows");
int r=s.nextInt();
for(int i=1;i<=r;i++){
for(int j=i;j<r;j++){
System.out.print(" ");
}
for(int j=1;j<=(2*i-1);j++){
System.out.print("* ");
}
System.out.println("");
}
}
}
Output
Enter the no.of.rows
5
*
***
*****
*******
*********
Question 2
Pattern of square with min function
import java.util.*;
public class Threepattern{
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter a number");
int n=s.nextInt();
int val=0;
int size=5;
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
val=n-Math.min(Math.min(i,j),Math.min(size-1-i,size-1-j));
System.out.print(val+” “);
}
System.out.println();
}
}
}
Output
Enter a number
3
33333
32223
32123
32223
33333

Question 3
Program to print Eiffel Tower star pattern
Code
import java.util.Scanner;

public class Eifflestar {


public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter any number");
int n = s.nextInt();
for (int i = 1; i <= n; i++) {
for (int j = n; j >= i; j--) {
int x = 2 * (i - 1) + 1;
while (x-- != 0) {
System.out.printf("*");
}
System.out.printf("\n");
}
}
}
}

Output
Enter any number
4
*
*
*
*
***
***
***
*****
*****
*******

Question 4
Permutation
Code
Output

Self-assesment
Question 1
Program to print Eiffel Tower pattern
Code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n,i,j,x; n=s.nextInt();
for(i=1;i<=n;i++) {
for(j=n;j>=i;j--) {
x=(2*(i-1)+1);
while(x--!=0) {
System.out.printf("%d",i);
}
System.out.printf("\n");
}}}}

Output

4
1
1
1
1
222
222
222
33333
33333
4444444

E:\java\internal>java Eiffletower.java
Enter any number
4
1
1
1
1
222
222
222
33333
33333
4444444

Question -2

print the following pattern


33333
32223
32123
32223
33333

Code
import java.util.*;
public class Threepattern{
public static void main(String[] args){
Scanner s=new Scanner(System.in);
System.out.println("Enter a number");
int n=s.nextInt();
int val=0;
int size=5;
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
val=n-Math.min(Math.min(i,j),Math.min(size-1-i,size-1-j));
System.out.print(val+” “);
}
System.out.println();
}
}
}
Output
Enter a number
3
33333
32223
32123
32223
33333
Question-3

Johnny Sins is going to participate in a game TV show called Reality Kings. The game is popularly
known as Me vs N.
The game goes in rounds, where in each round the host asks Johnny and his opponents a common
question. All participants failing to answer are eliminated. The show ends when only Johnny remains
(we assume that Johnny never answers a question wrong!).
For each question Johnny answers, if there are R (R>0) opponents remaining and T (0≤T≤R) of them
make a mistake on it, Johnny receives t/R dollars, and consequently there will be R−T opponents left
for the next question.
Johnny wonders what is the maximum possible reward he can receive in the best possible scenario.
Yet he has little time before show starts, so can you help him answering it instead?
INPUT FORMAT
The first line contains an integer N, the number of Johnny's opponents in the show.
OUTPUT FORMAT
Print a number denoting the maximum prize (in dollars) Johnny could have.
Your answer will be considered correct if it's absolute or relative error won't exceed 10^4.
INPUT CONSTRAINTS
1<=N<=10^5

Code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
long n;
int i;
double res = 0;
n=s.nextLong();
for(i=1 ; i<=n ; ++i) {
res += (1.0/i);
}
System.out.format("%.1f",res);
}}

Output
2
1.5

Day 7

1.Reverse Integer:
import java.util.*;
public class Reverseinteger {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of the array:");
int n = sc.nextInt();
int a[] = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
System.out.println("Reverse of the array is:");
System.out.print(a[n-1] + " ");
for (int i = 0; i < n-1; i++) {
System.out.print(a[i] + " ");
}
}
}
2.RECURSION:
PROGRAM A (TAIL):
PROGRAM B(INDIRECT):
PROGRAM C(TREE):

3.BINARY TREE:
SELF ASSESMENT:
PROGRAM A(2nd Largest Element):
import java.util.*;
public class Main
public static void main(String args[]) {
int i, j,temp;
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int array[]=new int[1000];
for(i=0;i < n;i++) {
array[i]=sc.nextInt(); }
int largest, second;
if(array[0] > array[1]) {
largest = array[0];
second = array[1]; }
else {
largest = array[1];
second = array[0]; }
for(i = 2; i < n; i++) {
if( largest < array[i] ) {
second = largest;
largest = array[i]; }
else if( second < array[i] ) {
second = array[i]; } }
System.out.printf("%d",second); } }
PROGRAM B(LEAP YEAR OR NOT):
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
int y=sc.nextInt();
if((y%4==0 && y%100!=0)||(y%400==0))
System.out.printf("Yes");
else
System.out.printf("No");
}}
PROGRAM C(SMALLEST POSSIBLE):
import java.util.*;
import java.io.*;
class Main {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
long n = input.nextLong();
if(n%9!=0)
System.out.print(n%9);
for(long i = n/9;i>0;i--)
System.out.print("9"); } }
Day 9
Question 1
Parathesis stack
Code
import java.util.Scanner;
import java.util.Stack;

public class Parathesisstack {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter no.of.Test Cases:");
int t = scanner.nextInt();
while (t > 0) {
String s = scanner.next();
System.out.println(isValid(s)? 1 : 0);
}
}

public static boolean isValid(String s) {


Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(c);
} else if (c == ')') {
if (stack.isEmpty() || stack.pop()!= '(') {
return false;
}
}
}
return stack.isEmpty();
}
}
Output
Enter no.of.Test Cases:
2
(
0
)
0
()
1

Question 2
Two friends, Dragon and Sloth, are writing a computer science examination series. There are three
subjects in this series: DSA, TOC, and DM. Each subject carries 100 marks.

You know the individual scores of both Dragon and Sloth in all 3 subjects. You have to determine
who got a better rank.

The rank is decided as follows:


The person with a bigger total score gets a better rank
If the total scores are tied, the person who scored higher in DSA gets a better rank
If the total score and the DSA score are tied, the person who scored higher in TOC gets a better rank
If everything is tied, they get the same rank.
Input Format
The first line of input contains a single integer T, denoting the number of test cases. The description
of T test cases follows.
The first line of each test case contains three space-separated integers denoting the scores of Dragon
in DSA, TOC and DM respectively.
The second line of each test case contains three space-separated integers denoting the scores of Sloth
in DSA, TOC and DM respectively.
Output Format
For each test case, if Dragon got a better rank then output "Dragon", else if Sloth got a better rank
then output "Sloth". If there was a tie then output "Tie". Note that the string you output should not
contain quotes.
The output is case insensitive. For example, If the output is "Tie" then "TiE", "tiE", "tie", etc are also
considered correct.
Constraints
1≤T≤1000
Each score of both Dragon and Sloth lies between 0 and 100.
Subtasks
Subtask #1 (100 points): Original constraints

Sample 1:
Input:

4
10 20 30
30 20 10
5 23 87
5 23 87
0 15 100
100 5 5
50 50 50
50 49 51

Output:

SLOTH
TIE
DRAGON
DRAGON

Explanation:
For the first test case, Sloth and Dragon have the same total score but Sloth gets a better rank because
he has a higher score in DSA.
For the second test case, Sloth and Dragon have the same rank because they have the same score
among all subjects.
For the third test case, Dragon gets a better rank because he has a greater total score.
For the fourth test case, Sloth and Dragon have the same total score and same DSA score. Dragon
gets a better rank because he has a greater TOC score
Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for (int i = 0; i < T; i++) {
int dragonDSA = scanner.nextInt();
int dragonTOC = scanner.nextInt();
int dragonDM = scanner.nextInt();
int slothDSA = scanner.nextInt();
int slothTOC = scanner.nextInt();
int slothDM = scanner.nextInt();
int dragonTotal = dragonDSA + dragonTOC + dragonDM;
int slothTotal = slothDSA + slothTOC + slothDM;
if (dragonTotal > slothTotal) {
System.out.println("Dragon");
} else if (slothTotal > dragonTotal) {
System.out.println("Sloth");
} else {
if (dragonDSA > slothDSA) {
System.out.println("Dragon");
} else if (slothDSA > dragonDSA) {
System.out.println("Sloth");
} else {
if (dragonTOC > slothTOC) {
System.out.println("Dragon");
} else if (slothTOC > dragonTOC) {
System.out.println("Sloth");
} else {
System.out.println("Tie");
}
}
}
}
scanner.close();
}
}

Question 3
Code
Aman and Akshat are trying to solve a task given to them by their teacher. They are given a pile of
stones containing
N stones with an integer written on each of them. There are two different kinds of moves that can be
performed on the pile :
1. Player will remove a stone from the top of the pile and put it back on the bottom of the pile
2. Player will remove a stone from the top of the pile and throw it away.
Aman in his turn will perform move 1 once and then move 2 once. Akshat in his turn will perform
move 1 twice and
then move 2 once.
They will stop making moves when there is only 1 stone left in the pile.
Both of them gets turn alternatively with Aman going first. Find the person performing the last move
and the number written
on the last stone left in the pile.
The stones at index i′th is located higher than the stones at index j′th , such that (i<j)
Input Format
• The first line contains an integer T, representing T Testcases.
• The first line of each test case contains an integer N, representing the size of Array A.
• The second line of each test case contains N integer, representing array A
Output Format
• For each test case, Print 2 space-separated integer representing the person making the last
move
(1 for Aman and 0 for Akshat) and the number written on the stone remaining.
Constraints
• 1≤T≤100
• 2≤N≤100000
• 10 power ≤Ai≤10 power 9
• Sum of N over all test cases does not exceed 10 power 6

Sample 1:

Input:
3
3
-5 0 5
4
-1 -3 2 4
6
-100000 0 0 100000 -1000000 1000000

Output:
0 -5
12
10

Code
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for (int t = 0; t < T; t++) {
int N = scanner.nextInt();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < N; i++) {
stack.push(scanner.nextInt());
}
boolean isAmanTurn = true;
while (stack.size() > 1) {
if (isAmanTurn) {
// Aman performs move 1 (remove top and put at bottom)
stack.add(0, stack.pop());
// Aman performs move 2 (remove top and discard)
stack.pop();
} else {
// Akshat performs move 1 twice (remove top and put at bottom twice)
stack.add(0, stack.pop());
stack.add(0, stack.pop());
// Akshat performs move 2 (remove top and discard)
stack.pop();
}
isAmanTurn = !isAmanTurn;
}
int lastStone = stack.pop();
int lastMoveBy = isAmanTurn ? 0 : 1; // If Aman just finished, it means last move is by
Akshat (0), otherwise Aman (1)
System.out.println(lastMoveBy + " " + lastStone);
}
scanner.close();
}
}
Question 4
Mohan and babu are working as gold miners. There are a total of N gold mines, numbered 1 through
N. For each valid i,
the i-th gold mine contains 𝐺𝑖 gold in total; if only Mohan worked in it, it would take him 𝐴𝑖 days to
completely mine it,
while if only Babu worked in it, it would take him 𝐵𝑖 days.

Each of our miners may only work in one mine at a time, but they may decide to start working in
another mine
at any time (even in the middle of some day), any number of times. They also choose the mines to
work in independently
from each other and they may work in the same mine at the same time.
Mining gold is a continuous process, i.e. if a miner works for 𝑡 days (where 𝑡 is a real number) in a
mine
where this miner has mining speed 𝑔 gold per day, then he will mine 𝑔⋅𝑡 gold. Obviously, it is
impossible to work in
a mine after no gold remains in it. For example, if a gold mine contains 30 gold and Mohan needs
2days to completely mine it,
but he spends 1 day in it, then he will mine 15 gold; if Babu needs 1 day to completely mine the same
gold mine,
and both Mohan and Babu start working in this mine at the same time, it will be empty after 2/3 days
― Babu will mine 20 gold,
while Mohan will mine 10 gold.

At each point of time, both Mohan and Babu know the gold mine in which the other miner is
working. Each of them wants to
gather the maximum amount of gold for himself. Find the amounts of gold the miners will have if
they both act optimally.
Input
The first line of the input contains a single integer 𝑇 denoting the number of test cases. The
description of 𝑇 test cases follows.
The first line of each test case contains a single integer 𝑁.
𝑁 lines follow. For each valid 𝑖, the 𝑖-th of these lines contains three space-separated integers 𝐺𝑖, 𝐴𝑖
and 𝐵𝑖.

Output
For each test case, print a single line containing two space-separated real numbers ― the amount of
gold mined by Mohan and
the amount of gold mined by Babu. Your answer will be considered correct if the absolute or relative
error of
each amount of gold does not exceed 10−6.

Constraints
1 ≤ 𝑇 ≤ 1,000
1≤N≤10^5
1≤𝐺𝑖≤10^5
for each valid 𝑖 1≤𝐴𝑖≤10^5
for each valid 𝑖 1≤𝐵𝑖≤10^5
for each valid 𝑖 the sum of 𝑁 over all test cases does not exceed 10^6

Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
for (int t = 0; t < T; t++) {
int N = scanner.nextInt();
double totalGoldMohan = 0;
double totalGoldBabu = 0;
for (int i = 0; i < N; i++) {
int G = scanner.nextInt();
int A = scanner.nextInt();
int B = scanner.nextInt();
double rateMohan = 1.0 / A;
double rateBabu = 1.0 / B;
double combinedRate = rateMohan + rateBabu;
totalGoldMohan += (rateMohan / combinedRate) * G;
totalGoldBabu += (rateBabu / combinedRate) * G;
}
System.out.printf("%.6f %.6f%n", totalGoldMohan, totalGoldBabu);
}
scanner.close();
}
}
Self -assessment
Question 1
“Imagine you’re a codebreaker tasked with decrypting a secret message. The message is encoded
using a special algorithm that relies on the prime factorization of a large number. You’ve been able to
crack most of the code, but there’s one crucial piece missing: the greatest prime divisor of the
number. If you can find this factor, you’ll be able to decrypt the rest of the message and uncover the
secret!”
Code
import java.util.*;
public class Main {
public static int maxPrimeFactors(int n) {
int maxPrime = -1;
while (n % 2 == 0) {
maxPrime = 2;
n >>= 1;
}
for (int i = 3; i <= (int) Math.sqrt(n); i += 2) {
while (n % i == 0) {
maxPrime = i;
n = n / i;
}
}
if (n > 2) maxPrime = n;
return maxPrime;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
System.out.printf("%d", maxPrimeFactors(n));
}
}
Question 2
Given a string, we have to reverse the string without changing the position of punctuations and
spaces.
Code
import java.util.*;
public class Main {
public static void main(String[] args) {
int i,j,len;
char temp;
Scanner s=new Scanner(System.in);
String ch=s.nextLine();
char [] str=ch.toCharArray();
len=str.length;
for(i=0,j=len-1;i<j;i++,j--) {
while(!(str[i]>=65&&str[i]<=122)) i++;
while(!(str[j]>=65&&str[j]<=122)) j--;
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
for(i=0;i<len;i++) System.out.printf("%c",str[i]);
}
}

Question 3
Computer hardware uses binary since that is relatively simple for it. However, binary is not easy for
humans to read as even small numbers have a lot of binary digits.

Grouping the bits in 3 bits allows us to have shorter representations of those binary numbers since
each group can be viewed easily.
Now your task is to Group the numbers as 3 from the binary number from left to right
Explanation: The binary number 111010 can be grouped as 111 and 010, which results in the decimal
value 72.
Code
import java.util.*;
public class Main{
public static void main(String[] args){
[...].
Scanner sc=new Scanner(System.in);
long a=0;
int []o=new int[20];
char[] s = sc.next().toCharArray();
int l=s.length;
for(int i=0;i<l;i++)
{
a+=(s[i]-48)*(1<<i);
}
int x=0;
while (a>0) {
o[x]=(int)a%8;
a/=8;
x++;
}
while(x>0){
System.out.print(o[--x]);
}
}
}

Day 10
1) Postfix evaluation string:

Code:
import java.util.*;
class stackpostfix{
public static void main(String args[]){
String exp = "a+b*c-d/e";
String[] exp1 = exp.split("(?<=[a-z])|(?=[a-z]" + ")");
Stack<String> stack = new Stack<String>();
for(int i=0;i<exp1.length;i++){
stack.push(exp1[i]);
}
String result = "";
while(!stack.isEmpty()){
result = result + stack.pop();
System.out.println(result);
}
}
}

2)Postfix evaluation :
CODE:
import java.util.*;
public class postfixnumber{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the postfix expression:");
String s=sc.nextLine();
Stack<Integer> st=new Stack<Integer>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='+'||s.charAt(i)=='-'||s.charAt(i)=='*'||
s.charAt(i)=='/'||s.charAt(i)=='^')
{
int a=st.pop();
int b=st.pop();
if(s.charAt(i)=='+')
st.push(a+b);
else if(s.charAt(i)=='-')
st.push(b-a);
else if(s.charAt(i)=='*')
st.push(a*b);
else if(s.charAt(i)=='/')
st.push(b/a);
else if(s.charAt(i)=='^')
st.push((int)Math.pow(b,a));
}
else
st.push(s.charAt(i)-'0');
}
System.out.println("The result is:"+st.pop());
}

3)Lucky number:
CODE:
import java.util.Scanner;
public class luckyletter {
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String S = scanner.nextLine();

char luckyLetter = S.charAt(6);

System.out.println(luckyLetter);
}
}

4)Circular Queue:
External JAVA Training
Batch III
10 Days Agenda
1.Problem solving
Basic input and output
Operator
Data types
Basic input inbuild functions
Keywords
2.Conditional statement
switch case,break
3.Methods and its type
Predefined methods
4.looping and loop based problems
5.patterns based problem
Type1(structural pattern eg: diamond,pyramid etc..)
Type2(Number based pattern eg: number)
Type3(grid pattern)
Type4(formula)
6.Digit manipulation or number based problem(eg:1235 separating an digit by using that we
solve an problem)
7.Number based problem(eg: factoriol,fibonaci….)
8.Pointors(basic)
9.Arrays and it’s operations
Memory Allocation of array
Operations:
Insertion
Delete
Update
Traverse
Searching
Sorting
10.Strings and it’s operation(same as of arrays and basic inbuild function in string)
11. Recursion
Direct (eg:func 1 call itself)
Head recursion
Tail recursion
Linear recursion
Nexted recursion
Tree recursion
Indirect(we can enhance )

12.Collection
List
Array list
Queue
Set
Map
DAY 1
PROBLEM STATEMENT:
1. If the number is divisible by 3 means print “hi” if the number is divisible by 5 means
print”hello” if the number is divisible by both 5 and 3 means print “hi hello”..

PROGRAM:
import java.util.Scanner;

public class Main {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("enter the number");
int n = sc.nextInt();
if(n % 3 == 0){
System.out.println("hi");
}
if(n % 5 == 0){
System.out.println("hi");
}
else if((n%3 == 0) && (n%5 ==0)){
System.out.println("hihello");
}

}
}

By optimizing
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter the number");
int n = sc.nextInt();
if(n % 3 == 0){
System.out.println("hi");
}
else if(n % 5 == 0){
System.out.println("hello");
}
Introduction
If there is no static in void display we need to create an object inside an main with an class
name
Batch3 key = new Batch();
Key.display();

Eg:

package training;

public class eg_1 {


static void display() {
System.out.println("Display");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello world");
display();
}

Explanation: In here static is head of all so If we use an static above an main function we
can run the program

package training;

public class eg_1 {


static {
System.out.println("static");
}
void display()
{
System.out.println("Display");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello world");
eg_1 key = new eg_1();
key.display();

In here we can call an func which is declared in another class.

package training;
public class eg_1 {
static {
System.out.println("static");
}
void display()
{
System.out.println("Display");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello world");
Batch2 key = new Batch2();
key.func1();

}
class Batch2{
void func1() {
System.out.println();
}
void func2() {
System.out.println();
}
}

Is java is an object oriented program?


Here we use an primitive data type for eg int ,float for that we cannot use an object

Operator
Bitwise operator
AND(&)
package training;

public class Batch3 {


public static void main(String[] args) {
int a=10,b=2;
System.out.println(a&b);

}
Output:2

OR(||)
NOT(!)
XOR(^)

Right shift
package training;

public class Batch3 {


public static void main(String[] args) {
int a=10,b=2;
System.out.println(a>>b);

Output:2
32 bits
|0000000000000000000000001010|after right shift
|000000000000000000000000010|10

-2147483648 to + 2147483647 – range for integer

DataTypes
Primitive – int ,float,char
Non Primitive
Non-linear -tree,graph
Linear = string,linked list,array

Datatype size will change depend on the compiler

Data size will not able to change – stack


Dynamic – heap

heap

10 n
stack 0
1000

code excecution

If we want to take an address inside the data use an Printf(“%d”,*(&n)); * denotes the value
of address

int – 4 byte
char – 1 byte
float =4 byte

1 byte has 8 bit


1 bit [ ]
2^8 - 256 range from negative to positive
0 to 9 48 to 57
A to Z (67 to 96)
a to b (97 to 128 )

int 4 byte = 32 bit


2^32 - 2147483648 to + 2147483647

Spacing:
package training;
public class Batch3 {
public static void main(String[] args) {
int a=1,b=10;
System.out.printf("%-5d%5d",a,b);
}
}

Output:1 10(5 space)

System.in - Interact with an machine


Scanner sc = new Scanner (System.in);
int a = sc.nextInt();
float f= sc.nextFloat();
char ch =sc.next().charAt(0);
System.out.printf("hi");
sc.close(); //memory destroy

Conditional statement question

1)Identify the given year is leap year or not?


package training;

import java.util.Scanner;

public class Batch3 {


public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int a = sc.nextInt();
if((a%4 == 0 && a%100 !=0 )|| a%400==0) {
System.out.println("its an leap year");
}
else {
System.out.println("not an leap");
}
sc.close();
}}

Output:
2024
its an leap year

2) get an largest number among 3


package training;
import java.util.Scanner;

public class Batch3 {


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 max=0,mid=0,min=0;
if(a>b && a>c) {
max=a;
if(b>c) {
mid=b;
min=c;
}
else {
min=b;
max=c;
}
}
else if(b>a && b>c) {
max=b;
if(a>c) {
mid=a;
min=c;
}
else {
min =a;
mid=c;
}
}
else if(c>a && c>b) {

max= c;
if(b>a) {
mid=b;
min=a;
}
else
{
min=b;
mid=a;
}
}
System.out.println("the maximum value is :"+max+"the mid value is"+mid+ "the
minimum"+min);

sc.close();
}
}
//Math.max(a,math.max(b,c));

Output:
10
78
20
the maximum value is :78the mid value is20the minimum10

Functions
function calling without parameter passing
without return
with return
function calling with parameter passing
without return
with return

function calling without parameter passing (with return)


return is used for to terminate
package training;

public class Batch3 {


static int display() {
System.out.println("display");
return 10; // returning a value
}

public static void main(String[] args) {


int result = display();
System.out.println("Returned value: " + result);
}
}
function calling without parameter passing (without return)

package training;

public class Batch3 {


static void display() {
System.out.println("display");
// No return needed as it is a void method
}

public static void main(String[] args) {


display();
}
}
function calling with parameter passing (without return)
package training;

public class Batch3 {


static void display(int x, int y) {
System.out.println(x + y);
// No return needed as it is a void method
}

public static void main(String[] args) {


int a = 10, b = 20;
display(a, b);
}
}
function calling with parameter passing (with return)
package training;

public class Batch3 {


static int display(int x, int y) {
System.out.println("display");
return x + y; // returning the sum of x and y
}

public static void main(String[] args) {


int a = 10, b = 20;
int result = display(a, b);
System.out.println("Returned value: " + result);
}
}
List of the programs solved

S.NO Program

If the number is divisible by 3 means print “hi” if the number is divisible by 5


1. means print”hello” if the number is divisible by both 5 and 3 means print “hi
hello”
2. Optimization of the above program code

3. Operator programs

(i) Program on Data types


4.
(i) Basic input inbuild functions

5. Identify the given year is leap year or not?

6. Largest number among 3 numbers

7. Function calling without parameter passing (with return)

8. Function calling without parameter passing (without return)

9. Function calling with parameter passing (without return)

10. Function calling with parameter passing (with return)


DAY 2
Date condition:
package proj;
import java.util.*;
public class project {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
String str=sc.nextLine(); //12,05,2024
String[]arr=str.split("/");
int d=Integer.parseInt(arr[0]);
int m=Integer.parseInt(arr[0]);
int y=Integer.parseInt(arr[0]);
if(y>=1900&&y<=9999&&m>=1&&m<=12) {
if((d>=1&&d<=31)&&(m==1||m==3||m==5||m==7||m==9||m==11)) {
System.out.println("valid");
}else if((d>=1&&d<=30)&&(m==4||m==6||m==8||m==10)) {
System.out.println("valid");
}else if(d>=1&&d<=28&&(m==2)) {
System.out.println("valid");
}else if((d<=29&&m==2)&&(y%4==0&&y%100!=0)||(y%400==0)){
System.out.println("valid");

}else {
System.out.println("invalid");
}
}else {
System.out.println("invalid");
}

Output:
2/2/2004
Valid

Print even number seprated by commas


package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n>=2) {
System.out.println(s);
}
for(int i=s+2;i<=n;i=i+2) {
System.out.println(","+i);
}}
}
Output:
2,4,6,8,10

Find factor for the number


package proj;
import java.util.*;
public class project {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=1;i<=n;i++) {
if(n%i==0) {
System.out.println(i);
}
}}}
Output:
10
1
2
5
10

Gcd
package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
int y=sc.nextInt();
int gcd=1;
for(int i=1;i<=x&&i<=y;i++) {
if(x%i==0&&y%i==0) {
gcd=i;
}}
System.out.println(gcd);
}}
Output:
12 8
4
Lcm
public class Main {
public static void main(String[] args) {
int n1 = 72, n2 = 120, lcm;
lcm = (n1 > n2) ? n1 : n2;
while(true) {
if( lcm % n1 == 0 && lcm % n2 == 0 ) {
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
break;
}
++lcm;
}
}
}

Output:
The LCM of 72 and 120 is 360.

Sum of factor
package proj;
import java.util.*;
public class project {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int sum=0;
for(int i=0;i<=n;i++) {
sum=sum+i;

}
System.out.println(sum);

Output
5
15
Prime number
package proj;
import java.util.*;
public class project {
static void isPrime(int n) {
for(int i=2;i*i<=n;i++) {
if(n%i==0) {
return;
}
}
System.out.println(n);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
isPrime(n);
}

Output1: Output2:
3 10
3
Power of 2
package proj;
import java.util.*;
public class project {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n%2==0)
n=n/2;
if(n==1)
System.out.println("yes");
else
System.out.println("no");
}

Output
16
Yes
(another way to solve)

package proj;
import java.util.*;
public class project {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n&n-1)==0)
System.out.println("yes");
else
System.out.println("no");
}}

Output
1024
Yes

Find the number even or odd(using bit)


package proj;
import java.util.*;
public class project {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if((n&1)==0)
System.out.println("even");
else
System.out.println("odd");
}

Output:
46
Even

On bits:
package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n!=0){
if((n&1)==1)
count++;
n=n>>1;
}
System.out.println(count);
}
}

Output:
1024
1

Print odd number between 10-20

package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
int number=20;
System.out.print("List of odd numbers from 10 to "+number+": ");
for (int i=10; i<=number; i++)
{
//logic to check if the number is odd or not
//if i%2 is not equal to zero, the number is odd
if (i%2!=0)
{
System.out.print(i + " ");
}
} } }

Output:
List of odd numbers from 1 to 20: 11 13 15 17 19
List of the programs solved

S.NO Program

1. Date Condition

2. Print even number seprated by commas

3. Gcd

4. Lcm

5. Sum of Factor

6. Prime Number

7. Power of 2

8. Find the number even or odd(using bit)

9. On bits

10. Print odd number between 10-20


Day 3
Pattern
square pattern
import java.util.Scanner;
public class Pattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
System.out.print("* ");}
System.out.println();
}
}
}
output
4
****
****
****
****
Right Triangle Star Pattern
import java.util.Scanner;
public class Pattern1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row <= n; row++) {
for (int col = 0; col <=row; col++) { //here it will depends on an row
System.out.print("* ");}
System.out.println();
}
}
}
OUTPUT
3
*
**
***
****
right-angled triangle pattern of asterisks
import java.util.Scanner;

public class Pattern2


{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = row; col < n; col++){
System.out.print("* ");
}
System.out.println();
}
}
}

4
****
***
**
*
import java.util.Scanner;

public class Pattern4 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = 0; col < row-1; col++) {
System.out.print(" ");}
for (int col = row; col < n; col++) {

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

}
}
Left Triangle Star Pattern
import java.util.Scanner;

public class Pattern3 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = row; col< n-1; col++){
System.out.print(" ");
}
for(int col=0;col<row;col++){
System.out.print("*");
}
System.out.println();
}
}
}

Pyramid Star Pattern


import java.util.Scanner;

public class Pattern5 {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = row; col <n-1; col++) {
System.out.print(" ");}
for (int col = 0; col < row; col++) {
System.out.print("* ");
}
System.out.println();}}
6

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

import java.util.Scanner;

public class Pattern6 {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


int n = sc.nextInt();
int t = 0;
for (int row = 0; row < n; row++) {

for (int col = 0; col < t; col++) {


System.out.print("*");
}
t = t + 2;
System.out.println();
}
}
}

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row <= n; row++) {
for (int col = row; col < n-1; col++) { //here it will depends on an row
System.out.print("* ");}
System.out.println();
}
}
}

Reverse Pyramid Star Pattern


Import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int t=1;
for(int row=0;row<n-1;row++) {
for(int col=row;col<n-1;col++) {
System.out.print(" ");
}
for(int col=0;col<t;col++) {
System.out.print("*");
}
t=t+2;
System.out.println();
}
t=(2*n)-1;
for(int row=0;row<n;row++) {
for(int col=0;col<=row-1;col++) {
System.out.print(" ");
}
for(int col=0;col<t;col++) {
System.out.print("*");
}
t=t-2;
System.out.println();
}
}
}
//5
//
//
//*********
// *******
// *****
// ***
// *

left-aligned, right-angled triangle pattern of asterisks with constant width, shifted to the
right on each subsequent row.

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

6
******
******
******
******
******
******
******
Number Pattern
import java.util.Scanner;

public class Num1 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
System.out.print(row+1);
}
System.out.println();
} }}

6
111111
222222
333333
444444
555555
666666

import java.util.Scanner;

public class Num2 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = row; col < n; col++) {
System.out.print(row+1);
}
System.out.println();
}
}
}

Output:

11111

2222

333

44

import java.util.Scanner;
public class Num3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
System.out.print(col+1);
}
System.out.println();
}
}
}
3
12345
12345
12345

import java.util.Scanner;
public class Num4 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k=1;
for (int row = 0; row < n; row++) {
for (int col = 0; col <=row; col++) {
System.out.print(k++);
}
System.out.println();

}
}
}

Output:

1
23
456
78910

In an add row we need add column in even we need even number


import java.util.Scanner;

public class Num5 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k=1;
for (int row = 0; row < n; row++) {
if((row +1) %2 ==0){
k=2;
}
else {
k=1;
}
for (int col =0;col<=row;col++){

System.out.print(k);
k=k+2;
}

System.out.println();
{

}
}
}

output
5
1
24
135
2468
13579

import java.util.Scanner;

public class Num6 {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


int n = sc.nextInt();

for (int row = 0; row <= n; row++) {


int k=row;
for (int col =0; col < row; col++) {
System.out.print(k++);
}
System.out.println();

}
}
}

1
23
345
4567
56789

import java.util.Scanner;

public class Num6 {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


int n = sc.nextInt();

for (int row = 0; row <= n; row++) {


// int k=row;
for (int col =0; col < row; col++) {
System.out.print(row-col-1);
}
System.out.println();

}
}}

0
10
210
3210
43210

import java.util.Scanner;

public class Num7 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d =n-1;
for (int row = 0; row < n; row++) {
int t =row+1;
for(int col=0;col<=row;col++){
System.out.print(t);
t=t+d;
d--;
}
d=n-1;
System.out.println();
}
}
}

5
1
26
3710
481113
59121415

5
1
26 4
3710 4 3
481113 4 3 21
59121415

Character:
Right Triangle Alphabetic Pattern
import java.util.Scanner;

public class Char1 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {

int A = 65;
for (int col = 0; col < row; col++) {
System.out.print((char) (A + col));
}
System.out.println();

}
}
}
Output:
5
A
AB
ABC
ABCD
ABCDE

import java.util.Scanner;

public class char2 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
int A = 65;
for (int col = 0; col <= row; col++) {
System.out.print((char) (A + row));
}
System.out.println();}}}

5
A
BB
CCC
DDDD
EEEEE

import java.util.Scanner;
public class char2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int A = 65;
for (int row = 0; row < n; row++) {

for (int col = 0; col <= row; col++) {


System.out.print((char)A+"");
A++;
}
System.out.println();

}
}}

A
BC
DEF
GHIJ
KLMNO
PQRSTU

Grid pattern

00 01 02 03 04

10 11 12 13 14

20 21 22 23 24
30 31 32 33 34

40 41 42 43 44

import java.util.Scanner;

public class GridM {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
if(col==0 || col == n-1 || (row+col == n-1 && row >=n/2) ||(row ==
col)&&(row>=n/2)){
System.out.print("*");
}
else{
System.out.print(" ");
}
}System.out.println();
}
}
}

10

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

import java.util.Scanner;

public class Grid {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
if(col==0 || col == n-1 || (row== col && row <=n/2) ||(row + col==n-
1)&&(row<=n/2)){
System.out.print("*");
}
else{
System.out.print(" ");
}
}System.out.println();
}
}
}

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

import java.util.Scanner;

public class GridDimond {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = 1;
for (int row = 0; row < n; row++) {
for (int col = row; col < n - 1; col++) {
System.out.print(" ");
}
for (int col = 0; col < t; col++) {
if (col == 0 || col == t - 1 || row == n - 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
t = t + 2;
System.out.println();
}} }

Output
5
*

**

* *

* *

*********

package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int t=1;
for(int row=0;row<n-1;row++) {
for(int col=row;col<n-1;col++) {
System.out.print(" ");
}
for(int col=0;col<t;col++) {
if(col==0||col==t-1)
System.out.print("*");
else
System.out.print(" ");
}
t=t+2;
System.out.println();
}
t=(2*n)-1;
for(int row=0;row<n;row++) {
for(int col=0;col<=row-1;col++) {
System.out.print(" ");
}
for(int col=0;col<t;col++) {
if(col==0||col==t-1)
System.out.print("*");
else
System.out.print(" ");
}
t=t-2;
System.out.println();
}
}
}
output
5
*
**
* *
* *
* *
* *
* *
**
*

Inner reducing pattern(Advanced level)


mport java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int t1=(2*n)-1;
for(int row=0;row<n;row++) {
int t=n;
for(int col=0;col<=row;col++) {
System.out.print(t--);
}
t=t+1;
for(int col=0;col<t1-1;col++) {
System.out.print(t);
}
t1=t1-2;
t=t+1;
for(int col=0;col<=row;col++) {
if(col!=row)
System.out.print(t++);
}
System.out.println();
}

}
}
//4
// 5 -> 7
// 4 -> 5
// 3 -> 3
// 1 -> 1
//4 44444 4
//43 333 34
//432 2 234
//432 1 234
//
//4322234
//4333334
//4444444
LIST OF PROGRAMS

S.no Program
1 Square pattern
2 Right Triangle Star Pattern
3 Right-angled triangle pattern of asterisks
4 Left Triangle Star Pattern
5 Pyramid Star Pattern
6 Reverse Pyramid Star Pattern
Left-aligned, right-angled triangle pattern of asterisks with constant width, shifted
7
to the right on each subsequent row.
8 7 Program solved in Number Pattern
9 Character pattern
10 Grid pattern for M,W and Diamond
11 Inner reducing pattern
DAY 4
Find the number of digit:
package proj;
import java.util.*;
public class program {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int len=(n==0)?1:(int)Math.log10(n)+1;
System.out.println(len);
}
}

Output:
12345
5

Reverse a number
package proj;
import java.util.*;
public class program {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n!=0) {
int last=n%10;
System.out.print(last);
n=n/10;
}
}
}

Output:
12345
54321

(Another way)

package proj;
import java.util.*;
public class program {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int sum =0;
while(n!=0) {
int last=n%10;
sum=sum*10+last;
n=n/10;
}
System.out.print(sum);

}
}
Output:
01234
4321

Count even number and odd number in a given digit using bitwise operator

package proj;
import java.util.*;
public class program {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int evenCount =0,oddCount=0;
while(n!=0) {
int last=n%10;
if((last&1)==0) {
evenCount++;
}else {
oddCount++;
}
n=n/10;
}
System.out.print(evenCount+"even"+" "+oddCount+"odd");

}
}

Output:
12345
2even 3odd

Counting trailing 0’s in given number

package proj;
import java.util.*;
public class program {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int count=0;
while(n!=0) {
int last=n%10;
n=n/10;
if(last==0) {
count++;
}else {
break;
}
System.out.print(count);
}
}
}

Output:
1234000
123

Print the prime digits in reverse order in the given number

package proj;
import java.util.*;
public class program {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int count=0;
while(n!=0) {
int last=n%10;
if(last==2||last==3||last==5||last==7) {
System.out.print(last);
n=n/10;
}
}
}
}

Factorial
package proj;
import java.util.*;
public class program{
public static void main(String args[]){
int i,fact=1;
int n =sc.nextInt();
for(i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("Factorial of "+n+" is: "+fact);
}
}
Output:
5
120

Factorial optimization:

package proj;
import java.util.*;
public class program {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();//1234
int sum=0;
//100-> 20+4=24
while(n>=5) {
sum=sum+(n/5);
n=n/5;
}
System.out.println(sum);

}
}
Output:
1000
249

Print the cube value of the given number


package proj;
import java.util.*;
public class program {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();//1234
for(int i=1;i<=n;i++) {
int m=i*i*i;
System.out.println(m);
}
}
}
Output:
1
8
27
64
125

Logical reasoning based number series problem


package proj;
import java.util.*;
public class program {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int m=2;
int n=sc.nextInt();
for(int i=0;i<n;i++) {
m=(2*m)-i;
System.out.println(m);
}
}

Output:
5
2
4
7
12
21
38

Decimal to binary

package proj;
import java.util.*;
public class program {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int m=2;
int n=sc.nextInt();
for(int i=31;i>=0;i--) {
int j=n>>i;
System.out.print(j&1);
}
}
}

Output:
5
00000000000000000000000000000101

Palindrome

package proj;
import java.util.*;
public class program {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int sum=0;
int t=n;
while(n!=0) {
sum=sum*10+(n%10);
n=n/10;
}
if(sum==t) {
System.out.println("yes");
}else {
System.out.println("no");
}
}
}
Output:
494
Yes

123
no

Fibonacci series

package proj;
import java.util.*;
public class program {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int f1=-1,f2=1,f3=0;
System.out.print("0 1 ");
for(int i=0;i<n;i++) {
f3=f1+f2;
System.out.print(f3+" ");
f1=f2;
f2=f3;
}
}
}

Output

5
0101123
LIST OF THE PROGRAMS

S.NO PROGRAM

1. Find the number of digit

2. Reverse a number

3. Count even number and odd number in a given digit using bitwise operator

4. Counting trailing 0’s in given number

5. Print the prime digits in reverse order in the given number

6. Factorial

7. Print the cube value of the given number

8. Logical reasoning based number series problem

9. Decimal to binary

10 Palindrome

11 Fibonacci series
Day 5

Pointers:
Why we go for an pointor?
To store an integer address.
Address has an 8byte,int has 4 bytes.

Double pointer
N 2000 ptr 2000 Ptr1 2500
2500 0005

Here the code **ptr1 points an


#include <stdio.h>

int main() {
int *ptr;
int **ptr1;
int n=10;
ptr=&n;
ptr1=&ptr;
printf("**ptr =%d",**ptr1);
return 0;
}

Output:**ptr =10

// Online C compiler to run C program online


#include <stdio.h>
int arr[100]; //global declare
int main() {
for(int i=0;i<=100;i++){
printf("%d",arr[i]);
}

return 0;
}
Output:
000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000
---------------------------------------------------------------------------------------------------------
//local variable declaration because it comes under an bracket..

// Online C compiler to run C program online


#include <stdio.h>
int main() {
int arr[100]=(0);
for(int i=0;i<=100;i++){
printf("%d",arr[i]);
}

return 0;
}
--------------------------------------------------------------------------------------------------------
Array starts from 0?
We able to accurately takes an address
#include <stdio.h>
int main() {
int arr[5]={10,20,30,40};
printf("%d",*arr); //to check it starts from 1000 we use * to show
return 0;
}
Output:
10 //shows an 1000 value in here

int main() {
int arr[5]={10,20,30,40};
printf("%d",*(arr+1)); //to check it starts from 1000 we use * to show
return 0;
}
//operator preference
//1004 (arr+1)goes to next near bytes is 1004.
10 +1 = 20

Output:
20
1000 1004 1008 1012
10 20 30 40

arr0 1 2 3
----------------------------------------------------------------------------------------------------------------
-----
interview question
#include <stdio.h>
//main access we can update in here
int main() {
int arr[5]={10,20,30,40};
int *a; //1000 value 10 next update to
a= arr;
int *b;
b=arr+1;
int i=*a++; // first i=*a will execute
//next a = arr update an a= a+1
printf("%d %d %d",*a,*b,i);
}
Output:
20 20 10

// Online C compiler to run C program online


#include <stdio.h>
void display(int* a){
a[2]=34; //main access we can update in here
}
int main() {
int arr[5]={10,20,30,40};
display(arr);
for(int i=0;i<5;i++){
printf(" %d",arr[i]);
}
}
Output:
10 20 34 40 0
----------------------------------------------------------------------------------------------------------------
----------
Arrays
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int[] arr = new int[5];
arr[0] =10;
arr[1] =20;
arr[2]=60;
arr[3]=30;
display(arr);
for(int i=0;i<4;i++){
System.out.println(arr[i]);
}
}
static void display(int a[]){
a[3] =23;
}
}
output: 10
20
60
23
C program

//here we use an malloc to store in heap


int arr[5]=(int*)malloc)5*sizeof(int));
________________________________________________________________
Array sample program:
import java.util.Arrays;
import java.util.Scanner;

public class properties {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[100];
for(int i=0;i<n;i++){
arr[i] =sc.nextInt();
}
for(int i=0;i<n;i++){
System.out.print(arr[i]+ " 4");
}
// Arrays.toString(arr);
// Arrays.fill(arr, 1);
// Arrays.sort(arr);
}
}

Output:
4
20 30 40 50 60
20 30 40 50
Insertion
import java.util.Scanner;

public class insertion {


static void display(int[] a, int n) {
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println(); }
static void insert(int[] a, int n) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the element to be inserted: ");
int data = sc.nextInt();

System.out.print("Enter the position to insert the element: ");


int pos = sc.nextInt();

if (pos < 0 || pos > n) {


System.out.println("Invalid position! Position should be between 0 and " + n);
return;
}

// Shift elements to make space for insertion


for (int i = n - 1; i >= pos; i--) {
a[i + 1] = a[i];
}

a[pos] = data;
display(a, n + 1); // array after insertion
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = sc.nextInt(); // Read number of elements

int[] arr = new int[n + 1]; // Declare array with extra space for potential insertion

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


for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt(); // Read elements into the array
}

insert(arr, n); // Call insert method


sc.close(); // Close the Scanner after using it
}
}
Output:
Enter the number of elements: 5
Enter the elements:
123456
Enter the element to be inserted: 45
Enter the position to insert the element: 2
Delete
import java.util.Scanner;

public class insertion {


static void display(int[] a, int n) {
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
static void delete(int arr[],int n) {
Scanner sc=new Scanner(System.in);
int pos=sc.nextInt();
pos=pos-1;
for(int i=pos;i<n-1;i++) {
arr[i]=arr[i+1];
}
display(arr,n-1);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = sc.nextInt(); // Read number of elements

int[] arr = new int[n + 1]; // Declare array with extra space for potential insertion

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


for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt(); // Read elements into the array
}

delete(arr, n); // Call insert method


sc.close(); // Close the Scanner after using it
}
}
Output:
Enter the number of elements: 5
Enter the elements:
12345
3
1245
Update:
import java.util.Scanner;

public class insertion {


static void display(int[] a, int n) {
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
static void update(int[] arr,int n){
Scanner sc=new Scanner(System.in);
int pos=sc.nextInt();
pos=pos-1;
int data=sc.nextInt();
arr[pos]=data;
display(arr,n);

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = sc.nextInt(); // Read number of elements

int[] arr = new int[n + 1]; // Declare array with extra space for potential insertion

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


for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt(); // Read elements into the array
}

update(arr, n); // Call insert method


sc.close(); // Close the Scanner after using it
}
}

Output:
Enter the number of elements: 5
Enter the elements:
123456
4
67
1 2 3 67 5

Search the element and delete


import java.util.Scanner;

public class Search {


static int n;

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
n = sc.nextInt(); //5
int[] arr = new int[100];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
search(arr);
display(arr);
}

static void search(int[] arr) {


Scanner sc=new Scanner(System.in);
int key=sc.nextInt();
int flag=0;
for(int i=0;i<n;i++) {
if (key == arr[i]) {
delete(arr, i);
flag = 1;
return;
}
}
if(flag == 0){
System.out.println("no");
}

}
static void delete(int arr[],int pos) {

for(int i=pos;i<n-1;i++) {
arr[i]=arr[i+1];
}
n=n-1;
}
static void display(int[] a) {
for(int i=0;i<n;i++) {
System.out.print(a[i]+" ");
}
}

}
output:
6
673452
4
67352
Happy number
import java.util.Scanner;

public class Happy {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n%9 ==0){
System.out.println("9");
}
else{
System.out.println(n%9);
}
}

}output:
1899
9

Armstrong
import java.util.Scanner;

public class count {


//153 =cube pani sum pana same ans
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t=n,sum=0;
int len=(n==0)?1:(int)Math.log10(n)+1;
while(n!=0) {
sum = sum + (int) Math.pow((n % 10), len);
n = n / 10;
}
if(sum==t){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}
output:
153
Yes
List of Programs
S.no Program
1. Pointers in c (5 programs)
2. Interview question asked in pointer (2 programs)
3. Arrays in java ( 2 programs)
4. Insertion operation
5. Search an element
6. Deletion operation
7 Updation operation
8 Sorting an elements
9 Happy number in java
10 Armstrong Number
Day 6

Reversal Array
package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
int t;
for(int i=0,j=n-1;i<j;i++,j--) {
t=arr[i];
arr[i]=arr[j];
arr[j]=t;

}
for(int i=0;i<n;i++) {
System.out.print(arr[i]+" ");
}
}
}

Output:
5
12345
54321

Find the maximum number in the array


package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
int t=arr[0];
for(int i=0;i<n;i++) {
if(t<arr[i]) {
t=arr[i];
}

}
System.out.print(t);
}

}
Output
5
89 4 56 78 55
89

Leaders Array
package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
for(int i=0;i<n;i++) {
int flag=0;
for(int j=i+1;j<n;j++) {
if(arr[i]<arr[j]) {
flag=1;
break;
}

}
if(flag==0) {
System.out.print(arr[i]+" ");
}
}

}
}

Output
5
89 4 56 78 55
89 78 55

Sum of Array
package proj;
import java.util.*;
public class project {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
int sum=0;
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
for(int i=0;i<arr.length;i++) {
sum=sum+arr[i];
}
System.out.println(sum);
}
}

Output
5
12345
15

Find the Single number in array

class Solution {
public int singleNumber(int[] nums) {
int n=nums.length,sum=0;
for(int i=0;i<n;i++){
sum=sum^nums[i];
}
return sum;
}
}

Output
[2,2,1]
1

Unique number
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
int[] countArr=new int[n];
for(int i=0;i<n;i++) {
if(countArr[i]!=-1) {
int count=1;
for(int j=i+1;j<n;j++) {
if(arr[i]==arr[j]) {
count++;
countArr[j]=-1;
}
}
countArr[i]=count;
}
}
for(int i=0;i<n;i++) {
if(countArr[i]==-1)
System.out.print(arr[i]+" ");
}

}
}

//3
//
//2 2 1 4 1
//
//sum=2;
//
//2^2 =0^1=1^4=5^1=4
//
//0001
//0100
//0101
//0001
//0100
LIST OF THE PROGRAMS

S.no Program

1 Reversal Array

2 Find the maximum number in the array

3 Leaders Array

4 Sum of Array

5 Find the Single number in array

6 Unique numbers
Day 7
Rotation in array
import java.util.Scanner;

public class Rotation {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int n_rot= sc.nextInt();
n_rot%=n;
for(int i=0;i<n_rot;i++){
rotate(arr);
}
display(arr);
}
static void rotate(int arr[]){
int pos=0; // for an second half rotation in pos give arr.length/2
int last=arr[arr.length-1];//for an half rotation arr.length/2
for(int i=arr.length-1;i>pos;i--){
arr[i]=arr[i-1];
}
arr[pos]=last;
}
static void display(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]+" ");
}
}

}
output:
5
12 34 56 78 90
2
78 90 12 34 56

String
public class literal {
public static void main(String[] args) {
String str1 =new String("hello");
System.out.println(str1.hashCode());
String str="hello";
if(str1 == str)
System.out.println("yes"); //== for address
// same location point means only yes else we need to use an
// .equals operator
else
System.out.println("no");
}

}
99162322
No
import java.util.Scanner;
public class literal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str= sc.nextLine();
int count=0;
for(int i=0;i<str.length();i++){
char ch =str.charAt(i);
ch=Character.toLowerCase(ch);
if(ch =='a' || ch=='e' || ch =='i' || ch=='o' || ch=='u'){
count++;
}
}
System.out.println(count);
}
}
hello
2
Anagram:
import java.util.Scanner;

public class anagram {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1= sc.nextLine();
String str2= sc.nextLine();
if(str1.length()!=str2.length()){
System.out.println("not an anagram");
}
int[] dp = new int[26];
for(int i=0;i<str1.length();i++){
dp[str1.charAt(i)-97]++; //here str.chatAt(i) is 97 if 97 - 97 ==0 means count
increment
}
for(int i=0;i<str1.length();i++){
dp[str2.charAt(i)-97]--;
}
for(int i=0;i<str1.length();i++){
if(dp[i]!=0){
System.out.println("Not an Anagram");
return ;
}

}
System.out.println("it ia an anagram");
}
}

ababab
aaabbb
it ia an anagram
import java.util.Scanner;

public class pangram {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

int[] dp = new int[26];


for(int i=0;i<str1.length();i++){
char ch = Character.toLowerCase(str1.charAt(i));
if(ch>='a' && ch<='z'){
dp[str1.charAt(i)-97]++;
}

//here str.chatAt(i) is 97 if 97 - 97 ==0 means count increment


}

for(int i=0;i<26;i++){
if(dp[i]==0){
System.out.println("Not an Pangrams");
return ;
}

}
System.out.println("it is an pangram");
}
}

output:
abcdefghijklmnopqrstuvwxyz

pangrams

import java.util.Scanner;

public class pangram {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

int[] dp = new int[26];


for(int i=0;i<str1.length();i++){
char ch = Character.toLowerCase(str1.charAt(i));
if(ch>='a' && ch<='z'){
dp[str1.charAt(i)-97]++;
}

//here str.chatAt(i) is 97 if 97 - 97 ==0 means count increment


}

for(int i=0;i<26;i++){
if(dp[i]>0){
System.out.println("Not an isogram");
return ;
}

}
System.out.println("it is not an anagram");
}
}

output:

abcdefh

it is anagram
LIST OF PROGRAMS

Sno Program

1 Rotation in array

2 String(2 programs)

3 Anagram (2 programs)

4 Pangram

5 Isogram
Day8
Recursion
Print the number in reverse order
package proj;
import java.util.*;
public class project {
static void display(int n) {
if(n==0) {
return;
}
System.out.println(n);
display(n-1);
}
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
display(n);
}
}
Output
5
5
4
3
2
1

Print the number in reverse order using recursion


package proj;
import java.util.*;
public class project {
static void display(int n) {
if(n==0) {
return;
}
display(n-1);
System.out.println(n);

}
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
display(n);
}
}
Output
5
1
2
3
4
5

Sum of natural number


package proj;
import java.util.*;
public class project {
static int sum(int n) {
if(n==0) {
return 0;
}
return n+sum(n-1);

}
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(sum(n));
}
}

Output
5
15

Nested recursion
package proj;
import java.util.*;
public class project {
static int nested(int n) {
if(n>100)
return n-10;
return nested(nested(n+11));

public static void main(String[]args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
System.out.println(nested(98));
}
}

Output
98
91

Fibonacci
package proj;
import java.util.*;
public class project {
static int fib(int n) {
if(n<1)
return n;
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));
}
}

Output
10
0 1 1 2 3 5 8 13 21 34

Perfect Square
package proj;
import java.util.*;
public class project {
static int sqrt(int n) {
int i;
for( i=1;i*i<=n;i++);
return i-1;
}
static boolean perfectsquare(int n) {
if(n==sqrt(n)*sqrt(n)) {
return true;
}
return false;
}
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<=n;i++) {
if(perfectsquare(n)) {
System.out.println(i);
}
}
}
}
Output
10
1 4 9 16 25 36 42 56 81 100

List Of Programs

S no Programs
1 Print the number in reverse order
2 Print the number in reverse order using recursion
3 Sum of natural number
4 Nested recursion
5 Fibonacci
6 Perfect Square
DAY 9
Collection
List
ArrayList
Linked List
Vector
Stack
Queue:
Priority
De queue
Double
Set:
Hash
Linked hash set
Pre set
Map:
Hash map:
Linked Hash map

ArrayList Declaration

import java.util.ArrayList;
import java.util.List;

public class Main {


public static void main(String[] args)
{
int n;
ArrayList list= new ArrayList();
list.add(10);
list.add(30);
System.out.println(list.get(1));
}
}
Can we strore an different datatypes in an array?
Yes we can .but they don’t know an what type of data ..so they use an wrapper class.int mean
Integer.

Two dimensional data


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {


public static void main(String[] args)
{
int n;
Scanner sc = new Scanner(System.in);
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
for(int i=0;i<2;i++){
ArrayList <Integer> list = new ArrayList<>();
for(int j=0;j<2;j++){
list.add(sc.nextInt());
}
arr.add(list);
}

System.out.println(arr);
}
}

// [[12 34 56 65],[34,56,78]].
1
2
3
4
[[1, 2], [3, 4]]

ADD in list
import java.util.ArrayList;
import java.util.Scanner;

public class add {


public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list= new ArrayList<>();
n = sc.nextInt();
for(int i=0;i<n;i++){
list.add(sc.nextInt());
}

int pos= sc.nextInt();


int data = sc.nextInt();
pos=pos-1;
list.add(pos,data);
System.out.println(list);
}
}
Output:
5
1
2
3
4
5
1
34
[34, 1, 2, 3, 4, 5]
Rotate
import java.util.ArrayList;
import java.util.Scanner;

public class rotate {


public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list= new ArrayList<>();
n = sc.nextInt();
for(int i=0;i<n;i++){
list.add(sc.nextInt());
}
int rotate = sc.nextInt();
rotate=rotate%list.size();
for(int i=0;i<rotate;i++){

int last=list.get(list.size()-1);
list.remove(list.size()-1);
list.add(0,last);
}
for(int i:list)
{
System.out.print(i+" ");
}
}
}
output:
5
12345
2
45123

Vector:
Vector<Interger> = new Vector<>();
List<Integer.>= new Stack<>();

Stack:
remove an last element using stack
public static void main(String[] args) {

Stack<Integer> s=new Stack<>();


s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.pop();
System.out.println(s);
System.out.println(s.peek());
}
[10, 20, 30]
30

Queue:
(print an first element)

import java.util.Stack;

public class last {


public static void main(String[] args) {

Stack<Integer> s=new Stack<>();


s.push(10);
s.push(20);
s.push(30);
s.push(40);
s.pop();
System.out.println(s);
System.out.println(s.peek());
}

}
output:
[10, 20, 30]
[20, 30]
20

Dequeue

Deque dq = new ArrayDeque();


Dq.add(10);
Dq.add(20);
Dq.add(30);
System.out.println(dq);
Dq.addFirst(23);
Dq.addLast(56);
System.out.println(dq);
System.out.println(dq.peekFirst());
HashMap
import java.util.HashMap;
import java.util.Map;

public class hash {


public static void main(String[] args) {
Map<String,String> hm = new HashMap<>(); //hash map order change
hm.put("name","ranjani");
hm.put("Phone","1231234"); // if we use linked means order
//if we use tree means sort
hm.put("email","ranjani@993");
System.out.println(hm.get("name"));
}
}
Output:
Ranjani

Subarray:
import java.util.Scanner;

public class sub_array2 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int[] arr= new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
int size = sc.nextInt();
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if((j-1)==size-1){
display(i,j,arr);
if(i<=j)
System.out.println();
}
}
}}
static void display(int start,int end,int[] arr){
for(int i=start;i<=end;i++){
System.out.print(arr[i]+ " ");
}
}}
Output:
5
12 13 14 15 16
3
12 13 14 15
13 14 15
14 15
15
LIST OF PROGRAMS

s.no Program(collection)
1 List
2. Array List Declaration
3 Two dimensional data
4. Add in list
5 Remove
6. Remove using stack
7. Print first element in queue
8. Dequeue
9. Hashmap
10. Subarray
Day 10
Two pointer approach:

Program1:

package proj;
import java.util.*;
public class project {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String str=sc.nextLine();
int open=0;
for(int start=0;start<str.length();start++) {
if(str.charAt(start)=='(')
open++;
else if(str.charAt(start)==')')
open--;
if(open==-1) {
System.out.println("Invalid");
return;
}
}
if(open!=0) {
System.out.println("invalid");
}else {
System.out.println("vaid");
}

}
}

Output
(()())
valid

program2:
package proj;
import java.util.*;
public class project {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int open=0,close=0;
for(int start=0,end=str.length()-1;start<str.length();start++,end--) {
if(str.charAt(start)=='(')
open++;
else if(str.charAt(start)==')')
open--;
if(open==-1) {
System.out.println("Invalid");
return;
}
if(str.charAt(end)=='(')
close++;
else if(str.charAt(end)==')')
close--;
if(close==-1) {
System.out.println("Invalid");
return;
}
}
System.out.println("valid");
}
}
Output
(()(((((((((((((((((((((((
Valid

program3
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int open=0,close=0;
char[] arr=str.toCharArray();
for(int start=0,end=str.length()-1;start<str.length();start++,end--) {
if(str.charAt(start)=='(')
open++;
else if(str.charAt(start)==')')
open--;
if(open==-1) {
arr[start]='*';
open=0;
}
if(str.charAt(end)==')')
close++;
else if(str.charAt(end)=='(')
close--;
if(close==-1) {
arr[end]='*';
close=0;
}
}
for(char i:arr) {
if(i!='*') {
System.out.print(i);
}
}
}
}

//*(())*
//-112101
//10121-1

Output
(()())(
(()())

Checking the balanced parentheses


package proj;
import java.util.*;
public class project {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
while(str.contains("()")||str.contains("[]")||str.contains("{}")){
str=str.replace("()", "");
str=str.replace("[]","");
str=str.replace("{}","");
}
if(str.length()==0) {
System.out.println("Valid");
}
else {
System.out.println("Invalid");
}

}
}
Output
(())
Valid
{([
Invalid

Print the word without vowels


package proj;
import java.util.*;
public class project {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
str=str.replace("a", "");
str=str.replace("e","");
str=str.replace("i","");
str=str.replace("o","");
str=str.replace("u","");
System.out.println(str);
}
}
Output
asbeeuiopljhtg
sbpljhtg

Long paranthesis
package proj;
import java.util.*;
public class project {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int open=0,close=0;
char[] arr=str.toCharArray();
for(int start=0,end=str.length()-1;start<str.length();start++,end--) {
if(str.charAt(start)=='(')
open++;
else if(str.charAt(start)==')')
open--;
if(open==-1) {
arr[start]='*';
open=0;
}
if(str.charAt(end)==')')
close++;
else if(str.charAt(end)=='(')
close--;
if(close==-1) {
arr[end]='*';
close=0;
}
}
for(char i:arr) {
if(i!='*') {
System.out.print(Arrays.toString(arr));
}
}
}
}
Output
()())())(()))
[(, ), (, ), *, (, ), *, (, (, ), ), *]

Longest valid parentheses


package proj;
import java.util.*;
public class project {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int open=0,close=0;
char[] arr=str.toCharArray();
for(int start=0,end=str.length()-1;start<str.length();start++,end--) {
if(str.charAt(start)=='(')
open++;
else if(str.charAt(start)==')')
open--;
if(open==-1) {
arr[start]='*';
open=0;
}
if(str.charAt(end)==')')
close++;
else if(str.charAt(end)=='(')
close--;
if(close==-1) {
arr[end]='*';
close=0;
}
}
int count=0,max=0;
for(int i=0;i<arr.length;i++) {
if(arr[i]!='*') {
count++;
}else {
if(max<count) {
max=count;
}
count=0;
}
}
if(max<count)
max=count;
System.out.println(max);
}
}
Output
()())((()))
6
Longest value parantheses
package engineering;
import java.util.*;
public class Batch3 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int open=0,close=0;
char[] arr=str.toCharArray();
for(int start=0,end=str.length()-1;start<str.length();start++,end--) {
if(str.charAt(start)=='(')
open++;
else if(str.charAt(start)==')')
open--;
if(open==-1) {
arr[start]='*';
open=0;
}
if(str.charAt(end)==')')
close++;
else if(str.charAt(end)=='(')
close--;
if(close==-1) {
arr[end]='*';
close=0;
}
}
int count=0,max=0,start=0,end=0;
System.out.println(Arrays.toString(arr));
for(int i=0;i<arr.length;i++) {
if(arr[i]!='*') {
count++;
}else {
if(max<count) {
max=count;
end=i-1;
start=end-max;
}
count=0;
}
}
System.out.println(str.substring(start+1,end-1));
}
}

//*(())*
//-112101
//10121-1

LIST OF PROGRAMS

S.no
Programs

1 Two Pointer approach programs

2 Print the word without vowels

3 Checking the balanced parantheses

4 Long parantheses
5 Longest valid parantheses
6 Longest value parantheses

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy