External Training JAVA Training - 01.07.2024 - 11.07.2024
External Training JAVA Training - 01.07.2024 - 11.07.2024
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;
}}
}
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 inputs
int x1 = scanner.nextInt();
int v1 = scanner.nextInt();
int x2 = scanner.nextInt();
int v2 = scanner.nextInt();
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
X = "AGGTAB"
Y = "GXTXAYB"
output : 4(GTAB)
2. vowels reverse
input: "Apple"
output: "epplA"
Output: 6
4. subarray :
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 Output 44
Code
import java.util.Scanner;
// The number of breaks required is one less than the number of levels
int breaks = input.length() - 1;
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.*;
sc.close();
}
}
Day 3
QUESTION 1:
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.*;
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:
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.
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] .
1<=n<=100
Output Format
Sample Input
1 -2 4 -5 1
Sample Output
ANSWER:
import java.util.Scanner;
int n = scanner.nextInt();
arr[i] = scanner.nextInt();
int count = 0;
int sum = 0;
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:
Function Description
Constraints
1<=T<=5
1<=|a|,|b|<=10 power 5
Sample Input
2
JACK
DANIEL
ABACABA
ABACABA
Sample Output
DAJACKNIEL
AABABACABACABA
ANSWER:
import java.util.Scanner;
import java.util.Stack;
stackA.push(a.charAt(i));
}
for (int i = b.length() - 1; i >= 0; i--) {
stackB.push(b.charAt(i));
if (stackA.isEmpty()) {
result.append(stackB.pop());
} else if (stackB.isEmpty()) {
result.append(stackA.pop());
result.append(stackA.pop());
} else {
result.append(stackB.pop());
return result.toString();
int T = scanner.nextInt();
String b = scanner.nextLine();
System.out.println(mergeStrings(a, b));
Day 4
Question 1 : Finding Intersection and union
Code
import java.util.Scanner;
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:
Function Description
Input Format
Constraints
1<=T<=5
1<=|a|,|b|<=10 power 5
Sample Input
2
JACK
DANIEL
ABACABA
ABACABA
Sample Output
DAJACKNIEL
AABABACABACABA
Explanation
Code
import java.util.Scanner;
import java.util.Stack;
return result.toString();
}
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;
int T = sc.nextInt();
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) {
if (C < 0 || C > A) {
if (D < 0 || D > B) {
int effectivePrice1 = A - C;
int effectivePrice2 = B - D;
System.out.println("First");
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
Input Constraints
1<=n,k<=10^12
Output Format
Single integer
Sample Input
11
Sample Output
Code
import java.util.*;
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
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
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;
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;
}
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 {
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]+" ");
}
}
}
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.*;
s.close();
}
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;
scanner.close();
}
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
Code
import java.util.Scanner;
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;
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
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;
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.
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) {
String S = scanner.nextLine();
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;
}
}
By optimizing
import java.util.Scanner;
Eg:
package training;
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;
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();
}
}
Operator
Bitwise operator
AND(&)
package training;
}
Output:2
OR(||)
NOT(!)
XOR(^)
Right shift
package training;
Output:2
32 bits
|0000000000000000000000001010|after right shift
|000000000000000000000000010|10
DataTypes
Primitive – int ,float,char
Non Primitive
Non-linear -tree,graph
Linear = string,linked list,array
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
Spacing:
package training;
public class Batch3 {
public static void main(String[] args) {
int a=1,b=10;
System.out.printf("%-5d%5d",a,b);
}
}
import java.util.Scanner;
Output:
2024
its an leap year
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
package training;
S.NO Program
3. Operator programs
}else {
System.out.println("invalid");
}
}else {
System.out.println("invalid");
}
Output:
2/2/2004
Valid
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 {
}
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 {
Output
16
Yes
(another way to solve)
package proj;
import java.util.*;
public class project {
Output
1024
Yes
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
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
3. Gcd
4. Lcm
5. Sum of Factor
6. Prime Number
7. Power of 2
9. On bits
4
****
***
**
*
import java.util.Scanner;
System.out.print("*");
}
System.out.println();
}
}
}
Left Triangle Star Pattern
import java.util.Scanner;
*
**
***
****
*****
import java.util.Scanner;
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();
}
}
}
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;
6
111111
222222
333333
444444
555555
666666
import java.util.Scanner;
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 {
}
}
}
Output:
1
23
456
78910
System.out.print(k);
k=k+2;
}
System.out.println();
{
}
}
}
output
5
1
24
135
2468
13579
import java.util.Scanner;
}
}
}
1
23
345
4567
56789
import java.util.Scanner;
}
}}
0
10
210
3210
43210
import java.util.Scanner;
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;
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;
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++) {
}
}}
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;
10
* *
* *
* *
* *
* *
* ** *
* * * *
** **
** **
* *
import java.util.Scanner;
** **
** **
* * * *
* ** *
* ** *
* *
* *
* *
* *
import java.util.Scanner;
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
*
**
* *
* *
* *
* *
* *
**
*
}
}
//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
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
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 {
}
}
Output:
1000
249
Output:
5
2
4
7
12
21
38
Decimal to binary
package proj;
import java.util.*;
public class program {
Output:
5
00000000000000000000000000000101
Palindrome
package proj;
import java.util.*;
public class program {
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
2. Reverse a number
3. Count even number and odd number in a given digit using bitwise operator
6. Factorial
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
int main() {
int *ptr;
int **ptr1;
int n=10;
ptr=&n;
ptr1=&ptr;
printf("**ptr =%d",**ptr1);
return 0;
}
Output:**ptr =10
return 0;
}
Output:
000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000
---------------------------------------------------------------------------------------------------------
//local variable declaration because it comes under an bracket..
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
Output:
4
20 30 40 50 60
20 30 40 50
Insertion
import java.util.Scanner;
a[pos] = data;
display(a, n + 1); // array after insertion
}
int[] arr = new int[n + 1]; // Declare array with extra space for potential insertion
int[] arr = new int[n + 1]; // Declare array with extra space for potential insertion
int[] arr = new int[n + 1]; // Declare array with extra space for potential insertion
Output:
Enter the number of elements: 5
Enter the elements:
123456
4
67
1 2 3 67 5
}
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;
}output:
1899
9
Armstrong
import java.util.Scanner;
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
}
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
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
3 Leaders Array
4 Sum of Array
6 Unique numbers
Day 7
Rotation in array
import java.util.Scanner;
}
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;
}
System.out.println("it ia an anagram");
}
}
ababab
aaabbb
it ia an anagram
import java.util.Scanner;
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;
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
}
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
}
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));
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);
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;
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;
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) {
Queue:
(print an first element)
import java.util.Stack;
}
output:
[10, 20, 30]
[20, 30]
20
Dequeue
Subarray:
import java.util.Scanner;
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
(()())(
(()())
}
}
Output
(())
Valid
{([
Invalid
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
()())())(()))
[(, ), (, ), *, (, ), *, (, (, ), ), *]
//*(())*
//-112101
//10121-1
LIST OF PROGRAMS
S.no
Programs
4 Long parantheses
5 Longest valid parantheses
6 Longest value parantheses