0% found this document useful (0 votes)
2 views

chapter 9 Nested Loop

Chapter 9 covers nested loops, explaining their structure and functionality. It includes fill-in-the-blank questions, true/false statements, and differentiations between related concepts like break and continue statements. Additionally, it provides programming exercises and solutions for various tasks involving nested loops.

Uploaded by

pragathipug
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

chapter 9 Nested Loop

Chapter 9 covers nested loops, explaining their structure and functionality. It includes fill-in-the-blank questions, true/false statements, and differentiations between related concepts like break and continue statements. Additionally, it provides programming exercises and solutions for various tasks involving nested loops.

Uploaded by

pragathipug
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Chapter 9

Nested Loops

Fill in the blanks


Question 1
A loop within another loop is called nested loops
Question 2
You can use break statement to terminate a loop block.
Question 3
Label is a tag that decides which of part the loop is to be used.
Question 4
Repetition of inner loop takes place before outer loop
Question 5
Continue statement will repeat a loop for next iteration after ignoring some statements of the loop.
Write whether the following statements are True/False
Question 1
Loop is a repetitive structure.
True
Question 2
Nesting of loops means restricting the use of inner loop.
False
Question 3
When break statement is applied, it terminates the program completely.
False
Question 4
When outer loop completes its iterations, the inner loop starts. False
Question 5 (Out of syllabus)
Labelled continue statement allows the next iteration of the loop from any place of looping structure.
False
Differentiate between the following
Question 1
Nested if and nested loop
Nested if is used to do conditional checks at multiple levels whereas nested loops are used to execute one
iterative set of statements inside another iterative set.
Question 2
Break and continue
break statement is used to unconditionally jump out of the loop whereas continue statement is used to
unconditionally jump to the next iteration of the loop, skipping the remaining statements of the current
iteration.
break statement is used in switch-case and loops whereas continue statement is only used in loops.
Question 3 (Out of syllabus)
Labelled break and Unlabelled break
Labelled break can be used to exit out of a deeply nested set of loops whereas Unlabelled break only exits
from the loop within which it is enclosed.
Answer the following questions
Question 1
What do you mean by a nested loop?
When a loop is contained inside another loop it is termed as nested loops
Question 2
In what situation you need a nested loop?
When the repetition of two tasks depend on each other in such a way that for every repetition of first
task, the second tasks needs to be repeated a number of times, then we use nested loops.
Question 3
How will you terminate outer loop from the block of the inner loop? (Out of syllabus)
By using Labelled break statement.
Question 4
What do you mean by labelled break statement? Give an example. (Out of syllabus)
Labelled break statement transfers program control out of the code block whose label is specified as its
target. The target code block must enclose the break statement but it does not need to be the immediately
enclosing block.
In the below code snippet:
first: for (int j = 1; j <= 5; j++) {
for (int k = 1; k <= j; k++) {
if (k > 4)
break first;
System.out.print(k);
}
System.out.println();
}
System.out.println("Outside code block labelled first");
the labelled break statement break first; will transfer the program control outside the outer for loop to the
statement System.out.println("Outside code block labelled first");
Question 5
Write down the syntax of the nested loop.
Below is the syntax of nested loop:

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


for (<initial value>; <test condition>; <update value>) {
executable statement(s)
}
}
Give the output of the following snippets based on nested loops
Question 1
int i,j;
for (i=0; i<4; i++)
{
for (j=i; j>=0; j--)
System.out.print(j);
System.out.println();
}
Output
0
10
210
3210
Explanation
For each iteration of outer for loop, inner for loop will iterate from i to 0 printing the above pattern.
Question 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
12
24
36
Explanation
x y p Remarks
1 1 1 1st iteration of outer for loop
2 2
2 1 2 2nd iteration of outer for loop
2 4
3 1 3 3rd iteration of outer for loop
2 6
Question 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
ABCDEF
BCDEF
Explanation
In the first iteration of outer for loop, the inner for loop will print characters with ASCII codes from 65 to 70 i.e.
letters from A to F.
In the second iteration of outer for loop, the inner for loop will print characters with ASCII codes from 66 to 70
i.e. letters from B to F.
Question 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

1
12

1234
Explanation
1st iteration of outer for
x=1
Inner for loop doesn't execute as y = 1 so the condition y<x is false
Just a newline is printed to the console due to System.out.println( );
2nd iteration of outer for
x=2
Inner for loop executes once printing 1 to the console
3rd iteration of outer for
x=3
Inner for loop executes twice printing 12 to the console
4th iteration of outer for
x=4
if(x == 4) becomes true inside inner for loop. break is executed, just a newline is printed to the console.
5th iteration of outer for
x=5
Inner for loop executes 4 times printing 1234 to the console
Question 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
5678910
56789
5678

Explanation
For the first 3 iterations of outer loop i * j >= 40. After that as the condition of if (i*j <40) becomes true, in each
iteration of inner for, continue statement transfers the program control to the next iteration of outer for loop.
Solution to unsolved programs

Question 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
public class pg1
{
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));
}
} }}
Question 2
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.util.Scanner;

import java.util.*;
public class pg2
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 20 numbers");
for (int i = 1; i <= 10; i++) {
int n = in.nextInt();
int c=0;
for (int j = 1; j <= n; j++) {
if (n % j == 0)
c++;
}
if (c==2)
System.out.println(n + " is a Prime Number");
} }}
Question 3
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.util.*;
public class pg3
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 2; i <= n; i++) {
double num = 0.0, d= 1.0;
for (int j = 1; j <= i; j++) {
num += j;
d*= j;
}
sum = sum + (num / d);
}
System.out.println("Sum=" + sum);
}}
Question 4
Write two separate programs to generate the following patterns using iteration (loop) statements:
(a)
*
* #
* # *
* # * #
* # * # *
public class pg4a
{
public static void main(String args[]) {
for (int i = 1; i <=5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print("# ");
else
System.out.print("* ");
}
System.out.println();
}
}}

(b)
54321
5432
543
54
5
public class pg4b
{
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();
} }}
Question 5
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 means: 5!=5*4*3*2*1]

import java.util.*;
public class pg5
{
public static void main(String args[]) {

Scanner in = new Scanner(System.in);


System.out.print("Enter m: ");
int m = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();

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


for (int i = m; i <= n; i++) {
int fact = 1;
for (int j = 1; j <= i; j++)
fact *= j;
System.out.println("Factorial of " + i + " = " + fact);
}
}
else {
System.out.println("Invalid Input");
} }}
Question 6
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.

import java.util.*;
public class pg6
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 1: to display all prime numbers");
System.out.println("Enter 2: to display all non-prime numbers");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
int c=0;
switch (ch) {
case 1:

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


for (int j = 1; j <= i ; j++) {
if (i % j == 0)
c++;
}
if (c==2)
System.out.print(i+" ");
c=0;
}
break;

case 2:

System.out.print(1+" ");
for (int i = 2; i <= 100; i++) {
for (int j = 1; j <= i; j++) {
if (i % j == 0)
c++;
}
if(c!=2)
System.out.print(i+" ");
c=0;
}
break;

default:
System.out.println("Incorrect Choice");
break;
} }}
Question 7
In an entrance examination, students have answered 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.

import java.util.*;
public class pg7
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = in.nextInt();
double totalMarks = 0.0;
for (int i = 1; i <=n; i++) {
System.out.println("Enter details of student " + i);
System.out.print("Name: ");
in.nextLine();
String name = in.nextLine();
System.out.print("Marks in English: ");
int engMarks = in.nextInt();
System.out.print("Marks in Science: ");
int sciMarks = in.nextInt();
System.out.print("Marks in Maths: ");
int mathsMarks = in.nextInt();
double avgMarks = (engMarks + sciMarks + mathsMarks) / 3.0;
totalMarks += avgMarks;
System.out.println("Average marks of " + name + " = " + avgMarks);
}
double classAvg = totalMarks / n;
System.out.println("Class Average = " + classAvg);
}}
Question 8
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 'Not a twisted Prime'.
Sample Input: 167
Sample Output: 167 and 761 both are prime.
It is a 'Twisted Prime'.

import java.util.*;
public class pg8
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();
int c=0;
if (num == 1) {
System.out.println(num + " is not a twisted prime number");
}
else {
for (int i = 1; i <= num; i++) {
if (num % i == 0)
c++;
}
if (c==2) {
int t = num;
int rev = 0;
while (t != 0) {
int d = t % 10;
t /= 10;
rev =rev*10 +d;
}
c=0;
for (int i = 1; i <= rev; i++) {
if (rev%i==0)
c++;
}
}
if (c==2)
System.out.println(num + " is a twisted prime number");
else
System.out.println(num + " is not a twisted prime number");
} }}
Question 9
Write a program to display the factorial of any ten numbers.
[Hint: Factorial of 5!=5*4*3*2*1]
Sample Input:8
Factorial of 8: 40320
Factorial of 11: 39916800
and so on………..

import java.util.*;
public class pg9{
public static void main(String args[]) {
int num, f = 1, i,n;
Scanner in = new Scanner(System.in);
System.out.println("Enter how many nos to find factorial");
n=in.nextInt();
for(int j=1;j<=n;j++){
System.out.println("Enter the number");
num = in.nextInt();
for (i = 1; i <= num; i++){
f = f * i;
}
System.out.println("Factorial of "+ num + " = " + f);
f=1;
} }}

Question 10
Write a program to input a number. Calculate and display factorial of each digit.
Sample Input: 365
Factorial of 5: 120
Factorial of 6: 720
Factorial of 3: 6

import java.util.*;
class pg10
{
public static void main(String args[])
{
int n,f=1,r,t=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter any no");
n=in.nextInt();
while(n>0)
{
r=n%10;
t=r;
n=n/10;
while(r>0)
{
f=f*r;
r--;
}
System.out.println("Factorial of "+t+ ": "+f);
f=1;
}
}
}

Question 11
Write a program to input a three digit number. Display its digits raised to the power of their respective position.
Sample Input: 465
Sample Output: 51=5
62=36
43=64
import java.util.*;
class pg11
{
public static void main(String args[]){
int n,c=0,r;
Scanner in=new Scanner(System.in);
System.out.println("Enter any 3 digit number");
n=in.nextInt();
while(n>0)
{
r=n%10;
n=n/10;
c++;
System.out.println(r+" to the power of "+c+" is "+(int)Math.pow(r,c));
} }}
Question 12
Write a program to display all composite numbers from 1 to 100. A number is said to be composite, if it has two
or more factors excluding 1 and the number itself.
Sample Input: 6
Sample Output: Factors of 6 are 2 and 3
Hence, 6 is a composite number
Few composite numbers are 4,6,8,9,10,12,14,15,16,18,20,21…..

class pg12
{
public static void main(String args[]){
int i,j,c=0;
for(i=1;i<=100;i++){
for(j=2;j<i;j++){
if(i%j==0)
c++;
}
if(c>=2)
System.out.println(i+ " is a composite number");
c=0;
} }}
Question 13
In a school, there are 4 different sections. In each section, there are 40students who have appeared for ICSE
Examination. Write a program to input percentage marks of each student of each section. Calculate and
display the number of students of each section, securing 95% and above in the council examination

import java.util.*;
class unsolpg13{
public static void main(String args[]){
int i,j,c=0;
char se;
double mper;
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of students");
int n=in.nextInt();
for(se='A';se<='D';se++)
{ c=0;
System.out.println("Enter the percentage marks of " +n+" student");
for(i=1; i<=n;i++){
mper=in.nextDouble();
if(mper>=95)
c++;
}
System.out.println("In section "+se+" out of "+n+" students "+c+" students secured above 95%");
} } }

Question 14
Write programs to find the sum of the given series:
(a) 1 + (1/2!) + (1/3!) + (1/4!) + .......... + (1/n!)
import java.util.*;

public class pg14a


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 1; i <= n; i++) {
int f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
sum += (1.0 / f);
}
System.out.println("Sum=" + sum);
}}
(b) 1 + (1+2) + (1+2+3) + .......... + (1+2+3+ ...... + n)
import java.util.*;

public class pg14b


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
sum += j;
} }
System.out.println("Sum=" + sum);
}}

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


import java.util.*;

public class pg14c


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
int p = 1;
for (int j = 1; j <= i; j++) {
p *= j;
}
sum += p;
}
System.out.println("Sum=" + sum);
}}

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

import java.util.*;
public class pg14d
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter n: ");
int n = in.nextInt();
double sum = 0.0;
for (int i = 1; i <= n; i++) {
int term = 0;
for (int j = 1; j <= i; j++) {
term += j;
}
sum += (1.0 / term);
}
System.out.println("Sum=" + sum);
}}

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


class pg14e
{
public static void main(String args[]){
double s=1/2.0;
int i;
for(i=3;i<30;i+=2)
s+=1.0/i;
System.out.println("Sum= "+s);
}
}
Question 15a
Write the programs in Java to display the following patterns:
(a)
1
21
321
4321
54321
public class pg15a
{ 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(); } }}
(b)
12345
1234
123
12
1
public class pg15b
{
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();
} }}

(c)
54321
5432
543
54
5
public class pg15c
{
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();
} }}

d) 1 3 5 7 9
1357
135
13
1
public class pg15d
{
public static void main(String args[]) {
for (int i = 9; i >= 1; i -= 2) {
for (int j = 1; j <= i; j += 2) {
System.out.print(j + " ");
}
System.out.println();
} }}
e)
5
54
543
5432
54321
public class pg15e
{
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();
}} }

f)
12345
2345
345
45
5

public class pg15f


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

g)
99999
77777
55555
33333
11111
public class pg15g
{
public static void main(String args[]) {
for (int i = 9; i >= 1; i -= 2) {
for (int j = 1; j <= 5; j++) {
System.out.print(i + " ");
}
System.out.println();
} }}

h)
9
79
579
3579
13579
public class pg15h
{
public static void main(String args[]) {
for (int i = 9; i >= 1; i -= 2) {
for (int j = i; j <= 9; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}} }
(i)
9
97
975
9753
97531
public class pg15i
{
public static void main(String args[]) {
for (int i = 9; i >= 1; i -= 2) {
for (int j = 9; j >= i; j -= 2) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

j
1
23
456
7 8 9 10
11 12 13 14 15

public class pg15j


{
public static void main(String args[]) {
int term = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(term++ + " ");
}
System.out.println();
} }}

You might also like