Lab 08: Repetition Structures

Objectives

  • To learn how to write and use for loops.
  • To learn how to write and use while loops.

Background

There may be a situation when you need to execute a block of code several times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. The drawing shows the general form of a loop statement for most programming languages. MATLAB provides various types of loops to handle looping requirements including: while loops, for loops,and nested loops. If you are trying to declare or write your own loops, you need to make sure that the loops are written as scripts and not directly in the Command Window. To start a new script, locate the button in the upper left corner of the window labeled New Script.

LoopStructure

Questions

  1. Write the MATLAB statements required to calculate and print out the squares of all the even integers between 0 and 50. Create a table consisting of each integer and its square, with appropriate labels over each column.
  2. A store owner asks you to design a system for user in the checkout process. The system should:
    • Prompt the user to enter the cost of the first item.
    • Continue to prompt for additional items, until the user enters 0.
    • Display the total.
    • Prompt for the dollar amount the customer submits as payment.
    • Display the charge due.
  3. A vectory is given by $X = \left[ {\matrix{-3.5 & -5 & 6.2 & 11 & 0 & 8.1 & -9 & 0 & 3 & -1 & 3 & 2.5 \cr} } \right]$. Using conditional statement and loops, develop a program that creates two vectors from X:
    • Vector P contains all positive elements of X
    • Vector N contains the negative elements of X.
    The elements in new vectors are in the same order as in X.