Skip to content Skip to navigation

Connexions

You are here: Home » Content » Programming with M-Files: While-Loop Drill Exercises

Navigation

Content Actions

Programming with M-Files: While-Loop Drill Exercises

Module by: Darryl Morrell

Summary: This module provides several simple exercises designed to test and increase your understanding of while loops in m-files.

Some While Loop Exercises

Problem 1

How many times will this loop print 'Hello World'?


n = 10;
while n > 0
    disp('Hello World')
    n = n - 1;
end

Solution 1

10 times.

[ Click for Solution 1 ]

Problem 2

How many times will this loop print 'Hello World'?


n = 1;
while n > 0
    disp('Hello World')
    n = n + 1;
end

Solution 2

This loop will continue to print 'Hello World' until the user stops the program. You can stop a program by holding down the 'Ctrl' key and simultaneously pressing the 'c' key.

[ Click for Solution 2 ]

Problem 3

What values will the following code print?

a = 1
while a < 100
    a = a*2
end

Solution 3

a =
     1
a =
     2
a =
     4
a =
     8
a =
    16
a =
    32
a =
    64
a =
   128

[ Click for Solution 3 ]

Problem 4

What values will the following code print?


a = 1;
n = 1;
while a < 100
    a = a*n
    n = n + 1;
end

Solution 4


a =
     1
a =
     2
a =
     6
a =
    24
a =
   120

[ Click for Solution 4 ]

Comments, questions, feedback, criticisms?

Send feedback