210 likes | 401 Vues
Computer Science. Repetition & Loops . Repetition & Loops. One of the BIG advantages of a computer: It can perform tasks over and over again, without getting bored or making mistakes (assuming we gave it the right instructions) Repetition : doing this over and over again
E N D
Computer Science Repetition & Loops
Repetition & Loops • One of the BIG advantages of a computer: • It can perform tasks over and over again, without getting bored or making mistakes (assuming we gave it the right instructions) • Repetition: doing this over and over again • Loops: going around in a circle and repeating the action • The way a computer performs repetitive tasks is by programming instructions that tell it to repeat a task. • The structure that is used for these instructions is called a Loop. • The loop structure allows for any number of statement to be performed repeatedly.
A Loop in Programming • A loop in programming is a block of code that will be executed repeatedly until a certain condition is met. Declare Number As Integer Repeat Write “Please enter a number” Input Number Write Number Until Number == 0 Write “List Ended” • The body of the loop is executed repeatedly until the user enters 0. • An iteration occurs each time the loop is run. Body
Do For a While • Programming languages have three statement that allow for the creation of loops known as conditional statements. • Conditional statement: keep doing something unless something changes (i.e. a condition is meat) • It requires conditional statements • For…this… do.. until that is true • While …this do… until that is true • While…this is true ….do this, otherwise do that…
Types of Loops • Loops create one of the most important and fundamental algorithm of a program • Loops are used perform any function that repeats itself such as loading data, calculating and manipulating data or user interaction • They are used in every computer programming language. • They can be divided into two basic types depending upon the when the condition is tested. • Pre-test: the condition is tested at the beginning • Post-test: the condition is tested at the end
Pre-test Loop • The pre-test loop test the condition before executing the body of the loop • The body of the pre-test loop will not be executed if the test condition is initially false • While…this is true ….do this, otherwise do that… • Pseudocode Example Write “Enter a number: “ Input Number WhileNumber!= 0 Write Number Input Number End While Write “Done”
Post-test Loop • The post-test loop test the condition after executing the body of the loop • The body of the post-test loops is always executed at least once • For…this… do.. until that is true • Pseudocode Example Do Write “Enter a number: “ Input Number Write Number WhileNumber!= 0 Write “Done”
Trace a Loop • Tracing a loop is It is like tracing a path to see where it leads. • Think of it as a manual walk-through – following each step. • Psuedocode Example Declare Number As Integer Write “Enter a number or 0 to quit:” Input Number WhileNumber> 0 Write Number^2 Input Number End While NumberOutput 3 9 1 1 -1
The while loop • From Java Text, using the cooking example • While there are lumps in the sauce keep stirring. • When there are no more lumps stop. while (there are lumps) stir sauce; Initialize Expression F While Loop Condition True Statement
Example from Java 4.1 • class PrintSquares • { • public static void main (String[] args) • { • System.out.println("Give an integer (zero to stop)"); • int value = In.getInt(); • while (value != 0) • { • System.out.println(value + " " + value*value); • System.out.println("Next integer (zero to stop)"); • value = In.getInt(); • } • } • } Initialize the value Sentinel: 0 – when program stops Condition Note: if condition is never met program will not stop This could create an infinite loop These statement will continue until condition is met
Example from Java 4.1 class AddMarks { public static void main (String[] args) { System.out.println("Submit marks (value < 0 to stop"); inttotalMarks = 0; intnumberOfMarks = 0; intnextMark = In.getInt(); while (nextMark >= 0) { totalMarks += nextMark; numberOfMarks++; System.out.println("Next mark:"); nextMark = In.getInt(); } if (numberOfMarks > 0) { int average = Math.round((float)totalMarks/numberOfMarks); System.out.println("Average for " + numberOfMarks + " students is " + average); } } }
The do loop • From Java Text, using the cooking example • Stir the sauce as long as there are lumps in it. • When there are no more lumps stop. do (the stirring) while (there are lumps in it) do Statement True While Loop Condition False
Example from Java 4.2 char response; do { System.out.println("Please enter a letter of the alphabet"); response = In.getChar(); } while ((response < 'a' || response > 'z') && (response < 'A' || response > 'Z')); } } Do the following statements Conditions
Counting Loops • Sometimes you may want to execute a loop a certain number of times without user input or regardless of the condition. • This is known as a Counter-Controlled Loop • This loop contains a variable which is known as the counter and this variable keeps track of the number of passes through the loop • To counter is defined, initialized and increased using the increment operator. int count=0 count=count +1 • Definea counter as an integer • Initializethecounter: set the counter to a beginning value. • Common variable names arecounter, Count, i, or j.
PsuedoCode Example: Use a Counter to Display the Squares of Numbers Declare PositiveIntegerAs Integer Declare Count As Integer Write “Please enter a positive integer: “ Input PositiveInteger Set Count = 1 While Count <= PositiveInteger Write Count + ““ + Count^2 Set Count = Count + 1 End While CountOutput 1 1 1 2 2 4 3 3 9 4 4 16 5 5 25
The for loop • From Java Text, using the cooking example • Stir the sauce for 100 times • (the assumption is that there will be no more lumps if you stir for that many times. for (100 times) stir sauce; • The for loop makes use of the count mechanism Initialize Expression 100 times False For Loop Condition True Statement
PsuedoCode Example: using the for loop For (Count=0, Count<=15; Count+5) Write Count End For
Example from Java 4.3 • This program reads integers and prints them along with their squares class IntegerTable { public static void main (String[] args) { final int UPPER_BOUND=10; System.out.println(“Number Square”); for (inti=1; i<=UPPER_BOUND; i++) { Out.print(i); Out.print(i*i); } } } Set condition Loop expression Number output Square output