0% found this document useful (0 votes)
6 views

java week 1 keys

The document outlines several programming problems related to Java, focusing on data types, variables, and operators. Each problem includes a description, input/output format, constraints, and sample inputs/outputs. Solutions are provided for each problem, demonstrating how to implement the required functionality in Java.

Uploaded by

shaiksubhani8433
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

java week 1 keys

The document outlines several programming problems related to Java, focusing on data types, variables, and operators. Each problem includes a description, input/output format, constraints, and sample inputs/outputs. Solutions are provided for each problem, demonstrating how to implement the required functionality in Java.

Uploaded by

shaiksubhani8433
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

CMREC_Java_Unit 1_COD_Datatypes_Variables_Operators

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.

Refer to the sample output for formatting specifications.


Constraints
1.0 ≤ total distance ≤ 100.0
1.0 ≤ speed ≤ 100.0
Sample Input Sample Output
15.0
7.5
Henry will complete the marathon in 2.0 hours.
Sample Input Sample Output
25.0
20.0
Henry will complete the marathon in 1.25 hours.
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
-106 ≤ X ≤ 106
Sample Input Sample Output
5
20
Sample Input Sample Output
-89
-356
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q5.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
1 ≤ N ≤ 20
Sample Input Sample Output
5
Square: 25
Cube: 125
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution

Solution
import java.util.Scanner;

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

int productCode = scanner.nextInt();


float price = scanner.nextFloat();
boolean inStock = scanner.nextBoolean();

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

String songTitle = scanner.nextLine();


int playCount = scanner.nextInt();

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;

System.out.println("Henry will complete the marathon in " + time + " hours.");

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

int square = num * num;


int cube = num * num * num;

System.out.println("Square: " + square);


System.out.println("Cube: " + cube);

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.

Follow the sequence of comparisons below:


1. If x is less than y, then the value is x.
2. Otherwise, compare y and z: if y is less than z, then the value is y.
3. Otherwise, compare z and w: if z is less than w, then the value is z.
4. Otherwise, the value is 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.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ x, y, z, w ≤ 150
Sample Input Sample Output
5238
Result: 2
Sample Input Sample Output
148 132 126 139
Result: 126
Sample Input Sample Output
12 25 36 67
Result: 12
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ n ≤ 100
Sample Input Sample Output
12
Flour: 2.50 cups
Sugar: 1.00 cups
Butter: 0.50 cups
Sample Input Sample Output
1
Flour: 0.21 cups
Sugar: 0.08 cups
Butter: 0.04 cups
Sample Input Sample Output
100
Flour: 20.83 cups
Sugar: 8.33 cups
Butter: 4.17 cups
Sample Input Sample Output
13
Flour: 2.71 cups
Sugar: 1.08 cups
Butter: 0.54 cups
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ N ≤ 104
1 ≤ S ≤ 40
Sample Input Sample Output
175
3
Download Time: 0 hours, 7 minutes, and 46 seconds
Sample Input Sample Output
1023
2
Download Time: 1 hours, 8 minutes, and 12 seconds
Sample Input Sample Output
800
40
Download Time: 0 hours, 2 minutes, and 40 seconds
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution

Solution
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

int x = scanner.nextInt();
int y = scanner.nextInt();
int z = scanner.nextInt();
int w = scanner.nextInt();

int result = x < y ? x : (y < z ? y : (z < w ? z : w));

System.out.printf("Result: %d", result);

scanner.close();
}
}

Q2

Solution
import java.util.Scanner;

public class Main {


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

int x;
double flourPer12Cupcakes = 2.5;
double sugarPer12Cupcakes = 1.0;
double butterPer12Cupcakes = 0.5;
x = scanner.nextInt();

double flourNeeded = (x / 12.0) * flourPer12Cupcakes;


double sugarNeeded = (x / 12.0) * sugarPer12Cupcakes;
double butterNeeded = (x / 12.0) * butterPer12Cupcakes;

System.out.printf("Flour: %.2f cups%n", flourNeeded);


System.out.printf("Sugar: %.2f cups%n", sugarNeeded);
System.out.printf("Butter: %.2f cups", butterNeeded);

scanner.close();
}
}

Q3

Solution
import java.util.Scanner;

public class Main {


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

int fileSizeMB, downloadSpeedMbps;

fileSizeMB = scanner.nextInt();
downloadSpeedMbps = scanner.nextInt();

int downloadTimeSeconds = (fileSizeMB * 8) / downloadSpeedMbps;

int hours = downloadTimeSeconds / 3600;


int remainingSeconds = downloadTimeSeconds % 3600;
int minutes = remainingSeconds / 60;
int seconds = remainingSeconds % 60;

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.

Write a program to assist Ramanan in this task.


Input Format
The input consists of a double value, representing the temperature in Fahrenheit.
Output Format
The output prints "Equivalent temperature in Celsius: " followed by a double value, representing the
equivalent temperature in Celsius, rounded off to exactly two decimal places.

Refer to the sample output for formatting specifications.


Constraints
32.0 ≤ fahrenheit ≤ 273.0
Sample Input Sample Output
98.6
Equivalent temperature in Celsius: 37.00
Sample Input Sample Output
32.0
Equivalent temperature in Celsius: 0.00
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem statement

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.

Help Amy by designing this program.

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.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1.0 ≤ R ≤ 100.0
Sample Input Sample Output
5.0
Area of the circle: 78.50
Perimeter of the circle: 31.40
Sample Input Sample Output
11.1
Area of the circle: 386.88
Perimeter of the circle: 69.71
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

Q1

Solution
import java.util.Scanner;

public class Main {


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

double fahrenheit = scanner.nextDouble();

// Convert Fahrenheit to Celsius


double celsius = (fahrenheit - 32) * 5 / 9;

// Display the equivalent temperature in Celsius with two decimals


System.out.printf("Equivalent temperature in Celsius: %.2f\n", celsius);

scanner.close();
}
}

Q2

Solution
import java.util.Scanner;

public class Main {


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

double radius = scanner.nextDouble();


double area = 3.14 * radius * radius;
double perimeter = 2 * 3.14 * radius;

System.out.printf("Area of the circle: %.2f%n", area);


System.out.printf("Perimeter of the circle: %.2f", perimeter);

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.

Note: The healthy range of BMI is 18.5 to 24.9 (both inclusive).


Input Format
The input consists of two double values: the weight in kilograms and the height in meters.
Output Format
The first line of output prints "BMI: X" where X is a double value, rounded off to two decimal places.
The second line prints one of the following:
1. If the BMI is within the valid range, print "Healthy Range".
2. Otherwise, print "Not in Healthy Range".

Refer to the sample output for formatting specifications


Constraints
10.0 ≤ weight ≤ 300.0
0.00 ≤ height ≤ 3.00
Sample Input Sample Output
65.8
1.75
BMI: 21.49
Healthy Range
Sample Input Sample Output
124.3
1.87
BMI: 35.55
Not in Healthy Range
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Help Arun to implement the project.


Input Format
The input consists of five space-separated integers, representing the marks in five subjects.
Output Format
The first line of output prints "Average score: " followed by an integer representing the average score.
The second line prints one of the following:
1. If the condition is satisfied, print "The student has passed".
2. Otherwise, the output prints "The student has failed".
Refer to the sample output for formatting specifications.
Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ marks ≤ 100
Sample Input Sample Output
50 60 70 80 90
Average score: 70
The student has passed
Sample Input Sample Output
39 25 30 45 67
Average score: 41
The student has failed
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

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).

Help Subha to write this program using a 'for' loop.


Input Format
The input consists of an integer N.
Output Format
The output displays the even numbers in the dataset separated by space, till the specified integer.

Refer to the sample output for formatting specifications.


Constraints
The given test cases fall under the following constraints:
1 ≤ N ≤ 100
Sample Input Sample Output
17
2 4 6 8 10 12 14 16
Sample Input Sample Output
6
246
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ n ≤ 1010
Sample Input Sample Output
456
The single-digit sum of 456 is 6.
Sample Input Sample Output
999
The single-digit sum of 999 is 9.
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q5.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
2 ≤ N ≤ 10
1 ≤ array elements ≤ 100
Sample Input Sample Output
3
578
-3
Sample Input Sample Output
6
347681
2
Sample Input Sample Output
10
100 8 5 46 38 49 98 45 32 76
24
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q6.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
The input 2D array should be a square matrix.
Sample Input Sample Output
3
123
456
789
Sum of the main diagonal: 15
Sum of the secondary diagonal: 15
Sample Input Sample Output
3
125
367
853
Sum of the main diagonal: 10
Sum of the secondary diagonal: 19
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q8.
Problem Statement
In a bustling city, the department of Urban Development is modernizing its infrastructure. As part of this
initiative, they need a program to transpose the layout matrix of city blocks.

Write a program that takes the dimensions and details of the original matrix representing city blocks and
outputs its transposed version.

Company Tags: Capgemini


Input Format
The first line of input consists of two space-separated integers N and M, representing the number of rows
and columns, respectively.
The following N lines consist of M space-separated characters, representing the characters that form the
layout matrix of city blocks.
Output Format
The output prints the transposed matrix, representing the rearranged city block layout.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ N, M ≤ 10
Sample Input Sample Output
33
ABC
DEF
GHI
ADG
BEH
CFI
Sample Input Sample Output
31
A
D
G
ADG
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution

Q1

Solution
import java.util.Scanner;

public class Main {


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

double weight = scanner.nextDouble();


double height = scanner.nextDouble();

double bmi = weight / (height * height);

String healthStatus;
if (bmi >= 18.5 && bmi <= 24.9) {
healthStatus = "Healthy Range";
} else {
healthStatus = "Not in Healthy Range";
}

System.out.printf("BMI: %.2f%n", bmi);


System.out.println(healthStatus);
}
}

Q2

Solution
import java.util.Scanner;

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

int subject1 = scanner.nextInt();


int subject2 = scanner.nextInt();
int subject3 = scanner.nextInt();
int subject4 = scanner.nextInt();
int subject5 = scanner.nextInt();

int totalMarks = subject1 + subject2 + subject3 + subject4 + subject5;

int averageMarks = totalMarks / 5;

if (averageMarks >= 50) {


System.out.println("Average score: "+averageMarks+"\nThe student has passed");
} else {
System.out.println("Average score: "+averageMarks+"\nThe student has failed");
}
}
}

Q3

Solution
import java.util.Scanner;

public class Main {


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

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


if (i % 2 == 0) {
System.out.print(i + " ");
}
}
}
}

Q4

Solution
import java.util.Scanner;

public class Main {


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

int input = scanner.nextInt();

int n = input;

while (n >= 10) {


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

System.out.println("The single-digit sum of " +input+ " is " + n + ".");

scanner.close();
}
}

Q5

Solution
import java.util.Scanner;

public class Main {


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

int size = scanner.nextInt();


int[] arr = new int[size];

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


arr[i] = scanner.nextInt();
}
int result = arr[0] - arr[size - 1];

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];

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


arr[i] = scanner.nextInt();
}

int count = 0;

for (int num : arr) {


if (num % 3 == 0) {
count++;
}
}

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 size = scanner.nextInt();

int[][] arr = new int[size][size];

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


for (int j = 0; j < size; j++) {
arr[i][j] = scanner.nextInt();
}
}

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];
}

System.out.println("Sum of the main diagonal: " + sum);


System.out.println("Sum of the secondary diagonal: " + sum1);

scanner.close();
}
}

Q8
Solution
import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();
int m = scanner.nextInt();

char[][] originalMatrix = new char[10][10];


for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
originalMatrix[i][j] = scanner.next().charAt(0);
}
}

char[][] mirroredMatrix = new char[10][10];


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
mirroredMatrix[i][j] = originalMatrix[j][i];
}
}

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


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

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.

Refer to the sample output for formatting specifications.


Constraints
1.00 ≤ units consumed ≤ 10000.00
Sample Input Sample Output
1000.0
200.0
100.0
124.20
Sample Input Sample Output
500.0
30.0
20.0
59.95
Sample Input Sample Output
120.0
70.0
45.0
21.50
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ X ≤ 107
Sample Input Sample Output
120
120 is divisible by the sum of its digits.
Sample Input Sample Output
157
157 is not divisible by the sum of its digits.
The closest smaller number that is divisible: 156
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
The given test cases fall under the following constraints:
1 ≤ N ≤ 15
0 ≤ array elements ≤ 100
Sample Input Sample Output
4
4021
8
Sample Input Sample Output
5
15792
14
Sample Input Sample Output
5
17089
0
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement
Stefan is working on a coding project that involves finding all pairs in an integer array that sum up to a
specific target value.

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.

Help Stefan to complete the project.


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.
The third line consists of an integer T, which is the sum Stefan wants to find pairs for.
Output Format
The first line of output prints "Pairs that sum up to T:".
The following lines print all pairs of integers that sum up to the given target in the format: X + Y

Refer to the sample output for the formatting specifications.


Constraints
1 ≤ N ≤ 20
1 ≤ array elements ≤ 100
1 ≤ T ≤ 100
Sample Input Sample Output
5
23578
10
Pairs that sum up to 10:
2+8
3+7
Sample Input Sample Output
8
3 8 15 6 12 7 9 2
17
Pairs that sum up to 17:
8+9
15 + 2
Sample Input Sample Output
12
6 10 14 25 3 11 18 1 7 40 15 9
34
Pairs that sum up to 34:
25 + 9
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q5.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ N ≤ 10
1 ≤ M ≤ 10
1 ≤ Dataset elements ≤ 500
Sample Input Sample Output
34
1234
5678
9 10 11 12
10
26
42
Sample Input Sample Output
22
12
34
3
7
Sample Input Sample Output
23
10 20 30
5 10 15
60
30
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

Q1

Solution
import java.util.Scanner;

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

double electricityUnits = scanner.nextDouble();


double waterUnits = scanner.nextDouble();
double gasUnits = scanner.nextDouble();

double electricityCost = electricityUnits * 0.12;


double waterCost = waterUnits * 0.05;
double gasCost = gasUnits * 0.08;

double totalCost = electricityCost + waterCost + gasCost;

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;

public class Main {


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

int sumOfDigits = 0;
int originalNumber = number;

while (number > 0) {


sumOfDigits += number % 10;
number /= 10;
}

boolean isDivisible = originalNumber % sumOfDigits == 0;

if (isDivisible) {
System.out.println(originalNumber + " is divisible by the sum of its digits.");
} else {
int closestSmallerNumber = -1;
number = originalNumber - 1;

while (number > 0) {


if (number % sumOfDigits == 0) {
closestSmallerNumber = number;
break;
}
number--;
}

System.out.println(originalNumber + " is not divisible by the sum of its digits.");


if (closestSmallerNumber != -1) {
System.out.println("The closest smaller number that is divisible: " + closestSmallerNumber);
}
}
}
}

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[] arr = new int[n];

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


arr[i] = scanner.nextInt();
}

int product = 1;

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


product *= arr[i];
}

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

int target = scanner.nextInt();

System.out.println("Pairs that sum up to " + target + ":");


for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == target) {
System.out.println(arr[i] + " + " + arr[j]);
}
}
}
}
}

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

int[][] dataset = new int[10][10];

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


for (int j = 0; j < M; j++) {
dataset[i][j] = scanner.nextInt();
}
}

int[] rowSums = new int[N];


for (int i = 0; i < N; i++) {
int sum = 0;
for (int j = 0; j < M; j++) {
sum += dataset[i][j];
}
rowSums[i] = sum;
}

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


System.out.print(rowSums[i]);
System.out.println();
}

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"

Refer to the sample output for the formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ n ≤ 105
Sample Input Sample Output
6
6 is a perfect number
Sample Input Sample Output
50
50 is not a perfect number
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
In this scenario, the test cases will fall under the following constraints:
1 ≤ n ≤ 10
1 ≤ elements ≤ 100
Sample Input Sample Output
6
10 20 30 40 50 60
Count of elements greater than the average: 3
Sample Input Sample Output
10
23 45 67 100 28 34 56 1 27 76
Count of elements greater than the average: 4
Sample Input Sample Output
3
45 67 89
Count of elements greater than the average: 1
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
1 ≤ M, N ≤ 10
Sample Input Sample Output
3
3
123
456
789
45
Sample Input Sample Output
3
2
11 2
12 3
13 4
45
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

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;

public class Main {


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

int n = scanner.nextInt();

int[] arr = new int[n];


int sum = 0;

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


arr[i] = scanner.nextInt();
sum += arr[i];
}

int average = sum / n;


int count = 0;

for (int element : arr) {


if (element > average) {
count++;
}
}

System.out.println("Count of elements greater than the average: " + count);

scanner.close();
}
}

Q3
Solution
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int numRows = scanner.nextInt();


int numCols = scanner.nextInt();

int[][] arr = new int[10][10];

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


for (int j = 0; j < numCols; j++) {
arr[i][j] = scanner.nextInt();
}
}

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.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ a, b, c ≤ 100
Sample Input Sample Output
345
Pythagorean triple
Sample Input Sample Output
1 100 95
Not a Pythagorean triple
Sample Input Sample Output
8 15 18
Not a Pythagorean triple
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ speed ≤ 200
Sample Input Sample Output
1
60
96.56
Sample Input Sample Output
2
200
124.27
Sample Input Sample Output
0
131
Invalid choice
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

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

David is assigned a programming task in his computer science class.

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.

Help David as he needs your assistance in completing this programming task.

Formula: Volume = width x height x depth


Input Format
The input consists of three space-separated double values, representing the width, height, and depth of the
box.
Output Format
The output prints a double value, representing the volume of the box, rounded off to two decimal places.

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.

Your task is to assist Akila in achieving this functionality.


Input Format
The input consists of an integer N, representing the day of the week (1 for Sunday, 2 for Monday, ..., 7 for
Saturday).
Output Format
The output displays the corresponding day of the week.
If the input is invalid, print "Invalid".

Refer to the sample output for formatting specifications.


Constraints
1 ≤ Valid value of N ≤ 7
Sample Input Sample Output
7
Saturday
Sample Input Sample Output
0
Invalid
Sample Input Sample Output
9
Invalid
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

Q1

Solution
import java.util.Scanner;

class Pythagorean {
int a, b, c;
}

public class Main {


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

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;
}

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
double speed = sc.nextDouble();

SpeedConverter s = new SpeedConverter();


s.speed = speed;
s.choice = 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');
}

public void checkAlphabetType(char ch) {


if (Character.isLetter(ch)) {
if (isVowel(Character.toLowerCase(ch))) {
System.out.println(ch + ": vowel");
} else {
System.out.println(ch + ": consonant");
}
} else {
System.out.println(ch + ": not an alphabet");
}
}

public static void main(String[] args) {


char ch;
Scanner in = new Scanner(System.in);
ch = in.next().charAt(0);

Main obj = new Main();


obj.checkAlphabetType(ch);
}
}

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;

Scanner sc = new Scanner(System.in);

mybox.width = sc.nextDouble();
mybox.height = sc.nextDouble();
mybox.depth = sc.nextDouble();

if (mybox.width > 0 && mybox.height > 0 && mybox.depth > 0) {


vol = mybox.width * mybox.height * mybox.depth;
System.out.printf("Volume: %.2f", vol);
}

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");
}
}
}

public class Main {


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

DayOfWeek dayOfWeek = new DayOfWeek();

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.

Help Arun to design the program.

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.

Refer to the sample output for the exact text.


Constraints
1 ≤ length, breadth ≤ 105
Sample Input Sample Output
21 53
Area: 1113
Perimeter: 148
Sample Input Sample Output
15 9
Area: 135
Perimeter: 48
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
In this scenario, the test cases fall under the following constraints:
1 ≤ N ≤ 1011
Sample Input Sample Output
12345
5
Sample Input Sample Output
22
2
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

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

int area = r.length * r.breadth;


int perimeter = 2 * (r.length + r.breadth);

System.out.println("Area: " + area);


System.out.println("Perimeter: " + perimeter);
}
}

Q2

Solution
import java.util.*;

class DigitsOpr {
private int num;

public void getNum(int x) {


num = x;
}

public int countDigits() {


int n, count;
n = num;
count = 0;
while (n > 0) {
n /= 10;
count++;
}
return count;
}
}

class Main {
public static void main(String[] s) {
DigitsOpr dig = new DigitsOpr();
int n;

Scanner sc = new Scanner(System.in);


n = sc.nextInt();

dig.getNum(n);
System.out.println(dig.countDigits());

}
}

CMREC_Java_Unit 1_COD_String Class


Q1.
Problem Statement
Jim is creating a program that transforms a given string.

The steps to transform the string:


1. Convert all characters to lowercase.
2. Convert all characters to uppercase.
3. Concatenate the lowercase and uppercase versions of the string with a space in between.

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.

Refer to the sample output for the formatting specifications.


Constraints
2 ≤ length of the string ≤ 1000
Sample Input Sample Output
Welcome
welcome WELCOME
Sample Input Sample Output
Programming World
programming world PROGRAMMING WORLD
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
The input string contains only lowercase letters.
The length of the input string is at most 1000 characters.
Sample Input Sample Output
string
1
Sample Input Sample Output
aeiouxyz
5
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

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.

Write a program to help Jei determine if a given string is a palindrome or not.


Input Format
The input consists of a single line containing a string s.
Output Format
The output displays a single line stating whether the input string s is a palindrome or not.
If s is a palindrome, print "'s' is a palindrome."
Otherwise, print "'s' is not a palindrome." where 's' is the input string.

Refer to the sample output for the formatting specifications.


Constraints
1 ≤ length of s ≤ 100
The characters are not case-sensitive.
Sample Input Sample Output
madam
'madam' is a palindrome.
Sample Input Sample Output
Noted
'Noted' is not a palindrome.
Sample Input Sample Output
ABba
'ABba' is a palindrome.
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement

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".

Refer to the sample output for the formatting specifications.


Constraints
The length of the string is at most 1000 characters.
The strings are case-sensitive.
Sample Input Sample Output
I felt happy because I saw the others were happy and because I knew I should feel happy
happy
3
Sample Input Sample Output
If you tell the truth, you don't have to remember anything. A lie can travel half way around the world
while the truth is putting on its shoes.
truth
2
Sample Input Sample Output
The sun
Sun
0
Sample Input Sample Output
Alone on a wide, Wide sea.
wide
1
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q5.
Problem Statement

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".

Refer to the sample output for the formatting specifications.


Constraints
2 ≤ length of st1 and str2 ≤ 1000 characters
Sample Input Sample Output
race
care
race and care are anagrams
Sample Input Sample Output
gram
arm
gram and arm are not anagrams
Sample Input Sample Output
a gentleman
elegant man
a gentleman and elegant man are anagrams
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q6.
Problem Statement

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.

Refer to the sample output for a better understanding.


Constraints
2 ≤ length of the input string ≤ 10 characters
Sample Input Sample Output
test
test
tets
tset
tste
ttse
ttes
etst
etts
estt
estt
etst
etts
sett
sett
stet
stte
stte
stet
test
tets
tset
tste
ttse
ttes
Sample Input Sample Output
set
set
ste
est
ets
tes
tse
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q7.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
The maximum length of the string is 100.
Only consecutive repeated characters are counted for frequency.
Sample Input Sample Output
aaaabbBccdee
a4b2B1c2d1e2
Sample Input Sample Output
abcdefgabc
a1b1c1d1e1f1g1a1b1c1
Sample Input Sample Output
acd
a1c1d1
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q8.
Problem Statement

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>.

Refer to the sample output for the formatting specifications.


Constraints
The length of the input string does not exceed 100 characters.
The input string contains any printable ASCII characters.
Sample Input Sample Output
Welcome to tulipflowers.com
Highest frequency character: o
Sample Input Sample Output
aaaaaaaaabbbbbbbbb
Highest frequency character: a
Sample Input Sample Output
aabb
Highest frequency character: a
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

Q1

Solution
import java.util.Scanner;

class Main {
static public String move(String str) {
String low = str.toLowerCase();
String upr = str.toUpperCase();

return low + " " +upr;


}

public static void main(String args[]) {


Scanner input = new Scanner(System.in);
String str = input.nextLine();
System.out.println(move(str));
}
}

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;
}

public static void main(String args[]) {


Scanner sc = new Scanner(System.in);
String s = sc.nextLine();

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

char[] charArray1 = str1.toCharArray();


char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
boolean result = Arrays.equals(charArray1, charArray2);

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;
}

private static void permutations(char[] chars, int currentIndex)


{
if (currentIndex == chars.length - 1) {
System.out.println(String.valueOf(chars));
}

for (int i = currentIndex; i < chars.length; i++)


{
swap(chars, currentIndex, i);
permutations(chars, currentIndex + 1);
swap(chars, currentIndex, i);
}
}

public static void findPermutations(String str) {

if (str == null || str.length() == 0) {


return;
}

permutations(str.toCharArray(), 0);
}

public static void main(String[] args)


{
Scanner sc= new Scanner(System.in);
String str =sc.next();
findPermutations(str);
}
}

Q7

Solution
import java.util.Scanner;

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

char prevCh = str.charAt(0);


int count = 1;
for (int i = 1; i < str.length(); i++) {
char currCh = str.charAt(i);
if (prevCh == currCh) {
count++;
} else {
System.out.print(prevCh + "" + count);
count = 1;
prevCh = currCh;
}
}

// Print the last character and its count


System.out.print(prevCh + "" + count);

}
}

Q8

Solution
import java.util.Scanner;

public class Main {


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

char[] str = new char[100];


int[] freq = new int[256]; // Using 256 to cover extended ASCII characters
int i = 0, max = 0; // Initialize max with a value
int ascii;

String input = scanner.nextLine();


str = input.toCharArray();

// Initializes frequency of all characters to 0


for (i = 0; i < 256; i++) {
freq[i] = 0;
}

// Finds frequency of each character


i = 0;
while (i < str.length) {
ascii = (int) str[i];
freq[ascii] += 1;
i++;
}

// Finds the character with the highest frequency


for (i = 0; i < 256; i++) {
if (freq[i] > freq[max]) {
max = i;
}
}

System.out.println("Highest frequency character: " + (char) max);

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.

Refer to the sample output for formatting specifications.


Constraints
The string contains uppercase, lowercase, and spaces with at most 50 characters.
Sample Input Sample Output
audacious
cio
aaa
audaaaaus
Sample Input Sample Output
Miss the boat
the
a
Miss a boat
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Write a program to help her students.


Input Format
The first line of input consists of a string.
The second line consists of an integer which is the length of the strings to be returned.
Output Format
The first line of output prints the lexicographically smallest substring of the given length.
The second line prints the lexicographically largest substring of the given length.
Refer to the sample output for the formatting specifications.
Constraints
The string consists of only lowercase characters.
Sample Input Sample Output
welcometojavaworld
4
avaw
worl
Sample Input Sample Output
calender
3
ale
nde
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

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.

Note: One extra space is added before printing the output.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ length of each words ≤ 100 characters
Sample Input Sample Output
4
Vellore
I
from
am
I am from Vellore
Sample Input Sample Output
2
Hi
JK
Hi JK
Sample Input Sample Output
3
Good 3
day
Hi
Hi day Good 3
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q4.
Problem Statement
Imagine you are working as a support staff in an Amusement park. People entering your ride are marked
with random Alphabets. Your job is to separate the people into different groups based on the Alphabet
series both forward and reverse. Separate the people with sequential alphabet into Groups.

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.

Refer to the sample output for formatting specifications.


Constraints
1 ≤ n ≤ 100
Sample Input Sample Output
5
ABwRS
AB
w
RS
Sample Input Sample Output
20
aaaaaLSBBkscnDNkcasP
a
a
a
a
a
L
S
B
B
k
s
c
n
D
N
k
c
a
s
P
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q5.
Problem Statement
Given a sentence, the task is to remove spaces from the sentence and rewrite in Camel case. It is a style of
writing where we don’t have spaces and all words begin with capital letters.

Example:

Input: I got intern at geeksforgeeks


Output: IGotInternAtGeeksforgeeks

Input: Here comes the garden


Output: HereComesTheGarden
Input Format
The input consists of a single line containing a sentence.
The sentence consists of multiple words separated by spaces.
Output Format
The output prints a single line containing the converted camel case sentence.

Refer to the sample output for the formatting specifications.


Constraints
In this scenario, the given test cases will fall under the following constraints:
1 ≤ length of the string ≤ 100 characters
The input sentence contains only lowercase letters and space characters.
Sample Input Sample Output
I got intern at geeksforgeeks
IGotInternAtGeeksforgeeks
Sample Input Sample Output
Here comes the garden
HereComesTheGarden
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

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

static String replaceString(String str, String searchStr, String replaceStr) {


StringBuilder sb = new StringBuilder(str);
int pos = -1;
while ((pos = sb.indexOf(searchStr)) != -1) {
sb.replace(pos, pos + searchStr.length(), replaceStr);
}
return sb.toString();
}
}
#include <stdio.h>
#include <string.h>

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;
}

memcpy(insertPoint, tmp, p - tmp);


insertPoint += p - tmp;

memcpy(insertPoint, replaceStr, replaceLen);


insertPoint += replaceLen;

tmp = p + searchLen;
}

strcpy(outString, buffer);
}

int main() {
char str[1000], searchStr[100], replaceStr[100], outString[1000];

fgets(str, sizeof(str), stdin);


fgets(searchStr, sizeof(searchStr), stdin);
fgets(replaceStr, sizeof(replaceStr), stdin);

str[strcspn(str, "\n")] = 0;
searchStr[strcspn(searchStr, "\n")] = 0;
replaceStr[strcspn(replaceStr, "\n")] = 0;

replaceString(str, searchStr, replaceStr, outString);

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

String line = scanner.nextLine();


int k = scanner.nextInt();

String minSubstring = line.substring(0,k);


String maxSubstring = line.substring(0,k);

for (int i = 1; i < line.length()-k+1; i++) {


String sub = line.substring(i,i+k);
if (sub.compareTo(minSubstring) < 0) {
minSubstring = sub;
}
if (sub.compareTo(maxSubstring) > 0) {
maxSubstring = sub;
}
}

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

char [] str = inputString.toCharArray();

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 {

// Function to remove spaces and convert into camel case


static String convert(String s) {
// to count spaces
int cnt = 0;
int n = s.length();
char ch[] = s.toCharArray();
int res_ind = 0;

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


// check for spaces in the sentence
if (ch[i] == ' ') {
cnt++;
// conversion into upper case
ch[i + 1] = Character.toUpperCase(ch[i + 1]);
continue;
} else {
// If not space, copy character
ch[res_ind++] = ch[i];
}
}

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

// Convert the input sentence to camel case


String camelCaseString = convert(str);

// Print the result


System.out.println(camelCaseString);
}
}
CMREC_Java_Unit 1_PAH_String Class
Q1.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
1 ≤ Length of the String ≤ 100
Sample Input Sample Output
This is a test.
This is a test.
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

Refer to the sample output for the formatting specifications.


Constraints
1 ≤ Length of the text ≤ 100 characters
The given character is case-sensitive.
Sample Input Sample Output
Hello World
o
2
Sample Input Sample Output
Programming is fun! Java is fun! String Methods!
i
4
Sample Input Sample Output
CODING
i
0
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

Q1

Solution
import java.util.Scanner;

public class Main {


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

String userInput = scanner.nextLine();

// Use regular expression to remove multiple white spaces


String trimmedString = userInput.trim().replaceAll("\\s+", " ");

System.out.println(trimmedString);

scanner.close();
}
}

Q2

Solution
import java.util.Scanner;

public class Main {


public static int countCharacterOccurrences(String text, char character) {
int count = 0;
char[] charArray = text.toCharArray();

for (char c : charArray) {


if (c == character) {
count++;
}
}

return count;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

String text = scanner.nextLine();


char character = scanner.next().charAt(0);

int result = countCharacterOccurrences(text, character);


System.out.println(result);
}
}
CMREC_Java_Unit 1_COD_Inheritance_Overriding
Q1.
Problem Statement

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.

Formula: Discounted Selling Price = Price * (1 - Discount Rate)


Input Format
The first line of input consists of a double value I, the initial price of the product.
The second line consists of a double value D, the discount rate.
Output Format
The output displays "Rs. X", where X is a double value representing the calculated discounted selling price,
rounded off to two decimal places.
If the discount rate is greater than 1, the output displays "Not applicable".

Refer to the sample output for the formatting specifications.


Constraints
1.00 ≤ I ≤ 1000.00
Sample Input Sample Output
50.00
0.20
Rs. 40.00
Sample Input Sample Output
399.50
1.23
Not applicable
Sample Input Sample Output
1000.0
0.01
Rs. 990.00
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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

Refer to the below class diagram:


Input Format
The first line of input consists of a double value representing the base monthly cost.
The second line of input consists of a double value representing the service tax.
The third line of input consists of double values representing an extra feature cost.
Output Format
The output displays a double point number, representing the total monthly cost in the format "Rs. [total
cost]".

Refer to the sample output for the formatting specifications.


Constraints
In this scenario, the test cases will fall under the following constraints:
0.1 ≤ base monthly cost, service tax, extra feature cost ≤ 100.00
Sample Input Sample Output
10.0
2.5
5.0
Rs. 17.50
Sample Input Sample Output
12.765
34.98
10.23
Rs. 57.97
Sample Input Sample Output
98.56
99.67
94.56
Rs. 292.79
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q3.
Problem Statement

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 DiscountedProduct extends Product {


private double discountRate;

public DiscountedProduct(double price, double discountRate) {


this.price = price;
this.discountRate = discountRate;
}

public double calculateSellingPrice() {


double discountedPrice = price * (1 - discountRate);
return discountedPrice;
}
}

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

double initialPrice = scanner.nextDouble();


double discountRate = scanner.nextDouble();
DiscountedProduct discountedProduct = new DiscountedProduct(initialPrice, discountRate);
double sellingPrice = discountedProduct.calculateSellingPrice();
if (sellingPrice >= 0) {
System.out.printf("Rs. %.2f%n", sellingPrice);
} else {
System.out.println("Not applicable");
}
scanner.close();
}
}

Q2

Solution
import java.util.Scanner;

class Subscription {
public double monthlyCost;
public double serviceTax;
public double extraFeatureCost;
}

class PremiumSubscription extends Subscription {


public PremiumSubscription(double monthlyCost, double serviceTax, double extraFeatureCost) {
this.monthlyCost = monthlyCost;
this.serviceTax = serviceTax;
this.extraFeatureCost = extraFeatureCost;
}

public double calculateMonthlyCost() {


double totalCost = monthlyCost + serviceTax + extraFeatureCost;
return totalCost;
}
}

public class Main {


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

double baseMonthlyCost = scanner.nextDouble();


double serviceTax = scanner.nextDouble();
double extraFeatureCost = scanner.nextDouble();

PremiumSubscription premiumSubscription = new PremiumSubscription(baseMonthlyCost, serviceTax,


extraFeatureCost);

double totalMonthlyCost = premiumSubscription.calculateMonthlyCost();

System.out.printf("Rs. %.2f%n", totalMonthlyCost);

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;
}
}

class SeasonalBusinessUtility extends BusinessUtility {

public double calculateMargin(double revenue, double cost) {


double baseMargin = super.calculateMargin(revenue, cost);
double seasonalMargin = baseMargin + 10;
return seasonalMargin;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

double revenue = scanner.nextDouble();


double cost = scanner.nextDouble();

BusinessUtility business = new BusinessUtility();


SeasonalBusinessUtility seasonalBusiness = new SeasonalBusinessUtility();

double regularMargin = business.calculateMargin(revenue, cost);


double seasonalMargin = seasonalBusiness.calculateMargin(revenue, cost);

DecimalFormat df = new DecimalFormat("#.00");

System.out.println("Regular Margin: " + df.format(regularMargin) + "%");


System.out.println("Seasonal Margin: " + df.format(seasonalMargin) + "%");

if (regularMargin < 10) {


System.out.println("Business is not profitable.");
} else {
System.out.println("Business is profitable.");
}

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.

Note: Travel Distance = Speed * Fuel Capacity.


Input Format
The first line of input consists of a double type representing the speed.
The second line consists of a double-type representing the fuel capacity.
Output Format
The first line of output prints "Speed: X km/h" where X is the double value representing the speed, rounded
off to two decimal places.
The second line prints "Fuel Capacity: Y liters" where Y is the double value representing the fuel capacity,
rounded off to two decimal places.
The third line prints "Travel Distance: Z km" where Z is the double value representing the total distance,
rounded off to two decimal places.

Refer to the sample output for formatting specifications.


Constraints
In this scenario, the test cases will fall under the following constraints:
10.0 ≤ speed ≤ 1000.0
1.0 ≤ fuel capacity ≤ 400.0
Sample Input Sample Output
10.0
1.0
Speed: 10.00 km/h
Fuel Capacity: 1.00 liters
Travel Distance: 10.00 km
Sample Input Sample Output
456.90
12.54
Speed: 456.90 km/h
Fuel Capacity: 12.54 liters
Travel Distance: 5729.53 km
Sample Input Sample Output
1000.00
400.00
Speed: 1000.00 km/h
Fuel Capacity: 400.00 liters
Travel Distance: 400000.00 km
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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.

For Regular Customers:


Loyalty points are calculated as one point for every ten units of currency spent.
Loyalty Points = Amount Spent / 10

For Premium Customers:


Premium customers receive double the loyalty points compared to regular customers. That is two points for
every ten units of currency spent.
Loyalty Points = 2 * (Amount Spent / 10)
Input Format
The first line of the input consists of the Amount spent (an integer) - The amount spent by the customer.
The second line of the input consists of Premium customer status (a string) - "yes" if the customer is a
premium customer, "no" if they are not.
Output Format
The output displays the loyalty points (an integer) earned based on the amount spent.

Refer to the sample output for the formatting specification.


Constraints
The test cases will fall under the following constraints:
1 ≤ amount ≤ 100,000.
The premium customer status is indicated as a string, which will be "yes" or "no."
Sample Input Sample Output
50
yes
10
Sample Input Sample Output
40
no
4
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding

Q1

Solution
import java.util.Scanner;

class Vehicle {
public double speed;
public double fuelCapacity;
}

class Car extends Vehicle {


public Car(double speed, double fuelCapacity) {
this.speed = speed;
this.fuelCapacity = fuelCapacity;
}

public double calculateTravelDistance() {


return speed * fuelCapacity;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

double speed = scanner.nextDouble();


double fuelCapacity = scanner.nextDouble();

Car car = new Car(speed, fuelCapacity);

System.out.println("Speed: " + String.format("%.2f", car.speed) + " km/h");


System.out.println("Fuel Capacity: " + String.format("%.2f", car.fuelCapacity) + " liters");
System.out.println("Travel Distance: " + String.format("%.2f", car.calculateTravelDistance()) + " km");

scanner.close();
}
}

Q2

Solution
import java.util.Scanner;

class Customer {
public int calculateLoyaltyPoints(int amountSpent) {
return amountSpent / 10;
}
}

class PremiumCustomer extends Customer {


public int calculateLoyaltyPoints(int amountSpent) {
return 2 * (amountSpent / 10);
}
}

public class Main {


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

int amountSpent = scanner.nextInt();

String isPremium = scanner.next().toLowerCase();

Customer customer;

if (isPremium.equals("yes")) {
customer = new PremiumCustomer();
} else {
customer = new Customer();
}

int loyaltyPoints = customer.calculateLoyaltyPoints(amountSpent);


System.out.println(loyaltyPoints);
}}
CMREC_Java_Unit 1_PAH_Inheritance_Overriding
Q1.
Problem Statement

Karthick is working on a program involving Parent and Main classes.

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.

Refer to the sample output for the formatting specifications.


Constraints
The test cases will fall under the following constraints:
1 ≤ N ≤ 106
Sample Input Sample Output
1234
30
Sample Input Sample Output
4356
86
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Q2.
Problem Statement

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]"

Refer to the sample output for formatting specifications.


Constraints
The base price and the cost per topping should be greater than zero.
1 ≤ numberOfToppings ≤ 10
Sample Input Sample Output
9.5
1.25
3
Price without discount: Rs.13.25
Price with discount: Rs.13.25
Sample Input Sample Output
11.0
2.0
7
Price without discount: Rs.25.00
Price with discount: Rs.22.50
Time Limit: - ms Memory Limit: - kb Code Size: - kb
Answer Key & Solution
Section 1 - Coding
Q1

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;
}

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


sum += a[i];
}

System.out.print(sum);
}
}

class Main extends Parent {


public static void main(String args[]) {
int n;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
Main t = new Main();
t.fun(n);
}
}

Q2

Solution
import java.util.Scanner;
import java.text.DecimalFormat;

class Pizza {
private double basePrice;
private double toppingCost;

public Pizza(double basePrice, double toppingCost) {


this.basePrice = basePrice;
this.toppingCost = toppingCost;
}

public double calculatePrice(int numberOfToppings) {


return basePrice + (numberOfToppings * toppingCost);
}
}
class DiscountedPizza extends Pizza {
public DiscountedPizza(double basePrice, double toppingCost) {
super(basePrice, toppingCost);
}

public double calculatePrice(int numberOfToppings) {


if (numberOfToppings > 3) {
return super.calculatePrice(numberOfToppings) * 0.9;
} else {
return super.calculatePrice(numberOfToppings);
}
}
}

public class Main {


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

double basePrice = scanner.nextDouble();


double toppingCost = scanner.nextDouble();
int numberOfToppings = scanner.nextInt();

Pizza pizza = new Pizza(basePrice, toppingCost);


DiscountedPizza discountedPizza = new DiscountedPizza(basePrice, toppingCost);

DecimalFormat df = new DecimalFormat("#.00");

double regularPrice = pizza.calculatePrice(numberOfToppings);


double discountedPrice = discountedPizza.calculatePrice(numberOfToppings);

System.out.println("Price without discount: Rs." + df.format(regularPrice));


System.out.println("Price with discount: Rs." + df.format(discountedPrice));

scanner.close();
}
}

You might also like