Monday, October 21, 2019
Definition for the Java Term Loops
Definition for the Java Term Loops A loop is a way of repeating lines of code more than once. The block of code contained within the loop will be executed again and again until the condition required by the loop is met. For example, you could set up a loop to print out the even numbers between 1 and 100. The code that gets executed each time the loop is run will be the printing out of an even number, the condition the loop is looking to meet is reaching 100 (i.e., 2 4 6 8....96 98). There are two types of loops: Indeterminate - An indeterminate loop does not know how many times it will run. For example, you could search through an int array looking for a specific value. The most logical way would be to search each element of the array in order until you find the right value. You dont know if the value is in the first element or the last so the number of times you loop around checking the next element of the array is unknown. Indeterminate loops are the while and do..while loops.Determinate - AÃ determinate loop knows exactly how many times it will loop. For example, if you want to know how much money youll be paid for the next twelve months minus tax you could perform the wage calculation 12 times. The determinate loop in Java is the for loop. Examples An indeterminate while loop to search for the number 10 in a randomly ordered int array: //int array of random numbers int[] numbers {1, 23, 56, 89, 3, 6, 9, 10, 123}; //a boolean variable that will act as the condition for the loop boolean numberFound false; int index 0; //this loop will continue running until numberFound true while (!numberFound) { System.out.println(Were looping around..); if (numbers[index] 10) { numberFound true; index; System.out.println(Weve found the number after index loops); } index; } A determinate for loop to display all the even numbers between 1 and 100: int number 0; //loop around 49 times to get the even numbers //between 1 and 100 for (int i1;i
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.