Chapter 8
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
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 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.
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
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.
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.
While (condition);
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.
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.
Int I;
System.out.printin (+i);
Variation1:
For (; I <10 ;) {
I++;
Variation2:
Int I =5;
For (;;) {
If (i==10)
Break;
Variation 3:
System.out.printin (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:
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:
The following program is an infinite loop as all the three parts of the for loop are
kept empty.
For (;;) {
Illustration
Int I,j,k;
K = i*j;
Illustration
1 1 1
Using for loop, find the sum of serried 1+ 1! + 2! + …+ 10 !.
Int I, fact, a, n, j;
Float sum;
N=10;
A =1;
Fact =1;
Sum =1;
Fact =fact * j;
A=1;
Fact=1;
Exceptions
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 java.io.*;
Class Fibonacci {
Public into n;
Public void get data ()[
Try {
Catch (exception e) {
System.out.printin (b);
C=a+b;
B=c;
Ob.generate ();
Fibonacci series is
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 block
//catch block
//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
Import java.io.*;
Try {
Ar[35] =99;
Catch (arrayindexoutofboundsexception e) {
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. E.g.filenotfoundexception 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.).
}
Illustration
To find the factorial of a given number with for, do while and while loops.
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);
System.out.printin (‘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++;
}
System.out.printin (“factorial of 10=”+fact);
}
}
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.
Int 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:
Int n;
Int digit, j;
Int s = 0;
Double average;
Int I =0;
System.out.printin (“\n”);
While (n > 0) {
Digit = n% 10;
S =s+digit;
N =n / 10;
I = I + 1;
System.out.printin (“\n”);
Average=(double) s / I;
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.
System.out.printin (/n”);
N = number% 10;
S = s +math.sqrt (n);
}
7 writers a program which the sum of even digits of number entered from the
keyboards.
System.out.printin (“\n”);
N = number % 10;
If(n % 2 == 0)
S = s + n;
8 writers a program which finds the sum of odd digits of a number entered from
the keyboard.
System.out.printin (“/n”0;
N=number % 10;
If (n % 2 ! =0)
S= s + n;
Number = number / 0;
9 write a program which accepts a number from keyboard and counts the
frequency of each digit in that number;
Int digit;
Int s =0;
Int I =0;
While (n > 0) {
Digit = n % 10;
S =s + digit;
N =n / 10;
Number[i] =digit;
I = I + 1;
If (number[k] == j)
Count ++;
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 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.
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: System.out.printfn(» ondaV). M
break; ' x;
case 2: System.out.println('Tuesday)-
break; ' y;
Break; 7
case 4: System.out.prindn(»Thursday’s
break; ' ''
case 5: System.out.println("Fridav"V
break; ' ;
case 6: System.out.println("Saturday») ;
Statements
While (expression) {statement2;
if(condition) break;
Statements;
}
Statement^ if(condition)
break; statement5;
}
statements;
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;
}
} System.out.println (i);
if(i== 41) {
break Outer Loop;
}
>
>
>
Continue;
statement2;
>
Statement;
•
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;
if(ctr % 2 == 0)
continue;
•
System.out.pnntln ("");
}
}
}
Output of the Program
1
2 3
4 5
6 7
8 9
10
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;
}
System.out.println (i +"! is=" +factorial);
}
}
}
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
System.out.print (“*”);
System.out.println ();
}
}
}
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++)
System.out.println (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) {
System.out.printf ( ");
}
Else {
System.out.printf ( ");
}
System.out.print ((row * column));
Column++:
}
•
Int i, j, k;
//outer label name
S«3
Outer: for (\ = 1; i < 10; {
System.out.printlnfPass:" i);
for(k = 2; k < 6; k++) {
for(j = 1; j < 20; {
if(j % k != 1)
Continue;
System.out.print (j + " ");
}
System. out.pn’ntln ();
if(i ==3)
break outer;
System.out.println ();
}
}
}
Output of the Program
1
12
233
3444
45555
566666
6777777
78888888
89999999
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));
System.out.println ("Enter your choice");
System.out.printlnfl (“1. For Checking Prime Number");
System.out.println ("2. For Checking Auto orphic Number");
System.out.printlnf'Enter your Choice:");
String r = input.readLine ();
Choice = Integer.parselnt(r);
System.out.println ("Enter Number ::");
String x = input.readLine ();
num = Integer.parselnt(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. Out.println ("Number is not prime number");
Else
System .out.println ("It is a prime number");
case 2:
if(d >= num){
if((num*num)%d==num){
}
else {
system.ot printin(“auto orphic number”);{
else {
System.out.println ("Not an auto orphic number");
}
•
else if (d <=num){
d=d*10;
if((num*num)% d== num){
system.out.printin (“automorphic number”);
}
Else {
System.out.println ("Not an auto orphic number");
}
}
Break;
default: System.out.println("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 java.io.*;
Class Menu Driven {
Public static void main (String args[]) throws I Exception { System.out.prmtln("********
SUMMATION PROGRAM **********'•);
InputStreamReader reader = new InputStreamReader (System. in); Buffered Reader
input = new Buffered Reader(reader);
System.out.printlnfl. s = 1/4 + 1/8 + 1/12 + upto n terms"); System.out.println ("2. s = 1/1! - 2/2! +
3/3! upto n terms");
System. out.printlnQ;
System.out.printlnf'Enter your choice ::");
String x = input.readLine ();
int ch = Integer.parselnt(x); switch (ch) {
case 1: int c = 1;
double y, s = 0;
•
int a = Integer.parseInt(object.readLine());
int fact = 1;
System .out. printl n("Factorial of" +a+);
•
while(n > 0) {
rem = n % 10; // get the remainder
n = n / 10; // get the quotient
sum += factorial(rem);
}
if(sum ==i)
System.out.println ("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 java.io.*;
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;
System.outprintlnCEnter 1. for BUZZ number")-
•
For an ISBN 1401601499Sum = lxl +2x4 +3x0 + 4x1 + 5x6 + 6x0 + 7x1 +8x4 + 9x9 + 10x9 = 253 which
is divisible by 11.Write 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 java.util.Scanner;
Import java.io.*;
class ISBN {
Public static void main throws lOException {
Buffered Reader br = new Buffered Reader (nevj InputStreamReader (System. in));
System.out.print ("Enter a 10 digit code: ");
String s = br.readLine ();
try {
Integer.parselnt( s);
System.out.println ();
}
catch (Exception e) {
System.out.println ("Input Error");
System. exit(O);
}
int len = s.length();
if(len 1= 10)
System.out.println ("Output: Illegal ISBN"); else {
char ch;
int dig = 0, sum = 0, k = 10;
for(int i = 0; i < len; i++) {
ch = s.charAt(i);
if(ch == 'X')
dig = 10;
else
•
Dig=ch-48;
Sum=sum+dig*k;
System.out.println ("Output: Sum = • + um);
S
if (sum % 11 == 0)
•
int t;
InputStreamReader reader = new InputStreamReader (System. in);
Buffered Reader input = new Buffered Reader (reader);
System.out.println ("Enter 1 for Checking Composite number :");
System.out.printlnf'Enter 2 for Checking the Smallest Digit:");
System.out.println ("Enter your choice:");
try {
DatalnputStream z = new DatalnputStream (System. in);
ch = Integer.parseInt(z.readLine());
}
catch (Exception e) {
System.out.println ("Input Error!");
System. exit (O);
}
System, outprintln ("Enter a number=");
try f
DatalnputStream y = new DatalnputStream (System. in);
n = Integer.parselnt (y.readUneQ);
}
catch (Exception e) {
System.out.printlnflnput Error*");
System.exit(O);
} d = l;
ctr = 0;
switch(ch) {
case 1:
while (d <= n) {
if(n == 1)
System.out.println (+n + ": is Not a composite number");
System. exit(O);
if (n % d == 0)
ctr++;
d = d + 1;
/f(ctr ==2)
System.out.print/n(+n + ": is a prime number"); else
System.outprintln (+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;
System.out.print/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 java.io.*;
public class FOverlaod {
//Overload volumes for volume of a cube void volumes (double s) {
System.out.println(" Volume of a cube:" + (s * s * s));
}
//Overload volumes for volume of a cylinder void volumes (double r, double h) {
System.out.println(" Volume of a sphere:" + (3.14 * r * r * h));
}
//Overload volumes for volume of a cuboid
void volumes (double I, double b, double h) { System.out.println(" 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);
/
obj.palindrorne(n);
break;
case 2:
obj.perfect(n); break;
case 3:
System.exit(O);
}
}
}
•
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 java.util.*;
class NivenNumber {
public static void main(String args[]) {
Scanner sc = new Scanner(System. in);
System.out.print (" Enter a number:");
int n = sc.nextlntQ;
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)
system.out pr\nl\n(n+" Is a Niven Number/');
else
system.out.prlntln(n i" Is not a Niven Number.");
}
}
In the above program, we have used the Scanner class of java.util package. The Java.utfl.Scann 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 java.io.*;
Class NivenNumber {
Public static void main(String args[]) throws IOException {
InputStreamReader read = new InputStreamReader (System.in); Buffered Reader in = new Buffered
Reader(read);
System.out.printfEnter a number: ");
Int n = Integer.parselnt (in.readLine ()); 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)
System.out.println (n+ "is a Niven Number.");
else
System.out.println (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 java.io.*;
class PatternPrint {
void print(int n) throws IOException {
System.outprintln( Value for n : ");
n
int i, j;
for(i = 1; i <= n; { for(j = 1; j <= i;
System.out.print ("a"); System.out.println ();
}
for(i = n -1; i >= 1; i-){ for(j = l;j<=i; J++)
System.out.print ("a");
System.out.println ();
}
}
}
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 java.io.*;
class PrintPatternl {
void print(int n) throws IOException {
System.out.println("Value for n = ");
Int i, j, k;
for(i = 1; I <= W <
for(j = l;j<=^'
+
System.out.pnnt(k); +)
System.out.pnnt()
}
for (k=i-1;k.=1;k---)
System.out.print(j);
for (k = i-l;k>=l;k--)
System.out.print(k);
System.out.printlnO;
}
}
}
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 java.io.*;
import java.uti/.*; class FloydPattern {
public void main(int choice) throws IOException {
InputStreamReader reader = new InputStreamReader(System.in); BufferedReader input = new
BufferedReader(reader);
System.out.printlnfEnter 1. Floyd's Triangle ");
System.out.println ( Enter 2. Pattern ");
B
switch(choice) { case 1:
•
int n, num = l, d;
C/
Scanner in =
new Scanner(System.in);
n = in.nextlntQ;
•
break;
case 2:
String str;
Scanner pattern = new Scanner (System.in); System.out.printlnfEnter the input");
str = pattern. next(); int I = str.lengthQ;
for(int i = 0; i < I; i++) { for(intj = 0; j <= i; j++)
System.out.print(str.charAt(j)); System.out.println();
break; default:
System.out.println("Incorrect Choice");
break;
}
>
term = (-x / 2!) * Math.pow((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
double term;
K«X* 3,14159/ 180; term « /;
sum » x;
for (fntla 1; I < n +1; j4+){
term - term * Math.pw^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 * Math.pow((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 * Math.pow((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!
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