Chapter 9

Nested for loops – This topic has been removed from the current 2021 syllabus

I. Fill in the blanks:

1. A loop within another loop is called as ________________

2. You can use ________________statement to terminate a loop block.

3. _________________is a tag that decides which part of the loop is to be used.

4.Repetition of ______________loop takes place before ________________loop.

5. _______________statement will repeat a loop for next iteration after ignoring some statements of the loop.

Ans.

1. nested loop

2. break

3. Label [Out of scope of present syllabus]

4. inner , outer

5. continue

II. Write whether the following statements are true/false:

1. Loop is a repetitive structure.

2. Nesting of loops means restricting the use of inner loop.

3. When break statement is applied, it terminates the program completely.

4. When the outer loop completes its iterations, the inner loop starts.

5. Labelled continue statement allows the next iteration of the loop from any place of looping structure.

Ans.

1. true

2. false

3. false

4. false

5. [Out of scope of present syllabus]

III. Differentiate between the following:

1. Nested if and nested loop

Ans.  

Nested if

i) A ‘Nested if’ construct does not get executed repeatedly.

ii) The ‘continue’ statement cannot be used in a ‘Nested if’ statement.

Nested loop

i) A ‘Nested loop’ construct gets executed repeatedly. All the iterations of the inner loop are executed for each iteration of the outer loop.

ii) The ‘continue’ statement can be used in a Nested if statement.

2. Break and continue

break:

i) The break statement can be used in a loop statement as well as in a switch case block.

ii) break statement is used to terminate a block in which it exists. i.e. (In a switch case block, it completely comes out of switch-case block and in case of loops, it terminates from the particular loop in which it is present.)

iii)

 Example

 for (i=1; i<=10; i++)

{

if (i= =5)

break;

System.out.println(i);

}

The above snippet prints the numbers from 1 to 4. When i=5, the break statement is executed and hence the control comes out of the loop.

continue:

i) The continue statement can be in a loop statement but not in switch case block.

ii) A continue statement is used to skip the execution of the remaining statements in the current iteration and moves on with the next iteration.

iii)

Example

 for (i=1; i<=10; i++)

{

if (i= =5)

continue;

System.out.println(i);

}

The above snippet prints all the numbers from 1 to 10 except 5 because of the continue statement.

3. Labelled break and Unlabelled break

   Ans: [This question is out of scope of the present syllabus.]

IV. Answer the following questions:

1. What do you mean by a nested loop?

Ans. The presence of one or more loops or iteration statements within one loop is known as a nested loop. In other words, a nested loop is defined as a loop programmed within another loop. In a nested loop, all the iterations of the inner loop get executed for each iteration of the outer loop. [ A nested loop is somewhat similar to a clock where the second hand moves 60 steps for each step of the minute hand. So we can consider the minute hand as the outer loop and the second hand as the inner loop]

Syntax of nested loop :

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

{ executable statements

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

    {

    executable statements

    }

    executable statements

 }

Example:

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

{     

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

    {

     System.out.print( j + “\t”);

    } //end of inner loop   

 } // end of outer loop

The inner loop prints 1 2 3 for each iteration of the outer loop. Since the outer loop has two iterations, the inner loop is repeated twice. Therefore, the output of the above snippet is as follows:

1   2    3

1   2    3

2. In what situation you need a nested loop?

Ans.

Nested loops are used mainly used when certain a certain loop or loops need to be repeated again and again.

Example

Suppose we want to print the numbers from 1 to 7. To avoid lengthy coding, we would prefer to use a loop for this task and the loop would create an output as shown below:

1 2 3 4 5 6 7

Now, suppose we need to repeat this task of printing 1 to 7, four times (each time starting in a new line), then we would use an outer loop which runs 4 times and an inner loop which runs 7 times. Thus, for each iteration of the outer loop, the inner loop completes all the iterations. Therefore, the output will be as follows:

1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7

1 2 3 4 5 6 7

3. How will you terminate outer loop from the block of the inner loop?

Ans.  [To terminate an outer loop from the inner loop, labelled break must be used which is out of scope of the present syllabus]

 A break statement (without a label) given in the inner loop will only terminate the inner loop. In order to terminate the outer loop, a break statement should be given in the outer loop directly.

4. What do you mean by labelled break statement? Give an example.

Ans. [This question is out of scope of the present syllabus.]

5. Write down the syntax of the nested loop.

Ans.

 Syntax of nested loop :

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

{ executable statements

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

    {

    executable statements

    }

    executable statements

 }

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

}

Ans.

1st iteration of the Outer Loop

Outer loop value : i=0

Inner loop  : The inner loop runs once for j=0

Since j values are printed, ‘0’ is printed in the first line.

2nd iteration of the Outer Loop

Outer loop value : i=1

Inner loop  : The inner loop runs for j=1 and then j=0

Since j values are printed, ‘10’ is printed in the second line.

3rd iteration of the Outer Loop

Outer loop value : i=2

Inner loop  : The inner loop runs for j=2 followed by j=1 and then j=0

Since j values are printed, ‘210’ is printed in the third line.

4th iteration of the Outer Loop

Outer loop value : i=3

Inner loop  : The inner loop runs for j=3, followed by j=2, followed by j=1 and then j=0

Since j values are printed, ‘3210’ is printed in the fourth line.

Therefore, the final output is as follows:

0

10

210

3210

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

}

Ans.

1st iteration of the Outer Loop

Outer loop value: x=1

Inner loop : The inner loop runs for y=1 and then y=2

p=x*y=1* 1=1

p=x*y =1*2 =2

Since ‘p’ values are printed in the same line, the output is 12

2nd iteration of the Outer Loop

Outer loop value : x=2

Inner loop : The inner loop runs for y=1 and then y=2

p=x*y=2* 1=2

p=x*y =2*2 =4

Since ‘p’ values are printed in the same line, the output is 24

3rd iteration of the Outer Loop

Outer loop value : x=3

Inner loop : The inner loop runs for y=1 and then y=2

p=x*y=3* 1=3

p=x*y =3*2 =6

Since ‘p’ values are printed in the same line, the output is 36

Therefore, the final output is as follows:

12

24

36

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

}

1st iteration of the Outer Loop

Outer loop value : a=1

Inner loop value : b=64+a =64+1=65, So the inner loop runs from b=65 to b=70

So, the output is, ABCDEF

2nd iteration of the Outer Loop

Outer loop value : a=2

Inner loop value : b=64+a =64+2=66, So the inner loop runs from b=66 to b=70

So, the output is, BCDEF

Therefore the final output is,

ABCDEF

BCDEF

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

}

Ans.

1st iteration of the Outer Loop

Outer loop value : x=1

Inner loop value : y=1

Condition y<x  that is , 1<1 is false so no output

2nd iteration of the Outer Loop

Outer loop value : x=2

Inner loop value : y=1

Condition y<x  that is , 1<2 is true so 1 is printed. The output in the first line is 1.

3rd iteration of the Outer Loop

Outer loop value : x=3

Inner loop value : y=1, y=2

Condition y<x  that is ,

1<3 is true so 1 is printed.

2<3 is true so 2 is printed. The output in the second line is 12

4th iteration of the Outer Loop

Outer loop value : x=4

Inner loop value : y=1, y=2,y=3

Condition y<x is true for all the y values given above. So, there’s no output in the fourth line and instead the inner loop is terminated because of the break statement given in the inner loop which is executed when x=4.

5th iteration of the Outer Loop

Outer loop value: x=5

Inner loop value: y=1, y=2, y=3, y=4

Condition y<x is true for above ‘y’ values. So, the output in the fifth line is, 1234.

Therefore, the final output is,

1

12

1234

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

}

Ans. [The above snippet involves a labelled break and hence out of scope of the present syllabus]

VI. Solved programs

  1. Write a program to display the Mathematical Table from 5 to 10 for 10 iterations in the given format:

Sample Output: Table of 5

5*1=5

5*2=10

……..

……..

5*10=50

Solution:

class Q1 {

static void main()

{

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

{System.out.println(“\n Table of “+i);

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

System.out.println(i+ “*” +j+ “=” +i*j);

}

}}

  • 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 divisible by 1 and the number itself]

Solution:

import java.util.*;

class Q2

{static void check()

{Scanner ob=new Scanner(System.in);

int n,cnt=0;

String s=”Prime numbers:”;

System.out.println(“Enter the numbers”);

for(int x=1;x<=20;x++)

{n=ob.nextInt();

cnt=0;

for(int i=1;i<=n/2;i++)

{if(n%i==0)

cnt++;

}     //End of Inner Looop

if(cnt==1)

s=s+”\n”+n;

}     //End of Outer Loop

System.out.println(s);

}}

  • Write a program to compute and display the sum of the following series:

                                                                                           [ICSE 2007]

S=1+2  +  1+2+3  +…………………………..+  1+2+3..………+n

    1*2       1*2*3                                                   1*2*3………..*n

Solution:

import java.util.*;

class Q3

{static void check()

{Scanner ob=new Scanner(System.in);

System.out.println(“Enter the number of terms”);

int n;

double term,sum=0,a=0,b=1; //denominator ,b=1 si it is used for multiplied result

n=ob.nextInt();

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

{for(double j=1.0;j<=i+1;j++)

{a+=j;

b*=j;

}

term=a/b;

System.out.println(term);    //OPTIONAL PRINT

sum+=term;

//reset a and b

a=0;

b=1;

}

System.out.println(“Sum of the series=”+sum);

}}

  • 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 

Solution:

class Q4 A{

static void pattern1()

{

char s=’*’;

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

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

{if(j%2!=0)

s=’*’;

else

s=’#’;

System.out.print(s+” “);

}

System.out.println();

}

}}

class Q4 B{

static void pattern2()

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

{for(int j=5;j>=i;j–)

System.out.print(j+” “);

System.out.println();

}

}}

  • Write a program to calculate and display the factorials of all the numbers between ‘m’ and ‘n’ (where m<n, m>0 n>0)

[Hint: Factorial of 5 (5!) means 5x4x3x2x1]

Solution:

import java.util.*;

class Q5 {

static void main()

{Scanner ob=new Scanner(System.in);

int m,n,fact;

System.out.println(“Enter the value of m”);

m=ob.nextInt();

System.out.println(“Enter the value of n”);

n=ob.nextInt();

if(m>0 && n>0 && m<n)

{

for(int i=m;i<=n;i++)

{fact=1;                     //reset fact for each value of i

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

fact=fact*j;

System.out.println(i+”! =”+fact);

}}

else System.out.println(“Invalid Input: Enter m>0,n>0 and m<n”);

}}

  • 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

Hint: A number is said to be prime if it is only divisible by 1 and the number itself.

Solution:

import java.util.*;

class Q6 {

static void main(){

Scanner ob=new Scanner(System.in);

String s1=”Prime Numbers from 1 to 100″;

String s2=”Non-Prime numbers from 1 to 100″;

int num,j,cnt;

//store prime numbers in ‘s1’ and non-prime numbers in ‘s2’

for(num=1;num<=100;num++)

{cnt=0;  //reset cnt for each value of n

for(j=1;j<=num;j++) //Check whether num is Prime

{if(num%j==0)

cnt++;

}

if(cnt==2)

s1+=”\n”+num;

else if(cnt>2)      

s2+=”\n”+num;

}

//input of user’s choice and printing

System.out.println(“***MENU***”);

System.out.println(“1.Display all the Prime numbers”);

System.out.println(“2.Display all non-prime numbers”);

System.out.println(“Enter your choice…input 1 or 2”);

switch(ob.nextInt())

{

    case 1:System.out.println(s1); 

           break;

    case 2:System.out.println(s2); 

           break;

    default:System.out.println(“Invalid input”);

}

}}

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

Solution:

import java.util.*;

class Q7 {

static void main()

{

Scanner sn=new Scanner(System.in);

int n;

double eng=0,math=0,sci=0,avg;

String name;

System.out.println(“Enter the number of students”);

n=sn.nextInt();

while(n>0)

{System.out.println(“\nEnter the name”);

name=sn.next();

System.out.println(“Enter the English mark”);

eng=sn.nextInt();

System.out.println(“Enter the Maths mark”);

math=sn.nextInt();

System.out.println(“Enter the Science mark”);

sci=sn.nextInt();

avg=(eng+math+sci)/3.0;

System.out.println(“Average mark of “+name+”:”+avg);

n–;

}}

  • Write a program to input a number and perform the following tasks:

a) To check whether it is prime or not.

b) to reverse the number.

If the number as well as the reverse is ‘Prime’ then display ‘Twisted Prime’ otherwise ‘Not a Twisted Prime’.

Sample Input:367

Sample Output: 167 and 761 both are prime.

It is a ‘Twisted Prime’.

Solution:

import java.util.*;

class Q8

{

static void check()

{

Scanner sn=new Scanner(System.in);

System.out.println(“Enter a number”);

int n,n1,cnt=0,d,rev=0,cnt1=0,cnt2=0;

n=sn.nextInt();

n1=n;

//finding the reverse of the number

while(n>0)

{

d=n%10;

rev=rev*10+d;

n=n/10;

}

System.out.println(“Reverse=”+rev);

//checking if the number is prime

for(int i=1;i<=n1/2;i++)

{if(n1%i==0)

cnt1++;

}

//checking if the reverse is also prime

for(int i=1;i<=rev/2;i++)

{if(rev%i==0)

cnt2++;

}

//checking if twisted prime

if(cnt1==1 && cnt2==1)

System.out.println(“It is a Twisted Prime number since both are prime”);

else

System.out.println(“It is not a Twisted Prime number”);

}}

  • Write programs to find the sum of the given series:

a) 1 + 1/2!  + 1/3! + 1/4! ……………….+ 1/n!

Solution:

class Q9a {

static void main(int n)

{int fact;

double sum=0;

for(int p=0;p<=n;p++)

{fact=1;              //reset fact=1 for each value of p

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

fact=fact*j;

sum+=1.0/fact;

}

System.out.println(“sum  :”+sum);

}}

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

Solution:

import java.util.*;

class Q9b

{static void check()

{Scanner ob=new Scanner(System.in);

double sum=0,term=0;

int n;

System.out.println(“Enter the number of terms”);

n=ob.nextInt();

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

{term=0;

for(double j=1.0;j<=i;j++)

{ term+=j;

}

sum+=term;

}

System.out.println(“Sum of the series=”+sum);

}}

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

Solution:

import java.util.*;

class Q9c

{static void check()

{Scanner ob=new Scanner(System.in);

int n;

double sum=0,term;

System.out.println(“Enter the number of terms”);

n=ob.nextInt();

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

{term=1;       //reset term=1 since it is multiplication

for(double j=1.0;j<=i;j++)

{ term*=j;

}

sum+=term;

}

System.out.println(“Sum of the series=”+sum);

}}

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

Solution:

import java.util.*;

class Q9d

{static void check()

{Scanner ob=new Scanner(System.in);

int n;

double sum=0,term;

System.out.println(“Enter the number of terms”);

n=ob.nextInt();

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

{term=0; 

for(double j=1.0;j<=i;j++)

{ term+=j;

}

sum+=(1.0/term);

}

System.out.println(“Sum of the series=”+sum);

}}

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

Solution:

class Q9e

{static void check()

{int cnt=0;

double term,sum=0;

//checking if the number is prime

for(int i=2;i<=4;i++)

{

cnt=0;      //reset cnt and term for each value of i

term=0.0;

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

{if(i%j==0)

cnt++;

}

if(cnt==1)

{term=1.0/i;

sum+=term;

}}

System.out.println(“Sum of the series=”+sum);

}}

10) Write the programs in Java to display the following patterns:

a)  1

     2  1

     3  2  1

     4  3  2  1

     5  4  3  2  1

Solution:

class Q10a {

static void main(){

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

{for(int j=i;j>=1;j–)

System.out.print(j +” “);

System.out.println();

}

}}

b) 1  2  3  4  5

     1  2  3  4 

     1  2  3 

     1  2 

     1 

class Q10b {

static void main(){

for(int i=5;i>=1;i–)

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

System.out.print(j +” “);

System.out.println();

}

}}

c) 5  4  3  2  1

    5  4  3  2 

    5  4  3 

    5  4 

    5 

Solution:

class Q10c {

static void main(){

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

{for(int j=5;j>=i;j–)

System.out.print(j+” “);

System.out.println();

}

}}

d) 1 3 5 7 9

     1 3 5 7

     1 3 5

     1 3

     1

Solution:

class Q10d {

static void main(){

for(int i=9;i>=1;i=i-2)

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

System.out.print(j +” “);

System.out.println();

}

}}

e) 5

    5 4

    5  4  3

    5  4  3  2

    5  4  3  2  1

Solution:

class Q10e {

static void main(){

for(int i=5;i>=1;i–)

{for(int j=5;j>=i;j–)

System.out.print(j +” “);

System.out.println();

}

}}

f) 1 2 3 4 5

    2 3 4 5

    3 4 5

    4 5

    5 

Solution:

class Q10f {

static void main(){

for(int i=9;i>=1;i=i-2)

{for(int j=i;j<=9;j=j+2)

System.out.print(j +” “);

System.out.println();

}

}}

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

Solution:

class Q10g {

static void main(){

int p=1;

for(int i=9;i>=1;i=i-2)

{for(int j=1;j<=5;j++)

System.out.print(i);

System.out.println();

}

}}

    h)  9

         7 9

         5 7 9

         3 5 7 9

         1 3 5 7 9

Solution:

class Q10h {

static void main(){

for(int i=9;i>=1;i=i-2)

{for(int j=i;j<=9;j=j+2)

System.out.print(j +” “);

System.out.println();

}

}}

     i) 9

        9 7

        9 7 5

        9 7 5 3

        9 7 5 3 1

Solution:

class Q10i {

static void main(){

for(int i=9;i>=1;i=i-2)

{for(int j=9;j>=i;j=j-2)

System.out.print(j +” “);

System.out.println();

}

}}

     j)

         1

         2    3

         4    5    6

         7    8    9    10

         11  12  13  14  15                                                        [ICSE 2016]

Solution:

class Q10j {

static void main(){

int p=1;

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

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

System.out.print(p++ +” “);

System.out.println();

}

}}

*************

%d bloggers like this: