CS 1102 Discussion Forum Unit 2 PDF

Title CS 1102 Discussion Forum Unit 2
Course Programming 1
Institution University of the People
Pages 6
File Size 343.1 KB
File Type PDF
Total Downloads 37
Total Views 140

Summary

Download CS 1102 Discussion Forum Unit 2 PDF


Description

While Loop A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10"

Example of a while loop

Example of “For” loop performing the function of the “while” loop above.

Example of “do while” loop performing the function of the “while” loop.

Do While Loop A “do while” loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given Boolean condition at the end of the block. So, the only difference between While loop and Do while loop is that the while loop can end without executing any statement and Do while loop will end only after executing one statement.

Example of “do while” loop.

Example of “while” loop performing the function of "do while" loop.

Example of “for” loop performing the function of "do while" loop.

For Loop In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly if we (or the computer) knows exactly how many times to execute a section of code (such as shuffling a deck of cards) we use a for loop.

Example of “for” loop

Example of “while” loop performing the function of "for" loop.

Example of “do while” loop performing the function of "for" loop.

Advantages and disadvantages of each looping structure: Utilizing the last example that was provided: In the “for loop” the initial value is 6 with a condition of i>1 and the decrease is i--; With this example the loop will execute by increment of -1 from 6 to 1. In the “while loop” original value of i=6 with a condition of i>1, ,decrease is i--With this example the loop will execute by increment of -1 from 6 to 1. In the “do while loop” the original value i=6 with a condition of i>1, decrease is i— With this example the loop will execute by an increment of -1 from 6 to 1. Loops can be controlled on entry or exit depending on the loop chosen by the programmer.

Reference(s): Anup (2018), What are the advantages and disadvantages of while loop, do while loop, for loop? Retrieved from: https://www.quora.com/What-are-the-advantages-and-

disadvantages-of-while-loop-do-while-loop-for-loop Loops in Java, Retrieved from: https://www.javatpoint.com/java-for-loop...


Similar Free PDFs