0% found this document useful (0 votes)
2 views30 pages

Chapter 10 Iteration Constructs in Java

The document discusses iteration constructs in Java, focusing on various loop types such as for, while, and do-while loops, along with their control statements. It explains the components of loops including initialization, test, update expressions, and the body of the loop, providing examples of each type. Additionally, it covers concepts like infinite loops, empty loops, and variable declaration within loops.

Uploaded by

celinejohncruz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

Chapter 10 Iteration Constructs in Java

The document discusses iteration constructs in Java, focusing on various loop types such as for, while, and do-while loops, along with their control statements. It explains the components of loops including initialization, test, update expressions, and the body of the loop, providing examples of each type. Additionally, it covers concepts like infinite loops, empty loops, and variable declaration within loops.

Uploaded by

celinejohncruz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Iteration Constructs in Java CHAPTER U t Chapter Outline 10.1 INTRODUCTION Programs not only store data but also manipulate 10.1 Introduction data in terms of consolidation, rearranging, 10.2 iteration Through Loops modifying data. To perform their manipulative 10.3. The for Loop ~ Fixed Number of iterations miracles, programs need tools for performing, 10.4 The while Loop repetitive actions and for making decisions. Java 10.5 The do-while Loop of course provides such tools by providing, 10.6 Jump Statements statements to attain so, Such statements are called program control statements. Various program control statements are selection statements, iteration or looping statements and jump statements. You have read about selection statements in previous chapter. This chapter shall talk about looping or iteration statements along with jump statements. COMPUTER? APPLICATIONS-1X jormed repeatedly until a certain statements are also calle 1s or looping statements. Java for loop, while loop, and do-while Toop. ‘All three loop constructs of Java repeat a set of statements as long as a specified condition aavraing true. This specified condition is generally referred [Link] a loop contol. For all three Joop Statements, a irue condition is the one that retums boolean true value and the false condition is the one that returns boolean false value. 10.2.1 sments that Control a Loop (Parts of a Loop) — Every loop has its elements that control and govern ifs execution, Generally, a loop has four clements that have different purposes. These elements are as given below : 1 Initialization Expression(s). Before entering in a loop, its control variable(s) must be ized "The initialization of the control variable(s) takes place under inibializlivn expression(@). The initialization expressions give the loop variables their first values. The initialization expressions are executed only once, in the beginning of the loop. 2 Test Expression, The test eypression or the test-condition is an expression whose truth value decides whether the loop-body will be executed or not If the test expression ve aluates to inue, the loop-body gets executed, otherwise the loop is terminated In an entry-controlled loop, the test-expression is evaluated before entering into a loop we sereas invan exitecontrotled loop, the lest-expression is evaluated before exiting from the Toop. In Java, the for loop and while loop are entry-controlied loops and do-while loop is exit-controlled loop. 3, Update Expression). The update expression(s) change the value(s) of loop variable(s). ‘The update expression(s) is executed ; at the end of the loop after the loop-body is executed. 4, The Body-of-the-Loop. The statements that are executed repeatedly (as long as the test-expression is nonzero) form the body of the loop. In an entry-controlied loop, first the fest-expression is evaluated and if itis true, the bedy-of-the-loop is executed ; if the fest-expression tvaluates to false, the loop is terminated. In an exil-controlled loop, the body Fthe-loop is cvecated first and then the fst-expression is evaluated. If it evaluates to fils, the loop is terminated, otherwise repeated. 10.3 The for Loop - Fixed Number of Iterations ‘The for loop is the easiest to understand of the Java loops. All its loop-control elements are gathered in one place (on the top of the loop), while in the other loop construction of Java, they (Cop-control elements) are scattered about the program. The general-form (eyntax) of the for loop statement is for (initialization expression(s); test-expression ; update expression(s)) body-of-the-loop ; ITERATION CONSTRUCTS IN JAVA, 209 aE The following example program illustrates the use of for statement Program 10.1 Program using for loop to print numbers from 1 to 5, public class Test { public void printNos( ) Here, the loop body contains just a single { Intizo; ~~ statement, So, here we could also omit the 3 curly braces of for loop, if we wanted. for(i=1;1<=5; +41) { [Link]( i) ; 3 ¥ The following lines explain the working of the above given for loop. Intasation Expression Test Expression es eras for (i= — — i<=5*; +H) { _body-of-the-loop. } 1. Firstly, initialization expression is executed ie, variable i, 2, Then, the test expression is evaluated ie,, '=5 which results into true. 3: Since, the fest-expression is true, the body-of:the-loop i, [Link] printin (i) is executed which prints the current value of i on the next line. :: which gives the first value 1 to 4. Al in loop-body, the update expression ie, #41 is executed which increments the value of i. (After first execution of the loop, the value of f Becomes 2 after the execution of ++i, since initially / was 1). 5. After the update expression is executed, the test-expression is again evaluated. If itis true the sequence is no 3, otherwise the loop terminates. The output produced by above program (10.1) Initiakzation Expression(s) 2 4 38 s y £ The adjacent figure (Fig, 10.1) outlines } Body ofthe the working of a for loop. Koop Update Expression(s) Figure 10.1 The execution of a for loop, = 210 COMPUTER APPLICATIONS-1X Let us have a look at some more for loop examples. AC Program 10.2 Write a program to print numbers between 0 to 20 with a gap of 3 i.e, like 0 3 6... publicclass Numbers { public static void main(String args 1) for (int i= 0;1<20;1+=3) € ~ ‘system. [Link](i +" + i Di Prowram 1 Bi ‘Write a program to print squares of numbers 1 to 5. public class Numbers public static void main(String args{ 1) intisq=0; eer as for (i= 1ji<=5;1 ++) { ut produced is = xl sq, [Link]. printin("Square of “+ 1+": + Sq); a Program 10.4 rite a program to print first 15 natural numbers. public class Test { void prnNaturalNos( ) { inti=1; for(i = 1; 1<= 15; i++) [Link](i); 2 (U))| Program 10.5 Write a program to print first 7 even numbers. public class Test { void prnEvenNos( ) £ inti, evnum = 2; for(i = 1; 1<= 7; 14+) ‘[Link](evnum); evnum = evnum + 2; ITERATION CONSTRUCTS IN JAVA 211 Wl | Program 10.6 Write a program to print table of a given number. import [Link] ; Cupane public class Test { a ae public static vold main( String args{]) Table of 7 is: Int num, 1; 7 ‘Scanner sc = new Scanner([Link]) ; 14 [Link](“Enter number : ”) ; oe ASTOR a System. out printin(*Table of "+num +" Is 2"); a for(i = 1; 1<= 10; I++) 49 [Link](num#i) ; 56 } 63 70 } || Program 10.7 Write a program to print first 20 numbers in reverse order ie., 20 to 1 public class Test { void prnRevNaturalNos() { inti; for(i = 20 ;1>=1;1--) [Link](I) ; , ‘Output produced is : } 20 19 18 17 16 15 14 13 12 1110987654321 Program 10.8 Write a program to print first 10 powers of 2. public class Powers { void prnPowers() Notice that there can be A t rutiple update egressions'”' °c Ee separated by commas 2M =2 intin=2,pwre2; ee for(i= 1; 1<=10; Ht pwre=2 ) 203 = 8 x 2A4 = 16 [Link](n+"A"-+i +" =" +pwr) j 205 } 2A6 = 64 2 2A7 = 128 } 2A8 = 256 209 = 512 210 = 1024 4 214 COMPUTER APPLICATIONS-IX For example, if we have to initialize two variables in the beginning of for loop, then we may write: Mulipl initialization Mudie update expressions expressions [7 (comma separated) 0 jf<=nj sum+=i,++l) in 1) 5 for (/=1,su [Link] ‘The above code fragment contains two initialization expressions {=1 and sum~=0 and two update expressions sum += i and ++i, These multiple expressions are executed in sequence ie, during initialization firstly /=1 takes place followed by sum = 0. Similarly, during updation, firstly sum += i takes place followed by ++i. 2. Optional Expressions aD Tn a for loop, initialization expression, test expression and update expression are optional ie, you can skip any or all of these expressions. Say, for example, you already have initialized the Joop variables and you want to scrap off the initialization expression then you can write for loop as follows : ‘The comma operator can serve in a for loop when you need more than one initialization and/or tupdation expressions. ia (|; test-expression; update-expression(s)) loop-body Seo, even if you skip initialization expression, but the semicolon (flowing it must be present Following code fragment also skips the initializtion-expression of a for loop. inti =1, sum =0; for (_ ; | <=20;sum +=i, +41) Le Sev initialization sa ead L aan [Link]( |) j Similarly, under certain circumstances the update expression(s) and the test expression can be omitted. For example, the following loop will run until j becomes equal to 242 for j= 075! 242; ee jee1l; es updaie expression shipped If the variable j has already been initialised before, then the above Toop may be written as : Both initialization & update expressions skipped ITERATION CONSTRUCTS IN JAVA 25 3. Infinite Loop tip SS ‘Although any loop statement can be used to create an infinite The ——_loop-control {endless loop) yet for is traditionally used for this purpose. An expressions i 2 oop infinite for loop can be created by omitting the fest-expression as statement are, optional shown below : S eae are for (j= 25; --1) ‘[Link] (“An infinite for loop”) j Similarly, the following for loop is also an infinite loop, A Alte epressons hipped for (7 Ee) ‘[Link] ("Endless for loop") ; Empty Loop and Time Delay Loop ae TFa loop does not contain any statement in its loop-body, cases, a Java loop cont is said to be an empty loop. In such ‘a null statement. Following for loop is an empty loop + Le for d= 2050 05D aS SS empry loop as it contains a null statement only in its loop-body. ee, the body of the above for loop contains ust (a null statement) itis an empty loop. An empty for loop has its applications in case where some Kind of delays are to be introduced purposely. Time delay loops are often used in programs. The following code shows how to create one by using for: An empiy loop being used for (b= 0; #2300744); ey 5. Declaration of Variables in the Loop t Java allows to declare variables anywhere in a program. So, they are generally declared immediately before their first reference. Also Java does not restrict declaring items as 9 state rent, 50 an item can be declared within afor or while loop condition statement. For instance, for (inti= 1; i while {body of the loop including ‘ + Following example program illustrates the working of a while loop. Program. 13 Program to calculate the factorial of an integer using while loop, public class Calculate { public void factorial(long num) < ee Sg i=0,fact=1; i=num ; Bit conan while ( 11=0 ) { fact = fact *1; Meer Be Sai of loop control variable within the loop body ‘ a [Link](“The factorial of” + num + “is! + fact) ; The output produced by above program for num =5 is : a the factorial of 5 is 120 ‘The above program receives an integer num and initializes a variable i with value num. Then as long asi is nonzero (according to while (i! = 0)) the loop-body interates i, fact is multiplied with iand the result is stored back in variable fact, followed by the decrement of i. Again the test-expression (i! = 0) is evaluated ; if itis true, the loop is repeated otherwise terminated. Program 10.14 Write a program to print squares of numbers 1 to 1, Read the value of 1 from user. import [Link]. Scanner ; oe public class Squares { ITERATION CONSTRUCTS IN JAVA 217 public static void main(Stringl ]args) { canner keyboard = new Scanner([Link]) ; [Link](*Input the maximum number to square: ") ; int maxNum = [Link]( ) ; int currentNum = 1; while (currentNum <= maxNum) { int square = currentNum * currentNum ; [Link](square + "") ; currentNum = currentNum + 1; + [Link]() ; Ga ? Input the maximum number to square : 7 > 149 16 25 36 49 Program 1 Write a program that calculates the sum of first 100 natural numbers and prints their sum. public class Numbers { public static void main(String(] args) { int currentNum = 1; int sum = 0; ae while (currentNum <= 100) {sum = sum + currentNum ; currentNum = currentNum + 1; * [Link](“The sum of the numbers from 1 to 100 is" + sum +™.") ; + } Output produced is : The sum of the numbers from 1 to 100 is 5050. Program 10.16 Program to calculate and print the sums of even and odd integers of the first # natural numbers. public class Numbers { public void sumOfNaturalNos(int n) { int sum_even = 0, sum_odd = 0, ctr while(ctr <=) {if (ctr % 2 == 0) ‘Output produced is : : ite ee ci sum of even integers upto 25 is 156 ees eae ‘sum of odd integers upto 25 is 169 ctr +4; Q fi [Link]("Sum of even integers “+ “upto” +n +" Is" + sum_even) j System. out. printin(*Sum of odd integers “+ “upto” +n +" Is" + sum_odd) 7 x 218 COMPUTER APPLICATIONS-IX (| Program 10.17 Write a program that inputs some positive numbers and prints their sum. Output produced is : import [Link]. Scanner ; public class Numbers { public static vold main(String[ ] args) ¢ ‘Scanner kb = new Scanner([Link]) ; Int num = ys int sum = 0; while (num != -1) £ sum = sum + num ; [Link]("Enter the next positive number to add (-1 to quit): ") ; num = [Link]( ) ; > ‘system. [Link](“Sum of the Input numbers is” + sum +™.") ; } s Program 10.18 Write a program that prints the series showing products of two consecutive numbers. Get the starting number from user and stop the moment product exceeds 100. vort [Link] ; uolie class Numbers2_{ public static void main(String[] args) q Scanner kb = new Scanner([Link]) ; int num = 0; int result = 0; [Link](*Enter starting number :") ; ee num = [Link]() ; while (result < 100) f result = num * (num +1) ; [Link],printin( num +" x"4(num+1) +" = "“tresult) ; num = num + 1 Output produced is: ITERATION CONSTRUCTS IN JAVA, 219 )) Program 10.19 Write a program to print sum of digits of a given number. public class Test { static int Sumbigits(int num) —{ int num2 = num j int dig, q, sum = 0; while(num2>0) { q=num2/ 10; dig = num2.% 10; aA sum = sum + dig ; num2 = 4 a return sum + public static void main( String argst]) { int ni = 345, n2 = 672, n3 = 13602; ints =0; s = SumDigits(n1) ; [Link]("Sum of digits of "+n +"is:" +5); 's = SumbDigits(n2) ; [Link]("Sum of digits of "+ n2 +" 15:" +8); s = Sumbigits(n3) ; [Link]("Sum of digits of” + n3 + "Is :" +8); } ; Output produced is is Sum of digits of 345 is : 12 ‘sum of digits of 672 is : 15 Program 10.20 sum of digits of 13602 is : 12 Write a program to reverse a given number. public class Test { static Int RevNum(int num) { Int num2 = num ; int dig, q, rnum = 0 ; oe while(num2>0) £ q= num2/10 ; dig = num2%10 ; rum = rnum*10 + dig ; num2 = 47 + return rum ; E if (nuM%i = { 220 COMPUTER APPLICATIONS-IX public static void main( String argsf 1) { Int n = 345, n2 = 672, 3 = 13602 ; ints =0; s = RevNum(n1) ; ‘[Link]("Reverse of "+n +"is:"+8); RevNum(n2) ; ‘[Link](“Reverse of "+ n2+"is:" +5); 5 = RevNum(n3) ; ‘[Link]("Reverse of "+3 +"is:" +5); } - } Output produced is Reverse of 345 is : Reverse of 672 is : Program 10.21 Reverse of 13602 is Write a program to count and display divisors of a number import [Link] ; public class Test { static void genDivisors(int num) { int i = 2, count = 2, im = num/2 ; //- count = 2 because 1 and num itself are 2 divisors 543 276 + 20631, ‘[Link](“Other than the number itself and 1, the divisors of” + num +“ are:”) ; while (i lim) { 0) “count++ ; ‘[Link](i) ; a : [Link]("Total number of divisors : " + count) ; % Output produced is : public static void main(String args[ 1) { entan She MaUMeh Wise divi ‘Scanner kb ew Scanner([Link]) ; sors are to be generated : 128 ‘[Link]. print(“Enter the number whose divisors are other than the number itself tobe generated :"); and 1, the divisors of 128 are : int num = [Link]( ) ; 2 genDivisors(num) ; { s 16 + 32 64 Total number of divisors : 8 ITERATION CONSTRUCTS IN JAVA 221 WH) Program 10.22 Write a program to print a series 1, 4, 7 upto 12 terms public class Test { void Series) { inti=1,term=1; while (i <= 12) [Link](term + * ") ; A i+; term = term +3; Output produced is : } 147 10 13 16 19 22 25 28 31 34 10,5 The do-while:Loo a ee Unlike the for and while loops, the do-while is an exit-controlled loop i.e., it evaluates its test-expression at the bottom of the loop after executing its loop-body statements. This means that a do-while loop always executes at least once. In the other two loops for and while, the test-expression is evaluated at the beginning, of the loop ie,, before executing the loop-body. If the test-expression evaluates to false for the first time itself, the loop is never executed. But in some situations, it is wanted that the loop-body is executed at least once, no matter what the initial state of the fesi-expression is. In such cases, the do-while loop is the obvious choice. The syntax of the do-while loop is : do {statement ; + hile (test-expression) ; The braces {} are not necessary when the loop-body contains a single statement. The detailed structure of,a do-while loop is like : initialization expréésion> do { body of the loop including }. while (test-expression), The following do-while loop prints all upper-case letters : char ch = "A’ do { [Link]. print(ch) ; ch+t 5 a } while (ch <= °2’) The above code characters from ‘A’ onwards until the condition ch becomes false. Let us now have a look at some programs using do-while loops. mr 222 COMPUTER APPLICATIONS-K (|| Program 10.23 Write a program that reads marks in 5 subjects and calculates the total marks. Import [Link] ; public class StudentResult { public static void main(si int count = 0; double marks = 0, total = 0; Scanner kb = new Scanner([Link]) ; ‘ingargs{]) { A do{ [Link](“enter marks in subject "+ (count+1) +": ") 7 marks = [Link]() ; total = total + marks ; Output produced fs = count +1; Enter marks in subject 1 : 68 Enter marks in subject 2 : 79 Enter marks in subject 3 : 80 count } while ( count <5); ‘[Link](*Total marks in ” oun + * subjects are i" + tots) (ih i i, enter marks in subject 5 : 69 > Total marks in 5 subjects are : 381.0 + (B)) Program 10.24 Write a program to find whether given number is Armstrong or not. An Armstrong number is a 3-digit number that is equal to sum of cubes ofits individual digits, eg. 153 is an Armstrong number as 1° +5° +3° =153. import [Link]. scanner public class Armstrong { public static void main(String args[ ]) { ‘Scanner sc = new Scanner([Link]) ; [Link]("Enter a 3digit number to be checked : ") ; int num = [Link]( ) ; intn = num; Output produced is : int check = 0, remainder ; Enter a 3digit number to be checked : 345 do { 345 is not a Armstrong Number Z remainder =n % 10 ; Enter a 3digit number to be checked : 153 153 is an Armstrong Number Enter a 3digit number to be checked : 407 407 is an Armstrong Number check = check + (int)[Link](remainder, 3) ; if(check = num ) // if sum of cubes is equal to number [Link](num +" is an Armstrong Number”) ; else [Link](num +" is not a Armstrong Number”) ; ITERATION CONSTRUCTS IN JAVA 223 es Program 10.25 Write a program to test if a number is a palindrome or not. A palindrome reads the same from both sides, e.g., 1331 is a palindrome number. import [Link] ; public class Palindrome { public static vold main(String args{]) q Scanner se = new Scanner([Link]) ; [Link]. print("Enter a number to be checked : " int number = [Link]() ; int reversedNumber = 0, temp = 0, savedNumber ; savedNumber = number ; utpitspiodcadite Heeisleethanimbar Enter a number to be checked : 1221 i 1221 is a palindrome oon Enter a nunber to be checked : 1212 i 1212 not a palindrone number = number / 10 ; reversedNumber = reversedNumber * 10 + temp ; } while(number != 0) ; if(reversedNumber == savedNumber) [Link](savedNumber + “is a palindrome") ; else System. [Link](savedNumber + not a palindrome”) ; + + Program 10.26 Write a program to print series having terms as 4N +1 (Print first 5 terms). public class Test ic void Serles( ) { intn =1,term=0; do val { term=4%n+1; ‘[Link](term) ; nt; Output produced is : } while (n <= 5) ; 5 } 9 } 3B Ww aaa me 224 COMPUTER APPLICATIONS-K Program 10.27 Write a program that reads some numbers until “1 is pressed and prints the maximum: of the input number import [Link] ; public class Maximum { public static vold main(String args{I){ ‘Scanner sc = new Scanner([Link]) ; int number, max = 0; dof ee [Link](*Enter a number (-1 to stop) :") j number = [Link]() ; if (number > max) ‘Output produced is : Enter a number (-1 to stop) : 9 uexpminiininetis enter a number (-1 to stop) : 3 while (number != -1 ) Enter a number (-1 to stop) : 5 [Link](*Maximum number is” + max); Enter a number (-1 to stop) + 23 } Enter a number (-1 to stop) : 76 } enter a nunber (-1 to stop) : -2 Maximum number is 76 Program 10.28 o Writea program that prints Mersenne nimbers (i, the numbersiin the form 2" ~1): Read a limit from :ser and print all Mersenne numbers until it exceeds the given limit. Also mention which (1th) Mersenne number has exceeded the limi import [Link]. Scanner ; public class Test { public static void main( String args(]){ Output produced is : int num = 0, limit ; a Scanner sc = new Scanner([Link]) ; 3 [Link](“Enter the maximum limit : ") 7 By ae limit = [Link]() ; a intn=1; 63 do { 127 num = (int) [Link](2,n) ~ 1; 255 [Link](num) | 8th Mersenne number exceeds 150 ntti Hence stopping here. } while (num < 150) ; ‘[Link]( (n~ 1) + “th Mersenne number exceeds ” + limit) j [Link] ("Hence stopping here.”) ; - ‘The most common use of the do-while loop is in menu selection routine, where the menu is flashed at least once. Then depending upon the user's response it is either repeated or terminated. Following program illustrates it. ITERATION CONSTRUCTS IN JAVA WH) Program 10.29 Write a menu program that reads the radius of a circle 25 and displays options to, calculate area or j perimeter of the circle and depending upon choice, does the same. import [Link] ; public class Menu { public static void main( String argsf]) £ double radius, area, perm ; Int choice ; Scanner sc = new Scanner([Link]) ; ‘[Link]("Enter radius of the circle : ") ; radius = [Link]( ) ; do { System. out printin("\t CIRCLE OPTIONS”) ‘System. [Link]("1. Calculate Area”) ; [Link](*2. Calculate Perimeter") ; [Link]("3. Exit”) ; [Link](“Enter your choice (1/2/3):") ; u choice = [Link]( ) ; switch(choice) { case area = [Link]* radius * radius ; System. out. printin(“Area of circle is ” + area) ; break ; case2: perm = 2 * [Link] * radius ; [Link](*Perimeter of circle is ” + perm) ; break ; case3: break ; default: [Link]("“Invalid choice”) ; 4 break - (e P } yefurn — faretr ; } while ( choice != 3) ; Sql ent om pgm } 10.6— Jump Statements pea ‘Output produced is : Enter radius of the circle : 6.25 CIRCLE OPTIONS 1. calculate area 2. Calculate Perimeter 3. exit Enter your choice (1 /2/3):1 Area of circle is 122.7184630308513 CIRCLE OPTIONS. 1. Calculate Area 2. Calculate Perimeter 3. exit Enter your choice (1 /2/3):2 Perimeter of circle is 39.269908169872416 The jump statements unconditionally transfer program control within a function. Java has three statements that perform an unconditional branch : retum, break, and continue. Of these, you may use return anywhere in the program whereas break and continue are used inside smallest enclosings like loops ete, In addition to the above three, Java provides a standard library function [Link]( ) that helps you break out of a program. x 226 COMPUTER APPLICATIONS-1k ‘The return statement is used to retum from a function. This statement has been already explained in details under chapter ‘Methods/Functions, Under this section we will deal with the rest of the jump statements : break and continue. 10.6.1 The break Statement ‘The break statement enables a program to skip over part of the code. A break statement terminates the smallest enclosing while, do-while, for or switch statement. Execution resumes at the statement immediately following the body of the trerminated statement. The following figure (Fig, 10.2) explains the working of a break statement: E Figure 10.2 The working of a break statement. a 'A break statement skips the rest of the loop and jumps over to the statement following the loop. ‘The following code fragment gives you an example of a break statement: public void Quotient(int a, int b) < /* values of integers a, b are received through parameters */ int inci for (/ = 0; 1 < 20; ++/) c=a/b; ‘[Link] (“Quotient = "+ ¢) ; | : ‘[Link] ("Program over !") ; 3 ‘The above code fragment receives two numbers as parameters. If the number b is zero, the Joop is immediately terminated and just a message Program Over ! gets displayed otherwise the numbers are repeated input and their quotients are displayed. Ifa break statement appears in a nested-loop structure, then it causes an exit from only the very loop it appears in. ITERATION CONSTRUCTS IN JAVA 227 For example, /*here character ch1 is available, which is received as parameter */ for (I= 0;1< 10; +41) { j=0; One can tell whether a char ch2 = chi j Toop has executed a . break statement by [Link](cht) ; peer es st test-condition, hence variable for (5 4) continuous loop { [Link].p Ke 10) = 4 TREES ee this break il ese an eit from hs oop [Link](*= - -------- =~ di % ‘The above code fragment receives a character (ch1) and prints it 10 times. The inner loop has an infinite loop structure but the break statement terminates it as soon as j becomes 10 and the control comes to the statement following the inner loop which prints a line of dashes. A break used in a switch statement will affect only that switch ic, it will terminate only the very switch it appears in, It does not affect any loop the switch happens to be in. ‘A loop variable remains in scope (provided it is not declared inside the loop) even after the loop is terminated either on maturation or prematurely. By examining the value of this loop variable, it can be told whether the loop has been terminated prematurely. The following code fragment illustrates it for (i= 0; 1 < 100; ++!) t if (ch =="q’) break ; + if (1< 100) ‘[Link] (“Loop has ended prematurely”) ; else ‘[Link] ("Normal termination has taken place.” ; If the fest expression of the loop is still true even after the termination of the loop, the loop has executed a break statement, COMPUTER APPLICATIONS-1X C228 fl) Program 10.30 Write a program to print 20 terms of series 3n+2. Stop as soon as ‘multiple of 4 is encountered. public class Test { public void Series( ) { inti = 1, term = 0; for (i= 1; 1<= 20; 14+) < vs term =3 if (term%4 - break ; ‘[Link]-printin(term) j $23 ) 4 | Program 10.31 Write a program to print squares of first 10 natural numbers, But if divisible by 2, 3 and 4, stop there and then. public class Test { void Squares( ) { intn=1,5q=0; while(n <= 10) { sq= nen; Le [Link](sq) i If(sq%2 == 0 B& 5q%3 == 0 && Sq%o4 == 0) break ; else net square ig encountered which is a } “The last square 36s divisible by 2,3 and 4, hence condition was fulfilled and break statement got executed and loop terminated. (| Program 10.32 Write a program that prints series of 2" publicclass Test { void Power2( ) v { upto 10 terms but stops as soon as the number exceeds 100. intn=1; double term = 0; ITERATION CONSTRUCTS IN JAVA 229 a do { term = [Link](2,n) ; if (term > 100) break j else Output produced is = [Link](term) ; 2.0 nee ae F 0 . } while(n <= 10) ; ed } 32.0 64.0 Program 10.33 Write a program to input a number and test if itis a prime number. import [Link] ; publicclass Prime { public static vold main( String argst]) { int number ; Scanner sc = new Scanner([Link]) j [Link]("Enter number =") ; number = [Link]( ) j int = 2, mid = number / 2; boolean primetest = true ; do { if (number % n == 0) { [Link] ("A factor” +n + “of " + number + "found!" ) i [Link] ("Hence NOT a prime number!!”) ; primetest = false ; break ; + nt; enter number : 15 af ‘A factor 3 of 15 found! } while (n<= mid) ¢ Hence NoT a prime number! ! if (primetest == true) enter number : 17 system [Link] ( number +" isa prime number!!") ; 7 4s @ prime munber!? Output produced is = + 10.6.2 The continue Statement ‘The continue is another jump statement like the break statement as both the statements skip over a part of the code, But the continue statement is somewhat different fro break. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code ta between. That is, continue statement skips only one iteration, the current eration of the loop and the loop continues with the next iteration. — 230 COMPUTER APPLICATIONS-1X Figure (Fig, 10.3) explains the working of continue statement. ‘while (expression) {or (Int; expression; update) do { { { statementt; statement1; statement 5 if (condition) if (condition) if (condition) continue j continue; continue; statement2; statement2; statement? ) ) } while (expression); statement’; statements ; Figure 10.3 The working of a continue statement. ‘The continue statement skips the rest of the loop statements and causes the next iteration of the loop. For the for loop, continue causes the next iteration by updating the variable and then causing the test-expression’s evaluation. For the while and do-while loops, the program control passes to the conditional tests. The following code-fragment gives you an example of continue statement int a, by G3 tip for (i= 0;1< 20; ++) Do not confuse the { _ [Link]("Enter 2 numbers") ; break and continue ‘// two numbers are read here ; ‘statements. if (b==0) {_System.[Link] (“The denominator cannot be zero. Enter again”) ; continue j y else c=a/b; [Link] ( "Quotient =" + ¢) ; } Sometimes you need to abandon iteration of a loop prematurely. Both the statements break and continue can help in that but in different situations. A break statement inside a loop will abort the loop and transfer control to the statement following the loop. A continue statement will just abandon the current iteration and let the loop start the next iteration. (Ul) Program 10.34 Writea progtam to print series of Sn +2, but skip the multiples of 3. Print upto first 10 terms of the series class Test { public void Series() { ITERATION CONSTRUCTS IN JAVA 231 Int = 1, term = for (i= 1; 1<= 10; i++) {term = 5*1 42; if (term%3 == 0) Pa continue ; [Link](term) ; “Output produced fs (Hl) Program 10.35 Write a program to print 10 terms of series 2" +2 Skip multiples of 3 but stop if the term is a multiple of 5 and greater than 100. (start with value of nas 3). public class Test { void prnseries() { intn=3; double term = 0 ; do { term =[Link](2,n) + 2; if (term > 100 && term % 5 == 0) break ; else if (term % 3 == 0) { nt+ et ea r else{ [Link](term) j nb; + } while(n <= 10) ; : : > Stopping the Program Execution Completely ([Link](0) ) Sometimes you need to stop the execution of your program completely irrespective of any other thing, To stop a program execution completely, you can use following statement in your program code : [Link](0)) ; Whenever the control reaches this statement, it will terminate program’s execution there and then, For example, it in your program you have a code like : fi if (count > 150) [Link](0) ; Whenever the count reaches above 150, the program will stop immediately. COMPUTER APPLICATIONS-IX > The statements that allow a set of instructions to be ‘performed repeatedly are iteration statements. > The iteration statements are also called loops or looping statements. > Java provides three loops : for, while and do-while, > ‘Theentry-controlled loops impose control atthe time cof entry into the loop by testing the test-expression before entering into a loop. The for and while loops ‘are entry-conirolled loops. > The exit-controlled loops impose control at the time of exit from the loop by testing the test-expression before exiting from the loop. The do-while is an exit-controlled loop. : a onceptual Questions ‘The do-while is executed at least once always as it evaluates the test expression at the end of the loop. ‘Abreak statement can appear in any of the loops and ‘a switch statement. Whichever statement it appears in, itcauses the termination ofthe statement there and then ‘and the control passes over to the statement following the ‘Statement containing break. The continue statement abandons the current iteration of the loop by skipping over the rest of the statements in the loop-body. It immediately transfers ‘control to the updation expression for loop or to the evaluation of the test-expression of other loops for the next iteration of the loop. | [Link](O) terminates the execution of whole panic | Séclion A ; Objective Type Questions ie 1, Which of the following loops is mostly used for fixed number of iterations ? (@) for (©) while (®) do-while (@ none of the above 2. Which of the following is not an entry controlled loop ? (@) for ( while (b) do-while (a) none of the above 3. Which of the following is an exit controlled loop ? @ for (2) while 4, Which of the following is not a jump statement ? ‘@) continue (0) [Link] (b) do-while (d) none of the above (b) return (a) break 5. Which of the following statements terminates the complete execution of a loop ? (a) break (0) terminate (®) continue (@ Systemexit(0) 6. Which of the following statements terminates the complete execution of a program ? (2) break (0) terminate (b) continue (a) [Link](0) ERATION CONSTRUCTS IN JAVA 233 a 7. How many times will the following code print “Welcome to Java” ? int count = 0 ; do{ ‘[Link](*Welcome to Java”) ; } while (++count < 10) ; @s (10 Og @u (0 8, How many times will the following code print “Welcome to Java” ? int count = 0; do { [Link]("Welcome to Java”) j count++ ; } while (count < 10) ; (9 (10 (0 @u 8 9, How many times will the following code print “Welcome to Java” ? int count = 1; while( ++count < 10) { ‘[Link]((count+1) +" Welcome to Java") ; + @9 10 0 @u 8 10. What will be output by the following code segment ? int sum = 0; Int count = 1; while (count < 5) {sum = sum + count ; count = count + 2; } ° [Link](sum) (a) 10 () 15 4 @9 (@) none of the above | 11, What will be output by the following code segment ? int sum = 0; int count = 5 5 while (count >1) {sum =sum + count ; count = count +2; } [Link](sum) ; @ 10 15 (4 @9 (¢) endless loop / 34 COMPUTER APPLICATIONS-1® Section B : Subjective Type Questions 1. What is the main difference between a while loop and a do..while loop ? ‘Ans. Both types of loops repeat a block of statements until some condition becomes filse. The main difference is that in a while loop, the test-condition is tested at the beginning of the loop, and in a do..while loop, the test-condition is tested at the end of the loop. It is possible that the body of a while loop might not be executed at all, However, the body of a do..while loop is executed at least once since the test-condition for ending the loop is not tested until the body of the loop has been executed. 2. What are jump statements ? Ans, The statements that cause unconditional control-transfer in program are called jump statements. Two most common jump statements are break and continue. 3. What does a break statement do ? ‘Ans. A break statement terminates the current loop and proceeds to the first statement that follows that loop. For example, the break statement in the following loop for(intd =2;d= 0) x e x= YK; m+; gic ue n=n42; > het tee 4 238 COMPUTER APPLICATIONS-IX 18. How many times is the following loop executed ? int 0,i=0; while (i++ < 5) sti; 19. Find out errors, if any : (@) m=1; n=0; for(;m+n<19; +4n) ‘[Link](*Hello \n") ; m=m+10; (b) while(ctr != 10) ; of Lecomte sum = sum +a; tra; > (0) fora=1,a>10;a=a+1) Cae * 2 20, Identify the possible error(s) in the following code fragment. Discuss the reason(s) of error(s) and correct the code : fel; for (Int a= 40 ; (a) ; a--) fa s=0; for (inta = 1; a < 40/a++) st+=a; 21. Write a short program to print the following series: 1 4 7 10...... 40. 22. Write a short program to print the following series: 1-4 7 —10 40. 23. Write a program to find the LCM and GCD of two numbers. 24, Write a program to find sum of the series S=14- 427 4.0.04" 25, Write a program to print place value of ten’s and thousand’s digit in a number e.., for a number 72149, it will print 2000 and 40. 26. Write a program to swap first and last digit of a 3-digit number. 27. Write a program to print 10 terms of series 1, (1 +2), (1 +2 +3), 28. Write a program to print add multiples of 3 from 3 to 50, 29. Write a program to test whether a given number is divisible by another given number. 30, Write a program to print cubes of first 15 natural numbers.

You might also like