LabSession June25
LabSession June25
SAGUNTHALA
R&D INSTITUTE OF SCIENCE AND TECHNOLOGY,
AVADI, CHENNAI. INDIA.
1 Decision Making
• If 1
• If Else
• Nested If
• Else if Ladder
• Switch Case (Java)
2 Loops
For 6
While
Do While (Java)
For each loop
3 Functions 8
• Types of Functions
• Defining a function
• Calling a function
• Processing the results from functions
4 Nested Loops
Pattern printing using nested loops 25
5 Arrays 29
6 String Handling 37
8. You have three hidden numbers, and your mission is to find out which one
is the greatest. Write a program that can reveal the highest of these three
numbers.
8A. Perform the above operation using ternary operator.
9. You have four secret numbers and your challenge is to write a program
that figures out which one is the largest and which one is the smallest. Use
your trusty if-else statements to solve this number mystery. Can you
determine the highest and lowest numbers among them?
Lab Day 4
Divisibility Test
10. You have two numbers, and your task is to write a program that adds
them together and checks if their total can be evenly divided by 2. Can you
figure out if the sum is even or not?
11. You have a number in hand, and your challenge is to write a program
that determines whether this number can be evenly divided by 100. Can you
uncover if it‘s a multiple of 100 or not?
A leap year is a year that contains one additional day beyond the typical
365 days of a standard year, making it 366 days in total. This extra day is added to
the month of February, which normally has 28 days but has 29 days in a leap
year.
1. Purpose: The extra day compensates for the fact that Earth's orbit around
the Sun takes approximately 365.2422 days. Without leap years, our
calendar would gradually drift out of sync with the Earth's orbit.
2. Rules for Leap Years:
o Divisibility by 4: A year is a leap year if it is divisible by 4. For
example, 2020 is a leap year because 2020 ÷ 4 = 505.
o Centennial Years: A year that is divisible by 100 is not a leap year,
unless:
Divisibility by 400: The year is also divisible by 400. For
example, the year 2000 was a leap year because 2000 ÷ 400 =
5, while the year 1900 was not a leap year because 1900 ÷ 400
= 4.75.
14. You have two numbers, and your challenge is to write a program that
performs both addition and subtraction with them. However, if any
subtraction results in a negative number, display it as a positive value. How
will you tackle this and show the final results?
For example, consider two numbers 20 and 15.
Addition of 2 values: 20 + 15 = 35.
Subtraction of 2 values: 20 - 15 = 5.
For example, consider two numbers 20 and -150.
Addition of 2 values: 20 + (-150) = -130 Absolute value of (-130) = 130.
Subtraction of 2 values: 20 - (-150) = 170.
20. Imagine you need to repeat a cheerful message. Write a program that
uses a `for` loop to print "ALL IS WELL" exactly twenty times. How will
you set up your loop to ensure this message appears the right number of
times?
21. You have a number (n), and your challenge is to write a program that
prints out a sequence starting from 1 and going up to (n). How will you
design your program to generate and display this sequence of numbers?
22. You need to write a program that reads a number (n) and prints all
numbers from 1 up to (n). However, there‘s a twist: keep the initialization
part outside of the `for` loop. How will you structure your program to
accomplish this?
Sample input:
Assume that N =5.
Sample output:
The first 5 natural numbers are 1, 2, 3, 4, 5.
23. You need to write a program that reads a number N and prints all
numbers from 1 up to N. The challenge is to keep the initialization statement
outside of the for loop and place the increment or decrement as the last
statement inside the for loop body. How will you design your program to
meet these conditions and produce the desired sequence?
Sample input:
Assume that N =5.
Sample output:
The first 5 natural numbers are 1, 2, 3, 4, 5.
24. You have a number (n), and your task is to write a program that prints
the squares and cubes of all numbers from 1 up to n. Use a `while` loop to
generate and display these values. How will you set up your program to
calculate and show both the squares and cubes for each number in the
range?
Sample input:
Assume that N =5.
Sample output:
The square of first 5 natural numbers are 1, 4, 9, 16, 25.
The cube of first 5 natural numbers are 1, 8, 27, 64, 125.
25. You need to write a program that reads a number (n) and calculates the
sum of the first (n) natural numbers. Use any type of loop to accomplish this.
How will you design your program to sum these numbers and display the
result?
Sample input:
Assume that n =5.
Sample output:
Sum of first 5 natural numbers = 1 + 2 + 3 + 4 +5 = 15.
Write a program to read print the ―welcome to the do while loop‖ greeting
message using do while loop. Just get the number n as input and print the
message n times.
You‘re tasked with creating a simple calculator using a `while` loop and a
`switch` statement. Your program should repeatedly prompt the user to
choose an arithmetic operation (like addition, subtraction, multiplication, or
division) and then perform the selected operation based on user input. How
will you set up your `while` loop and `switch` case to keep the calculator
running until the user decides to exit?
Create a method that prints the first (n) odd numbers, where (n) is provided as
input. How will you design this method to generate and display the sequence of
odd numbers correctly?
void oddSeries (int n) {
}
Sample Input/ Output:
Input: n=5
Output: 2 4 6 8 10
Input:
n=5
Output:
Cube (1) =1
Cube (2) =8
Cube (3) =27
Cube (4) =64
Cube (5) =125
32. Generation of Fibonacci series. You need to write a method that prints
the first (n) numbers in the Fibonacci series, where (n) is provided as input.
How will you design this method to generate and display the sequence of
Fibonacci numbers up to (n)?
33. You have a number and need to check if it belongs to the Fibonacci
sequence, where each number is the sum of the two preceding ones. Write a
method to determine if this number is part of the Fibonacci series. Return
`true` if it is, and `false` if it isn‘t. How will you uncover whether this number
fits into the famous Fibonacci pattern?
boolean isFib (int n) {
//write code
}
Note:
Fibonacci series: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ....
Nth Fibonacci number index: 1 2 3 4 5 6 7 8 9 10
Hint: Use Math.pow (x, y) for finding the x value raised to the power of y.
But, use the type casting (int) to get the integer result from the obtained
power.
int k = (int) Math.pow (x, y); // this will avoid the compile time error.
A method is there which tells how many dealerships are there and the total
number of cars and number of two wheelers in each dealership. Your job is to
calculate how many tyres would be there in each dealership and find the total
number of tyres.
Input
n=3
Dealership 1: number of cars = 4, number of two wheelers = 2
Dealership 2: number of cars = 4, number of two wheelers = 0
Dealership 3: number of cars = 1, number of two wheelers = 2
Output: 44
Explanation: There are total 3 dealerships: Dealerships1 contains 4 cars and 2
bikes. Dealerships2 contains 4 cars and 0 bikes. Dealerships3 contains 1 car and 2
bikes
37) You have a number and need to find out how many digits it contains.
How will you design your method to determine the total count of digits
accurately?
Sample Input/output 1:
Consider input1=12377.
Expected answer = 5.
Explanation: there are 5 digits‘ in the given number.
38) You have a number, and your challenge is to find the sum of its digits.
Write a method that adds up each digit in the number and gives you the
total. How will you craft your method to calculate this sum effectively?
39) You have a number, and your task is to repeatedly sum its digits until
you obtain a single-digit result. Write a method that performs this process
and returns the final single-digit sum. How will you design your method to
handle the iterative summing and achieve this ultimate single-digit result?
Sample Input/output 1:
Consider input1=12377.
Expected answer = 2.
Explanation: 1+2+3+7+7 = 20. Now, 20 is a two-digit number. So, again
apply the given logic on this number 20. Now, 2+0 =2. 2 is a single digit
number. So, stop and return the answer.
Sample Input/output 2:
Consider input1=9999.
Expected answer = 9.
Explanation: 9+9+9+9 = 36. Now, 36 is a two-digit number. So, again
apply the same logic on this number 36. Now, 3+6 =9. 9 is a single digit
number. So, stop and return the answer.
40) You have a number (n) and need to unravel its factorial. Write a method
that calculates the factorial of this number, which is the product of all
positive integers up to (n). Can you figure out how to find this magical
product?
41) Imagine you have two numbers, (n) and (r), and you need to uncover the
secret value of (nCr), which represents the number of ways to choose (r)
items from (n) items without regard to order. Write a method to calculate
this value. How will you solve this combinatorial puzzle?
// write code
}
Sample Input/Output-1:
nCr (5,2) --> 5! / ((3!) *(2!)) =10
Sample Input/Output-2:
nCr (5,1) --> 5! / ((4!) *(1!)) =5
42) You have a number, and you need to find the sum of the digits that are
prime numbers (2, 3, 5, or 7). Write a method to extract these prime digits
and calculate their sum. How will you design your method to identify and
total these prime digits from the given number?
43) You have a number and need to determine if it is a prime number, which
means it has no divisors other than 1 and itself. Write a method that tests
whether this number is prime. How will you design your method to uncover
if the number is truly a prime?
Explanation: A number is prime, if it has exactly 2 factors, which are 1 and the
number itself. Prime numbers have 1 and itself alone as factors.
Consider N =5. From 1 up to 5, inclusive of 5, we divide:
1 divides 5.
5 divides 5.
no other number divides 5.
So, number of factors = 2 (which are 1 and 5). Hence, 5 is PRIME
number.
Sample Input/Output-1:
isPrime (17) true because 17 is a prime number.
Sample Input/Output-2:
isPrime (15) false because 15 is not a prime number.
In the kingdom of numbers, you are given a range of integers and need to
determine how many of them are prime. Your quest is to count all the prime
numbers that lie within this specified range.
The Challenge:
1. Receive the Range: You are provided with two integers, start and end,
which define the inclusive range [start, end].
2. Identify Prime Numbers: Determine which numbers within this range are
prime.
3. Count the Primes: Calculate the total number of prime numbers in this
range.
4. Return the Count: Provide the number of primes found.
Rules to Follow:
Example:
Given Range: 10 to 50
o Primes in this Range: 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
o Total Count of Primes: 10
Can you solve the Prime Range Riddle and find out how many prime
numbers lie between the given start and end values?
45) You have a number and need to determine if it is a Strong number. A Strong
number is one where the sum of the factorials of its digits equals the number
itself. Write a method to check this property. How will you design your method to
compute the factorials of the digits, sum them up, and verify if the total matches
the original number?
Sample Input/output 2:
Consider n=145.
Individual digits are 1, 4, 5.
=> (1!) + (4!) + (5!) => 1+24+120= 125.
Here, Sum of factorial of digits is equal to given n. So, 145 is a Strong Number.
Sample Input/output 1:
Consider n=153. Number of digits in the given number = 3.
Individual digits are 1, 5, 3.
Sum = cube (1) + cube (5) + cube (3)
Sum = 1+125+27 = 153.
Here, Sum of cube of digits is equals to given number n. So, 153 is an Armstrong
Number.
Sample Input/output 2:
Consider n=123. Individual digits are 1, 2, 3.
==> cube (1) + cube (2) + cube (3)
==> 1+8+27 = 36.
Sum of cube of digits is NOT equal to given n. So, 123 is not an Armstrong
number.
Note: The actual ending value, end, will not to be included in the output. This is
similar to range function in python.
Sample Input/Output-1:
input (start=1, end=10, step=1)
answer = {1,2,3,4,5,6,7,8,9}
Sample Input/Output-2:
input (start=0, end=11, step=2)
answer = {0,2,4,6,8,10}
Output
4BA
Explanation
number1 = 451
number2 = 349
sum = 800
Output 1: 2
Explanation:
Adding ‗num 1‘ and ‗num 2‘ right-to-left results in 2 carries since (1+9) is 10. 1 is
carried and (5+4=1) is 10, again 1 is carried. Hence 2 is returned.
Sample Input2:
Number 1: 23
Number 2: 563
Sample Output2: 0 ( as there are no carries generated).
53. Create a method that determines if a given number is odd or even. If the
number is odd, the method should return "odd"; if it‘s even, it should return
"even". How will you write this method to check the number and provide the
correct result?
String isOddOrEven (int n) {
// write code
}
Sample Input/Output-2:
isMulOfX (10,3) --> false. Because, 10 not is a multiple of 3.
Sample Input/Output-3:
isMulOfX (10,10) --> true. Because, 10 is a multiple of 10.
55. Create a method that calculates the area of a square, given the side
length, a. If the length is negative, the method should return -1. How will you
implement this method to handle both positive and negative values and
compute the area correctly?
float areaOfSquare (int a) {
// code
}
56. Create a method to calculate the volume of a cube, where the side length
of the cube is given by (a). If (a) is negative, the method should return -1.
How will you design this method to handle the calculation and deal with
negative input values?
57. Create a method that calculates the area of a rectangle using its length
and breadth. If either the length or breadth is negative, the method should
return -1. How will you design this method to perform the area calculation
and handle negative inputs appropriately?
58. Create a method to calculate the area of a circle given its radius. If the
radius is negative, the method should return -1. How will you write this
method to compute the area correctly while handling negative radius values?
Hint: Area of Circle = PI*r*r, where PI = 3.14 and r is the given radius.
59. Create a method that calculates both simple interest and compound
interest given the principal (p), the number of years (n), and the rate of
interest (r). If any of these values are negative, the method should return -1.
How will you implement this method to compute the interests accurately and
handle invalid inputs?
60. Write a program to understand nested loops. Print the letters of the word
as shown below.
Example:
Sample input as ―possible‖
Sample output: p oo sss ssss iiiii bbbbbb lllllll eeeeeeee.
Explanation:
The ith character is printed ‗i‘ times.
That is, first character ‗p‘ is printed one time.
And, second character ‘o‘ is printed two times and so on.
You‘re supposed to reduce the size of this string using mathematical logic given
as in the example below:
Sample Input-1: aabbbbeeeeffggg
Sample Output -1: a2b4e4f2g3
You have write a method that accepts, a string which length is ―len‖, the
string has some ―#‖, in it you have to move all the hashes to the front of the
string and return the whole string back and print it.
65. Given a number as input, print the following pattern using ‗nested while‘
loops.
Example: INPUT: N=5
OUTPUT:
*
* A*
*B**
*C***
*D****
66. Given n as input, print the following pattern using ‗nested for loops‘
Example: INPUT: N=5
OUTPUT (print the Z like pattern using #):
#####
#
#
#
#####
Note that, the output totally has 5 rows and first row and last row are having same
number of hashes.
68. Write a method to print the following pattern, which looks a banner
format of letter ―C‖.
void print_C_BannerStars (int input1) {
// CODE
}
Sample Input/output 1:
Consider input1 is 5.
Sample output:
*1##*
**22$$**
***333##***
****4444$$*****
*****55555##*****
71) Write a method to print the following pattern. The given number n
represents the number of rows in the output.
Sample Input/output 1:
Consider input1 is 4.
Expected answer:
*
**
***
****
73) You need to write an efficient method to find the maximum value in a
given array without using `if` statements. How will you craft your method to
determine the highest value in the array using alternative techniques, such as
built-in functions or mathematical operations?
74) You need to write an efficient method to calculate the sum of all values
in a given array. How will you design your method to quickly and accurately
compute the total of the array's elements?
Lab Day 28
76) You need to write a method that searches for a value (x) in a sorted
array. If (x) is present in the array, the method should return `true`;
otherwise, it should return `false`. How will you design your method to
efficiently find (x) in the sorted array and determine its presence?
Sample Input/output 2:
Consider the sorted array [] = {15, 20, 25}
binarysearch (array, 40) should return false. Because, 40 is NOT
found in the array.
binarysearch (array, 43) should return false. Because, 43 is NOT
found in the array.
76A) Make all array elements equal just by using decrement by 1 operation
or increment by 1 operation. You need to make all the values equal to the
minimum value in the given array. And, return the total number of
operations needed to make all the elements equal as per the given
description.
Note: Return the answer, without actually performing the above operation.
Page / 30 of 80 Date : 02/06/2025 ,Version #3
int makeAllValuesEqual (int a []) {
//write code
}
Sample Input/output 1:
Input: {1, 2, 3}
Output: Minimum value in the array = 1
Total number of operations = absolute (2-1) + absolute (3-1) = 1+2 = 3.
Lab Day 29
77) Write a method to find the maximal subarray sum. Kadane's Algorithm
is an efficient method to find the maximum sum of a contiguous subarray
within a one-dimensional array of numbers. It's widely used in computer
science and competitive programming because of its simplicity and
efficiency. The algorithm operates in linear time, O(n), where n is the
number of elements in the array.
Sample Input/output 1:
Input Array: {5, 10, -15, 20, -30}
Output: 20.
Explanation:
Consider subarray with first 2 numbers. 5+10 =15.
Consider subarray with first 3 numbers. 5+10+ (-15) = 0.
Consider subarray with first 4 numbers. 5+10+ (-15) + 20 =20.
Consider subarray with first 5 numbers. 5+10+ (-15) + 20 + (-30) = -10.
In this case, an array consisting of first four numbers gives the maximum sub
array sum.
78. CAPEGEMINI 2023
You‘re given with the size of the array and an array of integers; print the number
of times each integer has occurred in the array.
Sample Input 1:
10
1233414512
Page / 31 of 80 Date : 02/06/2025 ,Version #3
Sample Output 1:
1 occurs 3 times
2 occurs 2 times
3 occurs 2 times
4 occurs 2 times
5 occurs 1 times
79. Write a method to find the number of longest increasing sub sequences
(LIS) found in the given array and return the same.
Lab Day 30
80. Write a method to find the number of longest decreasing sub sequence
(LDS) found in the given array and return the same. The LDS problem seeks
the longest subsequence where each element is smaller than the preceding
one, while maintaining the original order.
(Sub sequence #1: 11 1 -2 -3, sub sequence #2: 13 4 1, Sub sequence #3: 14 5 1 -
2)
Sample Input/output 1:
Input Array: {5, 10, 15, 20, 5, 30}
Output Array: {5, 10, 15, 20, 30}.
In this case, number 5 is repeated. So, it is removed.
Sample Input/output 2:
Input Array: {5, 10, 15}
Output Array: {5, 10, 15}.
In this case, all given numbers are unique. Hence, no number is
removed from the array.
Lab Day 31
82. ACCENTURE 2023
The method accepts two positive integers ‗r‘ and ‗unit‘ and a positive integer
array ‗arr‘ of size ‗n‘ as its argument ‗r‘ represents the number of rats present in
an area, ‗unit‘ is the amount of food each rat consumes and each ith element of
array ‗arr‘ represents the amount of food present in ‗i+1‘ house number, where 0
<= i.
Sample Output :8
Explanation:
1st hour: Entry: 7 Exit: 1
No. of guests on ship: 6
2nd hour: Entry: 0 Exit: 2
No. of guests on ship: 6-2=4
Hour 3: Entry: 5 Exit: 1
No. of guests on ship: 4+5-1=8
Hour 4: Entry: 1 Exit: 3
No. of guests on ship: 8+1-3=6
Hour 5: Entry: 3 Exit: 4
No. of guests on ship: 6+3-4=5
Hence, the maximum number of guests within 5 hours is 8.
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
9 8 7
6 5 4
3 2 1
Sample Output:
85. Write a method to multiply two matrices and return the resulting matrix.
Sample Input:
Matrix A:
1 2
3 4
Sample Output:
Resulting matrix = 19 22
43 50
86. Write a method to perform given operation on all elements of the matrix.
Modify entire matrix, using the given x value, based on operator given operator.
Input operator can be '+' or '-' or '*' or '/' or '%'.
Matrix A:
1 2
3 4
Sample Output:
Resulting matrix:
1+2=3 2+2=4
3+2=5 4+2=6
String Handling
87. Write a program to print ASCII values of all characters in the given
array.
void printASCII( int data[]) {
88. You need to write a method that calculates the sum of the ASCII values
of all characters in a given string. How will you design your method to iterate
through the string and compute the total ASCII sum for its characters?
Sample Input/Output-1:
asciiSum("AA") 130
Sample Input/Output-2:
asciiSum("aa") 97+97=194
90. You need to write a method that counts and prints the number of vowels
present in a given array of characters.
How will you design your method to identify vowels and tally their
occurrences?
Sample input:
char [] name = {‗a‘, ‗A‘, ‗z‘, ‘Z‘, ‗0‘};
Sample output:
Number of vowels = 2
Lab Day 34, 35
91. You need to write a method that identifies and prints the unique
consonants present in a given array of characters.
How will you design your method to filter out and display each distinct
consonant found in the array?
Sample input:
char [] name = {‗a‘, ‗A‘, ‗z‘, ‘Z‘};
Sample output:
Number of unique consonants = 2
92. You need to write a method that counts and prints the number of lower
case consonants and upper case vowels in a given array of characters.
How will you design your method to accurately tally and display the counts
for both consonants and vowels?
Sample input:char [] name = {‗a‘, ‗A‘, ‗z‘, ‘Z‘};
Sample output:
Number of lower case consonants = 2
Number of upper case vowels = 1
101. You need to write a method that sorts a given array in ascending order.
How will you design your method to arrange the elements from the smallest
to the largest value?
Sample input:
[4, 2, 7, 1, 9, 3]
Sample output:
[1, 2, 3, 4, 7, 9]
102. You need to write a method that sorts a given array in descending order.
How will you design your method to arrange the elements from the largest to
the smallest value?
Sample input: [4, 2, 7, 1, 9, 3]
Sample output: [9, 7, 4, 3, 2, 1]
103. You need to write a method that reverses the order of elements in a
given integer array. How will you design your method to flip the array so
that the last element becomes the first, and so on?
Sample input:
[4, 2, 7, 1, 9, 3]
Sample output:
[3, 9, 1, 7, 2, 4]
104. You need to write a method that toggles a given string, converting all
lowercase letters to uppercase and all uppercase letters to lowercase. How
will you design your method to transform each letter to its opposite case
while leaving non-letter characters unchanged?
Sample input= ―welcoME‖
Sample output =‖WELCOme‖
107. You‘ve stumbled upon a mysterious string, and you need to determine if
it reads the same forward and backward, ignoring case differences. A
palindrome is a sequence of characters that reads the same backward as
forward.
Your Task:
Write a method to check whether the given string is a palindrome.
The check should be case insensitive, meaning 'A' should be treated as equal to 'a',
'B' as 'b', and so on.
Example:
Input: "Racecar"
Output: True (since "racecar" reads the same forward and backward)
Lab Day 39
108. The Mirror Mystery
You‘ve encountered a cryptic message that you suspect might be a palindrome—a
sequence that reads the same forwards and backwards. However, this message is a
bit tricky, as its case-sensitive, and you need to solve the mystery by treating it
case-insensitively.
Your Challenge:
Decrypt the Message: You are given a string, and you need to check if it‘s a
palindrome.
Case Insensitivity: Remember, 'A' should be considered the same as 'a', 'B' as 'b',
and so on.
Comparison: The string should read the same forwards and backwards, ignoring
the case of the letters.
Example:
Input: "Madam"
Output: True (since "madam" reads the same forward and backward)
Input: "OpenAI"
Output: False (since "openai" does not read the same backward)
Can you solve the Mirror Mystery and confirm whether the given message is a
palindrome?
In a land of numerical mysteries, you‘ve discovered an ancient code that may hold
a hidden palindrome! A palindrome is a sequence that reads the same forwards
and backwards. Your task is to unravel the mystery of this number.
The Challenge:
1. Decrypt the Number: You are given a number, and you need to determine
if it is a palindrome.
2. Palindrome Check: A number is a palindrome if it remains the same when
its digits are reversed.
Your Mission:
Example:
Input: 12321
Output: True (since "12321" reads the same forward and backward)
Input: 12345
Output: False (since "12345" does not read the same backward)
Can you solve the Number Palindrome Quest and find out if the number is indeed
a palindrome?
You‘ve stumbled upon a magical string that holds many hidden secrets. Your
mission is to uncover all the possible substrings within this string. A substring is
any sequence of characters that appears consecutively within the original string.
The Challenge:
1. Discover the Substrings: Your task is to write a method that will reveal
every possible substring of the given string.
2. Print Each Substring: Display each substring, ensuring that no possible
combination is left out.
Can you crack the code and unveil all the hidden substrings within the string?
Lab Day 40
111. The Reverse Array Mystery
The Challenge:
Example:
Can you solve the Reverse Array Mystery and unveil the string‘s reversed
character array?
The Challenge:
Example:
Can you crack the code and transform the character array into its string form?
Lab Day 41
113. The Comma-Separated Character Transformation
The Challenge:
1. Read the Input String: You are given a string of characters separated by
commas.
2. Transform the Characters: Apply a specific transformation to each
character.
3. Return the Result: Output the transformed characters as a new string.
Transformation Rules:
In the realm of string mysteries, you are tasked with extracting crucial characters
from a given string. Your mission is to retrieve three special characters: the first,
the middle, and the last.
The Challenge:
Rules to Follow:
If the string has an odd length, the middle character is the exact center.
If the string has an even length, you can choose either of the two central
characters or apply your own rule.
Example:
Can you solve the Character Extraction Challenge and unveil the first, middle,
and last characters from the string?
115. In the realm of strings, you have been tasked with extracting a special
trio of characters from the heart of a string. Your mission is to find and
reveal the three characters located in the center of the string.
The Challenge:
1. Locate the Middle Trio: Write a method to identify and extract the three
characters that are centered within the string.
2. Handle Different Lengths: If the string has fewer than three characters,
you may need to adjust your approach accordingly.
Rules to Follow:
For strings with an odd length of 5 or more, the middle trio consists of the
three characters around the exact center.
For strings with an even length of 6 or more, you can either choose the
three characters around the left center or the right center, or apply your own
consistent rule.
Example:
Can you solve the Middle Trio Extraction and reveal the three characters that lie
at the center of the string?
You‘ve come across a string that holds a mix of characters, and your task is to
uncover the number of uppercase letters hidden within
// write code
}
The Challenge:
1. Count the Uppercase Letters: Write a method to scan through the given
string and count how many of the characters are uppercase letters.
2. Reveal the Count: Return the total number of uppercase letters found.
Rules to Follow:
Example:
Can you crack the Uppercase Count Quest and find out how many uppercase
letters are in the string?
In the land of strings, your task is to uncover how many lowercase letters are
hidden within a given string. The string is filled with various characters, but you
need to focus solely on those that are lowercase letters.
The Challenge:
1. Count the Lowercase Letters: Write a method to explore the given string
and determine how many characters are lowercase letters.
2. Reveal the Count: Return the total number of lowercase letters discovered.
Rules to Follow:
Example:
Can you solve the Lowercase Letter Count Challenge and determine how many
lowercase letters are in the string?
In a realm filled with strings of text, you are tasked with discovering how many
words are hidden within a given string. The words are neatly separated by spaces,
and your mission is to count them accurately.
The Challenge:
1. Count the Words: Write a method to scan through the given string and
determine how many distinct words are present.
2. Handle Spaces: Words are separated by spaces, and any extra spaces at the
beginning, end, or between words should be handled properly.
Rules to Follow:
Example:
Given String: "The quick brown fox jumps over the lazy dog"
o Words: The, quick, brown, fox, jumps, over, the, lazy, dog
o Expected Output: 9
Given String: " Hello world "
o Words: Hello, world
o Expected Output: 2
Can you crack the Word Count Conundrum and determine the total number
of words in the string?
The Challenge:
1. Extract the Words: Write a method to break down the given sentence into
individual words.
2. Return as Array: Provide the words in the form of a String array.
Rules to Follow:
Example:
Given Sentence: "The quick brown fox jumps over the lazy dog"
o Resulting Array: ["The", "quick", "brown", "fox", "jumps", "over",
"the", "lazy", "dog"]
Given Sentence: " Hello world "
o Resulting Array: ["Hello", "world"]
Can you complete the Word Extraction Expedition and return all the words from
the sentence as a String array?
The Challenge:
Rules to Follow:
Characters are considered repeated if they appear more than once in the
string.
Ensure that each repeated character is listed only once in the result.
The order of repeated characters should be preserved as they first appear in
the string.
Example:
Can you solve the Repeated Characters Riddle and uncover all the characters that
are repeated in the string?
Sample Input/output 2:
Input: "RRR"
Output: "R"
Here, character 'R' is the only repeated char. Hence, "R" is included in output.
In the land of strings, there exists a string filled with unnecessary whitespace that
you need to clear away. Your mission is to remove all spaces and return the string
in its cleanest form.
The Challenge:
Rules to Follow:
Can you complete the Whitespace Removal Challenge and return the string with
all whitespace removed?
Sample Input/output 1:
input1 = " Welcome to Java "
answer1 = "WelcometoJava"
Sample Input/output 2:
input2 = " Wel come "
answer2 = "Welcome"
In the world of mixed characters and numbers, you have a string that contains
various types of characters. Your quest is to uncover and extract only the digits
from this string and return them as a new string.
The Challenge:
1. Extract the Digits: Write a method to sift through the given string and pick
out all the digits.
2. Return the Digits: Provide the extracted digits concatenated together as a
single string.
Rules to Follow:
Can you solve the Digit Extraction Quest and extract all the digits from the string,
returning them as a single concatenated string?
Sample Input/output 1:
Consider input1="V12t34u5"
Expected answer = 12345.
Explanation: We are extracting the digits alone and returning them as
answer.
Sample Input/output 2:
Consider input1="Vtu17788"
Expected answer = 17788
Explanation: We are extracting the digits alone and returning them as
answer.
In the land of numbers, you have a number that may contain some digits
appearing more than once. Your task is to find out how many different digits are
duplicated within this number.
The Challenge:
Rules to Follow:
Digits are considered duplicated if they appear more than once in the
number.
Each duplicated digit should be counted only once.
Ignore any non-digit characters and focus only on the digits of the number.
Can you solve the Duplicate Digit Dilemma and count the number of distinct
digits that are duplicated in the number?
Sample Input/output 1:
Consider input1=12377.
Expected answer = 1.
Explanation: There is one duplicate digit in the given number.
Sample Input/output 2:
Consider input1=433377.
Expected answer = 2.
Explanation: There are 2 duplicate digits in the given number. 3 and 7 are
the duplicate digits.
In a string filled with characters, you need to uncover a special character that
appears only once. Your mission is to identify the first character that is unique
within the string.
The Challenge:
Rules to Follow:
Can you solve the Unique Character Search and find the first unique
character in the string?
Sample Input/output 1:
Consider the string string1="RajaRam Mohan Roy";
In the above string, 'j','h','n', 'y' is not repeated. And, 'j' is the first unique
char. So, the answer is 'j'.
Sample Input/output 2:
Consider the string str="1234123";
In the above string,'1','2' and '3' are repeated. '4' is not repeated. So, the
answer is '4'.
In a sentence filled with various letters, you need to embark on a quest to extract
only the vowels. Your mission is to filter out the vowels (both uppercase and
lowercase), concatenate them, and return the result as a single string.
The Challenge:
1. Extract the Vowels: Write a method to identify and extract all the vowels
from the given sentence.
2. Concatenate the Vowels: Combine these vowels into a single string,
preserving their order as they appear in the original sentence.
Rules to Follow:
Can you complete the Vowel Extraction Expedition and return the concatenated
string of vowels from the sentence?
Sample Input/output 1:
input1= " I am Java "
answer1= "Iaaa"
Explanation: Only the vowels are extracted from each word and we concat all of
them and return the answer.
Sample Input/output 2:
input2 = "Wel come "
answer2 = "eoe"
Explanation: There are 2 words in given string. {"Wel‖, ―come"}
Vowels in ("Wel") = "e"
Vowels in ("come") = "oe"
Finally, we concat all the above and return the answer.
In a sentence brimming with words, you need to reverse each individual word and
then concatenate them to form a new string. Your challenge is to manipulate each
word while maintaining their original order.
The Challenge:
1. Reverse Each Word: Write a method to reverse every word in the given
sentence.
2. Concatenate the Reversed Words: Combine these reversed words into a
single string, preserving their order in the sentence.
Rules to Follow:
Can you solve the Reversed Words Challenge and return the concatenated string
of reversed words from the sentence?
Sample Input/output 1:
input1 = " I am Java "
answer1 = "ImaavaJ"
The Challenge:
1. Validate the Email: Write a method to check if the provided email address
conforms to the standard email format.
2. Return the Result: Return true if the email is valid, and false if it is
invalid.
Rules to Follow:
In the digital domain, you need to determine whether a given URL is valid. Your
mission is to verify if the URL conforms to the standard format and return the
appropriate result.
The Challenge:
1. Validate the URL: Write a method to check if the provided URL adheres
to a valid format.
2. Return the Result: Return true if the URL is valid, and false if it is invalid.
Rules to Follow:
Can you solve the URL Validation Quest and determine if the given URL is
valid or invalid?
Lab Day 49
The Binary number system only uses two digits, 0 and 1 and number system can
be called binary string. You are required to implement the following method:
Sample Output:1
131. Write a program to count the number of command line arguments passed.
132. Write a program that gets a number as a command line input and finds the
square of that number using Integer.parseInt (String arg) method.
In the realm of binary operations, you have two numbers and need to uncover the
result of their bitwise AND operation. Your task is to compute this result and
present it.
The Challenge:
Rules to Follow:
The bitwise AND operation compares each bit of the numbers and returns a
new number where a bit is set to 1 only if both corresponding bits of the
original numbers are 1.
For example, given numbers 12 (which is 1100 in binary) and 7 (which is
0111 in binary), the result of the bitwise AND operation will be 4 (which is
0100 in binary).
Example:
Can you solve the Bitwise AND Conundrum and find the result of the bitwise
AND operation for the given numbers?
In the realm of binary operations, you have two numbers and need to compute the
result of their bitwise OR operation. Your task is to perform this operation and
reveal the outcome.
The Challenge:
Rules to Follow:
The bitwise OR operation compares each bit of the numbers and returns a
new number where a bit is set to 1 if either of the corresponding bits of the
original numbers is 1.
For example, given numbers 12 (which is 1100 in binary) and 7 (which is
0111 in binary), the result of the bitwise OR operation will be 15 (which is
1111 in binary).
Example:
Can you solve the Bitwise OR Challenge and find the result of the bitwise OR
operation for the given numbers?
In the world of binary operations, your mission is to compute the result of the
bitwise XOR operation between two given numbers. Your task is to perform this
operation and reveal the final outcome.
The Challenge:
Rules to Follow:
The bitwise XOR (exclusive OR) operation compares each bit of the
numbers and returns a new number where a bit is set to 1 if exactly one of
the corresponding bits of the original numbers is 1.
For example, given numbers 12 (which is 1100 in binary) and 7 (which is
0111 in binary), the result of the bitwise XOR operation will be 9 (which is
1001 in binary).
Example:
Can you solve the Bitwise XOR Expedition and find the result of the bitwise
XOR operation for the given numbers?
In the land of binary numbers, you have a number that you need to analyze. Your
task is to uncover how many 1s are present in its binary representation.
The Challenge:
Rules to Follow:
Convert the integer to its binary form, which will be a string of 0s and 1s.
Count how many 1s are present in this binary string.
For example, if the given number is 29, its binary equivalent is 11101,
which contains 4 ones.
Example:
Given Number: 29
o Binary Equivalent: 11101
o Number of 1‘s: 4
Given Number: 15
o Binary Equivalent: 1111
o Number of 1‘s: 4
Can you solve the Binary Ones Count Challenge and determine the number of 1s
in the binary representation of the given number?
In the realm of binary numbers, you need to uncover the 1‘s complement of a
given integer. Your task is to compute the complement by flipping all the bits of
its binary representation.
The Challenge:
Rules to Follow:
Convert the integer to its binary form. Ensure that the binary string has the
same length as the original binary representation.
Flip all bits (0 to 1 and 1 to 0).
Convert the resulting binary string back to a decimal integer.
Note: For simplicity, if the input number is negative, compute the 1's
complement for its positive magnitude and then apply the sign if needed.
Example:
Given Number: 5
o Binary Equivalent: 101
o 1‘s Complement: 010 (flipping the bits)
o Decimal Result: 2
Given Number: 9
o Binary Equivalent: 1001
o 1‘s Complement: 0110 (flipping the bits)
o Decimal Result: 6
Can you solve the 1‘s Complement Quest and determine the 1‘s complement of
the given number?
In the binary world, you are tasked with modifying a number‘s binary
representation. Your mission is to set the n-th bit from the left to 1 and then print
the updated number.
The Challenge:
Rules to Follow:
Example:
Can you solve the Bit Setting Challenge and determine the new number after
setting the n-th bit from the left to 1?
In the binary world, you have a number and need to modify its binary
representation. Your mission is to reset the n-th bit from the left to 0 and then
print the updated number.
The Challenge:
Rules to Follow:
Example:
Can you solve the Bit Resetting Quest and determine the new number after
resetting the n-th bit from the left to 0?
The method accepts two positive integers ‗r‘ and ‗unit‘ and a positive integer array ‗arr‘ of size
‗n‘ as its argument ‗r‘ represents the number of rats present in an area, ‗unit‘ is the amount of
food each rat consumes and each ith element of array ‗arr‘ represents the amount of food
present in ‗i+1‘ house number, where 0 <= i
Note:
Sample Input:
7
2
8
28357412
Sample Output: 4
Explanation:
Total amount of food required for all rats = r * unit ; which is = 7 * 2 = 14.The amount of food
in 1st houses = 2+8+3+5 = 18. Since, amount of food in 1st 4 houses is sufficient for all the
rats. Thus, output is 4.
The Binary number system only uses two digits, 0 and 1 and number system can be called
binary string. You are required to implement the following method:
The method accepts a string str as its argument. The string str consists of binary digits separated
with an alphabet as follows:
You are required to calculate the result of the string str, scanning the string to right taking one
operation at a time, and return the same.
Note:
Sample Output:1
Explanation: The alphabets in str when expanded becomes ―1 XOR 0 XOR 1 XOR 1 AND 0
OR 1‖, result of the expression becomes 1, hence 1 is returned.
A carry is a digit that is transferred to left if sum of digits exceeds 9 while adding two numbers
from right-to-left one digit at a time
You are required to implement the following method.
Int NumberOfCarries(int num1 , int num2);
The methods accepts two numbers ‗num1‘ and ‗num2‘ as its arguments. You are required to
calculate and return the total number of carries generated while adding digits of two numbers
‗num1‘ and ‗ num2‘.
Assumption: num1, num2>=0
Input 1: 451
349
Output 1: 2
Explanation:
Adding ‗num 1‘ and ‗num 2‘ right-to-left results in 2 carries since ( 1+9) is 10. 1 is carried and
(5+4=1) is 10, again 1 is carried. Hence 2 is returned.
Sample Input2:
Num 1: 23
Num 2: 563
Sample Output2: 0
You‘re supposed to reduce the size of this string using mathematical logic given as in the
example below:
You have write a method that accepts, a string which length is ―len‖, the string has some ―#‖, in
it you have to move all the hashes to the front of the string and return the whole string back and
print it.
You‘re given with the size of the array and an array of integers; print the number of times each
integer has occurred in the array.
Sample Input 1:
10
1233414512
Sample Output 1:
1 occurs 3 times
2 occurs 2 times
3 occurs 2 times
4 occurs 2 times
5 occurs 1 times
Write a method to solve the following equation a3 + a2b + 2a2b + 2ab2 + ab2 + b3. Write a
program to accept three values in order of a, b and c and get the result of the above equation.
Problem Statement – A method is there which tells how many dealerships there are and the
total number of cars in each dealership. Your job is to calculate how many tyres would be there
in each dealership and find the total number of tyres.
Input
42
40
12
Output
44
Explanation:
There are total 3 dealerships: Dealerships1 contains 4 cars and 2 bikes. Dealerships2 contains 4
cars and 0 bikes. Dealerships3 contains 1 car and 2 bikes
CTS -1:
CTS 2:
Write a Program to Find the Roots of a Quadratic Equation. If roots are possible, then,
there are four cases to be handled as explained below:
Case1) Roots are real and different. For this case, print ―RD‖.
Case2) Roots are real and same. For this case, print ―RS‖.
Case3) Roots are complex. For this case, print ―RC‖.
Case4) In case of wrong inputs, print ―Invalid‖.
CTS -3 :
Problem Statement – Ritik wants a magic board, which displays a character for a corresponding
number for his science project. Help him to develop such an application.
For example when the digits 65,66,67,68 are entered, the alphabet ABCD are to be displayed.
Sample Input 1:
65-A
66-B
67-C
68-D
Problem Statement – Chaman planned to choose a four digit lucky number for his
car. His lucky numbers are 3,5 and 7. Help him find the number, whose sum is
divisible by 3 or 5 or 7. Provide a valid car number, Fails to provide a valid input
then display that number is not a valid car number.
Note : The input other than 4 digit positive number[includes negative and 0] is
considered as invalid.
InfyTQ question 1
Write a function to check whether three given numbers can form the sides of a triangle.
Hint: Three numbers can be the sides of a triangle if none of the numbers are greater than
or equal to the sum of the other two numbers.
InfyTQ question 2
Write a program to solve a classic ancient Chinese puzzle. We count 35 heads and 94 legs
among the chickens and rabbits in a farm. How many rabbits and how many chickens do
we have?
InfyTQ question 3
The road transport corporation (RTC) of a city wants to know whether a particular bus-
route is running on profit or loss. Assume that the following information are given:
Price per litre of fuel = 70
Mileage of the bus in km/litre of fuel = 10
Price(Rs) per ticket = 80
The bus runs on multiple routes having different distance in kms and number of
passengers.
Write a function to calculate and return the profit earned (Rs) in each route. Return -1 in
case of loss.
InfyTQ question 4
Given a string containing uppercase characters (A-Z), compress the string using
Run Length encoding. Repetition of character has to be replaced by storing the length of
that run. Write a function which performs the run length encoding for a given String and
returns the run length encoded String.