java week 1 keys
java week 1 keys
Q1.
Problem Statement
At GreenLeaf Grocery, Mr. Thompson asks Jamie, a student, to create a tool for checking product details.
Jamie should create a tool that takes a product code, price and stock status (boolean) as input and displays
the details in a clear comma-separated format.
Input Format
The first line of input consists of an integer, representing the product code.
The second line consists of a float value, indicating the price of the product.
The third line consists of a boolean value, indicating the stock status.
Output Format
The output prints the product code, price and availability status of the product.
Separate the values by a comma.
Refer to the sample output for the exact text and format.
Constraints
1 ≤ product code ≤ 106
1.0 ≤ price ≤ 1000.0
Sample Input Sample Output
12345
21.95
true
Product Code: 12345, Price: $21.95, Availability: true
Sample Input Sample Output
67890
89.59
false
Product Code: 67890, Price: $89.59, Availability: false
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement
Alex wants to congratulate Jorden on his impressive play count for his favourite Arijit Singh song. To do
this, Alex decides to write a program. The program should print, "Wow Jorden! You played your favourite
song X times!" where X is the play count.
Input Format
The first line of input consists of a string, representing Jorden’s favourite Arijit Singh song.
The second line consists of an integer, representing the number of times it has been played.
Output Format
The output prints the congratulatory message for Jorden.
Refer to the sample output for the exact text and format.
Constraints
1 ≤ song play count ≤ 5000
Sample Input Sample Output
Apna Bana Le
345
Wow Jorden! You played your favourite song 345 times!
Sample Input Sample Output
Tum Hi Ho
798
Wow Jorden! You played your favourite song 798 times!
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement
Henry is actively participating in a marathon and is currently in the process of crafting a program to
determine the amount of time he will require to complete the entire marathon.
Your task is to write a program to calculate the time he will be required to complete the marathon.
Input Format
The first line of input consists of a double value, representing the total distance of the marathon.
The second line consists of a double value, representing Henry's speed.
Output Format
The output prints "Henry will complete the marathon in X hours." where X is a double value representing
the time taken to complete the marathon.
Sheela is a software developer working on a project that involves optimizing data manipulation operations.
She is currently working on a program that involves bitwise left-shifting of integer values.
To help her with this task, you need to design a program that takes an integer input from the user, left-shifts
it by 2 bits, and then displays the result.
Input Format
The input consists of an integer value X.
Output Format
The output prints an integer representing the result of left-shifting the input integer by 2 bits.
You are tasked with creating a program that calculates and displays various mathematical properties of a
given number. The program should take an integer input and compute the square and cube of that number,
presenting the results in a clear format.
Input Format
The input consists of an integer N.
Output Format
The first line of output displays "Square: " followed by the square value of N.
The second line of output displays "Cube: " followed by the cube value of N.
Solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Product Code: " + productCode + ", Price: $" +price + ", Availability: " + inStock);
}
}
Q2
Solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Wow Jorden! You played your favourite song " + playCount + " times!");
}
}
Solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double totalDistance = scanner.nextDouble();
double speed = scanner.nextDouble();
double time = totalDistance / speed;
scanner.close();
}
}
Solution
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int x;
Scanner sc=new Scanner(System.in);
x=sc.nextInt();
int result = x << 2;
System.out.println(result);
}
}
Solution
import java.util.Scanner;
class SquareCube {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int num;
num = sc.nextInt();
sc.close();
}
}
CMREC_Java_Unit 1_CY_Datatypes_Variables_Operators
Q1.
Problem Statement
Saran is exploring operator precedence and wants to create a program that calculates a result using user
input for four integer values: x, y, z, and w.
Assist Saran in completing the program by creating the expression while ensuring proper adherence to the
rules of operator precedence.
Input Format
The input consists of four space-separated integers x, y, z and w.
Output Format
The output prints "Result: " followed by an integer, representing the result of the expression.
A baker has a cupcake recipe that yields 12 cupcakes, with the following ingredient quantities: 2.5 cups of
flour, 1 cup of sugar, and 0.5 cups of butter.
Write a program to calculate the amounts of flour, sugar, and butter needed for a different number of
cupcakes. Provide the ingredient quantities for a specified number of cupcakes, maintaining the original
proportions of the recipe.
Input Format
The input consists of an integer n, representing the number of cupcakes.
Output Format
The first line prints "Flour: X cups" where X represents the amount of flour required for n cupcakes, as a
double value rounded to two decimal places.
The second line prints "Sugar: Y cups" where Y represents the amount of Sugar required for n, as a double
value rounded to two decimal places.
The third line prints "Butter: Z cups" where Z represents the amount of flour required for n, as a double
value rounded to two decimal places.
Emily wants to calculate the download time for a file, given its size in megabytes (MB) and download speed
in megabits per second (mbps), considering there are 8 megabits in 1 megabyte.
Your task is to write a program for Emily to calculate and display the time taken to download the file in
hours, minutes, and seconds format.
Example
Input:
MB = 800
mbps = 40
Output:
Download Time: 0 hours, 2 minutes, and 40 seconds
Explanation:
1. Convert the file size to bits (800 MB * 8 bits/byte = 6400 megabits) and divide it by the download speed
(6400 mbps / 40 mbps = 160 seconds).
2. Now, convert the download time in seconds to hours, minutes and seconds: 160 seconds is equal to 2
minutes and 40 seconds.
So, the download time is 0 hours, 2 minutes and 40 seconds.
Input Format
The first line of input consists of an integer N, representing the file size in megabytes (MB).
The second line consists of an integer S, representing the network speed in megabits per second(mbps).
Output Format
The output prints "Download Time: X hours, Y minutes, and Z seconds", where X, Y and Z are integers
representing the hours, minutes and seconds respectively.
Solution
import java.util.Scanner;
int x = scanner.nextInt();
int y = scanner.nextInt();
int z = scanner.nextInt();
int w = scanner.nextInt();
scanner.close();
}
}
Q2
Solution
import java.util.Scanner;
int x;
double flourPer12Cupcakes = 2.5;
double sugarPer12Cupcakes = 1.0;
double butterPer12Cupcakes = 0.5;
x = scanner.nextInt();
scanner.close();
}
}
Q3
Solution
import java.util.Scanner;
fileSizeMB = scanner.nextInt();
downloadSpeedMbps = scanner.nextInt();
System.out.print("Download Time: " + hours + " hours, " + minutes + " minutes, and " + seconds + "
seconds");
scanner.close();
}
}
CMREC_Java_Unit
1_PAH_Datatypes_Variables_Operators
Q1.
Problem Statement
Ramanan is an aspiring meteorologist who is working on a weather application. He needs your help to create
a program that converts temperatures from Fahrenheit to Celsius.
Amy is a mathematics teacher, and she wants to teach her students how to calculate the area and perimeter
of a circle.
To assist her students in understanding the concept better, she asks you to create a Java program that takes
the radius of a circle as input and calculates both the area and perimeter of the circle.
Formula:
1. Area of a circle = π * (radius2).
2. Perimeter of a circle = 2 * π * radius.
3. Assume π = 3.14.
Input Format
The input consists of a double value R, representing the radius of the circle.
Output Format
The first line of the output prints "Area of the circle: " followed by a double value representing the area of
the circle rounded off to two decimal places.
The second line prints "Perimeter of the circle: " followed by a double value representing the perimeter of
the circle rounded off to two decimal places.
Q1
Solution
import java.util.Scanner;
scanner.close();
}
}
Q2
Solution
import java.util.Scanner;
scanner.close();
}
}
CMREC_Java_Unit 1_COD_Control
Statements_Arrays
Q1.
Problem Statement
John is a fitness trainer and needs to calculate the Body Mass Index (BMI) for his clients to assess their
health status. Write a program for him that takes the weight in kilograms and height in meters of a client as
input, calculates their BMI, and determines if they fall within the healthy range.
Arun is working on a project to automate the process of determining whether a student has passed or failed
based on their subject marks.
He aims to create a simple program that takes positive integers as marks for five subjects from the user. If
the average of the marks is greater than or equal to 50, the student has passed the exam. Else, the student has
failed.
Subha is tasked with developing a program to analyze and categorize a large dataset of numerical data
points.
As a part of her program, she needs to identify and extract all the even numbers from the dataset, which
ranges from 2 to a specified integer(inclusive).
James, a mathematics teacher, is developing a programming exercise to help his students practice
continuously summing the digits of a number until it becomes a single-digit integer.
He wants to create a simple program using a 'while' loop that takes a positive integer input and generates the
final single-digit result.
Input Format
The input consists of a positive integer n.
Output Format
The output prints "The single-digit sum of n is Y." where n is the input integer and Y is its single-digit sum.
John is working on a program to calculate the difference between the first and last elements of an array.
He needs your assistance in creating a program that takes the size and elements of an array as input and
outputs the difference between the first and last elements.
Input Format
The first line of input is an integer N, representing the size of the array.
The second line consists of N space-separated integers, representing the elements of the array.
Output Format
The output displays a single integer representing the difference between the first and last elements of the
array.
Imagine you are developing a utility that analyzes data stored in an integer array.
Your program needs to provide valuable insights into the dataset, and one specific requirement is to count
the number of elements that are multiples of 3. This feature will help the users understand how many values
in the dataset are multiples of 3.
Input Format
The first line of input consists of an integer N, representing the number of data stored in the array.
The second line consists of N space-separated integers, representing the data.
Output Format
The output prints the count of data that are multiples of 3.
Constraints
The given test cases fall under the following constraints:
1 ≤ N ≤ 20
1 ≤ data ≤ 104
Sample Input Sample Output
4
3 6 9 12
4
Sample Input Sample Output
4
1247
0
Sample Input Sample Output
6
9 15 21 85 43 84
4
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q7.
Problem Statement
Monica is interested in finding a treasure but the key to opening is to get the sum of the main diagonal
elements and secondary diagonal elements. Write a program to help Monica find the diagonal sum of a
square 2D array.
Note: The main diagonal of the array consists of the elements traversing from the top-left corner to the
bottom-right corner. The secondary diagonal includes elements from the top-right corner to the bottom-left
corner.
Input Format
The first line of input consists of an integer N, representing the number of rows and columns.
The following N lines consist of N space-separated integers, representing the 2D array elements.
Output Format
The first line of output prints "Sum of the main diagonal: " followed by the sum of the main diagonal.
The second line prints "Sum of the secondary diagonal: " followed by the sum of the secondary diagonal.
Write a program that takes the dimensions and details of the original matrix representing city blocks and
outputs its transposed version.
Q1
Solution
import java.util.Scanner;
String healthStatus;
if (bmi >= 18.5 && bmi <= 24.9) {
healthStatus = "Healthy Range";
} else {
healthStatus = "Not in Healthy Range";
}
Q2
Solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Q3
Solution
import java.util.Scanner;
Q4
Solution
import java.util.Scanner;
int n = input;
scanner.close();
}
}
Q5
Solution
import java.util.Scanner;
System.out.println(result);
}
}
Q6
Solution
import java.util.Scanner;
class CountMultiplesOf3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] arr = new int[size];
int count = 0;
System.out.println(count);
}
}
Q7
Solution
import java.util.Scanner;
class DiagonalSumOfSquareArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i][i];
}
int sum1 = 0;
for (int i = 0; i < arr.length; i++) {
sum1 += arr[i][arr.length - 1 - i];
}
scanner.close();
}
}
Q8
Solution
import java.util.Scanner;
int n = scanner.nextInt();
int m = scanner.nextInt();
scanner.close();
}
}
CMREC_Java_Unit 1_CY_Control Statements_Arrays
Q1.
Problem Statement
Ravi wants to estimate the total utility bill for a household based on the consumption of electricity, water,
and gas.
Write a program to calculate the total bill using the following criteria:
1. The cost per unit for electricity is 0.12, for water is 0.05, and for gas is 0.08.
2. A discount is applied to the total cost based on the following conditions:
3. If the total cost is 100 or more, a 10% discount is applied.
4. If the total cost is between 50 and 99.99, a 5% discount is applied.
5. No discount is applied if the total cost is less than 50.
The program should output the total bill after applying the discount with two decimal places.
Input Format
The input consists of three double values, representing the number of units consumed for electricity, water,
and gas respectively.
Output Format
The output prints a double value, representing the total bill after applying the discount, formatted to two
decimal places.
Joe has a favourite number, let's call it X. He wants to check if X is divisible by the sum of its digits. If it is,
he considers it a lucky number. If not, he wants to find the closest smaller lucky number. Joe has challenged
his friends to solve this puzzle at his birthday party.
Your task as one of Joe's friends is to help him with this challenge using the 'while' loop. You need to write
a program that takes Joe's favourite number X as input, and then:
1. Check if X is a lucky number (divisible by the sum of its digits).
2. If it is a lucky number, congratulate Joe and let him know.
3. If it is not a lucky number, find and display the closest smaller lucky number.
Input Format
The input consists of an integer X, representing Joe's favourite number.
Output Format
If X is a lucky number, then the output must be in the format: "X is divisible by the sum of its digits."
If not, then the output must be in the format:
"X is not divisible by the sum of its digits.
The closest smaller number that is divisible: Y",
where X is the entered number and Y is the closest number.
Arun is given an array of integers. His task is to find the product of elements at odd positions in the array.
Write a program to help Arun that takes an integer N as input, representing the size of the array, followed by
N integers representing the elements of the array. The program should then calculate and print the product of
elements at odd positions.
Input Format
The first line of input consists of an integer N, representing the number of elements in the array.
The second line consists of N space-separated integers, representing the elements of the array.
Output Format
The output prints the product of elements at odd positions. Position starts from 1.
He needs to create a program to automate this task. The program should take an array of integers and a
target value as input and then find and display all pairs of integers in the array that add up to the given
target.
Sarah is an accountant working with a large dataset. She has a table with data organized into rows and
columns. She needs to calculate the sum of each row and display it as a new column. This will help her
perform row-wise calculations more efficiently.
Help her in printing a new column that contains the sum of each respective row to her dataset.
Input Format
The first line of input consists of two space-separated integers N and M, representing the number of rows
and columns in the dataset, respectively.
The following N lines consist of M space-separated integers, representing the values in each row of the
dataset.
Output Format
The output prints N lines representing a column containing the sum of each respective row.
Q1
Solution
import java.util.Scanner;
class UtilityBillEstimator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double totalBill = 0;
if (totalCost >= 100) {
totalBill = totalCost * 0.9;
} else if (totalCost >= 50) {
totalBill = totalCost * 0.95;
} else {
totalBill = totalCost;
}
System.out.printf("%.2f", totalBill);
scanner.close();
}
}
Q2
Solution
import java.util.Scanner;
int sumOfDigits = 0;
int originalNumber = number;
if (isDivisible) {
System.out.println(originalNumber + " is divisible by the sum of its digits.");
} else {
int closestSmallerNumber = -1;
number = originalNumber - 1;
Q3
Solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int product = 1;
System.out.println(product);
scanner.close();
}
}
Q4
Solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
Q5
Solution
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int M = scanner.nextInt();
scanner.close();
}
}
CMREC_Java_Unit 1_PAH_Control Statements_Arrays
Q1.
Problem Statement
Mithun is fascinated by perfect numbers, and he is trying to identify whether a given number is perfect or
not. A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself.
Write a program to help Mithun determine whether a given number is a perfect number or not.
For example,
6 is the first perfect number
The proper divisors of 6 are 1, 2, and 3. The sum of its proper divisors is 1 + 2 + 3 = 6. Hence, 6 is a perfect
number.
Input Format
The input consists of a single integer, n, representing the number to be checked for perfection.
Output Format
The output displays whether it is a perfect number or not in the following format:
"[n] is a perfect number" if it's a perfect number, otherwise, prints "[n] is not a perfect number"
Henry is working on a program to find the count of elements greater than the average of an array.
He needs your help to create a program that takes input for an array, calculates the average of its elements,
and then counts how many elements are greater than this average.
Input Format
The first line of the input is an integer n, representing the number of elements in the array.
The second line of input consists of n space-separated integers, the elements of the array.
Output Format
The output displays "Count of elements greater than the average: " followed by the count of elements greater
than the calculated average.
Eminem is a billiard player who enjoys playing billiards and also likes solving mathematical puzzles. He
notices that the billiard balls on the table are arranged in a grid, and he is curious to find the sum of the
numbers written on each ball.
Write a program to find the sum of all the numbers written on each ball in the grid.
Input Format
The first line of input consists of an integer N, representing the number of rows.
The second line of input consists of an integer M, representing the number of columns.
The following lines N lines consist of M space-separated integers, representing the numbers written on each
ball.
Output Format
The output prints an integer representing the sum of all the numbers written on each ball.
Q1
Solution
import java.util.Scanner;
class Perfect
{
public static void main(String arg[])
{
int n,sum=0;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
int i=1;
while(i<=n/2)
{
if(n%i==0)
{
sum+=i;
}
i++;
}
if(sum==n)
{
System.out.println(n+" is a perfect number");
}
else{
System.out.println(n+" is not a perfect number");
}
}
}
Q2
Solution
import java.util.Scanner;
int n = scanner.nextInt();
scanner.close();
}
}
Q3
Solution
import java.util.Scanner;
int sum = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
System.out.println(sum);
scanner.close();
}
CMREC_Java_Unit 1_COD_Class and Objects
Q1.
Problem Statement
Laura is learning about Pythagorean triples in her math class. She wants to create a program to determine
whether a set of three integers forms a Pythagorean triple.
Implement a program using the Pythagorean class to input the sides of a triangle and determine if it is a
Pythagorean triple or not.
Input Format
The input consists of three space-separated integers a, b, and c representing the sides of a triangle.
Output Format
The output prints "Pythagorean triple" or "Not a Pythagorean triple" based on the inputs.
Emily is planning a road trip to a country that uses kilometers per hour (km/h) for speed limits, but she's
more familiar with miles per hour (mph).
To help her with her trip, she wants to create a SpeedConverter class that holds the choice ('1' for mph to
km/h conversion, '2' for km/h to mph conversion) and speed as attributes. The program should convert
speeds from miles per hour to km per hour and vice versa.
Formulas used:
1. Miles per hour = speed * 1.60934
2. km per hour = speed / 1.60934
Input Format
The first line of input consists of an integer representing the choice ('1' for mph to km/h conversion, '2' for
km/h to mph conversion).
The second line consists of the speed value.
Output Format
The output displays a double value representing the converted speed, rounded off to two decimal places.
The output displays "Invalid choice" if the choice is neither 1 nor 2.
Develop a program to check the type of a lowercase alphabet. Implement a Main class and a method
checkAlphabetType() to determine if a given character is a vowel, consonant, or not an alphabet.
Input Format
The input consists of a single character.
Output Format
The output prints the result indicating whether the character is a vowel, consonant or not an alphabet.
Refer to the sample output for the exact text and format.
Constraints
The input is a valid ASCII character.
Sample Input Sample Output
j
j: consonant
Sample Input Sample Output
E
E: vowel
Sample Input Sample Output
5
5: not an alphabet
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement
The task involves creating two classes: a Box class and a Main class. In the Main class, he is required to
instantiate an object of the Box class and calculate the volume of the box.
Refer to the sample output for the exact text and format.
Constraints
1.1 ≤ width, height, depth ≤ 50.0
Sample Input Sample Output
7.2 8.3 1.1
Volume: 65.74
Sample Input Sample Output
2.2 1.1 3.2
Volume: 7.74
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q5.
Problem Statement
Akila is developing a program to identify the day of the week based on a numerical input. She has designed
a DayOfWeek class containing a method printDay for this purpose. The program takes an integer input
representing a day of the week, and the printDay method prints the corresponding day.
Q1
Solution
import java.util.Scanner;
class Pythagorean {
int a, b, c;
}
p.a = sc.nextInt();
p.b = sc.nextInt();
p.c = sc.nextInt();
boolean isPythagorean = (p.a * p.a + p.b * p.b == p.c * p.c) ||
(p.a * p.a + p.c * p.c == p.b * p.b) ||
(p.b * p.b + p.c * p.c == p.a * p.a);
if (isPythagorean) {
System.out.print("Pythagorean triple");
} else {
System.out.println("Not a Pythagorean triple");
}
}
}
Q2
Solution
import java.util.Scanner;
class SpeedConverter {
double speed;
int choice;
}
if (choice == 1) {
double convertedSpeed = s.speed * 1.60934;
System.out.format("%.2f", convertedSpeed);
} else if (choice == 2) {
double convertedSpeed = s.speed / 1.60934;
System.out.format("%.2f", convertedSpeed);
} else {
System.out.println("Invalid choice");
}
}
}
Q3
Solution
import java.util.Scanner;
class Main {
private boolean isVowel(char ch) {
return (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
}
Q4
Solution
import java.util.Scanner;
class Box {
double width;
double height;
double depth;
}
class Main {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = sc.nextDouble();
mybox.height = sc.nextDouble();
mybox.depth = sc.nextDouble();
sc.close();
}
}
Q5
Solution
import java.util.Scanner;
class DayOfWeek {
public void printDay(int day) {
if (day >= 1 && day <= 7) {
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Weekend");
break;
}
} else {
System.out.println("Invalid");
}
}
}
dayOfWeek.printDay(day);
}
}
CMREC_Java_Unit 1_PAH_Class and Objects
Q1.
Problem Statement
Arun wants to design a program using a class that calculates and prints both the area and perimeter of a
rectangle.
Define a class named Rectangle to encapsulate the properties and behaviour related to a rectangle. Include
two integer variables to represent the dimensions of the rectangle. Calculate the area and perimeter of the
rectangle. Print the calculated area and perimeter.
Formula
Area = l × w
Perimeter = 2(l + w)
Input Format
The input consists of two space-separated integers, representing the length (l) and breadth (w) of a rectangle.
Output Format
The first line of output prints the area of the rectangle.
The second line prints the perimeter of the rectangle.
Write a program to find the count of all digits of a number using a class and objects. Create a class named
DigitsOpr, define getNum() to get the input from the Main class, and countDigits() to count the actual
number of digits in the given input.
Input Format
The input consists of an integer N.
Output Format
The output prints the total number of digits in the given integer.
Q1
Solution
import java.util.Scanner;
class Rectangle {
int length;
int breadth;
}
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Rectangle r = new Rectangle();
r.length = sc.nextInt();
r.breadth = sc.nextInt();
Q2
Solution
import java.util.*;
class DigitsOpr {
private int num;
class Main {
public static void main(String[] s) {
DigitsOpr dig = new DigitsOpr();
int n;
dig.getNum(n);
System.out.println(dig.countDigits());
}
}
Assist Jim in finishing the program successfully using the string methods.
Input Format
The input consists of a string. It contains lowercase and uppercase letters.
Output Format
The output prints the concatenated lowercase and uppercase letters, separated by a space.
John is developing a program that counts the number of vowels in a given string.
He wants to create a program that takes a string input from the user and outputs the count of vowels in that
string.
Input Format
The input consists of a single line containing a string.
Output Format
The output displays a single integer representing the count of vowels in the input string.
Jei loves playing with strings. She is interested in finding out whether a given string is a palindrome or not.
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and
backward, ignoring spaces, punctuation, and capitalization.
Gowri needs to write a paragraph about modern history. While writing, she noticed that some words were
repeated again and again. She started counting the number of times a particular word was repeated.
Write a program to get a string from the user, and count the number of times a word is repeated in the string.
Input Format
The first line of input consists of a string, separated by a space.
The second line consists of a single word that needs to be counted in the string.
Output Format
The output displays the number of times the given word is present in the string.
If the second string is not present in the first string, print "0".
Given two strings, check whether the given strings are anagrams of each other or not.
An anagram of a string is another string that contains the same characters, only the order of characters can
be different.
Input Format
The first line consists of the string, representing the string 1 as str1.
The second line consists of the string, representing the string2, as str2.
Output Format
If str1 and str2 are anagrams of each other, output: "str1 and str2 are anagrams".
If str1 and str2 are not anagrams of each other, output: "str1 and str2 are not anagrams".
Sophia is working on a programming project that involves generating all possible permutations of a given
string. She needs a program that can efficiently compute these permutations and help her analyze the
different arrangements of characters in the string.
To achieve this, she is seeking assistance in creating a program that can produce all the permutations of a
given string.
Input Format
The input consists of the string.
Output Format
The output displays all possible permutations.
Arya is working on a data analysis project and needs a program to help her analyze a given string's character
occurrences. She wants to count the consecutive occurrences of each character in the string and display the
results for her analysis.
To streamline her work, Arya is looking for assistance in creating a program that can accurately count and
display the consecutive occurrences of characters in a string.
Input Format
The input consists of a single line containing a string.
Output Format
The output prints each character in the string followed by its count, without any spaces between them.
Mukhil is working on a program to analyze the frequency of characters in a string. He wants to find the
character with the highest frequency in the string. Write a Java program to help Mukhil with his character
frequency analysis.
The program should prompt Mukhil to enter a string. After receiving the input, the program should count the
frequency of each character in the string and then determine and display the character with the highest
frequency.
Input Format
The input consists of a string containing printable ASCII characters.
Output Format
The program displays the character with the highest frequency in the entered string using the following
format: Highest frequency character: <character>.
Q1
Solution
import java.util.Scanner;
class Main {
static public String move(String str) {
String low = str.toLowerCase();
String upr = str.toUpperCase();
Q2
Solution
import java.util.Scanner;
class Vow{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str = in.nextLine();
System.out.print(count_Vowels(str));
}
public static int count_Vowels(String str)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
count++;
}
}
return count;
}
}
Q3
Solution
import java.util.Scanner;
class Main {
public static boolean isPalindrome(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
while (i < j && !Character.isLetterOrDigit(s.charAt(i))) {
i++;
}
while (i < j && !Character.isLetterOrDigit(s.charAt(j))) {
j--;
}
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
return false;
}
}
return true;
}
if (isPalindrome(s)) {
System.out.println("'" + s + "' is a palindrome.");
} else {
System.out.println("'" + s + "' is not a palindrome.");
}
}
}
Q4
Solution
import java.util.Scanner;
class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String str1 = sc.nextLine();
int len=str1.length();
int count =0;
if(len> 0)
{
int first = str.indexOf(str1);
while(first!=-1)
{
count++;
first = str.indexOf(str1,first + len);
}
}
System.out.println(count);
}
}
Q5
Solution
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String str1= sc.nextLine();
String str2= sc.nextLine();
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
if(str1.length() == str2.length()) {
if(result) {
System.out.println(str1 + " and " + str2 + " are anagrams");
}
else {
System.out.println(str1 + " and " + str2 + " are not anagrams");
}
}
else {
System.out.println(str1 + " and " + str2 + " are not anagrams");
}
}
}
Q6
Solution
import java.util.*;
class Main
{
private static void swap(char[] chars, int i, int j)
{
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
permutations(str.toCharArray(), 0);
}
Q7
Solution
import java.util.Scanner;
class CharacterCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
}
}
Q8
Solution
import java.util.Scanner;
scanner.close();
}
}
CMREC_Java_Unit 1_CY_String Class
Section 1 – Coding
Q1.
Problem Statement
Heather is learning about strings and she is assigned a task. The task is to write a program to obtain a string,
a substring, and the string that has to replace the substring and print the modified string. Help her by writing
a program for the same.
Example
Input:
Original string = Miss the boat
Substring = the
String to replace = a
Output:
Modified string = Miss a boat
Explanation:
The program replaces the occurrence of "the" with "a", resulting in the modified string "Miss a boat".
Input Format
The first line of input consists of a string.
The second line consists of the substring.
The third line consists of the string that has to replace the substring.
Output Format
The output prints the modified string.
Sonam, an English teacher explains the word arrangement in the dictionary where the words are arranged in
Lexicographical order. She asked her students to find the lexicographically smallest and largest substrings of
a given length in the given string, using string methods.
Swati is given a set of words by her teacher. She has to calculate the length of each word and arrange them
in ascending order of their lengths.
Input Format
The first line of input consists of integer 'n' which describes the number of words in the string,
The next n lines of the input consist of strings.
Output Format
The output displays the input strings in the ascending order of their lengths.
For Example, In "ABCFRzyx", "ABC" is the sequential alphabet in forward order. so, they can be
considered as a group. Similarly "zyx" is also a sequential alphabet in reverse order. They can also form a
group. "C", "F", and "R" has no sequential alphabets so they are made as separate groups.
Note: Two or more persons can be assigned with the same alphabet. Also, the alphabets are not case-
sensitive,
Input Format
The first line represents "n" number of people coming to your ride.
The second line represents the people with their corresponding alphabet characters.
Output Format
The output prints the Alphabet of the people in the same group and makes sure each group is printed in a
new line.
Example:
Q1
lution
import java.util.*;
import java.lang.*;
import java.io.*;
class Main{
public static void main (String[] args) {
Scanner input = new Scanner(System. in);
String str = input.nextLine();
String searchStr = input.nextLine();
String replaceStr = input.nextLine();
String outString = replaceString(str, searchStr, replaceStr);
System.out.println(outString);
}
void replaceString(char* str, const char* searchStr, const char* replaceStr, char* outString) {
char buffer[1000];
char* insertPoint = &buffer[0];
const char* tmp = str;
size_t searchLen = strlen(searchStr);
size_t replaceLen = strlen(replaceStr);
while (1) {
const char* p = strstr(tmp, searchStr);
if (p == NULL) {
strcpy(insertPoint, tmp);
break;
}
tmp = p + searchLen;
}
strcpy(outString, buffer);
}
int main() {
char str[1000], searchStr[100], replaceStr[100], outString[1000];
str[strcspn(str, "\n")] = 0;
searchStr[strcspn(searchStr, "\n")] = 0;
replaceStr[strcspn(replaceStr, "\n")] = 0;
printf("%s\n", outString);
return 0;
}
Q2
lution
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(minSubstring);
System.out.println(maxSubstring);
}
}
Q3Solution
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int i,j;
n=n+1;
String[] array= new String[n];
String s;
for(i=0;i<n;i++)
{
array[i] =sc.nextLine();
}
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
if(array[i].length()>array[j].length())
{
s=array[i];
array[i]=array[j];
array[j]=s;
}
}
}
for(i=0;i<n;i++)
{
System.out.print(array[i]+" ");
}
sc.close();
}
}
Q4
Solution
import java.util.*;
import java.io.*;
class Main {
public static void main(String []args) {
Scanner in =new Scanner(System.in);
in.nextLine();
String inputString = in.nextLine();
System.out.print(str[0]);
for (int i=1; i<str.length ; i++) {
if (str[i] != ' ') {
if ((str[i] == str[i-1]+1) || (str[i] == str[i-1]-1)) {
System.out.print(str[i]);
}
else {
System.out.print("\n" + str[i]);
}
}
}
}
}
Q5
lution
import java.util.Scanner;
class CamelCaseConverter {
// new string will be reduced by the size of spaces in the original string
return String.valueOf(ch, 0, n - cnt);
}
// Driver code
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
scanner.close();
Ben is a passionate text enthusiast who loves making text more readable and cleaner. He's organized a "Text
Cleanup Challenge" for his friends.
Participants are tasked with writing a program to clean up text by removing extra white spaces, both at the
beginning and end and within sentences or words.
Input Format
The first line of input represents a text string with potential white space issues.
Output Format
The output prints the cleaned text with extra white spaces removed.
Alex needs to count the number of occurrences of a specific character in a given text. She wants to create a
simple program to help her with this task.
The program will take a text input and a character to count, and it should provide the count of occurrences of
that character in the text.
Input Format
The first line consists of a string representing the text in which you need to count the occurrences of a
character.
The second line contains a single character to count the occurrences in the text.
Output Format
The output is a single integer, representing the count of occurrences of the specified character in the given
text.
Q1
Solution
import java.util.Scanner;
System.out.println(trimmedString);
scanner.close();
}
}
Q2
Solution
import java.util.Scanner;
return count;
}
Alice is managing an online store and wants to implement a program in the pricing system for her products.
She has a base class called Product with a public double attribute price.
Additionally, she has a subclass called DiscountedProduct, which extends Product and includes a private
double attribute discountRate.
This subclass has a method called calculateSellingPrice() to determine the final selling price after applying
the discount.
Elsa subscribes to a premium service with a base monthly cost, a service tax, and an extra feature cost. She
wants to write a program that takes input for these values and calculates the total monthly cost of Elsa's
subscription.
The PremiumSubscription class inherits from the Subscription class and has a method,
calculateMonthlyCost(), to determine the total cost.
Note
Total Cost = Monthly Cost + Service Tax + Extra Feature Cost
Mary is managing a business and wants to analyze its profitability. She has a regular business model and a
seasonal one. Mary is using a program that calculates and compares the profit margins of both models based
on revenue and costs.
The program defines a base class BusinessUtility with a method for calculating the profit margin and a
derived class SeasonalBusinessUtility that overrides the margin calculation method to include an additional
seasonal adjustment.
.
Note
Margin = (Revenue − Cost)/Revenue * 100
Seasonal margin = (margin + 10)
Input Format
The first line of input consists of a double that represents the revenue value 'R'.
The second line of input consists of a double that represents the cost value 'C'.
Output Format
The output should display the margin and seasonal margin of the company's business in the following
format:
"Regular Margin: [margin]%
Seasonal Margin: [seasonal margin]%
If the regular margin is less than 10%, print "Business is not profitable."; otherwise, print "Business is
profitable."
Round off both margins to two decimal places.
Refer to the sample output for formatting specifications.
Constraints
In this scenario, the test cases fall under the following constraints:
0.0 ≤ R ≤ 1000.0
0.0 ≤ C ≤ 1000.0
Sample Input Sample Output
1000.0
800.0
Regular Margin: 20.00%
Seasonal Margin: 30.00%
Business is profitable.
Sample Input Sample Output
1000.0
950.0
Regular Margin: 5.00%
Seasonal Margin: 15.00%
Business is not profitable.
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding
Q1
Solution
import java.util.Scanner;
class Product {
public double price;
}
class ProductPricing {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Q2
Solution
import java.util.Scanner;
class Subscription {
public double monthlyCost;
public double serviceTax;
public double extraFeatureCost;
}
scanner.close();
}
}
Q3
Solution
import java.util.Scanner;
import java.text.DecimalFormat;
class BusinessUtility {
public double calculateMargin(double revenue, double cost) {
double margin = ((revenue - cost) / revenue) * 100;
return margin;
}
}
scanner.close();
}
}
CMREC_Java_Unit 1_CY_Inheritance_Overriding
Q1.
Problem Statement
Adhi, a travel enthusiast, wishes to calculate the travel distance of his car based on its speed and fuel
capacity. He decides to create a program using single inheritance.
The Vehicle class holds attributes for speed and fuel capacity, while the Car class extends Vehicle and
includes a method to calculate travel distance.
Adhi inputs speed and fuel capacity, and the program displays the details, including the calculated travel
distance.
Teena's Retail Store has implemented a Loyalty Points System to reward customers based on their spending.
The program includes two classes: Customer and PremiumCustomer.
Loyalty points for Regular Customers are calculated as one point per ten units spent, while Premium
Customers, through the overridden method in the PremiumCustomer class, receive double points.
Q1
Solution
import java.util.Scanner;
class Vehicle {
public double speed;
public double fuelCapacity;
}
scanner.close();
}
}
Q2
Solution
import java.util.Scanner;
class Customer {
public int calculateLoyaltyPoints(int amountSpent) {
return amountSpent / 10;
}
}
Customer customer;
if (isPremium.equals("yes")) {
customer = new PremiumCustomer();
} else {
customer = new Customer();
}
The Parent class contains a method named fun that takes an integer N as input and performs the following
operations:
1. Extract each digit from the given integer N.
2. Calculate the square of each digit.
3. Sum up the squares of all the digits.
4. Print the final sum.
The Main class extends the Parent class and includes the main method. The main method prompts the user
for an integer N, creates an instance of the Main class, and invokes the fun method of the Parent class.
Example
Input
1234
Output
30
Explanation
1. Calculate the square of each digit: 12 + 22 + 32 + 42
2. Sum up the squares of all the digits: 1 + 4+ 9 + 16 =
3. Print final sum: 30
Input Format
The input consists of an integer, N.
Output Format
The output prints a single integer, representing the sum of the squares of the digits of the input number.
Rithish is developing a straightforward pizza ordering system. To achieve this, he needs a Pizza class with a
constructor for the base price and topping cost, along with a calculatePrice method overriding. He also wants
a DiscountedPizza class that inherits from Pizza, applying a 10% discount for more than three toppings.
The program prompts the user for inputs, creates instances of both classes, calculates regular and discounted
prices, and displays them formatted appropriately.
Example 1
Input:
9.5
1.25
3
Output:
Price without discount: Rs.13.25
Price with discount: Rs.13.25
Explanation:
Rithish orders a pizza with a base price of Rs. 9.5, a topping cost of Rs. 1.25, and selects 3 toppings. The
price is calculated as 9.5 + (1.25 * 3) = 13.25. The regular and discounted prices are both Rs. 13.25, as
there's no discount applied.
Example 2
Input:
11.0
2.0
7
Output:
Price without discount: Rs.25.00
Price with discount: Rs.22.50
Explanation:
Rithish orders another pizza with a higher base price of Rs. 11.0, a topping cost of Rs. 2.0, and chooses 7
toppings.
Regular Price: 11.0 + (2.0 * 7) = Rs. 25.00.
Discounted Price: The discounted price is calculated as 90% of the regular price, i.e., 0.9 * 25.00 =
Rs.22.50.
Input Format
The first line of the input consists of a double datatype number representing the base price of the pizza.
The second line of input consists of a double datatype number representing the cost per topping.
The third line of input consists of an integer representing the number of toppings chosen for the pizza.
Output Format
The output displays a double value with two decimal places - the price information, in the following format:
"Price without discount: Rs.[price without discount]"
"Price with discount: Rs.[price with discount]"
Solution
import java.util.Scanner;
class Parent {
void fun(int n) {
int i, j, k = 0, sum = 0;
int a[] = new int[10];
while (n != 0) {
i = n % 10;
a[k++] = i * i;
n = n / 10;
}
System.out.print(sum);
}
}
Q2
Solution
import java.util.Scanner;
import java.text.DecimalFormat;
class Pizza {
private double basePrice;
private double toppingCost;
scanner.close();
}
}