Question
Hello, Please code is in Java: What students will learn: The purpose of repetition structures Three kinds of loops that are found in most languages
Hello, Please code is in Java:
What students will learn: The purpose of repetition structures Three kinds of loops that are found in most languages Knowing when to use a specific kind of loop How to apply repetition to solve problems Overview: If theres one thing computers are good at, its repeating something over and over. The concept of repetition (which some call iteration and others looping) is not terribly difficult since we humans repeat things in our daily lives. Any decent programming language is going to support iteration and usually allows for three different kinds of looping templates. These templates are exactly what this lab is going to cover. The three kinds of loops well cover are the for, while and do-while loop. You want to memorize the templates for these. Before that, its important to know when to use them. Heres an overall guideline to help you out: 1. Use a for loop when you want to repeat something a certain number of times. For example, if you want to repeat something 100 times, and a for loop is a good candidate for that. Or, if you wanted to count from 50 to 3000 in increments of 10, you could do that too. 2. Use a while loop is useful when you dont know how many times something will repeat; the loop could go on forever. As an example, if you ask a user to enter a number between 1- 10 and they consistently enter 45, this could go on forever. Eventually (and hopefully), the user would enter a valid number. 3. Use a do-while loop when the loop must execute at least one time. The loops above can execute 0 times, but not this one! The reason is because, for all loops, there is a test to see if the loop should continue repeating. With a do-while loop, that test is at the bottom. The best way to show these loops is through examples. The code below sums the numbers from 1 to 100. You should see that all loops have a 1) test to continue, and 2) make progress towards completing. int sum = 0; for (int i = 1; i <= 100; i++) { sum += i; } int sum = 0; int i = 1; while(i <= 100) { sum += i; i++; } int sum = 0; int i = 1; do { sum += i; i++; } while(i <= 100); The for loop starts a counter (called i) at 1. So long as i is <= 100, the loop continues. We then execute sum += i. Finally, i++ occurs and the test to continue is evaluated again. The while and do-while loops are nearly identical. However, notice that the do-while has the test to continue at the bottom and also has a semicolon at the end. Be careful!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started