Chapter 8
Iteration statements
Iteration statement causes statement to be executed zero or more times, subject to some loop-
termination criteria. When these statement are compound statement they are executed in order except
when either the break statement or the continue statement is encountered.
Java provides three iteration statements-while, do and for. Each of these iterates until its expression
evacuates to zero (false) or until loop termination is record with a break statement.
The statement part of an iteration statement cannot be a declaration. However, it can be a compound
statement containing a declaration. A detailed coverage of all these iteration statements has been given
in this chapter.
Before moving a head, let us first see what the elements that control a loop are
Elements of a loop
A loop consists of following your elemts:
Initialization expression
When the loop first start, the initialization of the loop is executed. Generally, this is an expression htat
sets the value of the loop control variable, which acts as a counter that controls the loop. It is
important to understand that the initialization expression is only executed once
Test expression
After initialization expression, test expression is evaluated. This must be a Boolean expression. It usally
tests the loop control variable against a target value. It this expression is true, then the body of the loop
is executed. If it is false, the loop terminates.
Update expression
After the test expression, the iteration portion of the loop is executed. This is usually an expression that
increments or decrements the loop control variable. The loop then iterates, first evaluating the test
expression, then executing the body of the loop and then executing the iteration expression with each
pass. This process repeats until the test expression is false.
Body of the loop
Body of the loop is that place where all statements are placed for execution. The statements that are
executed repeatedly as long as the test expression is true, from the body of the loop.
If the test expression is true then the body of loop is executed, after execution of loop body test
expression is tested again and if the test expression is true then body false.
Loop construct
Loop construct is also a respective control structure in nature. Computers are the suitable machines for
repetitive execution of statements. Sometimes we require a set of statements to be executed number of
times by chaining the values of one or more variables each time to obtain a different result. This type of
program execution is called looping. Java provides the following loop constructs for iterations:
1. While loop
2. Do-while loop
3. For loop
While loop
The while loop construct is used for repetitive execution of a program subject to the conditions which
may have zero (false) or non-zero (true) value.
General syntax for the while loop:
While (condition statements)
While is a keyword in java, condition is an expression and the statement can be a smile or compound
one.
Flow chart for the while loop
In the flow chart, if the condition evaluates to a non-zero(true) execution, the condition is
evaluated again and if te condition evaluates to a zero (false) execution, the while loop is
terminated.
Llustration-1
Post-increment, continue while loop.
This while-loop uses several syntax forms. It uses a post-increment in the while
loop condition. This means the < test is done before the increment is done.
Modulo: we also use a modulo test to see if a number is evenly divisible by 2. We
use the continue statement to stop the current iteration.
Java program that uses while, post increment, continues:
Do-while loop
Like a while loop, the do-while loop is another repetitive control structure. In
while loop, the condition is tested before execution whereas in a do while loop,
the condition is tested after execution. The do while loop is an exit-controlled
loop in java.
Condition may be a signal or compound statement. The condition may have 0 or
non-zero. A semicolon is placed at the end of the while statement.
While (condition);
Two types of loop
A pre-test loop is a loop in which the loop condition is tested before execution of
the body –for example, a while loop. The for loop is also a pre-test loop. Pre-test
loop is also known by the other names entry-controlled or top-tested loops.
A post-test loop is a loop in which the loop condition is tested after execution of
the body –for e3xample, a do-while loop. Post-test loop is also known by the
other names exit-controlled or bottom-tested loops.
Illustration-1
Develop a java program which counts the number of bounces a rubber ball makes
before it stops bouncing.
It is assumed that the ball reaches to 0.9 times of its previous bounce (height).
The ball is considered to be at rest if the height of the bounce is less than 0.5 cm
above the ground.
Give that initial height is 3 metre (notr: this program will work for any given
height)
For loop
The for loop is also used for repetitive execution of a code but for a fixed number
of times. The program knows well in advance how many times the loop is to be
executed.
This loop is executed at initial value, middle value and final value.
Execution of a for loop
1. In first step, the initial expression is evaluated.
2. In next step, the test expression is evaluated if the value is non-zero; the
loop is terminated without execution.
3. After the execution of for loop, the update expression is evaluated.
Flow chart for execution of for loop
The for loop is better when you are counting something. If you are doing
something an indefinite number of times, while loop may be the better choice.
1. As the cups comes upon the for keyword, control is diverted to the
initialization expression.
2. Once the expression is executed, control moves over to the test expression.
3. If the test expression is true, control passes to the body of the for loop
4. If the test expression is false, control passes to the next statement after the
closed brace.
5. Once control has passed through the body of the loop, the cup is forced to
perform a u-turn back up to the update expression of the loop.
6. Then control return to the test expression and back to step 3 and 4.
Simple program on for loop
Class for loop {
Public void main () {
Int I;
For (i=1; I <=5; i++) {
[Link] (+i);
Output of the program
Variations of for loop in java
The initialization statement, condition statement and iteration statement are
not compulsory and they can be kept empty.
We can rewrite the above program in these ways also:
Variation1:
For loop without initialization and iteration statement
Public class for loop {
Public void main () {
Int I =5;
For (; I <10 ;) {
[Link] (“I =” +i);
I++;
[Link] (“after for loop”);
In the above program, we have intentionally kept the initialization and
iteration part empty. But, to achieve this, we had to write the initialization
statement before the for loop and had to increment the counter inside the
body of the loop.
Variation2:
For loop without the condition statement
In the following program, we have eliminated the condition statement also,
but we have to modify the body of the for loop so that it does not become an
infinite loop. This is done by using the break statement the for loop body.
When the value of I becomes 10, the break statement terminates the for loop.
We will discuss the break statement in ht next topic>
Class for loop {
Public void main () {
Int I =5;
For (;;) {
[Link] (“i=” +i);
I++;
If (i==10)
Break;
[Link] (“after for loop”);
Variation 3:
For loop with multiple initialization and update expression
It is not uncommon to initialize more than one variable, to test a compound
logical expression and to execute more than one statement. The initialization
and the action may be replaced by multiple statements, each separated by a
comma. The program segment given below demonstrates the initialization and
increment of two variables.
For (i=0, j=0; I <10; i++, j++)
[Link] (i);
In the above program segment, there are two initialization expressions; I =0 and j
=0. Next I < 10; is test expression and there are two update expressions; i++ and j+
+. These multiple expressions are executed in a sequence. First I =0 takes place
followed by j =0. During execution, first i++ takes place and then j++.
Variation 4:
For loop with optional expression
Sometimes, the update expression(s) and the test expression can be omitted.
For (i=0,i!=20;)
I+=2;
In the above statement, the update expression is skipped. This loop will run until I
become 20.
If the variable I has alrey been initialized before, then the above statement can be
written as:
For (;i!=20;)
I+=2;
In the above loop statement, both the initialization and update expressions are
skipped.
Variation 5:
For loop running infinitely
The following program is an infinite loop as all the three parts of the for loop are
kept empty.
Public class for loop {
Public void main () {
For (;;) {
[Link] (“inside infinite loop”);
Illustration
Write a program to create a mathematical table.
Class math table {
Public void main () {
Int I,j,k;
For (i=0; I <= 15; i++) {
For (j =0; j< = 15; j++) {
K = i*j;
[Link] (+i+ ‘*” +j +”=” +k);
Illustration
1 1 1
Using for loop, find the sum of serried 1+ 1! + 2! + …+ 10 !.
Class for looping {
Public void main () {
Int I, fact, a, n, j;
Float sum;
N=10;
A =1;
Fact =1;
Sum =1;
For (I =1; < =n; i++) {
For (j=1; j< =I; j++)
Fact =fact * j;
Sum =sum + a /fact;
A=1;
Fact=1;
[Link] (“sum of series=” +sum);
Exceptions
Output of the program
Division by zero is not acceptable
Statement after catch
In the above program, the print in () inside the try block is not execute. It is
because, once an exception is thrown, the program transfers the control out of
the try block into the catch block. Once the catch statement is executed, the
program control continues with the next line in the java program just following
the try-catch block.
Write a java program to print Fibonacci series up to n terms using try and catch
statements.
Import [Link].*;
Class Fibonacci {
Public into n;
Public void get data ()[
Try {
Datainputstream d =new datainputstream (system. in);
[Link] (“enter the limit :”);
N=[Link] ([Link] ());
Catch (exception e) {
[Link] (“input error!”);
System. Exit (0);
Public void main () [
Int a=0, b=1, c, I;
[Link] (“Fibonacci series is \n” +a);
[Link] (b);
For (i=1;I <=n-2;i++) {
C=a+b;
B=c;
Public void main () {
Fibonacci ob =new Fibonacci ();
[Link] ();
[Link] ();
Output of the program
Enter the limit:
Fibonacci series is
Multiple catch clauses
In java programming, more than one exception could be raised by a single
program code. This situation can be handled by two or more catch clauses. Each
clause catches different types of exception. When an exception is thrown, each
catch statement is looked in order. The first catch clause whose type matches the
exception is executed.
After execution of one catch statement, the other catch statements are bypassed.
In such a case, the execution continues after the try/catch block.
A try block an be followed by multiple catch blocks. The syntax for multiple catch
blocks looked like the following:
Try {
//protected code
} catch (exception tyoe1 e1) {
// catch block
} catch (exception type2 e2) {
//catch block
} catch (exception type3 e3) {
//catch block
You can have any number of catches after a single try. If an exception occurs in
the protected code, the exception is thrown to the first catch block in the list. If
the data type of the exception throw matches exception type1, it gets caught
there. If not, the exception passes down to the second catch statement. This
continues until the exception either is caught or falls through all catches, in which
case the current method stops execution and the exception is thrown to the
previous method on the call stack.
Illustration
Show the use of multiple catch clauses:
Import [Link].*;
Class multiple catch {
Public static void main (string args []) {
Try {
Int number =args. Length;
[Link](“the number is =+number);
Int value =25 /number;
Int ar[] ={1];
Ar[35] =99;
Catch (arithmetic exception e) {
[Link] (“divide the number by zero” +e);
Catch (arrayindexoutofboundsexception e) {
[Link] (“array object” +e);
[Link] (“after try/catch blocks”);
Output of the program
The number is=0
Divide the number by zero [Link]:/by zero
After try/catch blocks
Distinction between an error and exception
error Exception
(i) An error I an irrecoverable (i) Exceptions are conditions that occur
Condition occurring at runtime. because of bad input.
Such as out of memory error. [Link] will be the
row if the specified file does not exist or
a nullpointerexception will take place if
you try using a null reference.
(ii) These are JVM errors and you (ii) in most of the cases, it is possible to
cannot repair them at runtime recover from an exception (probably by
giving use a feedback for entering
proper values etc.).
Conversion of one from of a loop into other loop
To find 12+22+………………..+52which for and while loops.
(I) With for loop
Class withforloop {
Public void main () {
Int I,s;
S=0;
For (i=1;I < =5; i++) {
S =s + i*I;
}
[Link] (“sum=”+s);
}
(iii) With wile loop
Class with while loop {
Public void main () {
Int I,s;
S=0;
While (i=n) {
S =s + i*i;
I++;
}
[Link] (“sum=”+s);
}
}
Illustration
To find the factorial of a given number with for, do while and while loops.
(i) factorial of a number with for loop
Class factorialforloop {
Public void main () {
Int a;
Int n=10;
Double fact;
Fact =1;
For (a=1;a<=n;a++) {
Fact=fact*a;
}
[Link] (‘factorial of 10=”+fact);
}
}
(ii) Factorial of a number with do while loop
Class factorialforloop {
Public void main () {
Int a;
Int n=10;
Double fact;
Fact =1;
a=1;
Do=1;
Fact=fact*a;
a++;
}
While (a<=n);
[Link] (‘factorial of 10=”+fact);
}
}
(ii) factorial of a number with while loop
Class factorialwhileloop {
public void main () {
int a;
int n=10;
double fact;
fact =1;
a=1;
while (a<=n) {
fact=fact*a;
a++;
}
[Link] (“factorial of 10=”+fact);
}
}
Understanding an infinite loop
The for loop is used to repeat one or more than one statement for a specified
number of times. While using for loops in the programs, it should be ensured that
loop’s ending condition should be met. If the ending condition is not met, the
loop continues for ever. This unending loop is called infinite loop. If such a
condition happens, this means that the program has an error in the loop.
Consider the following program:
Class infinite loop {
Public void main () {
Int n;
For (n=0; n< 100; n--) {
[Link] (“number is=”+n);
}
}
In the above program, the variable n is being decremented every time in the for
loop. But the was initialized to 0 in the start. In such a case, it will never be equal
to 100 but will remain less than 100. The loop will terminate only if n reaches 100
but beaver happens to be in the above program. Therefore, the loop will never
end. The above program can be corrected by suing the correct for statement as in
the following corrected program:
Class loop correct {
Public void main () {
Int n;
For (n=0; n < 100; n++) {
[Link] (“number is =”+n);
More worked out illustrations
1. To find the sum of a geometric series like a+ar+ar 2 +ar 3 +______up to 6
terms.
Answer. Class gp {
Public void main (int a, int.r){
[Link] (“value of first ‘a’-“+a);
[Link] (“value of common ratio ‘r’=”+r);
Int s, n, I;
S=0;
I=1;
N=0;
Do {
S=s+a*=I;
I=i*r;
}
While (i>n+1);
[Link] (“sum of geometric series=”+s);
}
}
Output of the program
Value of first term ‘a’=3
Value of common ratio ‘r’=2
Sum of geometric series=214783645
2. Write a program to display a series of Fibonacci. The Fibonacci numbers are
those in which every number is the sum of its previous two numbers
(except the first two numbers). For example -0,1,1,2,3,5,8,13,21…….
Answer: class fibonacciseries {
Public void main (int.n) {
[Link] (“number is:”+n);
Int a=1,b=1,c,i=0;
C=a+b;
[Link] (“the series is:");
[Link] (“\t”+a);
[Link] (“\t”+b);
[Link] (“\t”+c);
While (i<n-3){
A=b;
B=c;
C=a+b;
[Link] (“\t”+c);
I++;
}
}
}
3. a perfect integer is a number which is equal to the sum of all its factors,
e.g.28 is a perfect integer as it is the sum of the all its factors. For example:
1+2+4+7+14. Write a program to display perfect integers from 1 to 1000.
Answer: class perfect {
Public void perfect() {
[Link] (“perfect integers are:”);
Int a, I, n , s;
For (n=2;n <=n <1000;n++){
S=0;
For(i=1;i<=n/2;i++){
A=n % I ;
If(a==0)
S+=I;
}
If (n ==s)
[Link] (+n);
}
}
}
4. to find whether a number is odd, even or prime.
Answer: class oddevenprime {
Public void main (int number) {
Int count = 0;
Int I;
[Link] (“number=”+number);
If(number % 2==0){
[Link] (“the number is even”);
}
Else{
[Link] (“the number is odd”);
}
If(number ==1) {
[Link] (“the number is also prime”);
}
For(i=2; i<= number /2; ++) {
If(number % 2==0) {
Count ++;
}
}
If(count>0) {
5. Write a program which accepts a number from keyboard and find:
(i) Sum of digits
(ii) Average of digits.
Answer: class average {
Public void min (int n) {
Int digit, j;
Int s = 0;
Double average;
Int I =0;
[Link] (the number is =”+n);
[Link] (“\n”);
While (n > 0) {
Digit = n% 10;
S =s+digit;
N =n / 10;
I = I + 1;
[Link] (“the sum of the number =’+ s);
[Link] (“\n”);
Average=(double) s / I;
[Link] (“average of digits =” +average);
6 write a program which accepts a number from the keywords finds sequare root
of each digit and sums up the digits after square root.
Answer: class sumsquareroot {
Public void ssroot (int number) {
Double n,s =0;
[Link] (/n”);
While (number >0) {
N = number% 10;
S = s +[Link] (n);
Number = number / 10;
[Link] (“sum of sequare roots of each digital of number =”s)
}
7 writers a program which the sum of even digits of number entered from the
keyboards.
Answer: class sum of even {
Public void sum (int number) {
Int n,s =0;
[Link] (“you have entered the number =” +number);
[Link] (“\n”);
While (number >0) {
N = number % 10;
If(n % 2 == 0)
S = s + n;
Number = Number / 10;
[Link] (“sum of even digital of the number =” +s);
Output of the program
You have entered the number =1234567
Sum of even digital of the number =12
8 writers a program which finds the sum of odd digits of a number entered from
the keyboard.
Answer: class sum of odd {
Public void sumodd (int number) {
Int n,s =0;
[Link] (“the number is =” +number);
[Link] (“/n”0;
While (number >0) {
N=number % 10;
If (n % 2 ! =0)
S= s + n;
Number = number / 0;
[Link] (“sum of odd digits of the number =” +s);
Output of the program
The number is =136
Sum of odd digits of the number =4
9 write a program which accepts a number from keyboard and counts the
frequency of each digit in that number;
Answer: class frequency {
Public void frequency (int n) {
Int number [] =new int [9];
Int digit;
Int s =0;
Int I =0;
[Link] (“number is =”+n);
While (n > 0) {
Digit = n % 10;
S =s + digit;
N =n / 10;
Number[i] =digit;
I = I + 1;
Int count =0;
For (int j =0; < =9; j ++) {
For (int k =0; k < I; k++) {
If (number[k] == j)
Count ++;
[Link] (“the digit “+j+ “occurs” +count+ “times”);
Count =0;
Jumping Jumping means transferring of control from one part to another part in a given program.
Jump statements transfer control unconditionally.
There are three types of jump statements in Java:
Nottit
•> continue statement
Break statement
*
Return statement
Out of these statements, the return statement can be used anywhere in the program
Whereas the other two statements are used inside the parts of the programs like loops.
Java also provides a function System. exit () that helps you break out of a program.
The break statement
The break statement is used when you want to skip over a loop instead of exiting
the entire program
The break statement appears in the body of while, for or switch statements.
The break statement exist the most currently loop.
If your program consists a while loop with another while loop, then the break
exist only the internal loop.
Syntax-
Look at the following program segment:
While (expression) {
Statement!; If(interest > 5000)
Break;
statement2;
}
statement3;
do {
Statement; if (interest > 5000)
break; statement2;
}
wWle(expression);
statement3;
for(int; expression; stop) { statement;
if(interest > 5000) break;
statement2;
}
statement3;
case 1: [Link](» ondaV). M
break; ' x;
case 2: [Link]('Tuesday)-
break; ' y;
Case 3: [Link] (- <ln sday").
We e
Break; 7
case 4: [Link](»Thursday’s
break; ' ''
case 5: [Link]("Fridav"V
break; ' ;
case 6: [Link]("Saturday») ;
case 7: [Link]("Sunday") break; ;
default: [Link]("invalid Choice"); break;
}
}
}
Use of break statement in the nested loops
for(int; expression; stop) {
Statements
While (expression) {statement2;
if(condition) break;
Statements;
}
Statement^ if(condition)
break; statement5;
}
statements;
The labeled break statement
The break statement can be followed by a label. The presence of a iau^ . start f
c 0
the code Identified by the label. ... . . •
r rtr
jtch for, while or do-while statem
f sW
The unlabeled form of the break statement terminates the innermo specified in the b '
Whereas the labeled form terminates an outer statement which is idem i r eak
Statement.
Fltisfradon
Public class Main Class {
Public static void main (String args[]) { Outer Loop : for(int i = 2; ; {
for(int j = 2; j < I; { if(i %j == 0){
Continue Outer Loop;
}
} [Link] (i);
if(i== 41) {
break Outer Loop;
}
>
>
>
The continue statement
The break statement causes termination of the loop and reaches at the bottom of the loop. The continue
statement does opposite of the break statement. It forces the next iteration of the loop.
In case you use a continue statement in the body of while, do-while, for loop, the computer ignores any
other statement in the loop that follows the continue statement.
Syntax-
Continue;
whi/e(condition) {
Statement;
if(condition)
•
Continue;
statement2;
>
Statement;
•
CANDID ICSE COMPUTER APPLICATIONS- 10
do {
Statement;1
-•
•
if (condition)
Continue;
Statement!;
}
While (condition);
Statements;
For (int; expression; stop) {
Statement;
The break statement can be used with while,
if(condition)
Continue;
do-while, tor and switch
Statements.
statement2;
}
statement3;
Use of continue statement in nested loops
Do {
statement1;
The continue statement forces the next iteration
of the loop.
While (expression) {
statement2;
if(condition)
Continue;
statement3;
}
Statement4;
if(condition)
Continue;
statement5;
}
While (expression);
Statements;
In the above nested loop, two hops have been used. The first loop is do loop and the second is while loop. In the
continue statement in while loop, the program execution reaches to the first statement of while loop where the
condition is tested. The statements after not execute. When the execution reaches at do loop, the execution
reaches at the end of do loop, (i.e. while statement) with the use of continue statement. Here again the
condition of execution of do loop is tested.
Program to show the use of continue statement
Class Counting {
Public void main () {
int ctr;
for(ctr = 1; ctr <= 10; ctr++) {
System. out print(ctr +• ");
•
if(ctr % 2 == 0)
continue;
•
[Link] ("");
}
}
}
Output of the Program
1
2 3
4 5
6 7
8 9
10
The labeled continue statement
The iabeied form of the continue statement skips the current iteration of an hop marked with the given label. The
following program uses nested loopsprogram uses the labeled form of continue to skip an iteration in the outer
loop
Illustration
public class MainClass1 {
Public static void main (String args[]) {
int limit = 20;
int factorial = 1;
Outer Loop ; for(int i = 1; i <= limit; {
Factorial = 1;
for(intj = 2;j<= j j +){
; +
if(i>10&&i%2 == 1){
continue Outer Loop;
}
factorial *= j;
}
[Link] (i +"! is=" +factorial);
}
}
}
The return statement
The lastJump statement is return. The return statement is used to explicitly return from a method. That is, it
causes program control to transfer back to the caller of the method. The return statement immediately
Terminates the method in which it is executed
the return statement has two forms:
(1) one that returns a value and (2) one that does not. To return a value, simply put the value (or an expression
that calculates the value) after the return keyword.
return ++count;
the data type of the value returned by return must match the type of the method's declared return value.
When a method is declared void, use the form of return that does not return a value.
return;
Need of loops
Loops are the heart of programming. To write an efficient program, loops are required. Imagine you have to
write a program which performs a repetitive task such as counting from 1 to 100. Coding 100 lines to do this
task would be very cumbersome. There has to be an easier way, right? This is where loops come into the
picture. Loops are specifically designed to perform repetitive tasks with one set of code. Loops save a lot of
time. Let us have an idea as to why there is need of loops in Java programs.
1. Loops make the program code shorter. For known or unknown number of iterations, they are used in the
programs to execute the part of the program up to a fixed number of times or till a condition is met.
2. Nested loops are used for calculations in matrices and arrays. They can be used for sorting of array
elements, prepare number tables, searching an element, etc.
3. Loops can be used for recursion process. Methods can be used through loops and need of calling them
again and again is avoided.
4. Loops can be used for calculations.
Nested Loops
A nested loop is a term that describes when one loop is placed inside another loop. It is the same as using
ordinary loops, but it has some other options that you cannot do without using nested loops. The following
example prints a triangle of stars and shows you how to use nested loops.
Example:
Class Nested Loops {
Public void main () {
For (int row = 1; row <= 5; row++) {
For (int col = 1; col <= row; col++) //nested loop
[Link] (“*”);
[Link] ();
}
}
}
Output of the Program
*
**
***
****
*****
Nested loops are also very useful when using two or more dimensional arrays. While all type of loops may
be nested, the most commonly nested loops areforloops are for loos..
A nested for loop has been shown below:
for(num2 = 0; num2 <= 9; num2++)
for(numl = 0;numl <= 9; numl++)
[Link] (num2 + " +numl);
-•
n
}
}
You can even have multiple levels of /7fis///7# such as a while loop inside an if statement inside another while
loop.
Nested loops
Program using nested do-while loops to generate a 9x9 multiplication table.
//multiple level of nesting
Class Multiple Nesting {
Public static void main (String args []) {
int row = 1;
do {
int column=1;
do {
if((row * column) < 10) {
[Link] ( ");
}
Else {
[Link] ( ");
}
[Link] ((row * column));
Column++:
}
•
Whi!e(column <= 9);
[Link]"); row++;
}
While (row <= 9);
}
}
Let us see how nested lops can be controlled using both continue andbreastatement
[Link] {
Public static void main () {
int i, j, k;
//outer label name
Outer: for(i = 1; i < 10; i++) {
[Link] ("Pass: +i); M
for(k = 2; k < 6; k++) {
for(j = 1; j < 20; j++) {
if(j % k != 1)
Continue;
[Link] (j + "");
}
[Link] ();
}
if(i ==3)
Break outer;
System. [Link] ();
ffl
Let us now see an example of labeled continue
Illustration
Use of Labeled Continue statement
Class Continue Break {
Public static void main () {
.*
Int i, j, k;
//outer label name
S«3
Outer: for (\ = 1; i < 10; {
[Link]:" i);
for(k = 2; k < 6; k++) {
for(j = 1; j < 20; {
if(j % k != 1)
Continue;
[Link] (j + " ");
}
System. [Link]’ntln ();
if(i ==3)
break outer;
[Link] ();
}
}
}
Output of the Program
1
12
233
3444
45555
566666
6777777
78888888
89999999
More programs related to this chapter
1 write a menu driven program to accept a number and check and sidplay
whether it is a prime number or not or an automorphric number or not. (Use
switch case statement).
(a) Prime number: A number is said to be a prime number if it is divisible only by 1 and itself
and not by any other number.
Example: 3, 5, 7, 11, 13....etc.
(b) Auto orphic number: An auto orphic number is the number which is contained in the last
digit(s) of its square.
Example: 25 is an auto orphic number as its square is 625 and 25 is present as the last two
digits.
Answer.
Import java .io.*;
Class Prime Auto {
Static int d = 10;
Public static void main (String args[]) throws I Exception {
Int num, choice;
Buffered Reader input= new Buffered Reader (new InputStreamReader (System. in));
[Link] ("Enter your choice");
[Link] (“1. For Checking Prime Number");
[Link] ("2. For Checking Auto orphic Number");
[Link]'Enter your Choice:");
String r = [Link] ();
Choice = [Link](r);
[Link] ("Enter Number ::");
String x = [Link] ();
num = [Link](x);
switch (choice) {
Case 1:
int i, f = 0;
int a, b;
for (i = 2; i <= num - 1; i++) {
int p = num % i;
if (p == 0)
f = i;
}
System. [Link] ("Number is not prime number");
Else
System .[Link] ("It is a prime number");
case 2:
if(d >= num){
if((num*num)%d==num){
}
else {
[Link] printin(“auto orphic number”);{
else {
[Link] ("Not an auto orphic number");
}
•
else if (d <=num){
d=d*10;
if((num*num)% d== num){
[Link] (“automorphic number”);
}
Else {
[Link] ("Not an auto orphic number");
}
}
Break;
default: [Link]("Wrong choice");
}
}
}
2 write a menu drivn program to find the sum of the following series depending
on the user choosing 1 or 2
1. S = 1/4 + 1/8 + 1/12………….up to n terms
2. S= 1/11-2/2! +3/3!.................. up to n terms
where ! Stands for factorial of the number and the factorial value of a number is the product of
all integers from 1 to that number, e.g. 5! = 1 x 2 x 3 x 4 x 5.
(use switch-case).
Answer.
Import [Link].*;
Class Menu Driven {
Public static void main (String args[]) throws I Exception { [Link]("********
SUMMATION PROGRAM **********'•);
InputStreamReader reader = new InputStreamReader (System. in); Buffered Reader
input = new Buffered Reader(reader);
[Link]. s = 1/4 + 1/8 + 1/12 + upto n terms"); [Link] ("2. s = 1/1! - 2/2! +
3/3! upto n terms");
System. [Link];
[Link]'Enter your choice ::");
String x = [Link] ();
int ch = [Link](x); switch (ch) {
case 1: int c = 1;
double y, s = 0;
•
[Link] ("Enter the no. of terms");
String a = [Link] ();
int n = [Link](a);
for (int i = 4; c <= n; i = i + 4) {
y=1.0/i;
s = s + y;
C++:
}
-
[Link](s);
break;
case 2:
int j;
double d=1;
double sum = 0;
double w = 0;
[Link] (“enter the no, of terms”);
String t = input. read line();
int m = [Link](t);
for(j = j;j<m;j++){
int p=1;
for(int k = l; k <=m; k++){
P = P * k;
}
W= (d+j)/p; lf(j%2«0)
sum = sum - w;
else
sum = sum + w;
}
[Link] (sum);
}
}
}
3 write a program to input a number and print whether the number is a special
number or not.
(A number is said to be a special number, if the sum of the factorial of the digits of the number is
same as the original number).
Example: 145 is a special number, because 1! + 4! + 5 ! =1 + 24 + 120 = 145
(Where! stands for factorial of the number and the factorial value of a number is the product of all
integers from 1 to that number, example 51=1*2*3*4*5 = 120). (From ICSE Exams)
Answer,
import [Link].*;
class Factorial {
public static void main(String args[]) {
try {
Buffered Reader object = new Buffered Reader (new InputStreamReader(System. in));
[Link] ( Enter the number");
n
int a = [Link]([Link]());
int fact = 1;
System .out. printl n("Factorial of" +a+);
•
for (int i = 1; I <= a; /++){
fact = fact * i;
}
[Link](fact);
}
catch (Exception e){}
void Special Numbers() {
int limit= 1000;
for (int=i1 i<= limit; i++){
int n = i;
// resolve the number
int rem, sum = 0;
•
while(n > 0) {
rem = n % 10; // get the remainder
n = n / 10; // get the quotient
sum += factorial(rem);
}
if(sum ==i)
[Link] ("Special number: " + i);
}
}
Private static int factorial (int number) {
int f = 1;
for (int 1=1; i <= number;
f *= i;
return f;
}
}
4 write a menu driven program to access a number from the user and check
whether it is a BUZZ number or to accept any two numbers and to print the GCD
of them.
(a) A BUZZ number is the number which either ends with 7 or is divisible by 7.
(b) GCD (Greatest Common Divisor) of two integers is calculated by continued division method. Divide
the larger number by the smaller; the remainder then divides the previous divisor.
The process is repeated till the remainder is zero. The divisor then results the GCD.
(From ICSE Exams)
Answer.
import [Link].*;
class Buzz {
public static void main(String argsf ]) throws I Exception {
Buffered Reader input = new Buffered Reader(new InputStreamReader (System. in)); int number, a, b,
remainder = 0;
[Link] 1. for BUZZ number")-
•
[Link] ("Enter 2. for GCD");
[Link] ("Enter your choice:");
int ch = [Link]([Link] ());
switch(ch) {
case 1:
-
[Link] ("Enter a number: ");
a = [Link] ([Link] ()); remainder = a % 10;
Number = a % 7;
if(remainder == 7 || number == 0)
[Link] ("BUZZ no." +a); else
[Link] ("Not a BUZZ no." +a);
Break;
Case 2:
[Link] ("Enter the 1st number :");
a = [Link] ([Link] ());
[Link] ("Enter the 2nd number:");
b = [Link] ([Link] ());
Remainder = a % b;
While (remainder!= 0) {
a = b;
b = remainder;
Remainder = a % b;
}
[Link] ("GCD = " +b);
default:
[Link] ("Wrong Choice");
}
}
}
Output of the Program :
Enter 1. for BUZZ number
Enter 2. tor GCD
Enter your choice: 1
Enter a number: 1516
Not a BUZZ no. 1516
5 the international standard book number (ISBN) is a unique numeric-book
identifier which is printed on every book. The ISBN is based upon a 10-digit code.
The ISBN is legal if:
lxdigitj + 2xd/git + 3xdigtt + 4xdig/t + 5xd/git + 6xdigit + 7xdigit + 8xdigit + 10xdig/t is divisible by 11.
2 3 4 5 6 7 8 9xdjnj 10
For an ISBN 1401601499Sum = lxl +2x4 +3x0 + 4x1 + 5x6 + 6x0 + 7x1 +8x4 + 9x9 + 10x9 = 253 which
is divisible by [Link] a program to:
(i) Input the ISBN code as a 10-digit integer.
(ii) If the ISBN is not a 10-digit integer, output the message, "Illegal ISBN" and terminate
program.
(iii) If the number is 10-digit, extract the digit of the number and compute the sum as explained above.
If the sum is divisible by 11, output the message, "Legal ISBN". If the sum is not divisible by 11, output the
message, "Iliegal ISBN".
Answer, import [Link];
Import [Link].*;
class ISBN {
Public static void main throws lOException {
Buffered Reader br = new Buffered Reader (nevj InputStreamReader (System. in));
[Link] ("Enter a 10 digit code: ");
String s = [Link] ();
try {
[Link]( s);
[Link] ();
}
catch (Exception e) {
[Link] ("Input Error");
System. exit(O);
}
int len = [Link]();
if(len 1= 10)
[Link] ("Output: Illegal ISBN"); else {
char ch;
int dig = 0, sum = 0, k = 10;
for(int i = 0; i < len; i++) {
ch = [Link](i);
if(ch == 'X')
dig = 10;
else
•
Dig=ch-48;
Sum=sum+dig*k;
[Link] ("Output: Sum = • + um);
S
if (sum % 11 == 0)
•
[Link] ("Leaves No Remainder - Legal ISBN Code");
else
[Link] ("Leaves Remainder - Illegal ISBN ");
}
}
}
6 using the switch statement write a menu driven program.
(i) To check and display whether a number input by the user is a composite number or not (A number is
said to be a composite if it has one or more than one factor excluding 1 andthe number itself).
Example : 4, 6, 8, 9
(ii) To find the smallest digit of an integer that is input.
Sample input : 6524
Sample output : Smallest digit is 2
For an incorrect choice, an appropriate message should be displayed.
Answer, import [Link].*;
class Switch Case {
Public static void main(String args[]) throws I Exception {
int n = 0, d ctr, ch;
#
int t;
InputStreamReader reader = new InputStreamReader (System. in);
Buffered Reader input = new Buffered Reader (reader);
[Link] ("Enter 1 for Checking Composite number :");
[Link]'Enter 2 for Checking the Smallest Digit:");
[Link] ("Enter your choice:");
try {
DatalnputStream z = new DatalnputStream (System. in);
ch = [Link]([Link]());
}
catch (Exception e) {
[Link] ("Input Error!");
System. exit (O);
}
System, outprintln ("Enter a number=");
try f
DatalnputStream y = new DatalnputStream (System. in);
n = [Link] ([Link]);
}
catch (Exception e) {
[Link] Error*");
[Link](O);
} d = l;
ctr = 0;
switch(ch) {
case 1:
while (d <= n) {
if(n == 1)
[Link] (+n + ": is Not a composite number");
System. exit(O);
if (n % d == 0)
ctr++;
d = d + 1;
/f(ctr ==2)
[Link]/n(+n + ": is a prime number"); else
[Link] (+n + ": is a composite number");
}
break;
case 2:
int min = n % 10;
white(n > 0) {
int a = n % 10;
if(a < min)
min = a;
n = n / 10;
[Link]/nCThe smallest digit is :" +min); break;
}
}
}
7 write a class with the name overloads using function overloading that computer
the volume of a cube, a cylinder and cuboids.
Volume of a cube =s*s*s (where is the side of a cube)
volume of a cylinder = pi * r * r * h (where pi=3.14or 22/7,r is radius and h is height of cylinder)
volume of a cuboid = l*b*h (where b is breadth and is headth and h is height of the cuboid)
nqth
Answer.
import [Link].*;
public class FOverlaod {
//Overload volumes for volume of a cube void volumes (double s) {
[Link](" Volume of a cube:" + (s * s * s));
}
//Overload volumes for volume of a cylinder void volumes (double r, double h) {
[Link](" Volume of a sphere:" + (3.14 * r * r * h));
}
//Overload volumes for volume of a cuboid
void volumes (double I, double b, double h) { [Link](" Volume of a cuboid:" + (I * b *
h));
>
public static void main(String args[]) throws I Exception {
FOverlaod vl = new FOverlaod();
//call to all versions of volumes()
volumes(7.0);
volumes(4.0 6.0);
/
volumes(4.0, 5.0, 6.0);
}
}
Output of the Program :
Volume of a cube:343.0
Volume of a sphere:301.44
Volume of a cuboid:120.0
8 writers a menu driven program to accept a number from the user and check
whether it is a palindrome or a perfect number.
Palindrome number - (a number is a Palindrome which when read in reverse order is same as
read in the right order)
Example: 11, 101, 151, etc.
Perfect number - (a number is called Perfect if it is equal to the sum of its factors others than the
number itself.)
Example: 6 = 1 + 2 + 3 (From ICSE Exams) import [Link].*;
public class Plainpert {
r Answer.
import java.o.*;
pubic class pa,inpert{
void palindrome(int number) {
int p, d, r = 0; p = number;
do {
d = number % 10;
r = r* 10 + d;
number = number / 10;
} whi/e(number l=
System. [Link] (The number” +p +" is a palindrome");
else
[Link] (" The number " +p +" is not a palindrome");
}
void perfect(int number) {
int a, s = 0;
for(a = 1; a < number; a++) { if(number % a == 0)
s = s + a;
}
if(s == number)
[Link] ("The number" +number +" is a perfect number"); else
[Link] (“The number " +number +" is not a perfect number");
}
Void perfect (int number) {
Int a, s=0;
For(a=1; a<number; a++){
[Link](‘the number” + number+”is a perfect number”);
Else
[Link](‘the number” + number+”is a perfect number”);
}
public static void main(String args[]) throws lOException {
int n, m = 1, r = 0
; int s = 0;
int choice;
InputStreamReader read = new InputStreamReader (System. in);
Buffered Reader in = new Buffered Reader(read);
[Link] ("Enter the number: ");
n = [Link] ([Link]());
PalinPerf obj = new PalinPerf {);
System [Link]/n(' ****'' * ****Menu********* )•
< , C) < ,,
[Link] (" Press 1. To check for palindrome number ;");
[Link] Press 2. To Check for perfect number:");
[Link](" Press 3. To Exit :");
while(m 1= 0) {
[Link]'Enter your choice; ")•
m «[Link]());
choice o m;
sw(tch(cho(ce) {
case 1:
•
[Link](n);
break;
case 2:
[Link](n); break;
case 3:
[Link](O);
}
}
}
•
Output of the Program :
Enter the number: 1234589 * * * * * * * * * * menu *********
Press 1. To check for palindrome number :
Press 2. To Check for perfect number :
Press 3. To Exit : Enter your choice: 2
The number 1234589 is not a perfect number Enter your choice: 1
The number 1234589 is not a palindrome Enter your choice:
MISCELLANEOUS
Miscellaneous program
1 write a program to accept a number and check and display whether it is a niven
number or not.
(Niven number is that number which is divisible by its sum of digits).
Example :
Consider the number 126.
Sum of its digits is 1 + 2 + 6 = 9 and 126 is divisible by 9.
(From ICSE Exams)
Answer,
import [Link].*;
class NivenNumber {
public static void main(String args[]) {
Scanner sc = new Scanner(System. in);
[Link] (" Enter a number:");
int n = [Link];
int c = n, d, sum = 0; //finding sum of digits
while(c > 0) {
d = c % 10; sum = sum + d;
c = c/10;
}
if(n % sum == 0)
[Link] pr\nl\n(n+" Is a Niven Number/');
else
[Link](n i" Is not a Niven Number.");
}
}
In the above program, we have used the Scanner class of [Link] package. The [Link] e
class is a simple text scanner which can parse primitive types and strings using regular expressions
Otherwise normally, we have used Buffered Reader class of Java Jo package.
Buffered Reader reads text from a character-input stream. It buffers characters and provides efffcfe
reading of characters, arrays and lines. The buffer size may be specified or the default size may 5
used. The default is large enough for most purposes.
Where Scanner is a simple text scanner which can parse primitive types and strings using requl
expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default match
whitespace. The resulting tokens may then be converted into values of different types usinq tlT
various next methods. e
Use BufferedReader if you want to get long strings from a stream and use Scanner if you wanf parse
specific type of token from a stream. t0
The same program has been written using Buffered Reader:
Import [Link].*;
Class NivenNumber {
Public static void main(String args[]) throws IOException {
InputStreamReader read = new InputStreamReader ([Link]); Buffered Reader in = new Buffered
Reader(read);
[Link] a number: ");
Int n = [Link] ([Link] ()); int c = n, d, sum = 0;
//finding sum of digits while(c > 0) {
d = c % 10;
sum = sum + d;
c = c / 10;
}
if(n % sum == 0)
[Link] (n+ "is a Niven Number.");
else
[Link] (n "is not a Niven Number.");
+
}
}
2 write a program in java to print the given pattern till value of n entered by the
user.
For example –if the user enters 5, the following pattern should be printed.
a
aa
aaa
aaaa
aaaaa
aaaa
aaa
aa
Answer;
mport [Link].*;
class PatternPrint {
void print(int n) throws IOException {
[Link]( Value for n : ");
n
int i, j;
for(i = 1; i <= n; { for(j = 1; j <= i;
[Link] ("a"); [Link] ();
}
for(i = n -1; i >= 1; i-){ for(j = l;j<=i; J++)
[Link] ("a");
[Link] ();
}
}
}
3 write a program in java to print the following pattern till the value of n enterd
by the user:
1
121
12321
1234321
12345321
1234321
12321
121
1
Answer.
import [Link].*;
class PrintPatternl {
void print(int n) throws IOException {
[Link]("Value for n = ");
Int i, j, k;
for(i = 1; I <= W <
for(j = l;j<=^'
+
[Link](k); +)
[Link]()
}
for (k=i-1;k.=1;k---)
[Link](j);
for (k = i-l;k>=l;k--)
[Link](k);
[Link];
}
}
}
4 using the switch statement write a menu driven program for the following:
(i) to print the Floyd’s triangle
1
23
456
7 8 9 10
1112 13 14 15
(ii) To display the following pattern I
IC ICS
ICSE
For an incorrect option, an appropriate error message should be displayed.
Answer, import [Link].*;
import [Link]/.*; class FloydPattern {
public void main(int choice) throws IOException {
InputStreamReader reader = new InputStreamReader([Link]); BufferedReader input = new
BufferedReader(reader);
[Link] 1. Floyd's Triangle ");
[Link] ( Enter 2. Pattern ");
B
switch(choice) { case 1:
•
int n, num = l, d;
C/
Scanner in =
new Scanner([Link]);
n = [Link];
•
[Link]("Floyd's triangle:"); for (c = 1; c <= n; C++) {
for (d = l;d<=c;d++){
[Link](num+"");
num++;
}
[Link]();
}
•
break;
case 2:
String str;
Scanner pattern = new Scanner ([Link]); [Link] the input");
str = pattern. next(); int I = [Link];
for(int i = 0; i < I; i++) { for(intj = 0; j <= i; j++)
[Link]([Link](j)); [Link]();
break; default:
[Link]("Incorrect Choice");
break;
}
>
5 write a java program to find the sum of series:
∞
(−1 ) n 2 n x2 x 4
Cos x = ∑ x =1− + -….for all x
n=0 ( 2n ) ! 2! 4!
The given series is caUed cosine series.
Answer, import [Link].*;
class CosineSeries {
void SumSeries(int n, double x) throws IOException {
[Link]("Value of n =" +n);
[Link]("Value of x =" +x);
double sum = 1;
double term = 1;
x = x*3.14159/ 180;
for (Int I» 1; I < n + 1; I++M i» * x * x/(2 * I* o *
term = term * [Link]((double)(-l), (double) (2 * i - 1) *x* x/ (2*i*(2*i-1));
sum = sum + term;
}
[Link]("cos(x) = " +sum);
}
}
Output of the Program:
Value cf n =20
Value cf x =60.0
ccs(x) - 0.5000007660251953
Explanation of above program
Let n = 2, then the cosine series generated by above program is as follows:
initially, x\s converted to radian by multiplying it by 3.14159/180 and term and sum are also assigned the
value of L So, after line number 16 of the program, we have:
term = 1 and sum = 1
Now let us take a look at the working of for loop with n = 2:
Expression 1: term = term * [Link]((double)(-l), (double) (2 * i - 1)) * x * x / (2 * i * (2 * i - 1))
Expression 2: sum = sum + term Iteration 1: i = 1, term = 1, sum =1
Putting these values in Expression 1 we get,
term = 1 * [Link]((double)(-l), (double) (2 * 1 - 1)) * x * x / (2 * 1 * (2 * 1 - 1)) term = 1 * (-1)* x * x / 2 = -
x / 2!
2
Putting value of term in Expression 2 we have,
sum= l + (-x /2!) = l-x /2!
2 2
Iteration 2: i = 2, term = -x / 2!, sum = 1 - x / 2! Putting these values in Expression 1 we get,
2 2
term = (-x / 2!) * [Link]((double) (-1), (double) (2 * 2 - 1)) * x * x / (2 * 2 * (2 * 2 - 1)) term =-x / 2! *(-l) *
2 2
x * x / 12 = x /4! 4
Putting value of term in Expression 2 we get, sum = l-x /2! +x /4
2 4
6 writers a java program to find the sum of series:
∞ 3 5
(−1 ) n x x
sin=∑
2 n +1
! ¿ x =x− + - -....for all x The given series is called sine series.
•
n=0 2n+ 1¿ 3! 5 !
h dm StoeSertes {
j ^um^im n, double /) throws IO&teptfcm { Sj«[Link],prfritlnf'Value of n «• + ); n
V^m^ut,pr(rrtJn('Value of x «" 4/);'
?1
double term;
K«X* 3,14159/ 180; term « /;
sum » x;
for (fntla 1; I < n +1; j4+){
term - term * [Link]^doubleX-l), (doubfe) (2 * f -1)) * x * x / (2 * f * (2 * i + 1)); sum a surn + term;
}
System,outprlntfn(*sfn(x) =" +sum); }
}
Output of the Program
•
Value or r. -20
Value of z -30.0
8ia(x) - 0.4933996169572557
Explanation of above program
Let //« 2, then the sine series generated by above program is as follows:
Initially, X is converted to radian by multiplying it by 3.14159/180 and term and sum are also assigned the
value of x.
term =xand 5^/77 «*
Now let us take a look at the vjorklng of for loop with n - 2:
Expression 1: term = (term * [Link]((double) (-1), (double) (2 * I -1)) * x * x) / (2 * I * (2 * I + 1))
Expression 2: sum = sum + term Iteration 1:1 = 1, term = x, sum = x
Putting these values in Expression 1 we get,
term = (x * [Link]((double) (-1), (double) (2 * 1 -1)) * x * x) / (2 * 1 * (2 * 1 + 1))
term = xM-l)*** / - / Putting value of t In Expression 2 we get,
x 6= x3 3!
sum= x + (-x /3!) = x-x /3!
3 3
Iteration 2:1 = 2, term = -x / 3!, sum = x - x / 3! Putting these values in Expression 1 we get,
3 3
term - (-x / 3! * pow ((double) (-1), (double) (2 * 2 - 1)) * * x) / (2 * 2 * (2 * 2 + 1)) t = (-x /3!)*(-l)*x*x/20
3 x 3
= x /5!
5
Putting value of t in Expression 2 we get, sum = x~x /3! + x /5!
3 5
Switch statement tests a value against a set of integer’s constants including
characters.
Switch statement may be nested.
No semicolon is allowed with switch construct.
An infinite loop is that which never ends.
Java provides three loop constructs- while loop, do- while loop an for loop.
A semicolon should be placed after do while and while statements.
In a do-while loop the condition is tested after execution whereas it is
tested before execution in a while loop.
The for loop is used when the number of times the loop be executed is
known in advance.
You cannot use continue statement in a switch statement.