Categories

# Nested For Loops

## I. Fill in the blanks:

1. A loop within another loop is called nested loop.
2. You can use break statement to terminate a loop block.
3. Label is a tag that decides which part of the loop is to be used.
4. Repetition of outer loop takes place before inner loop.
5. Continue statement will repeat a loop for next iteration after ignoring some statements of the loop.

## II. Write whether the following statements are True/False:

1. Loop is a repetitive structure. (True)
2. Nesting of loops means restricting the use of inner loop. (True)
3. When break statement is applied, it terminates the program completely. (False)
4. When outer loop completes its iterations, the inner loop starts. (False)
5. Labelled continue statement allows the next iteration of the loop from any place of looping structure. (True)

## III. Differentiate between the following:

1. Nested if and nested loop.
a) Nested if is an example of conditional statement. Nested loop is an example of iterative statement.
b) The break and continue statements cannot be applied in nested ifs is they are not enclosed in any loop, but they can be applied in nested loops.
2. Break and continue.
The break keyword allows us to terminate a loop or switch statement. The continue keyword allows us to move to the next iteration of the loop.
3. Labelled break and unlabelled break.
Labelled break can be used to terminate any loop (inner or outer) whereas unlabelled break can only terminate the loop in which it is executed.

## IV. Answer the following questions:

1. What do you mean by a nested loop?
Nested loop is a loop programmed within another loop.
2. In what situation you need a nested loop?
Nested loops are needed when we need to execute N number of tasks such that each task itself repeats for P number of times.
3. How will you terminate outer loop from the block of the inner loop?
Using a labelled break statement, we can terminate outer loop from the block of the inner loop.
4. What do you mean by labelled break statement? Give an example.
Labelled break statement is one in which we label the outer loop so that we can terminate it using break keyword present within the inner loop.
`outer:for(int i = 1; i <= 5; i++){    for(int j = 1; j <= 5; j++){        if(i % 3 == 0)            break outer;    }}`
5. Write down the syntax of the nested loop.
`for(initial value; condition; update value){    for(initial value; conditon; update value){        <loop body>    }}`

## V. Give the output of the following snippets based on nested loops:

1. `int i, j;for(i = 0; i < 4; i++){    for(j = i; j >= 0; j--)        System.out.print(j);    System.out.println();}`
OUTPUT:
`0102103210`
2. `int y, p;for(int x = 1; x <= 3; x++){    for(y = 1; y <= 2; y++){        p = x * y;        System.out.print(p);    }    System.out.println();}`
OUTPUT:
`122436`
3. `int a, b;for(a = 1; a <= 2; a++){    for(b = (64 + a); b <= 70; b++)        System.out.print((char)b);    System.out.println();}`
OUTPUT:
`ABCDEFBCDEF`
4. `int x, y;for(x = 1; x <= 5; x++){    for(y = 1; y < x; y++){        if(x == 4)            break;        System.out.print(y);    }    System.out.println();}`
OUTPUT:
`1121234`
5. `int i, j;first:for(i = 10; i >= 5; i--){    for(j = 5; j <= i; j++){        if(i * j < 40)            continue first;        System.out.print(j);    }    System.out.println();`
}
OUTPUT:
`5678910567895678`

## VI. Unsolved Programs:

Q1. Write a program to display the mathematical table from 5 to 10 for 10 iterations in the given format:
Table of 5
5 * 1 = 5
5 * 2 = 10

5 * 10 = 50

``````class Table{
public static void main(String args[]){
for(int i = 5; i <= 10; i++){
System.out.println("Table of " + i);
for(int j = 1; j <= 10; j++)
System.out.println(i + " * " + j + " = " + (i * j));
}
}
}``````

Q2. Write a program to accept any 20 numbers and display only those numbers which are prime. Hint: A number is said to be prime if it is only divisible by 1 and the number itself.

``````import java.io.*;
class Prime{
public static void main(String args[])
throws IOException{
for(int i = 1; i <= 20; i++){
int f = 0;
System.out.print("N = ");
for(int j = 1; j <= n; j++){
if(n % j == 0)
f++;
}
if(f == 2)
System.out.println(n + " is prime.");
}
}
}``````

Q3. Write a program to compute and display the sum of the following series:
s = (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + … + (1 + 2 + 3 + … + n) / (1 * 2 * 3 * … * n)

``````import java.io.*;
class Series{
public static void main(String args[])
throws IOException{
System.out.print("N = ");
double s = 0.0;
int limit = 2;
for(int i = 1; i <= n; i++){
int sum = 0;
int prod = 1;
for(int j = 1; j <= limit; j++)
sum += j;
for(int k = 1; k <= limit; k++)
prod *= k;
s += (double)sum / prod;
limit++;
if(limit > n)
break;
}
System.out.println("Sum = " + s);
}
}``````

Q4. Write two separate programs to generate the following patterns using iteration (loop) statements:
a)
*
* #
* # *
* # * #
* # * # *
b)
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5

``````//Pattern 1
class Pattern{
public static void main(String args[]){
for(int i = 1; i <= 5; i++){
char ch = '*';
for(int j = 1; j <= i; j++){
System.out.print(ch + " ");
if(ch == '*')
ch = '#';
else
ch = '*';
}
System.out.println();
}
}
}

//Pattern 2
class Pattern{
public static void main(String args[]){
for(int i = 1; i <= 5; i++){
for(int j = 5; j >= i; j--)
System.out.print(j + " ");
System.out.println();
}
}
}``````

Q5. Write a program to calculate and display the factorials of all the numbers between ‘m’ and ‘n’ where m < n, m > 0 and n > 0. Hint: Factorial of 5 means 5! = 5 * 4 * 3 * 2 * 1.

``````import java.io.*;
class Factorials{
public static void main(String args[])
throws IOException{
System.out.print("M = ");
System.out.print("N = ");
if(m < n && m > 0 && n > 0){
for(int i = m; i <= n; i++){
int f = 1;
for(int j = 1; j <= i; j++)
f *= j;
System.out.println(i + "! = " + f);
}
}
}
}``````

Q6. Write a menu-driven program to display all prime and non-prime numbers from 1 to 100.
Enter 1: to display all prime numbers.
Enter 2: to display all non-prime numbers.

``````import java.io.*;
public static void main(String args[])
throws IOException{
System.out.println("Enter 1: to display all prime numbers.");
System.out.println("Enter 2: to display all non-prime numbers.");
switch(choice){
case 1:
for(int i = 1; i <= 100; i++){
int f = 0;
for(int j = 1; j <= i; j++){
if(i % j == 0)
f++;
}
if(f == 2)
System.out.print(i + "\t");
}
break;
case 2:
for(int i = 1; i <= 100; i++){
int f = 0;
for(int j = 1; j <= i; j++){
if(i % j == 0)
f++;
}
if(f != 2)
System.out.print(i + "\t");
}
break;
default:
System.out.println("Invalid choice!");
}
}
}``````

Q7. In an entrance examination, students have answered English, Math 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.

``````import java.io.*;
class Exam{
public static void main(String args[])
throws IOException{
System.out.print("Number of students: " );
for(int i = 1; i <= n; i++){
double avg = 0.0;
System.out.print("Enter name: ");
System.out.println("Marks in English, Math, Science:");
for(int j = 1; j <= 3; j++){
avg += m;
}
avg /= 3;
System.out.println(name +" average marks: " + avg);
}
}
}``````

Q8. Write a program to input a number and perform the following tasks:
a) To check whether it is a prime number or not.
b) To reverse the number. If the number as well as the reverse is also prime, then display “Twisted Prime” otherwise display “Not a twisted prime”.
Sample Input: 367
Sample output: 367 is a twisted prime.

``````import java.io.*;
public static void main(String args[])
throws IOException{
System.out.print("Enter the number: ");
int f = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0)
f++;
}
if(f == 2)
System.out.println(n + " is prime.");
else
System.out.println(n + " is not prime.");
int rev = 0;
f = 0;
for(int i = n; i != 0; i /= 10)
rev = rev * 10 + i % 10;
int g = 0;
for(int i = 1; i <= n; i++){
if(n % i == 0)
f++;
}
for(int i = 1; i <= rev; i++){
if(n % i == 0)
g++;
}
if(f == 2 && g == 2)
System.out.println(n + " is twisted prime.");
else
System.out.println(n + " is not twisted prime.");
}
}``````

Q9. Write programs to find the sum of the given series:
a) 1 + 1/2! + 1/3! + … + 1/n!

``````import java.io.*;
class Question9a{
public static void main(String args[])throws IOException{
System.out.print("N = ");
double sum = 0.0;
int f = 1;
for(int i = 1; i <= n; i++){
f *= i;
sum += 1.0 / f;
}
System.out.println("Sum = " + sum);
}
}``````

b) 1 + (1+2) + (1+2+3) + … (1+2+3+…+n)

``````import java.io.*;
class Question9b{
public static void main(String args[])throws IOException{
System.out.print("N = ");
int sum = 0;
int s = 0;
for(int i = 1; i <= n; i++){
s += i;
sum += s;
}
System.out.println("Sum = " + sum);
}
}``````

c) 1 + (1×2) + (1×2×3) + … + (1×2×3×…×n)

``````import java.io.*;
class Question9c{
public static void main(String args[])throws IOException{
System.out.print("N = ");
int sum = 0;
int s = 1;
for(int i = 1; i <= n; i++){
s *= i;
sum += s;
}
System.out.println("Sum = " + sum);
}
}``````

d) 1 + 1/(1+2) + 1/(1+2+3) + … 1/(1+2+3+…+n)

``````import java.io.*;
class Question9d{
public static void main(String args[])throws IOException{
System.out.print("N = ");
double sum = 0.0;
int s = 0;
for(int i = 1; i <= n; i++){
s += i;
sum += 1.0 / s;
}
System.out.println("Sum = " + sum);
}
}``````

e) 1/2 + 1/3 + 1/5 + … + 1/29.

``````class Question9e{
public static void main(String args[]){
double sum = 0.0;
int p = 2;
while(true){
int f = 0;
for(int j = 1; j <= p; j++){
if(p % j == 0)
f++;
}
if(f == 2)
sum += 1.0 / p;
p++;
if(p > 29)
break;
}
System.out.println("Sum = " + sum);
}
}``````

Q10. Write a program in Java to display the following patterns:

```1
2 1
3 2 1
4 3 2 1
5 4 3 2 1```
``````class PatternA{
public static void main(String args[]){
for(int i = 1; i <= 5; i++){
for(int j = i; j >= 1; j--)
System.out.print(j + " ");
System.out.println();
}
}
}``````
```1 2 3 4 5
1 2 3 4
1 2 3
1 2
1```
``````class PatternB{
public static void main(String args[]){
for(int i = 5; i >= 1; i--){
for(int j = 1; j <= i; j++)
System.out.print(j + " ");
System.out.println();
}
}
}``````
```5 4 3 2 1
5 4 3 2
5 4 3
5 4
5```
``````class PatternC{
public static void main(String args[]){
for(int i = 1; i <= 5; i++){
for(int j = 5; j >= i; j--)
System.out.print(j + " ");
System.out.println();
}
}
}``````
```1 3 5 7 9
1 3 5 7
1 3 5
1 3
1```
``````class PatternD{
public static void main(String args[]){
for(int i = 1; i <= 5; i++){
int value = 1;
for(int j = 1; j <= i; j++){
System.out.print(value + " ");
value += 2;
}
System.out.println();
}
}
}``````
```5
5 4
5 4 3
5 4 3 2
5 4 3 2 1```
``````class PatternE{
public static void main(String args[]){
for(int i = 5; i >= 1; i--){
for(int j = 5; j >= i; j--)
System.out.print(j + " ");
System.out.println();
}
}
}``````
```1 2 3 4 5
2 3 4 5
3 4 5
4 5
5```
``````class PatternF{
public static void main(String args[]){
for(int i = 1; i <= 5; i++){
for(int j = i; j <= 5; j++)
System.out.print(j + " ");
System.out.println();
}
}
}``````
```9 9 9 9 9
7 7 7 7 7
5 5 5 5 5
3 3 3 3 3
1 1 1 1 1```
``````class PatternG{
public static void main(String args[]){
int value = 9;
for(int i = 1; i <= 5; i++){
for(int j = 1; j <= 5; j++)
System.out.print(value + " ");
value -= 2;
System.out.println();
}
}
}``````
```9
7 9
5 7 9
3 5 7 9
1 3 5 7 9```
``````class PatternH{
public static void main(String args[]){
int value = 9;
for(int i = 1; i <= 5; i++){
for(int j = value; j <= 9; j += 2)
System.out.print(j + " ");
value -= 2;
System.out.println();
}
}
}``````
```9
9 7
9 7 5
9 7 5 3
9 7 5 3 1```
``````class PatternI{
public static void main(String args[]){
int value = 9;
for(int i = 1; i <= 5; i++){
for(int j = 9; j >= value; j -= 2)
System.out.print(j + " ");
value -= 2;
System.out.println();
}
}
}``````
```1
2    3
4    5    6
7    8    9    10
11   12   13   14   15```
``````class PatternJ{
public static void main(String args[]){
int value = 1;
for(int i = 1; i <= 5; i++){
for(int j = 1; j <= i; j++){
System.out.print(value + "\t");
value++;
}
System.out.println();
}
}
}`````` I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website happycompiler.com

## 16 replies on “Nested For Loops” Anand Lamasays:

No V- 2) Answer is also wrong. Correct output is:
12
24
36
and not
12
24
26 adminsays:

Thank you, the correction has been done. Anand Lamasays:

II 2)Nesting of loops means restricting the use of inner loop. (True)
Its not True adminsays:

I wrote True because the outer loop decides how many times the inner loop will be executed. So it should be True. aakanksha sakharesays:

very well put together & helpful. adminsays:

Thank you so much! Jassisays:

Sir Thanks for the solutions
But you haven’t uploaded Q 10 adminsays:

Yes, it will be uploaded soon. adminsays:

Now Question 10 is solved. Karamsays:

Question number 10 is not here adminsays:

Now Question is solved. adminsays:

Now Question 10 is solved. aniketsays:

Please send the chapter computing and etichs adminsays:

Here is the link to computing and ethics chapter solved question answers. Shersays: Raktim Mondalsays: