70 likes | 196 Vues
Loops are essential in programming, allowing blocks of code to be repeated without retyping. This guide introduces the two primary types of loops in MATLAB: the 'for' loop and the 'while' loop. The 'for' loop is used when the number of iterations is known, while the 'while' loop is utilized when it's not. Every loop requires a starting point, an ending point, and a loop-control variable to manage the counting process. Discover how these structures enhance efficiency in your code and learn practical examples of their applications.
E N D
General Knowledge Two Types of Loops Intro to Loops 1
1. General Knowledge • Loops are used when blocks of code need to be repeated (without having to retype all the code!) • There are 2 methods to deal with loops
1. General Knowledge • Loops are used when blocks of code need to be repeated (without having to retype all the code!) • There are 2 methods to deal with loops • The number of time the block of code repeats is determined as the code runs • Example: Ask for username/password until the user gives a correct combination • Example: Allow the user to repeat the entire code, until s/he quits
1. General Knowledge • Loops are used when blocks of code need to be repeated (without having to retype all the code!) • There are 2 methods to deal with loops • The number of time the block of code repeats is determined as the code runs • Example: Ask for username/password until the user gives a correct combination • Example: Allow the user to repeat the entire code, until s/he quits • The programmer knows how many times the block of code needs to be repeated • Example: Ask for 5 grades, and 5 only. • Example: Suppose there are 30 items stored in a variable. Loop to display each item.
General Knowledge, cont. • Regardless of which loop method is used, three (3) criteria are common to both. • When repeating anything, a loop needs: • A starting point • An ending point • A mean to know at what point the loop is at! • “A loop-control variable”
2. Two types of loops • Matlab has two loops, one for each method explained previously: while • Generic, all-purpose. Best used when the programmer does not know how many times the block of code needs to repeat. • Repeats until a CONDITION is no longer met. for • A COUNTING loop. Best used when the programmer knows how many times the block of code needs to repeat.
Wrap Up • Loops are meant to repeat blocks of code (WITHOUT having to copy/paste the block of code itself!) • FACT: • Sometimes, the programmer knows how many times to repeat the code-block, and sometimes, the programmer does not! • There are 2 types of loops in MATLAB • The for loop: when the number of iterations is known • The while loop: when the number of iterations is unknown • All loops require 3 criteria: a starting point, an ending point, and a variable to count from one end to the other.