Programming in Java – 18CS653 Module 2 Solutions
MODULE 2
1. Discuss the label break and continue with example. (Mar 2022) (05 Marks) (Sept
2020) (06 Marks) (July 2019) (08 Marks)(Feb 2023)(10M)(Aug 2022)(6M)
Break and Continue
o break is used to break out of loop, it acts as an exit statement for loops.
Example,
for(int i ; i<5; i++)
{
if(i==4)
{
break;
}
System.out.print(i);
}
OUTPUT: 1 2 3
o continue is used to continue the loop execution by discarding all the statements
next to continue keyword.
Example,
for(int i ; i<5; i++)
{
if(i==3)
{
continue;
}
System.out.print(i);
}
OUTPUT: 1 2 4 5
2. List and explain different iteration. (Mar 2022) (07 Marks) (Feb 2021) (06 Marks)
(July 2019) (08 Marks)(Fe 2023)(8M)
The types of iterations are
i. while
ii. do-while
iii. for
iv. for-each
while Loop
It is an entry-controlled looping structure. It is used when user does not know how many
times the loop might execute
Syntax:
while(test-expression)
{
Body of the loop;
}
Prof. Jayashree N, Dept. of ISE, CiTech. 1
Programming in Java – 18CS653 Module 2 Solutions
Next statement;
Example,
int i=0
While(1)
{
if(i>10){
break;
}
System.out.println(“i=” + i);
i++;
}
do-while Loop
It is an Exit-controlled looping structure. It executed the body of the loop at least once
before checking the condition.
Syntax:
do
{
Body of the loop;
} while(test-expression);
Next statement;
Example,
int i=0
do
{
System.out.println(“i=” + i);
i++;
} While(i>10);
for Loop
It is an entry-controlled looping structure. It is used when user exactly knows the
number of times the loop must execute.
Syntax:
For(assignment; condition, expression)
Prof. Jayashree N, Dept. of ISE, CiTech. 2
Programming in Java – 18CS653 Module 2 Solutions
Next statement;
Example,
For(int i=0 ;i <10 ; i++)
{
System.out.println(“i=” + i);
}
for-each Loop
It is a loop used to read container classes and Arrays. It is an easy approach to read all
the contents of array. Remember this loop cannot be used to read specific contents, it is
used to read entire data in array or container classed like linked list, queue, stack, etc.
Syntax:
for(variable : array_name)
{
Statement;
}
Next statement;
Example,
int a[]={1, 2, 3}
for(int i : a)
{
System.out.println( i);
}
3. Write a JAVA program to display prime numbers between two intervals. (Mar
2022) (07 Marks) (Sept 2020) (06 Marks)
class Prime {
public static void main(String[] args) {
int low = 1, high = 10;
while (low < high) {
boolean flag = false;
for(int i = 2; i <= low/2; ++i) {
// condition for nonprime number
if(low % i == 0) {
flag = true;
break;
}
}
if (!flag)
Prof. Jayashree N, Dept. of ISE, CiTech. 3
Programming in Java – 18CS653 Module 2 Solutions
System.out.print(low + " ");
++low;
}
}
}
OUTPUT:
2357
4. With syntax, describe switch statement. (Mar 2022) (05 Marks) (July 2019) (06
Marks)
Switch statement is a multi-way decision statement it is similar to the switch statement
of C and C++ and the general syntax is as follows:
switch(expression)
{
case value-1: block-1;
break;
case value-2: block-2
break;
...
default : default-block;
break;
}
Statement-X;
The expression must be of type byte, short, int, or char; each of the values specified in
the case statements must be of a type compatible with the expression.
• The value of the expression is compared with each of the literal values in the
case statements.
• If a match is found, the code sequence following that case statement is executed.
• If none of the constants matches the value of the expression, then the default
statement is executed.
• The default statement is optional. If no case matches and no default is present,
then no further action is taken
Example,
switch(choice)
{
case 1: System.out.println(“Case-1”);
break;
case 2: System.out.println(“Case-2”);
break;
case 3: System.out.println(“Case-3”);
break;
default: System.out.println(“Default value”);
break;
}
System.out.println(“statement outside switch”);
Prof. Jayashree N, Dept. of ISE, CiTech. 4
Programming in Java – 18CS653 Module 2 Solutions
}
5. What are multi-dimensional arrays? Write a JAVA program to add two matrices.
(Mar 2022) (08 Marks)
Multi-dimensional arrays are arrays of arrays. To declare a multidimensional array
variable, specify each additional index using another set of square brackets.
JAVA program to add two matrices
class MatrixAdditionExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//adding and printing addition of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
OUTPUT:
268
486
469
6. What is Ternary operator? Write a JAVA program to find the absolute value of a
variable. (Mar 2022) (07 Marks)
? is a ternary operator to replace certain types of if-then-else statements. It has this
general form:
expression1?expression2:expression3
• Here, expression1 can be any expression that evaluates to a boolean value.
• If expression1 is true, then expression2 is evaluated; otherwise, expression3
is evaluated.
• The result of the ? operation is that of the expression evaluated. Both
expression2 and expression3 are required to return the same type, which
can’t be void.
JAVA program to fine absolute value of a variable
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
Prof. Jayashree N, Dept. of ISE, CiTech. 5
Programming in Java – 18CS653 Module 2 Solutions
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
The output generated by the program is shown here:
Absolute value of 10 is 10
Absolute value of -10 is 10
7. With syntax describe the following : (i) if-else-if ladder (ii) for loop. (Mar 2022)
(05 Marks)
if-else Ladder
A common programming construct that is based upon a sequence of nested ifs is the if-
else-if ladder. It looks like this:
if(test expression)
{
statement1;
statement2;
}
else if(test expression)
{
Statement3;
}
else
{
Statement 4;
}
• The if statements are executed from the top down.
• As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed.
• If none of the conditions is true, then the final else statement will be executed.
• The final else acts as a default condition; that is, if all other conditional tests
fail, then the last else statement is performed. If there is no final else and all
other conditions are false, then no action will take place.
for Loop
It is an entry-controlled looping structure. It is used when user exactly knows the
number of times the loop must execute.
Syntax:
For(assignment; condition, expression)
Next statement;
Example,
Prof. Jayashree N, Dept. of ISE, CiTech. 6
Programming in Java – 18CS653 Module 2 Solutions
For(int i=0 ;i <10 ; i++)
{
System.out.println(“i=” + i);
}
8. Explain with example,
i. Short Circuit Logic Operator
ii. Foreach (Mar 2022) (02 Marks)
Short-circuit Logic Operator
The short-circuit logic operators are:
i. || → short-circuit OR
ii. && → short-circuit AND
When these operators are used, Java will not bother to evaluate the right-hand operand
when the outcome of the expression can be determined by the left operand alone.
Example,
int denom=0;
if (denom != 0 && num / denom > 10)
the above statement will not throw a run-time exception for the right-hand operand
since && is used.
For each
It is a loop used to read container classes and Arrays. It is an easy approach to read all
the contents of array. Remember this loop cannot be used to read specific contents, it is
used to read entire data in array or container classed like linked list, queue, stack, etc.
Syntax:
for(variable : array_name)
{
Statement;
}
Next statement;
Example,
int a[]={1, 2, 3}
for(int i : a)
{
System.out.println( i);
}
Prof. Jayashree N, Dept. of ISE, CiTech. 7
Programming in Java – 18CS653 Module 2 Solutions
9. List different types of operators. Explain any two/three. (July 2021) (04 Marks)
(Feb 2021) (08 Marks) (July 2019)(08 Marks) (July 2019) (08 Marks)(Aug
2022)(8M)
Types of operators:
i. The Basic Arithmetic Operators
ii. The Modulus Operator
iii. Arithmetic Compound Assignment Operators
iv. Increment and Decrement
The Basic Arithmetic Operators:
• The basic arithmetic operations—addition, subtraction, multiplication, and
division.
• The minus operator also has a unary form
• that negates its single operand
• Example snippet
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
The Modulus Operator:
• The modulus operator, %, returns the remainder of a division operation.
• It can be applied to floating-point types as well as integer types.
• Example,
int x = 42;
double y = 42.25;
c=x % 10 // returns 2
d=y % 10 //returns 2.25
Arithmetic Compound Assignment Operators
• Used to combine an arithmetic operation with an assignment.
• Example,
a = a + 4;
can be written using compound assignment operator as
a += 4;
Increment and Decrement
• The ++ and the – – are Java’s increment and decrement operators
• The increment operator increases its operand by one.
• The decrement operator decreases its operand by one.
• Example,
x=x+1;
can be written using increment operator as
Prof. Jayashree N, Dept. of ISE, CiTech. 8
Programming in Java – 18CS653 Module 2 Solutions
x++ ;
• There are two forms for both operators: Pre-increment/decrement and Post-
increment/decrement.
o The pre-operator updates the value of the operand first and then applied the
value in an expression. ( ++x or --x)
o The post-operator evaluates the expression with the current value of the
operand and then updates the value of the operand. (x++ or x--)
10. Develop the program to calculate the average among the elements {4, 8, 10, 12}
using foreach in Java. How foreach is different from for? (July 2021) (08 Marks)
(Feb 2021) (06 Marks) (Feb 2021) (08 Marks) (Sept 2020) (04 Marks) (July 2019)
(08 Marks) (Sept 2020) (06 Marks) (Sept 2020) (08 Marks)(Feb
2023)(6M)(10M)(Aug 2022)(6M)
// Use a for-each style for loop to find sum and average of array elements
class ForEach1 {
public static void main(String args[]) {
int nums[] = { 4,8,10,12 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
System.out.println("Average: " + sum/nums.length);
}
}
//Program to find sum of even numbers in an array
class ForEachE {
public static void main(String args[]) {
int nums[] = { 4,5,6,7,8,9,10,11,12 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
if(x%2==0){
System.out.println("Value is: " + x);
sum += x;
}
}
System.out.println("Summation: " + sum);
}
}
Prof. Jayashree N, Dept. of ISE, CiTech. 9
Programming in Java – 18CS653 Module 2 Solutions
Difference between foreach and for
for Loop
for loop is used to iterate through the array or the elements for a specified number of
times. If a certain amount of iteration is known, it should be used.
Syntax:
For(assignment; condition, expression)
Next statement;
Example:
For(int i=0 ;i <10 ; i++)
{
System.out.println(“i=” + i);
}
Foreach Loop
It is a loop used to read container classed and Arrays. It is an easy approach to read all
the contents of array. Remember this loop cannot be used to read specific contents, it is
used to read entire data in array or container classed like linked list, queue, stack, etc.
Syntax:
for(variable : array_name)
{
Statement;
}
Next statement;
Example:
int a[]={1, 2, 3}
for(int i : a)
{
System.out.println( i);
}
11. Write a Java program to read n elements using array and a key element to search.
Perform linear search operation using ‘foreach’ statement and print suitable
message for successful and unsuccessful search. (Feb 2021) (06 Marks)
import java.util.Scanner;
class example3
{
public static void main(String args[])
{
int i,len, key, array[];
Scanner input = new Scanner(System.in);
System.out.println("Enter Array length:");
len = input.nextInt();
Prof. Jayashree N, Dept. of ISE, CiTech. 10
Programming in Java – 18CS653 Module 2 Solutions
array = new int[len];
System.out.println("Enter " + len + " elements");
for (i = 0; i < len; i++)
{
array[i] = input.nextInt();
}
System.out.println("Enter the search key value:");
key = input.nextInt();
int j=0;
for (int x:array)
{
if (x== key)
{
System.out.println(key+" is present at location "+(j+1));
break;
}
j++;
}
if (i == len+1)
System.out.println(key + " doesn't exist in array.");
}
}
12. Write a note on:
i. Type casting
ii. Short circuit operator
iii. >> and >>> (Feb 2021) (08 Marks)
(Jan 2019) (04 Marks) (Jan 2019)(05 Marks) (Feb 2023)(6M)(Aug
2022)(6M)
i. Type Casting
When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place.
For example, the
int type is always large enough to hold all valid byte values, so no explicit
cast statement is required.
If the destination type is shorter than the source type then narrowing
conversion takes place. To create a conversion between two incompatible
types, you must use a cast. A cast is simply an explicit type conversion.
General form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to
Prof. Jayashree N, Dept. of ISE, CiTech. 11
Programming in Java – 18CS653 Module 2 Solutions
For example,
int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is
assigned to an integer type: truncation.
ii. Short Circuit Operator
The short-circuit logic operators are:
iii. || → short-circuit OR
iv. && → short-circuit AND
When these operators are used, Java will not bother to evaluate the right-hand
operand when the outcome of the expression can be determined by the left
operand alone.
Example,
int denom=0;
if (denom != 0 && num / denom > 10)
the above statement will not throw a run-time exception for the right-hand
operand since && is used.
iii. >> and >>>
>>
• The right shift operator, >>, shifts all of the bits in a value to the right a
specified number of times.
• Syntax:
value >> num
✓ num specifies the number of positions to right-shift the value in value.
✓ the >> moves all of the bits in the specified value to the right the number of bit
positions specified by num
• Example,
int a = 32;
a = a >> 2; // a now contains 8
• When a value has bits that are “shifted off,” those bits are lost.
• Example,
int a = 35;
Prof. Jayashree N, Dept. of ISE, CiTech. 12
Programming in Java – 18CS653 Module 2 Solutions
a = a >> 2; // a still contains 8
i.e.,
00100011 35
>> 2
00001000 8
• Right shift operator retains the sign of the number. This is termed as sign
extension.
• Example, if the given number is a negative number, the resulting number is
also negative.
11111000 –8
>>1
11111100 –4
i.e. the sign extension brings ones into the high-order bits while shifting.
>>>
• It is an unsigned right shift with zero fill operator.
• It is used to shift a number that does not represent a numeric value. For example,
pixel-based value.
• This operator shifts a zero into the high-order bit no matter what is its initial
value was.
• Example,
int a = -1;
a = a >>> 24;
The binary representation of the initial and shifted values of a are as follows:
11111111 11111111 11111111 11111111 –1 in binary as an int
>>>24
00000000 00000000 00000000 11111111 255 in binary as an int
Smaller values are automatically promoted to int in expressions. This means
that sign-extension occurs and that the shift will take place on a 32-bit rather
than on an 8- or 16-bit value.
13. What is an array? Write a Java program to print sum of each row of two-
dimensional array.
𝟏 𝟐 𝟑
For example, [𝟒 𝟓 𝟔]
𝟕 𝟖 𝟗
𝟔
O/p should be [𝟏𝟓] (Feb 2021) (08 Marks)
𝟐𝟒
(Feb 2021) (08 Marks)
Prof. Jayashree N, Dept. of ISE, CiTech. 13
Programming in Java – 18CS653 Module 2 Solutions
Array
An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and may have one or more dimensions. A specific
element in an array is accessed by its index. Arrays offer a convenient means of
grouping related information.
// Java program to print sum of each row of two-dimensional array.
import java.util.Scanner;
public class SumOfMatrixRows {
public static void main(String[] args) {
int i, j, sum,m,n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows and columns");
m=sc.nextInt();
n=sc.nextInt();
int SumOfRows_arr[][]=new int[m][n];
System.out.println("Enter the matrix elements\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
SumOfRows_arr[i][j]=sc.nextInt();
System.out.println("\nThe Sum of Matrix Items in matrix is");
for(i = 0; i < m; i++)
{
sum = 0;
for(j = 0; j < n; j++)
{
sum = sum + SumOfRows_arr[i][j];
}
System.out.println(sum);
}
}
}
14. Explain switch case with an example. (Feb 2021) (04 Marks)
Switch statement is a multi-way decision statement it is similar to the switch statement
of C and C++ and the general form is as follows: -
switch(expression)
{
case value-1: block-1;
break;
case value-2: block-2
break;
...
default : default-block;
break;
}
Statement-X;
Prof. Jayashree N, Dept. of ISE, CiTech. 14
Programming in Java – 18CS653 Module 2 Solutions
For example,
switch(choice)
{
case 1: System.out.println(“Case-1”);
break;
case 2: System.out.println(“Case-2”);
break;
case 3: System.out.println(“Case-3”);
break;
default: System.out.println(“Default value”);
break;
}
System.out.println(“statement outside switch”);
}
15. Discuss Bitwise and relational operators in Java. (Feb 2021) (02 Marks)
Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types, long, int,
short, char, and byte. These operators act upon the individual bits of their operands.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown
here:
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
16. Write a Java program to find largest of 3 numbers. (Feb 2021) (06 Marks)
import java.util.Scanner;
public class LargestNumber
{
Prof. Jayashree N, Dept. of ISE, CiTech. 15
Programming in Java – 18CS653 Module 2 Solutions
public static void main(String[] args)
{
int a, b, c, largest, temp;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first number:");
a = sc.nextInt();
System.out.println("Enter the second number:");
b = sc.nextInt();
System.out.println("Enter the third number:");
c = sc.nextInt();
temp=a>b?a:b;
largest=c>temp?c:temp;
//prints the largest number
System.out.println("The largest number is: "+largest);
}
}
17. Write a JAVA program to calculate Sum and average of first six elements of an
array {10, 20, 32, 42, 55, 60, 75, 82, 90, 92} using for each loop. How for each is
different from for loop[Refer QUESTION 18 for difference]. (Sept 2020)(6 Marks)
(Jan 2019) (06 Marks)
// Use a for-each style for loop.
class ForEach2 {
public static void main(String args[]) {
int nums[] = {10, 20, 32, 42, 55, 60, 75, 82, 90, 92} ;
int sum = 0;
int i=0;
// use for-each style for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
if(x==nums[6-1]) break;
}
System.out.println("Summation: " + sum);
System.out.println("Average: " + sum/6);
}
}
18. class Example {
public static void main (String args[ ]) {
int a;
for (a = 0; a < 3; a++)
{ int b = −1;
System.out.println (“ ” + b);
b = 50;
System.out.println (“ ” + b);
}
}
}
Prof. Jayashree N, Dept. of ISE, CiTech. 16
Programming in Java – 18CS653 Module 2 Solutions
What is the output of the above code? If you insert another ‘int b’ outside the for
loop, what is the output. (Jan 2019) (04 Marks)
The output of the given program is
-1
50
-1
50
-1
50
If another int b is inserted outside the for loop, it does not affect the output as the first
b in the for loop is local variable within the scope of for loop.
19. Explain with examples three uses of break statement in java. (July 2019) (08
Marks)
break to exit a loop
Using break immediate termination of a loop can be forced, bypassing the conditional
expression and any remaining code in the body of the loop.
• When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
• Example,
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Break as a form of goto
The goto can be useful while exiting from a deeply nested set of loops. To handle such
situations, Java defines an expanded form of the break statement. By using this form of
break, it is possible to, for example, break out of one or more blocks of code. These
blocks need not be part of a loop or a switch. They can be any block. For example,
class Break {
public static void main(String args[]) {
boolean t = true;
boolean u = true;
boolean v = true;
first: {
System.out.println("First block starts");
second: {
System.out.println("Second block starts");
third: {
System.out.println("Third block starts");
if(t) break third; // break out of second block
System.out.println("This won't execute");
}
Prof. Jayashree N, Dept. of ISE, CiTech. 17
Programming in Java – 18CS653 Module 2 Solutions
System.out.println("This is after break to third block.");
if(u) break second;
}
System.out.println("This is after break to second block.");
if(v) break first;
}
System.out.println("This is after break to first block.");
}
}
20. Write a Java program to initialize an array of 5 elements {12,25,42,35,65}; and
display the sum and average of the numbers. (Aug 2022)(6M)
class SumAvg {
public static void main(String args[]) {
int nums[] = { 12,25,42,35,65 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
System.out.println("Average: " + sum/nums.length);
}
}
Prof. Jayashree N, Dept. of ISE, CiTech. 18