90 likes | 194 Vues
This guide provides an overview of various loop constructs in Java, including for, while, and do-while loops. Each loop type is explored with a focus on its unique advantages and typical use cases. You will learn how to implement and nest loops effectively to meet your programming requirements. Additionally, the guide includes practical examples and a comparative analysis of loop implementations, emphasizing the importance of condition checks and execution flow. By the end of this guide, you'll be equipped to apply loops in diverse programming scenarios confidently.
E N D
CS 240 – Computer Programming ILab KalpaGunaratna – kalpa@knoesis.org http://knoesis.wright.edu/researchers/kalpa/
Contact • Contact by e-mail • kalpa@knoesis.org • Office hours • 376 Joshi • Mondays & Wednesday 3:00 pm – 4:00 pm
Intention • Familiar yourself with various loops available in Java language. • Some loops have advantages above others but all loops can be used most of the time for many tasks. • Loops, • for , while, do while • Any loop can be nested in whatever you want and for your requirement.
while loop • while (<boolean condition>) { // loop body } Until the boolean condition is false Loop will iterate. First checks the condition and execute The body. <boolean condition> false true <loop body>
do – while loop • do { // loop body } while (<boolean condition>) • Loops body is executed at least before checking the condition. <loop body> <boolean condition> true false
for loop • Steps, initial action (only once) -> check condition -> body -> final action -> loop <initial action> <boolean condition> false true <loop body> <action>
Following two for loops and while loop are equivalent. for( ; ; ){ // do something } for( ; true; ) { // do something } while( true ){ // do something }
In lab • Remember the last week’s lab about printing a triangle. • Numbers you have to print is all about powers of 2. • Math.pow(2, <power>); • Numbers should be exactly as they are shown in the assignment and also they should align in the exact way !
Post lab • Repeat the same process as you did in in lab and use whole and do – while loops. No for loops ! • You should use at least one of while and do – while loops.