0% found this document useful (0 votes)
14 views32 pages

Understanding Nested Loops in Java

The document covers the concept of nested loops in programming, specifically in Java, including multiple choice questions and answers related to nested loops, break statements, and loop iterations. It also provides programming exercises to calculate series sums, check for twin primes, display numbers without zeros, and find prime palindromes, among others. Additionally, it includes sample code for various Java programs that demonstrate these concepts.

Uploaded by

Ashok Garg
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)
14 views32 pages

Understanding Nested Loops in Java

The document covers the concept of nested loops in programming, specifically in Java, including multiple choice questions and answers related to nested loops, break statements, and loop iterations. It also provides programming exercises to calculate series sums, check for twin primes, display numbers without zeros, and find prime palindromes, among others. Additionally, it includes sample code for various Java programs that demonstrate these concepts.

Uploaded by

Ashok Garg
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

Chapter 1 - Unit 9

Nested Loop
Class 10 - APC Understanding Computer Applications
with BlueJ

Multiple Choice Questions

Question 1

A loop within another loop is called a:

1. double loop
2. embedded loop
3. circular loop
4. nested loop

Answer

nested loop

Reason — A loop within another loop is called a nested loop.

Question 2

The ............... break is used to terminate the outer loop from the block of inner loop.

1. level
2. labelled
3. unlabelled
4. forced

Answer

labelled

Reason — The labelled break is used to terminate the outer loop from the block of inner loop.

Question 3

Which of the following keywords can be used to terminate a switch case as well as a loop construct?

1. continue
2. void
3. break
4. stop

Answer

break
Reason — break can be used to terminate a switch case as well as a loop construct.

Question 4

Given: for(i = 0 ; i < 4 ; i++)


for(j = 1 ; j < 4 ; j++)
...............
Statement
...............
How many times the above nested loop will iterate?

1. 12 times
2. 8 times
3. 4 times
4. 16 times

Answer

12 times

Reason — The outer loop will execute 4 times. For each iteration of outer loop, the inner loop will execute 3 times.
Therefore, total iterations of nested loop will be 4 x 3 = 12 times. The below table summarizes the iteration of nested
loops:

Value of i Value of j

0 1

1 1

2 1

3 1

2
Value of i Value of j

Question 5

Which of the following statements is not valid for a nested loop?

1. The break statement can be used to terminate inner as well as outer loop.
2. The outer loop can be terminated from the block of inner loop.
3. The inner loop can be terminated from the block of outer loop.
4. The inner loop repeats the execution a number of times for each iteration of the outer loop.

Answer

The inner loop can be terminated from the block of outer loop.

Reason — The inner loop cannot be terminated from the block of outer loop.

State True or False

Question 1

Nested loop contains a single loop.


False

Question 2

When break statement is applied, it terminates the loop.


True

Question 3

The outer loop follows next iteration when iterations of inner loop is over.
True

Question 4

Nested loop means the using of two or more loops in a program.


False

Question 5

Labelled break statement allows the next iteration of the loop from any place of looping structure.
False

Question 6

In a nested loop, break and continue can be used simultaneously.


False

Answer the following questions


Question 1

What is a nested loop?

Answer

When we use a loop within another loop, it is said to be a nested loop. The inner loop repeats a number of times for
each repetition of the outer loop.

Question 2

Write down the syntax of a nested for loop.

Answer

The syntax of nested loop is as follows:

for (<initial value>; <test condition>; <update value>) {

for (<initial value>; <test condition>; <update value>) {

executable statement(s)

Question 3

What action will you take to terminate an outer loop from the block of an inner loop?

Answer

An outer loop can be terminated from the block of an inner loop by using labelled break statement as shown in the
example given below:

outer: for (int i = 1; i <= 5; i++) {


for (int j = 1; j <= 10; j++) {
[Link](j);
if (i == 3)
break outer;
}
}
[Link]("Outside outer loop");

Question 4

What is significance of break outer and continue outer in a nested loop?

Answer

break outer will terminate the loop that is labelled as outer in a nested loop and transfer the program control to the
statement just after the loop labelled as outer.

continue outer will skip the remaining statements of the nested loop and start the next iteration of the loop that is
labelled as outer.
Question 6

Write down the constructs (syntax) of:

(a) Nested do-while loop

(b) Nested while loop

Answer

(a) Construct of Nested do-while loop

do {
//statements of outer do-while loop
..
..
do {
//statements of inner do-while loop
} while (<condition>);
..
..
} while (<condition>);
(b) Construct of Nested while loop

while (<condition>) {
//statements of outer while loop
..
..
while (<condition>) {
//statements of inner while loop
}
..
..
}
Solutions to Unsolved Java Programs

Question 1

Write programs to find the sum of the following series:

(a) S = 1 + (3/2!) + (5/3!) + (7/4!) + ....... to n

import [Link];

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner([Link]);
[Link]("Enter n: ");
int n = [Link]();
double sum = 0.0;
for (int i = 1, j = 1; i <= n; i++, j = j + 2) {
double f = 1;
for (int k = 1; k <= i; k++) {
f *= k;
}
sum += j / f;
}
[Link]("Sum=" + sum);
}
}

Output

(b) S = a + (a/2!) + (a/3!) + (a/4!) + ....... + (a/n!)

import [Link];

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner([Link]);
[Link]("Enter a: ");
int a = [Link]();
[Link]("Enter n: ");
int n = [Link]();
double sum = 0;

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


double f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
sum += a / f;
}
[Link]("Sum=" + sum);

}
}
Output

(c) S = a - (a/2!) + (a/3!) - (a/4!) + ....... to n

import [Link];

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner([Link]);
[Link]("Enter a: ");
int a = [Link]();
[Link]("Enter n: ");
int n = [Link]();
double sum = 0;

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


double f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
if (i % 2 == 0)
sum -= a / f;
else
sum += a / f;
}
[Link]("Sum=" + sum);

}
}
Output

(d) S = (a/2!) - (a/3!) + (a/4!) - (a/5!) + ....... + (a/10!)

import [Link];

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner([Link]);
[Link]("Enter a: ");
int a = [Link]();
double sum = 0;

for (int i = 2; i <= 10; i++) {


double f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
if (i % 2 == 0)
sum += a / f;
else
sum -= a / f;
}
[Link]("Sum=" + sum);

}
}
Output

(e) S = (2/a) + (3/a2) + (5/a3) + (7/a4) + ....... to n

import [Link];

public class KboatSeries


{
public void computeSum() {
Scanner in = new Scanner([Link]);
[Link]("Enter a: ");
int a = [Link]();
[Link]("Enter n: ");
int n = [Link]();
double sum = 0;
int lastPrime = 1;

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


for (int j = lastPrime + 1; j <= Integer.MAX_VALUE; j++) {
boolean isPrime = true;
for (int k = 2; k <= j / 2; k++) {
if (j % k == 0) {
isPrime = false;
break;
}
}

if (isPrime) {
sum += j / [Link](a, i);
lastPrime = j;
break;
}
}
}
[Link]("Sum=" + sum);
}
}

Output

Question 2

Write a program to input two numbers and check whether they are twin prime numbers or not.
Hint: Twin prime numbers are the prime numbers whose difference is 2.
For example: (5,7), (11,13), ....... and so on.

import [Link];

public class KboatTwinPrime


{
public void twinPrimeCheck() {

Scanner in = new Scanner([Link]);

[Link]("Enter first number: ");


int a = [Link]();

[Link]("Enter second number: ");


int b = [Link]();

boolean isAPrime = true;

for (int i = 2; i <= a / 2; i++) {

if (a % i == 0) {
isAPrime = false;
break;
}
}

if (isAPrime && [Link](a - b) == 2) {

boolean isBPrime = true;

for (int i = 2; i <= b / 2; i++) {

if (b % i == 0) {
isBPrime = false;
break;
}

if (isBPrime)
[Link](a + " and " + b + " are twin prime");
else
[Link](a + " and " + b + " are not twin prime");
}
else
[Link](a + " and " + b + " are not twin prime");
}
}

Output
Question 3

Write a program to display all the numbers between 100 and 200 which don't contain zeros at any position.
For example: 111, 112, 113, ....... , 199

public class KboatNoZero


{
public void display() {

int count = 0;
for (int i = 100; i <= 200; i++) {

boolean isNoZero = true;


int t = i;
while (t > 0) {
if (t % 10 == 0) {
isNoZero = false;
break;
}

t /= 10;
}

if (isNoZero) {
[Link](i + " ");
count++;
}

//This will print 10 numbers per line


if (count == 10) {
[Link]();
count = 0;
}
}

}
}
Output

Question 4

Write a program to display all prime palindrome numbers between 10 and 1000.
[Hint: A number which is prime as well a palindrome is said to be 'Prime Palindrome' number.]
For example: 11, 101, 131, 151,

public class KboatPrimePalindrome


{
public void displayPrimePalindrome() {

int count = 0;

for (int i = 10; i <= 1000; i++) {

int num = i, revNum = 0;


while (num != 0) {
int digit = num % 10;
num /= 10;
revNum = revNum * 10 + digit;
}

if (revNum == i) {
boolean isPrime = true;
for (int j = 2; j <= i / 2; j++) {

if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
[Link](i + " ");
count++;
if (count == 10) {
[Link]();
count = 0;
}
}
}
}
}
}

Output

Question 5

In an entrance examination, students have been appeared in English, Maths and Science papers. Write a program to
calculate and display average marks obtained by all the students. Take number of students appeared and marks
obtained in all three subjects by every student along with the name as inputs.
Display the name, marks obtained in three subjects and the average of all the students.

import [Link];

public class KboatStudentMarks


{
public void studentMarks() {
Scanner in = new Scanner([Link]);
[Link]("Enter number of students: ");
int studentCount = [Link]();

String names[] = new String[studentCount];


int engMarks[] = new int[studentCount];
int sciMarks[] = new int[studentCount];
int mathsMarks[] = new int[studentCount];
double avgMarks[] = new double[studentCount];
double totalMarks = 0.0;

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


[Link]("Enter details of student " + (i + 1));
[Link]("Name: ");
[Link]();
names[i] = [Link]();
[Link]("Marks in English: ");
engMarks[i] = [Link]();
[Link]("Marks in Science: ");
sciMarks[i] = [Link]();
[Link]("Marks in Maths: ");
mathsMarks[i] = [Link]();
avgMarks[i] = (engMarks[i] + sciMarks[i] + mathsMarks[i]) / 3.0;
totalMarks += avgMarks[i];
}

[Link]();

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


[Link]("Details of student " + (i + 1));
[Link]("Name: " + names[i]);
[Link]("English: " + engMarks[i]);
[Link]("Science: " + sciMarks[i]);
[Link]("Maths: " + mathsMarks[i]);
[Link]("Average: " + avgMarks[i]);
}

double classAvg = totalMarks / studentCount;


[Link]("\nAverage of all students is " + classAvg);
}
}
Output

Question 6

Write a program in Java to enter a number containing three digits or more. Arrange the digits of the entered number
in ascending order and display the result.
Sample Input: Enter a number 4972
Sample Output: 2, 4, 7, 9

import [Link];
public class KboatDigitSort
{
public void sortDigits() {
Scanner in = new Scanner([Link]);
[Link]("Enter a number having 3 or more digits: ");
int OrgNum = [Link]();

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


int num = OrgNum;
int c = 0;
while (num != 0) {
if (num % 10 == i)
c++;
num /= 10;
}
for (int j = 1; j <= c; j++) {
[Link](i + ", ");
}
}

[Link]();
}
}

Output

Question 7

Write a program to input a number and check whether it is 'Magic Number' or not. Display the message accordingly.
A number is said to be a magic number if the eventual sum of digits of the number is one.
Sample Input : 55
Then, 5 + 5 = 10, 1 + 0 = 1
Sample Output: Hence, 55 is a Magic Number.
Similarly, 289 is a Magic Number.

import [Link];

public class KboatMagicNum


{

public static void main(String args[]) {


Scanner in = new Scanner([Link]);
[Link]("Enter number to check: ");
int num = [Link]();
int n = num;

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

if (n == 1)
[Link](num + " is Magic Number");
else
[Link](num + " is not Magic Number");

}
}

Output

Question 8

A number is said to be Multiple Harshad number, when divided by the sum of its digits, produces another 'Harshad
Number'. Write a program to input a number and check whether it is a Multiple Harshad Number or not.
(When a number is divisible by the sum of its digit, it is called 'Harshad Number').

Hint: 6804 ⇒ 6+8+0+4 = 18 ⇒ 6804/18 = 378


Sample Input: 6804

378 ⇒ 3+7+8= 18 ⇒ 378/18 = 21


21 ⇒ 2+1 = 3 ⇒ 21/3 = 7
Sample Output: Multiple Harshad Number

import [Link];

public class KboatMultipleHarshad


{
public void checkMultipleHarshad() {

Scanner in = new Scanner([Link]);


[Link]("Enter number to check: ");
int num = [Link]();
int dividend = num;
int divisor;
int count = 0;

while (dividend > 1) {


divisor=0;
int t = dividend;
while (t > 0) {
int d = t % 10;
divisor += d;
t /= 10;
}

if (dividend % divisor == 0 && divisor != 1) {


dividend = dividend / divisor;
count++;
}
else {
break;
}
}

if (dividend == 1 && count > 1)


[Link](num + " is Multiple Harshad Number");
else
[Link](num + " is not Multiple Harshad Number");
}
}

Output

Question 9

Write the programs to display the following patterns:

(a)
1
31
531
7531
97531

public class KboatPattern


{
public void displayPattern() {
for (int i = 1; i < 10; i = i + 2) {
for (int j = i; j > 0; j = j - 2) {
[Link](j + " ");
}
[Link]();
}
}
}

Output

(b)

1 2 3 4 5
6 7 8 9
10 11 12
13 14
15

public class KboatPattern


{
public void displayPattern() {
int a = 1;
for (int i = 5; i > 0; i--) {
for (int j = 1; j <= i; j++) {
[Link](a++ + "\t");
}
[Link]();
}
}
}
Output

(c)

15 14 13 12 11
10 9 8 7
6 5 4
3 2
1

public class KboatPattern


{
public void displayPattern() {
int a = 15;
for (int i = 5; i > 0; i--) {
for (int j = 1; j <= i; j++) {
[Link](a-- + "\t");
}
[Link]();
}
}
}

Output

(d)

1
10
101
1010
10101

public class KboatPattern


{
public void displayPattern() {
int a = 1, b = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
[Link](b + " ");
else
[Link](a + " ");
}
[Link]();
}
}
}

Output

(e)

55555
4444
333
22
1

public class KboatPattern


{
public void displayPattern() {
for (int i = 0; i < 5; i++) {

for (int j = i; j > 0; j--) {


[Link](" ");
}

for (int k = 5 - i; k > 0; k--) {


[Link]((5 - i) + " ");
}

[Link]();
}
}
}
Output

(f)

12345
22345
33345
44445
55555

public class KboatPattern


{
public void displayPattern() {
for (int i = 1; i <= 5; i++) {

for (int j = 1; j < i; j++)


[Link](i + " ");

for (int k = i; k <= 5; k++)


[Link](k + " ");

[Link]();
}
}
}
Output

(g)

*
*#
*#*
*#*#
*#*#*

public class KboatPattern


{
public void displayPattern() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
[Link]("# ");
else
[Link]("* ");
}
[Link]();
}
}
}
Output

(h)

54321
5432
543
54
5

public class KboatPattern


{
public void displayPattern() {
for (int i = 1; i <= 5; i++) {
for (int j = 5; j >= i; j--) {
[Link](j + " ");
}
[Link]();
}
}
}
Output

(i)

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

public class KboatPattern


{
public void displayPattern() {
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link](a++ + "\t");
}
[Link]();
}
}
}

Output
Question 10

Write a program to generate a triangle or an inverted triangle till n terms based upon the user's choice.

Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter the number of terms 5
Sample Output:
1
22
333
4444
55555

Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter the number of terms 6
Sample Output:
666666
55555
4444
333
22
1

import [Link];

public class KboatPattern


{
public void choosePattern() {

Scanner in = new Scanner([Link]);


[Link]("Type 1 for a triangle");
[Link]("Type 2 for an inverted triangle");

[Link]("Enter your choice: ");


int ch = [Link]();

[Link]("Enter the number of terms: ");


int n = [Link]();

switch (ch) {
case 1:
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
[Link](i + " ");
}
[Link]();
}
break;

case 2:
for (int i = n; i > 0; i--) {
for (int j = 1; j <= i; j++) {
[Link](i + " ");
}
[Link]();
}
break;

default:
[Link]("Incorrect Choice");
}
}
}

Output

Question 11

Using the switch statement, write a menu driven program for the following:

(a) To print the Floyd's triangle:


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

(b) To display the following pattern:


I
IC
ICS
ICSE

For an incorrect option, an appropriate error message should be displayed.

import [Link];

public class KboatPattern


{
public void choosePattern() {
Scanner in = new Scanner([Link]);
[Link]("Type 1 for Floyd's triangle");
[Link]("Type 2 for an ICSE pattern");

[Link]("Enter your choice: ");


int ch = [Link]();

switch (ch) {
case 1:
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link](a++ + "\t");
}
[Link]();
}
break;

case 2:
String s = "ICSE";
for (int i = 0; i < [Link](); i++) {
for (int j = 0; j <= i; j++) {
[Link]([Link](j) + " ");
}
[Link]();
}
break;

default:
[Link]("Incorrect Choice");
}
}
}
Output

Question 12

Using the switch case statement, write a menu driven program for the following:

(a) To input a number and display only those factors of the numbers which are prime.
Sample Input: 84
Sample Output: 2, 3, 7

(b) A program that displays the multiplication table from 1 to 10, as shown:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
...................................
...................................
...................................
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

import [Link];
public class KboatPrimeFactorsNTables
{
public static void main(String args[]) {
Scanner in = new Scanner([Link]);

[Link]("Enter 1 for prime factors");


[Link]("Enter 2 for multiplication tables");

[Link]("Enter your choice: ");


int ch = [Link]();

switch (ch) {
case 1:
[Link]("Enter a number: ");
int num = [Link]();

for(int i = 2; i <= num/2; i++) {


int c = 0;
if(num % i == 0) {
for (int j = 1; j <= i; j++) {
if(i % j == 0)
c++;
}
if(c == 2)
[Link](i + " ");
}
}
break;

case 2:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++)
[Link]((i * j) + " ");
[Link]();
}
break;

default:
[Link]("Incorrect Choice");
}
}
}
Output

Common questions

Powered by AI

Challenges with nested loops include maintaining clarity of control flow, especially when using 'break' and 'continue', which can lead to confusing and potentially erroneous behavior if not managed correctly. Nested loops can obscure the logical sequence of operations due to multiple overlapping iterations, exacerbated by break and continue conditions that may cause premature exits or unintended skips, further complicating debugging and comprehension .

Handling input validation is crucial because nested loops often perform extensive computations that are highly sensitive to input values. Incorrect inputs can lead to invalid results, infinite loops, or crashes. Ensuring inputs are within expected ranges prevents erroneous calculations and enhances program robustness, especially in mathematical applications where the accuracy and reliability of output directly depend on valid and logical inputs .

The 'break' statement is used to exit a loop completely, thus terminating the execution of the loop it is called in. In nested loops, a labeled 'break' can specifically target and terminate an outer loop from within an inner loop . On the other hand, the 'continue' statement skips the current iteration of the loop it is called in and proceeds with the next iteration. In nested loops, 'continue' affects only the innermost loop .

The inner loop cannot be terminated from within the block of an outer loop because the scope of execution for control statements like 'break' is limited to the loop in which it is directly invoked. Without explicit control mechanisms such as a labelled break, the default behavior of control statements does not allow direct influence of the inner loop from the outer loop's scope .

Nested loops are highly effective for pattern generation because they allow for structured repetition of rows and columns, key aspects of patterns. With nested loops, the outer loop typically controls the number of rows, while the inner loop handles the repetitions or conditions needed within each row. This dual control mechanism enables intricate and customizable designs, such as incremental number sequences or geometric shapes, highlighting their suitability for such tasks .

A labelled break statement allows a specific loop, identified by a label, to be terminated from within its nested inner loops. This is particularly significant in nested loops as it provides a controlled exit strategy from multiple layers of looping. By using a labelled break, you can bypass the rest of the iterations in both the inner and outer loops, thus facilitating more complex control over program flow .

Labelled control flow in Java adds versatility to nested loops by providing named points that can be referenced with statements like 'break' and 'continue'. With these labels, programmers can terminate or skip specific loops within nested structures without ambiguity, which is critical in managing complex loop interdependencies and ensuring correct program logic. This capability is especially valuable when dealing with deeply nested loops or when the exit condition depends on multiple factors spread across different loop levels .

The program first checks if each number is a prime number. It does this by attempting to divide each number by all integers up to its half. If a number is perfectly divisible by any of these integers, it is not a prime. If both numbers are prime, the program then checks if their absolute difference is 2, which confirms they are twin primes .

Nestled loops significantly increase the computational complexity of a program, often resulting in quadratic or even exponential time complexities. This occurs because for every iteration of the outer loop, all iterations of the inner loop are executed, leading to O(n^2) complexity for two nested loops, where n is the number of iterations. Such complexity has profound implications on performance, particularly with large input sizes, where the processing time can increase exponentially .

In the given program, a nested loop calculates the factorial by initializing a variable 'f' to 1. For each iteration of the outer loop, which dictates the term in a series, the inner loop runs from 1 up to the current term index 'i'. Each iteration of the inner loop multiplies 'f' by the loop's index 'k', effectively calculating 'i!'. This value is then used to compute terms in the series, demonstrating an efficient nested loop-based approach to factorial calculation .

You might also like