180 likes | 190 Views
Explore the versatility of while, for, and do-while loops in Java programming. Learn their applications, advantages, and how to use them effectively in your projects. Master loop handling for efficient coding.
E N D
Week 6 - Monday COMP 1600
Last time • What did we talk about last time? • while loop examples
3 loops in Java • while loops • Used when you don’t know how many times you are going to need to repeat • for loops • Used when you do know how many times you are going to repeat • do-while loops • Used never • Oh, okay, they are used whenever you need to be guaranteed the loop runs at least once
Loops are interchangeable • Any problem that uses loops can use any kind of loop • The choice is supposed to make things easier on the programmer • Some loops are more convenient for certain kinds of problems
Background on for loops • for loops are great when you know how many times a loop will run • They are the most commonly used of all loops • They are perfect for any task that needs to run, say, 100 times • A for loop has 3 parts in its header: • Initialization • Condition • Increment
Anatomy of a for loop Starting Point Way to Progress for( init; condition; inc) { statement1; statement2; … statementn; } Ending Point
A for loop with only one statement • A for loop will usually have multiple statements in its body • However, it is possible to make a for loop with only a single statement • Then, like if-statements and while-loops, the braces are optional for( init; condition; inc ) statement;
for loop example • Let’s print the numbers from 1 to 100 (again) • Remember how this was done with while: inti = 1; while( i <= 100 ) { System.out.println(i); ++i; }
for loop example • A for loop is specifically designed for this sort of thing: • The initialization and the increment are built-in for( inti = 1; i <= 100; ++i ) { System.out.println(i); }
Odd numbers • Ask the user to input a positive integer n • Now, write a for loop to print out the first n odd numbers • Example: If the user enters 10, print out: 1 3 5 7 9 11 13 15 17 19
Approximating π y • We can do something called a Monte Carlo approximation of π • We “throw” darts at a 1 x 1 square in the upper right corner of a circle with radius 1 • We count the ones that fall inside the circle and divide by the total darts thrown • That fraction is an estimation of the area of one fourth of the circle • By multiplying by 4, we approximate π x
Next time… • do-while loops • Examples with forloops and do-while loops • Lab 6 is tomorrow
Reminders • Keep reading Chapter 5 of the textbook • Keep working on Project 2 • Due Friday!