{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Loop Programming Patterns

# Loop Programming Patterns - Loop Programming Patterns A...

This preview shows pages 1–2. Sign up to view the full content.

1 1 Loop Programming Patterns A software pattern is a reusable solution to a recurring problem 2 Programming patterns • ( idioms , coding patterns ) are low-level patterns specific to a programming language. Experienced programmers automatically call upon these patterns when they see that one is appropriate to the task. 3 Programming Patterns A pattern has (at least) a name , a problem to be solved, a standard solution , and examples that illustrate it. 4 Name: Loop condition Problem: A test must be applied to each value in a vector. Solution: Use an if statement to apply the test inside a for loop. Example: % Display all negative values in the vector x for n = 1:length(x) if x(n) < 0 disp(x(n)) end end 5 Name: Counter Problem: It is necessary to count occurrences of some condition in the loop. Solution: Maintain a separate counter variable. Example: % Count the negative values in vector x counter = 0; %initialize counter for n = 1:length(x) if x(n) < 0 count = count + 1; %increment counter end end 6 Name: Compute from index Problem: A value must change with each pass through the loop, but that value is not the loop variable. Solution: Compute the value using the loop variable.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 3

Loop Programming Patterns - Loop Programming Patterns A...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online