0% found this document useful (0 votes)
156 views17 pages

Iamneo Control Statements and Arrays

The document contains a series of Java programming problems and their solutions, covering topics such as control statements, arrays, and mathematical calculations. Each problem is presented with a specific scenario, followed by the corresponding Java code that implements the solution. The problems range from calculating BMI and utility bills to finding diagonal sums in matrices and identifying lucky numbers based on digit sums.

Uploaded by

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

Iamneo Control Statements and Arrays

The document contains a series of Java programming problems and their solutions, covering topics such as control statements, arrays, and mathematical calculations. Each problem is presented with a specific scenario, followed by the corresponding Java code that implements the solution. The problems range from calculating BMI and utility bills to finding diagonal sums in matrices and identifying lucky numbers based on digit sums.

Uploaded by

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

What will be the output of the following program?

public class Main {

public static void main(String[] args) {

int a=15;

int b=25;

if ((a<b) || (a=5)>15)

System.out.print(a);

else

System.out.print(b);

Ans:15

2.What will be the output of the following code?

public class Main {

public static void main(String[] args) {

int a = 5;

a +=5;

switch(a) {

case 5:

System.out.print("5");

break;

case 10:

System.out.print("10");

break;

default:

System.out.print("0");

Ans :10

3.
public class Main {

public static void main(String[] args) {

int hops = 0;

int jumps = 0;

jumps = hops++;

if (jumps != 0) {

System.out.print("Jump!");

} else {

System.out.print("Hop!");

Ans:Hop!

4.How many times the word "main" will be printed?

public class Main {

public static void main(String[] args) {

while(true) {

System.out.println("main");

Ans: Infinite times

5.What will be the output of the following code?

public class Main {

public static void main(String args[]) {

int i = 0;

for (System.out.print("Wise"); i < 1; i++)

System.out.print("Stark");

}
}

Ans: WiseStark

6. class Main {

public static void main(String args[]) {

int x = 2;

int y = 0;

for ( ; y < 10; ++y) {

if (y % x == 0)

continue;

else if (y == 8)

break;

else

System.out.print(y + " ");

Ans:

13579

7.public class Main {

public static void main(String[] args) {

int[] x = {120, 200, 164};

for(int i = 0; i < 3; i++)

System.out.print(x[i] + " ");

Ans:

120 200 164

8. public class Main {

public static void main(String args[]) {

int[] myList = {1, 5, 6, 7, 8, 9};

int max = myList[0];

int index = 0;

for(int i = 1; i < myList.length; i++){


if(myList[i] > max){

max = myList[i];

index = i;

System.out.print(index);

Ans:

Q9.

Consider a 2D array in Java with dimensions M x N, where M represents the number of rows and N
represents the number of columns.

The array is filled with integers such that the element at index (i, j) is denoted by arr[i][j]. The indices
are 0-based, i.e., the first row and first column have index 0.

Which of the following options correctly represents the code to calculate the sum of all elements in
the array?

ANS:

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

10Which of the following statements assigns the letter S to the third row and first column of a two-
dimensional array named strGrid (assuming row-major order)?

ANS:

strGrid[2][0] = "S";
CMREC_Java_Unit 1_COD_Control Statements_Arrays Problem Statement

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

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

SOLUTION: HINT: FIND THE EVEN NUMBER FROM 2 TO GIVEN NUMBER


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:
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.
Solution hint: finding sum of the individual digits in a given number
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();
}
}

5Problem 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.
Solutiom: hint: create a single dimensional array of n elements and find difference between the first
and last elements.
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);
}
}
6Problem 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.
Solution: to find number of elements divisible by 3

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

7.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.
Solution: hint : sum of diagonal elements

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

8.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
Solution: hint: transpose of given matrix
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

1. 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:
The cost per unit for electricity is 0.12, for water is 0.05, and for gas is
0.08.
A discount is applied to the total cost based on the following conditions:
If the total cost is 100 or more, a 10% discount is applied.
If the total cost is between 50 and 99.99, a 5% discount is applied.
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.

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

Check if X is a lucky number (divisible by the sum of its digits).


If it is a lucky number, congratulate Joe and let him know.
If it is not a lucky number, find and display the closest smaller lucky number.

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

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.
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.
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.
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.
Solution:hint: display the row sum as a matrix of columns
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.

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

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy